"use strict";

localStorage.setItem("apiTimeStamp", String(Date.now()));

function setNativeToJSCallback(name, fn) {
  if (fn) {
    window.topcheerNativeToJSCallbackHandle[name] = function (res) {
      if (res) {
        var result = typeof res == "string" ? JSON.parse(res) : res;
        fn(result.data);
      }
    };
  } else {
    delete window.topcheerNativeToJSCallbackHandle[name];
  }
}

var httpseq = 0;

function getUUID() {
  httpseq += 1;
  return httpseq;
}

function postMessageToNative(method) {
  var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var callback = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

  if (!window.webkit && !window.InAppBrowser && !window.topcheerAndroidNativeBridge && !window.TopCheerNativeHandle) {
    return;
  }

  if (!method) {
    return;
  }

  var uuid = getUUID();

  if (Math.abs(uuid - httpseq) > 2) {
    return;
  }

  var callbackName = method + "_" + uuid;

  if (params.jsCallbackName) {
    callbackName = params.jsCallbackName;
  }

  setNativeToJSCallback(callbackName, function (res) {
    try {
      callback(res);
    } catch (error) {}

    if (res && res.pydx_callback_id) {
      delete window.topcheerNativeToJSCallbackHandle[res.pydx_callback_id];
    }
  });
  var message = {
    command: method,
    value: params,
    pydx_callback_name: callbackName
  };

  if (window.webkit) {
    window.webkit.messageHandlers.nativeData.postMessage(message);
  } else {
    window.nativeData.postMessageToNative(JSON.stringify(message));
  }
}

var watermarkText = "";
setTimeout(function () {
  watermarkText = window.nativeData ? window.nativeData.getUserName() : "用户";

  __svgWM({
    content: watermarkText
  });
}, 1000);

setTimeout(function () {
  console.log("URL:", location.href);
  enterFile();
}, 2000);



window.beforeWebViewClose = function () {};

function submitLearningData(closeWebView, isTimerEvent) {
  let isfile = location.href.includes("fileupload") || location.href.includes(".pdf");
  if (closeWebView) {
    setTimeout(function () {
      postMessageToNative("closeWebView");
    }, 2000);
  }
  if (!isfile) {
    console.log("退出 - 不是文档");
    postMessageToNative("closeWebView");
    return;
  }

  postMessageToNative("http", window.data1, function (res) {
    if (Number(res.code) != 200) { 
      return;
    }
    var ciphertext = res.data.data ? res.data.data.EncrptString : "";
    var learntime = String(timerCount);
    var data2 = {
      url: "https://pydxapp.spdb.com.cn/pydxapi/app/api",
      params: {
        className: "FileStudyService",
        method: "getFileStudyLog",
        param: {
          documentId: fileid,
          businessId: peixunbanID,
          exitpagenum: "1",
          businesstype: peixunbanID.length > 0 ? "2" : "",
          finished: "1",
          learncount: "0",
          learntime: "" + learntime,
          ciphertext: ciphertext
        }
      }
    };
    postMessageToNative("http", data2, function (res) {
      if (closeWebView) {
        postMessageToNative("closeWebView");
      }

      if (isTimerEvent) {
        timerCount = 0;
      }
    });
  });
}



function enterFile() {
  let isfile = location.href.includes("fileupload") || location.href.includes(".pdf");
  if (!isfile) {
    console.log("----------不是文档");
    return;
  }
  postMessageToNative("http", window.data1, function (res) {
    if (Number(res.code) != 200) { 
      return;
    }
    var ciphertext = res.data.data ? res.data.data.EncrptString : "";
    var current = Date.now();
    var last = Number(localStorage.getItem("apiTimeStamp"));

    if (Math.abs(current - last) < 1000) {
      return;
    }

    localStorage.setItem("apiTimeStamp", String(Date.now()));
    var data2 = {
      url: "https://pydxapp.spdb.com.cn/pydxapi/app/api",
      params: {
        className: "FileStudyService",
        method: "enterFile",
        param: {
          documentId: fileid,
          ciphertext: ciphertext
        }
      }
    };
    postMessageToNative("http", data2, function (res) {
      if (Number(res.data.code) == 200) {
        var resObj = JSON.parse(res.data.data);
        pcFileData = resObj.data;
      }
    });
  });
}

