const { ipcRenderer } = require("electron");
// const $ = require('jquery');
let fanyiSource = "sougou";
let translateInfo = null;
// window.onload = function(){
// }

if (document.readyState === "loading") {
  // 此时加载尚未完成
  document.addEventListener("DOMContentLoaded", initFanYiService);
} else {
  // 此时`DOMContentLoaded` 已经被触发
  initFanYiService();
}

addEvents();

function initFanYiService() {
  ipcRenderer.invoke("getTranslateConnect").then((result) => {
    setTimeout(() => {
      initFanYiStyle();
    }, 800);
    createActionBtn(result);
    addEvents();
  });
}



function initFanYiStyle() {
  const styleTag = document.createElement("style");
  styleTag.setAttribute("tyoe", "text/css");
  let cssText = "";
  if (fanyiSource == "CNKI") {
    cssText = `
        body, html {
            min-width:500px !important;
            overflow-x: hidden;
         }
         .translate{
          display: flex;
          flex-direction: column;
          width: 500px !important;
          margin: 10px 0 25px;
         }
         .trans-left{
          width: 375px !important;
         }
         .trans-right{
          width: 375px !important;
         }

        .fir-trans-btns{
            display: flex;
            position: fixed;
            left: 0;
            bottom: 0;
            z-index: 2147483647;
            width: 100%;
            align-items: center;
            justify-content: center;
            padding: 15px 0;
            box-shadow: 0 -1px 2px -2px rgba(0, 0, 0, 0.08), 0 -3px 6px 0 rgba(0, 0, 0, 0.05), 0 -5px 12px 4px rgba(0, 0, 0, 0.03);
            background-color: #fff;
        }
        .fir-trans-btn{
            height: 32px;
            width: 90px;
            background-color: #fff;
            border: 1px solid #e1e1e1;
            border-radius: 2px;
            margin: 0 5px;
            font-size: 14px;
            color: #666;
            cursor: pointer;
        }
        .fir-trans-btn-act {
            background-color: #55c0ff;
            border-color:  #55c0ff;
            color: #fff;
        }
        #trans-input {
            min-height: 0 !important;
        }
        #dl_cookieBanner {
            display: none !important;
        }
        .fir-connect {
            display: flex;
            align-items: center;
            color: #666;
            margin-right: 10px;
        }
        .fir-connect input {
            -webkit-appearance: auto;
            margin-right: 5px;
        }
        ::-webkit-scrollbar{width:0px;height:2px}
        ::-webkit-scrollbar-button{width:8px;height:0}
        ::-webkit-scrollbar-track{background:0 0}
        ::-webkit-scrollbar-thumb{background:#fff;-webkit-transition:.3s;transition:.3s}
    `;
  } else if (fanyiSource == 'caiyun') {
    cssText = `
    .two-column-layout{
      display: flex;
      flex-direction: column;
      width:620px;
    }
    .fir-trans-btns{
        display: flex;
        position: fixed;
        left: 0;
        bottom: 0;
        z-index: 2147483647;
        width: 100%;
        align-items: center;
        justify-content: center;
        padding: 15px 0;
        box-shadow: 0 -1px 2px -2px rgba(0, 0, 0, 0.08), 0 -3px 6px 0 rgba(0, 0, 0, 0.05), 0 -5px 12px 4px rgba(0, 0, 0, 0.03);
        background-color: #fff;
    }
    .fir-trans-btn{
        height: 32px;
        width: 90px;
        background-color: #fff;
        border: 1px solid #e1e1e1;
        border-radius: 2px;
        margin: 0 5px;
        font-size: 14px;
        color: #666;
        cursor: pointer;
    }
    .fir-trans-btn-act {
        background-color: #55c0ff;
        border-color:  #55c0ff;
        color: #fff;
    }
    #trans-input {
        min-height: 0 !important;
    }
    #dl_cookieBanner {
        display: none !important;
    }
    .fir-connect {
        display: flex;
        align-items: center;
        color: #666;
        margin-right: 10px;
    }
    .fir-connect input {
        -webkit-appearance: auto;
        margin-right: 5px;
    }
    ::-webkit-scrollbar{width:0px;height:2px}
    ::-webkit-scrollbar-button{width:8px;height:0}
    ::-webkit-scrollbar-track{background:0 0}
    ::-webkit-scrollbar-thumb{background:#fff;-webkit-transition:.3s;transition:.3s}
`;
  } else {
    cssText = `
        .fir-trans-btns{
            display: flex;
            position: fixed;
            left: 0;
            bottom: 0;
            z-index: 2147483647;
            width: 100%;
            align-items: center;
            justify-content: center;
            padding: 15px 0;
            box-shadow: 0 -1px 2px -2px rgba(0, 0, 0, 0.08), 0 -3px 6px 0 rgba(0, 0, 0, 0.05), 0 -5px 12px 4px rgba(0, 0, 0, 0.03);
            background-color: #fff;
        }
        .fir-trans-btn{
            height: 32px;
            width: 90px;
            background-color: #fff;
            border: 1px solid #e1e1e1;
            border-radius: 2px;
            margin: 0 5px;
            font-size: 14px;
            color: #666;
            cursor: pointer;
        }
        .fir-trans-btn-act {
            background-color: #55c0ff;
            border-color:  #55c0ff;
            color: #fff;
        }
        #trans-input {
            min-height: 0 !important;
        }
        #dl_cookieBanner {
            display: none !important;
        }
        .fir-connect {
            display: flex;
            align-items: center;
            color: #666;
            margin-right: 10px;
        }
        .fir-connect input {
            -webkit-appearance: auto;
            margin-right: 5px;
        }
        ::-webkit-scrollbar{width:0px;height:2px}
        ::-webkit-scrollbar-button{width:8px;height:0}
        ::-webkit-scrollbar-track{background:0 0}
        ::-webkit-scrollbar-thumb{background:#fff;-webkit-transition:.3s;transition:.3s}
    `;
  }
  const cssNode = document.createTextNode(cssText);
  styleTag.appendChild(cssNode);
  const head = document.getElementsByTagName("head");
  if (head.length) {
    head[0].appendChild(styleTag);
  }
}

// 创建操作按钮
function createActionBtn(connectChecked) {
  const warp = document.createElement("div");

  const extractBtn = document.createElement("button");
  const copyBtn = document.createElement("button");
  const closeBtn = document.createElement("button");

  const checkboxWarp = document.createElement("label");

  // const

  warp.appendChild(checkboxWarp);
  warp.appendChild(copyBtn);
  warp.appendChild(extractBtn);

  warp.setAttribute("class", "fir-trans-btns");
  copyBtn.setAttribute("class", "fir-trans-btn");
  closeBtn.setAttribute("class", "fir-trans-btn");
  extractBtn.setAttribute("class", "fir-trans-btn fir-trans-btn-act");
  checkboxWarp.setAttribute("class", "fir-connect");

  const escapeHTMLPolicy = trustedTypes.createPolicy("myEscapePolicy", {
    createHTML: (string) => string,
  });

  const escaped = escapeHTMLPolicy.createHTML(
    "<input type='checkbox' id='connectTrans' /> 连续"
  );
  checkboxWarp.innerHTML = escaped;
  copyBtn.innerText = "复制译文";
  extractBtn.innerText = "摘录译文";
  // closeBtn.innerText = "关闭";

  copyBtn.onclick = function () {
    btnAction("copy");
  };

  extractBtn.onclick = function () {
    btnAction("extract");
  };

  // closeBtn.onclick = function() {
  //     btnAction('close');
  // }

  checkboxWarp.onclick = function () {
    btnAction("changeConnect");
  };

  document.body.appendChild(warp);
  document.getElementById("connectTrans").checked = connectChecked;
}

function btnAction(action) {
  if (action == "close") {
    ipcRenderer.sendToHost("closeTranslateRes");
    return;
  }

  if (action == "changeConnect") {
    const connectTransInput = document.getElementById("connectTrans");
    ipcRenderer.send("changeConnect", connectTransInput.checked);
    ipcRenderer.sendToHost("changeConnect", connectTransInput.checked);
    return;
  }

  let tranresEle, tranContentEle;
  translateInfo = getTranslateInfo();
  if (fanyiSource == "sougou") {
    tranresEle = document.getElementById("trans-result");
    tranContentEle = document.getElementById("trans-input");
  }

  if (fanyiSource === "youdao") {
    tranresEle = document.getElementById("translateResult");
    tranContentEle = document.getElementById("inputText");
  }

  if (fanyiSource === "deepl") {
    tranresEle = document.querySelector(
      '[data-testid="translator-target-input"]'
    );

    let sourceTextarea = document.querySelector(
      '[aria-labelledby="translation-source-heading"]'
    );;
    tranContentEle = sourceTextarea.querySelector("p");
  }

  if (fanyiSource === "baidu") {
    tranresEle = document.querySelector(".trans-content");
    tranContentEle = document.querySelector("#j-textarea");
  }

  if (fanyiSource === "caiyun") {
    tranresEle = document.querySelector(".target-translate");
    tranContentEle = document.querySelector(".column-choose-content textarea");
  }

  if (fanyiSource === "google") {
    tranresEle = document.querySelector(".HwtZe");
    tranContentEle = document.querySelector("textarea");
  }
  if (fanyiSource === "CNKI") {
    tranresEle = document.querySelector(".translatedContent-inner");
    tranContentEle = document.querySelector(".trans-left textarea");
  }

  if (!tranresEle) {
    return;
  }
  let res = tranresEle.innerText;
  // if(fanyiSource === "deepl") {
  //     res = tranresEle.value;
  // }
  if (action == "copy") {
    ipcRenderer.sendToHost("copyTranslateRes", res);
  }
  if (action == "extract") {
    translateInfo.content = tranContentEle.value;
    if (fanyiSource === "deepl") {
      // res = tranresEle.value;
      translateInfo.content = tranContentEle.textContent;
    }
    if (fanyiSource === "caiyun") {
      translateInfo.content = tranContentEle.value;
    }
    if (translateInfo.params && translateInfo.params.selectContent) {
      translateInfo.params.selectContent = tranContentEle.value;
    }
    const translateRes = {
      info: { ...translateInfo },
      res,
    };
    ipcRenderer.sendToHost("translateRes", translateRes);
  }
}