var date = new Date();

function toLocal(date) {
  var local = new Date(date);
  local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
  var aaa = local.toJSON();
  aaa = aaa.replace("T", " ");
  return aaa.substring(0, 19);
}

function __svgWM() {
  var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      _ref$container = _ref.container,
      container = _ref$container === void 0 ? document.body : _ref$container,
      _ref$content = _ref.content,
      content = _ref$content === void 0 ? "请勿外传" : _ref$content,
      _ref$width = _ref.width,
      width = _ref$width === void 0 ? "160" : _ref$width,
      _ref$height = _ref.height,
      height = _ref$height === void 0 ? "160" : _ref$height,
      _ref$opacity = _ref.opacity,
      opacity = _ref$opacity === void 0 ? "0.05" : _ref$opacity,
      _ref$fontSize = _ref.fontSize,
      fontSize = _ref$fontSize === void 0 ? "14px" : _ref$fontSize,
      _ref$zIndex = _ref.zIndex,
      zIndex = _ref$zIndex === void 0 ? 1000 : _ref$zIndex;

  var args = arguments[0];
  var svgStr = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"".concat(width, "\" height=\"").concat(width, "\">\n    <style>\n        text {\n            font-family:arial,sans-serif\n        }\n    </style>\n  <text x=\"80\" y=\"80\" dy=\"-23\"\n    text-anchor=\"middle\"\n    stroke=\"#888888\"\n    stroke-width=\"1\"\n    stroke-opacity=\"").concat(opacity, "\"\n    fill=\"#888888\"\n    fill-opacity=\"").concat(opacity, "\"\n    transform=\"rotate(-45,80,80)\"\n    style=\"font-size: ").concat(fontSize, ";\">\n    ").concat(content, "\n  </text>\n<text x=\"80\" y=\"80\" \n    text-anchor=\"middle\"\n    stroke=\"#888888\"\n    stroke-width=\"1\"\n    stroke-opacity=\"").concat(opacity, "\"\n    fill=\"#888888\"\n    fill-opacity=\"").concat(opacity, "\"\n    transform=\"rotate(-44,80,80)\"\n    style=\"font-size: 12px;\">\n    ").concat(toLocal(new Date()), "\n  </text>  \n</svg>");
  var base64Url = "data:image/svg+xml;base64,".concat(window.btoa(unescape(encodeURIComponent(svgStr))));

  var __wm = document.querySelector(".__wm");

  var watermarkDiv = __wm || document.createElement("div");

  var styleStr = "\n      position:fixed;\n      top:0;\n      left:0;\n      bottom:0;\n      right:0;\n      width:100%;\n      height:100%;\n      z-index:".concat(zIndex, ";\n      pointer-events:none;\n      background-repeat:repeat;\n      background-image:url('").concat(base64Url, "')");
  watermarkDiv.setAttribute("style", styleStr);
  watermarkDiv.classList.add("__wm");

  if (!__wm) {
    container.insertBefore(watermarkDiv, container.firstChild);
  }
}


let hasParam = location.href.split("?").length > 1;
if (hasParam) {
  postMessageToNative("interceptUserAction", {
    jsCallbackName: "interceptUserAction"
  }, function (res) {
    submitLearningData(true, false);
  });
  
  var newURL = new URL(decodeURIComponent(location.href.split("?")[1]).replace("url=", ""));
  var fileid = newURL.searchParams.get("id");
  var peixunbanID = newURL.searchParams.get("trainId");
  peixunbanID = peixunbanID ? peixunbanID : "";
  clearInterval(window.fileLearningTimer);
  window.fileLearningTimer = setInterval(timerEvent, 1000);
  window.data1 = {
    url: "https://pydxapp.spdb.com.cn/api/service-app/app/api",
    params: {
      className: "Sm4EcbService",
      method: "getCommonEncrptString"
    }
  };
  var timerCount = 0;

  function timerEvent() {
    timerCount += 1;

    if (timerCount % 120 == 0) {
      submitLearningData(false, true);
    }
  }

}