function getTranslateInfo() {
  try {
    return translateInfo || JSON.parse(localStorage.getItem("translateInfo"));
  } catch (error) {
    return null;
  }
}

function addEvents() {
  ipcRenderer.on("translate", (arg, info) => {
    if (info.content) {
      translateInfo = info;
      localStorage.setItem("translateInfo", JSON.stringify(info));
      dispatchFanyi();
    }
  });

  ipcRenderer.on("initTranslateSource", (arg, key) => {
    fanyiSource = key;
  });
  ipcRenderer.on("changeTranslateSource", (arg, key) => {
    fanyiSource = key;
    if (translateInfo && translateInfo.content) {
      dispatchFanyi();
    }
  });
}

function setNativeValue(element, value) {
  const valueSetter = Object.getOwnPropertyDescriptor(element, "value").set;
  const prototype = Object.getPrototypeOf(element);
  const prototypeValueSetter = Object.getOwnPropertyDescriptor(
    prototype,
    "value"
  ).set;

  if (valueSetter && valueSetter !== prototypeValueSetter) {
    prototypeValueSetter.call(element, value);
  } else {
    valueSetter.call(element, value);
  }
}

function dispatchFanyi() {
  let inputEle = null;

  if (fanyiSource === "baidu") {
    inputEle = document.getElementById("j-textarea");
    // if(inputEle.fireEvent) {
    //     inputEle.fireEvent('onchange')
    // } else {
    // const inputEv = new Event('input');
    // const focusEv = new Event('focus');
    // const changeEv = new Event('click');
    // inputEle.click()
    // inputEle.dispatchEvent(changeEv);
    // inputEle.value = translateInfo.content;
    // inputEle.dispatchEvent(focusEv);
    // inputEle.dispatchEvent(inputEv);

    // setTimeout(() => {
    //     document.getElementsByClassName('trans-btn j-tranBtn')[0].click()
    // }, 100)
    location.replace(`#zh/en/${decodeURIComponent(translateInfo.content.replaceAll('%', ''))}`);

    // }
  }

  if (fanyiSource === "sougou") {
    inputEle = document.getElementById("trans-input");
    if (inputEle.fireEvent) {
      inputEle.fireEvent("onchange");
    } else {
      const inputEv = new Event("input", { bubbles: true });
      const focusEv = new Event("focus", { bubbles: true });
      inputEle.dispatchEvent(focusEv);
      inputEle.value = translateInfo.content;

      inputEle.dispatchEvent(inputEv);
      setTimeout(() => {
        document.getElementById("trans-input").style.minHeight = 0;
        document.getElementsByClassName("btn-primary larger")[0].click();
      }, 0);
    }
  }

  if (fanyiSource === "youdao") {
    inputEle = document.getElementById("inputText");
    inputEle.value = translateInfo.content;
    document.querySelector('input[value="翻译"]').click();
  }

  if (fanyiSource === "deepl") {
    // inputEle = document.querySelector('textarea[dl-test="translator-source-input"]');
    // inputEle.value = translateInfo.content;
    // const inputEv = new Event('input', { bubbles: true });
    // inputEle.dispatchEvent(inputEv);
    // document.querySelector('.lmt__sides_container').scrollIntoView();
    location.replace(`/translator#en/zh/${translateInfo.content}`);
  }

  if (fanyiSource === "caiyun") {
    setTimeout(() => {
      inputEle = document.querySelector(".column-choose-content textarea");
      inputEle.value = translateInfo.content;
      document.querySelector(".custom-textarea").click();
      const inputEv = new Event("input", { bubbles: true });
      inputEle.dispatchEvent(inputEv);
    }, 1000);
  }

  if (fanyiSource === "google") {
    inputEle = document.querySelector("textarea");
    inputEle.value = translateInfo.content;
    // setNativeValue(inputEle, translateInfo.content)
    const inputEv = new Event("input", { bubbles: true });
    inputEle.dispatchEvent(inputEv);
  }

  if (fanyiSource == "CNKI") {
    inputEle = document.getElementById("translateLeft");
    inputEle.value = translateInfo.content;
    const inputEv = new Event("input", { bubbles: true });
    inputEle.dispatchEvent(inputEv);
  }
}
