import { message } from "antd";

import { Print, StartPrint, getFaHuoYiSetting } from "../types";
import { ScanPrintingForm } from "../types/scanPrinting";
export enum PlatformCode {
  "淘系及其他平台订单模板" = 0,
  "拼多多订单模板" = 1,
  "京东订单模板" = 2,
  "抖音订单模板" = 3,
}

type Params = {
  waybillNo: string; // 运单号
  platform: PlatformCode;
  wayCompanyId: string;
} & {
  orderNo: string; // 订单号
  wayCompanyId: string; // 快递公司的Id
  platform: PlatformCode; // 平台编码，淘系及其他平台订单模板的为0，拼多多订单的为1，京东订单的为2，抖音订单为3
};

interface Response {
  data: {
    action: "StartPrint";
    value: Params;
  };
}
window.addEventListener("message", function (res: Response) { // 浏览器层级window监听消息
  if (res.data.action === "StartPrint") { // 锐图后台发起打印行为
    console.log('锐图后台发起打印行为')
    chrome.storage?.local.get(
      {
        list: [],
        scanPrintingForm: {
          waybillTemplates: [],
          shippingAddresses: [],
          printers: [],
        },
        isAutoEmit: false,
      },
      function (storage) {
      console.log('StartPrint---storage:', storage)
        // @ts-ignore
        if (
          storage.list.length == 0 ||
          !storage.list[0].wayCompanyId ||
          !storage.list[0].waybillTemplateList.some((item: any) => item)
        ) {
          alert("请选择快递模板");
          return;
        }
        // @ts-ignore
        if (
          storage.scanPrintingForm.waybillTemplates.length == 0 ||
          storage.scanPrintingForm.shippingAddresses.length == 0 ||
          storage.scanPrintingForm.printers.length == 0
        ) {
          alert("发货易配置信息为空或获取失败");
          return;
        }
        // 从锐图后台接收打印的参数
        const { wayCompanyId, waybillNo, orderNo, platform } = res.data.value;
        console.log('StartPrint---Response:', res)
        if (
          !waybillNo &&
          (!wayCompanyId || !orderNo || ![0, 1, 2, 3].includes(Number(platform)))
        ) {
          alert("参数传递错误");
          return;
        }
        console.log('storage.scanPrintingForm', storage.scanPrintingForm);
        console.log('storage.list', storage.list);
        console.log('storage.isAutoEmit', storage.isAutoEmit);
        let newValue = {
          ...res.data.value,
          scanPrintingForm: storage.scanPrintingForm,
          list: storage.list,
          isAutoEmit: storage.isAutoEmit,
        };
        console.log('newValue', newValue);
        chrome.runtime.sendMessage(
          { action: StartPrint, value: newValue },
          function (response) {}
        );
      }
    );
  } else if (res.data.action === getFaHuoYiSetting) {
    console.log("content recive:", res.data.value);

    chrome.storage.local.set(
      {
        // @ts-ignore
        scanPrintingForm: JSON.parse(res.data.value),
      },
      () => {}
    );
    chrome.runtime.sendMessage(
      { action: getFaHuoYiSetting, value: res.data },
      function (response) {}
    );
  }
});
enum SelectOptions {
  "waybillNo" = "waybillNo",
  "orderOriginalId" = "orderOriginalId",
}
// fahuoyi.com
interface Message {
  action: "Print";
  value: Params;
}
const printWayBillByOld = function (waybillNo: string, wayCompanyId: string) {
  chrome.storage.local.get({ list: [], isAutoEmit: false }, function (res) {
    // 选择使用旧单号打印
    let oldOptionDom = document.querySelectorAll(
      ".form-group.mr20>.radio-inline"
    )[1] as HTMLLabelElement;
    let waybillNoBtn = document.querySelector(
      ".form-group>.form-control.original-id-input-label>option[value=waybillNo]"
    ) as HTMLOptionElement;
    let selectDom = document.querySelector(
      "select.form-control.original-id-input-label"
    ) as HTMLSelectElement;
    let inputDom = document.querySelector(
      ".form-group>.form-control.original-id-input"
    ) as HTMLInputElement;
    let serachBtn = document.querySelector(
      ".form-group>.btn.btn-primary[type=button]"
    ) as HTMLButtonElement;
    let printDom = document.querySelector(
      "#elContainer>div>.form-inline.panel-border.p15.search-panel>div[class]>.form-group.mr20[style]>select.form-control"
    ) as HTMLSelectElement;
    let autoDom = document.querySelectorAll(
      "#elContainer>div>.form-inline.panel-border.p15.search-panel>div.mt10>div.form-group.mr20>select.form-control"
    )[1] as HTMLSelectElement;
    // 默认参数写死
    let hiddenInputDom = document.querySelector(
      "#forcePrintMergerOrderInput"
    ) as HTMLInputElement;

    let printId: string;
    // @ts-ignore
    res.list.forEach((item) => {
      if (item.wayCompanyId === wayCompanyId) {
        printId =
          item.printId === "仅获取电子面单号不打印面单"
            ? "isGenerateWaybillNoOnly"
            : item.printId;
        // printId = item.printId
      }
    });

    // 1.选择旧单号打印
    oldOptionDom.click();

    // 2.选择打单模板
    waybillNoBtn.selected = true;
    console.log('2.选择打单模板', SelectOptions, SelectOptions.waybillNo)
    selectDom.value = SelectOptions.waybillNo;
    // @ts-ignore
    selectDom.dispatchEvent(new Event("change", { bubbles: true }));
    // 3.选择打印机
    printDom.value = printId!;
    printDom.dispatchEvent(new Event("change", { bubbles: true }));
    // 4.自动发货
    autoDom.value = "true";
    autoDom.dispatchEvent(new Event("change", { bubbles: true }));
    // 5.自己联系快递公司
    let bySelf = document.querySelectorAll(
      "#elContainer>div>.form-inline.panel-border.p15.search-panel>div.mt10>div.form-group.mr20>select.form-control"
    )[2] as HTMLSelectElement;
    bySelf.value = "OFFLINE";
    bySelf.dispatchEvent(new Event("change", { bubbles: true }));
    // 6.输入运单号
    // selectDom.__reactEventHandlers$8wsw7c8olk.onChange({ target: { value: SelectOptions.waybillNo } })
    inputDom.value = waybillNo;

    // 7.默认参数写死
    hiddenInputDom.value = "true";

    serachBtn.click();
  });
};

const printWayBillByNew = function ({
  orderNo,
  wayCompanyId,
  platform,
}: Pick<Params, "orderNo" | "wayCompanyId" | "platform">) {
  // console.log(orderNo, wayCompanyId, platform)
  // 根据快递公司的companyId选择相应的配置
  chrome.storage.local.get({ list: [], isAutoEmit: false }, function (res) {
    // console.log(res, 'res') //res:{isAutoEmit:boolean,list:[{waybillCompanyId:"",waybillTemplateList:[x,x,x]}]}
    let waybillTemplate: string;

    let printId: string;

    // @ts-ignore
    res.list.forEach((item) => {
      if (item.wayCompanyId === wayCompanyId) {
        waybillTemplate = item.waybillTemplateList[platform];
        printId =
          item.printId === "仅获取电子面单号不打印面单"
            ? "isGenerateWaybillNoOnly"
            : item.printId;
        // printId = item.printId
      }
    });

    let newOrderBtn = document.querySelector(
      ".form-group.mr20>.radio-inline.mr10"
    ) as HTMLLabelElement;

    let wayTemplateSelect = document.querySelector(
      ".form-group.mr20>.form-control.waybill-template-select"
    ) as HTMLSelectElement;

    // let orderBtn = document.querySelector(".form-group>.form-control.original-id-input-label>option[value=orderOriginalId]") as HTMLOptionElement
    let selectDom = document.querySelector(
      "select.form-control.original-id-input-label"
    ) as HTMLSelectElement;
    let inputDom = document.querySelector(
      ".form-group>.form-control.original-id-input"
    ) as HTMLInputElement;

    let searchDom = document.querySelector(
      ".form-group>.btn.btn-primary"
    ) as HTMLButtonElement;

    let printDom = document.querySelector(
      "#elContainer>div>.form-inline.panel-border.p15.search-panel>div[class]>.form-group.mr20[style]>select.form-control"
    ) as HTMLSelectElement;
    let autoDom = document.querySelectorAll(
      "#elContainer>div>.form-inline.panel-border.p15.search-panel>div.mt10>div.form-group.mr20>select.form-control"
    )[1] as HTMLSelectElement;

    // 默认参数写死
    let hiddenInputDom = document.querySelector(
      "#forcePrintMergerOrderInput"
    ) as HTMLInputElement;

    //1.点击 获取新单号打印
    newOrderBtn.click();
    //2.选择快递单模板
    wayTemplateSelect.value = waybillTemplate! + "";
    wayTemplateSelect.dispatchEvent(new Event("change", { bubbles: true }));

    //3.点击订单编号
    selectDom.value = SelectOptions.orderOriginalId;
    // @ts-ignore
    selectDom.dispatchEvent(new Event("change", { bubbles: true }));

    // 4. 选择打印机
    printDom!.value = printId!;

    printDom.dispatchEvent(new Event("change", { bubbles: true }));
    // orderBtn.click()

    // 5.自动发货
    autoDom.value = "true";
    autoDom.dispatchEvent(new Event("change", { bubbles: true }));
    // 6.自己联系快递公司
    let bySelf = document.querySelectorAll(
      "#elContainer>div>.form-inline.panel-border.p15.search-panel>div.mt10>div.form-group.mr20>select.form-control"
    )[2] as HTMLSelectElement;
    bySelf.value = "OFFLINE";
    bySelf.dispatchEvent(new Event("change", { bubbles: true }));
    //7.输入订单编号
    inputDom.value = orderNo;

    // 8.默认参数写死
    hiddenInputDom.value = "true";

    //9.点击搜索并打印
    searchDom.click();
  });
};

//发货易页面

chrome.runtime.onMessage.addListener(function ( // 浏览器扩展插件层级监听消息
  message: Message,
  sender,
  response
) {
  if (message.action === Print) { // 从bg转发的打印请求在这里接收
    //console.log(message.js);
    let btn_js: HTMLButtonElement = document.createElement("button");
    btn_js.style.cssText = "width:0;heigth:0";
    document.body.appendChild(btn_js);
    // @ts-ignore
    btn_js.setAttribute("onclick", message.js); // 这里触发接收信息的js事件
    btn_js.click();
    btn_js.setAttribute("onclick", "");
    btn_js.remove();

    // return;
    if (message.value.waybillNo) {
      printWayBillByOld(message.value.waybillNo, message.value.wayCompanyId);
    } else {
      const { orderNo, wayCompanyId, platform } = message.value;

      printWayBillByNew({ orderNo, wayCompanyId, platform });
    }
  }
});

// 拿到打印机
chrome.runtime.onConnect.addListener(function (port) {
  if (port.name === "getPrinter") {
    port.onMessage.addListener(function (msg) {
      if (msg.action === "getPrint") {
        // @ts-ignore
        let options: HTMLOptionElement[] = document.querySelectorAll(
          "#elContainer>div>.form-inline.panel-border.p15.search-panel>div[class]>.form-group.mr20[style]>select.form-control>option"
        );
        // console.log(2)
        // console.log(options, options[0].value, '3')

        let arr = [];
        for (let i = 0; i < options.length; i++) {
          arr.push(options[i].textContent);
          // arr.push(options[i].value)
        }

        port.postMessage(arr);
      }
    });
  }
});

// 厂家content.js页面
// chrome.runtime.onMessage.addListener(function (message, sender, response) {
//     if (message.action === "newWaybillNo") {
//         window.postMessage(message, "*")
//     }
// })
// let FactoryPost = chrome.runtime.connect({ name: "getMessage" })
// FactoryPost.onMessage.addListener(function (msg) {
//     if (msg.action === "newWaybillNo") {
//         window.postMessage(msg, "*")
//     }
// })
chrome.runtime.onConnect.addListener(function (port) {
  console.log("content chrome onConnect", port);
  if (port.name === "sendNewWaybillNo") {
    // console.log(port, 'port')
    port.onMessage.addListener(function (msg) {
      // console.log(msg, 'msg')
      console.log("content port onMessage", msg);
      if (msg.action === "sendNewWaybillNo") {
        window.postMessage(
          {
            action: "newWaybillNo",
            message: msg?.message,
            orderNo: msg?.orderNo,
            waybillNo: msg?.waybillNo,
            result: msg.result,
          },
          "*"
        );

        port.postMessage({ action: "answer" });
      }
    });
  }
});

// inject.js
// 给锐图后台调用的方法，挂载与window上
const startPrintWayBill = function (params: Params) {
  // 通知content.js触发事件
  window.postMessage({ action: "StartPrint", value: params }, "*");
  return new Promise(function (resolve, reject) {
    // @ts-ignore
    // 在锐图后台挂载接收信息的方法
    window.onmessage = function (res) {
      if (res.data.action === "newWaybillNo") {
        console.log(res.data, "res.data");
        res.data.result ? resolve(res.data.waybillNo) : reject(res.data);
      }
    };
  });
};

const injectGetFaHuoYiSetting = function (params: Params) {
  // 通知content.js触发事件
  window.addEventListener("onSEScanPrintingFormLoad", () => {
    // scanPrintingForm.onLoad((data: OnLoadData) => {
    //   //const { waybillTemplates, shippingAddresses, printers } = data;
    //   console.log("init", data);
    //   //   window.postMessage(
    //   //     { action: getFaHuoYiSetting, value: JSON.stringify(data) },
    //   //     "*"
    //   //   );
    // });
    //@ts-ignore
    var scanPrintingForm: ScanPrintingForm = window["scan-printing-form"];
    var timer: number = window.setInterval(function () {
      if (scanPrintingForm === undefined) {
        //@ts-ignore
        scanPrintingForm = window["scan-printing-form"];
      }
      if (
        //@ts-ignore
        scanPrintingForm.waybillTemplates.length > 0 ||
        //@ts-ignore
        scanPrintingForm.shippingAddresses.length > 0 ||
        //@ts-ignore
        scanPrintingForm.printers.length > 0
      ) {
        console.log(scanPrintingForm);
        window.postMessage(
          {
            action: "getFaHuoYiSetting",
            value: JSON.stringify(scanPrintingForm),
          },
          "*"
        );
        clearInterval(timer);
      }
    }, 1000);

    // return new Promise(function (resolve, reject) {
    //   // @ts-ignore
    //   window.onmessage = function (res) {
    //     if (res.data.action === getFaHuoYiSetting) {
    //       console.log(res.data, getFaHuoYiSetting);
    //       res.data.result ? resolve(res.data) : reject(res.data);
    //     }
    //   };
    // });
  });
};
/**
 * 发货易content
 */

window.addEventListener("message", function (msg) {
  if (msg.data.action === "sendNewWaybillNo") {
    // chrome.runtime.onConnect.addListener(function (port) {
    //     console.log(port, 'port')
    //     port.postMessage(msg.data)
    // })
    chrome.runtime.sendMessage(msg.data);
  }
  if (msg.data.action === getFaHuoYiSetting) {
    console.log("content Get Test Message", JSON.parse(msg.data.value));
  }
});

function observerDom(): Boolean {
  let tbodyDom = document.querySelector(
    "#root > section > main > div > div.content-right.background-white.h > div > div > div > div.ant-table-wrapper > div > div > div > div > div > table > tbody"
  );
  console.log("observer", tbodyDom);
  if (!tbodyDom) return false;
  if (tbodyDom) {
    console.log("observer");
    let observe = new MutationObserver(function (mutations, observe) {
      console.log(mutations, "mutations");

      let td = mutations[mutations.length - 1].addedNodes[0].childNodes[3];
      console.log(td, "td");

      if (!td) return;
      let tdObserve = new MutationObserver(function (mutations, observe) {
        console.log(mutations, "mutations");
        mutations.forEach((item) => {
          item.addedNodes.forEach((node) => {
            // @ts-ignore
            if (
              node.nodeType == 3 &&
              node.parentElement?.className.includes("danger")
            ) {
              console.log(node.textContent, "nodeTextContent");
              // @ts-ignore
              return window.postMessage(
                {
                  action: "sendNewWaybillNo",
                  //@ts-ignorenpm
                  message: node?.wholeText,
                  result: false,
                },
                "*"
              );
            }
            if (node.nodeName == "DIV") {
              let text = node.childNodes[2].textContent;
              let orderNo =
                item.target.parentElement?.children[0]?.children[0]
                  ?.childNodes[0]?.textContent;
              console.log(orderNo, "orderNo");
              console.log(text, "text", node);
              window.postMessage(
                {
                  action: "sendNewWaybillNo",
                  waybillNo: text,
                  orderNo,
                  result: true,
                },
                "*"
              );
              // 从发货易页面发消息给bg
              // chrome.runtime.sendMessage({ action: "newWaybillNo", value: text }, function (res) {

              // })
              // console.log("fahuoyi")
              // let fahuoyiPort = chrome.runtime.connect({ name: "sendMessage" })
              // fahuoyiPort.postMessage({ action: "newWaybillNo", value: text })
              // chrome.runtime.onConnect.addListener(function (port) {
              //     console.log(port, 'port')
              //     port.postMessage({ action: "newWaybillNo", value: text })
              // })
            }
          });
        });
      });
      tdObserve.observe(td, {
        childList: true,
        characterData: true,
        subtree: true,
        attributes: true,
      });
    });

    observe.observe(tbodyDom, {
      childList: true,
    });

    let bfqxDom = document.querySelector("body");
    let observe1 = new MutationObserver(function (mutations, observe) {
      // mutations[0].addedNodes[0].className
      console.log(mutations, "bfqxDom");
      mutations.forEach((item) => {
        item.addedNodes.forEach((node) => {
          console.log("node.textContent", node.textContent, node.textContent ==
          "该订单有商品正在退款中或者已取消，是否确认继续打印？取 消确 定");
          // node.textContent == 'bootbox modal fade sui-modal in' &&
          let printAndCancel = false
          if ( // 未打印已取消
            node.textContent ==
            "该订单有商品正在退款中或者已取消，是否确认继续打印？取 消确 定"
          ) {
            printAndCancel = false
            // let bfqxyesbtn = document.querySelector(
            //   "body > div:nth-child(19) > div > div.ant-modal-wrap > div > div.ant-modal-content > div > div > div.ant-modal-confirm-btns > button.ant-btn.ant-btn-primary"
            // ) as HTMLButtonElement;
            // let bfqxnobtn = document.querySelector(
            //   "body > div:nth-child(19) > div > div.ant-modal-wrap > div > div.ant-modal-content > div > div > div.ant-modal-confirm-btns > button:nth-child(1)"
            // ) as HTMLButtonElement;
            // console.log("bfqxyesbtn", bfqxyesbtn);
            // bfqxyesbtn.click();
          } else if ( // 已打印已取消
            node.textContent?.includes("对应订单已经打印成功，确认再次打印该订单吗？取 消确 定")
          ) {
            printAndCancel = true
          }
          let bfqxyesbtn = document.querySelector(
            "body > div:last-child div.ant-modal-confirm-btns > button.ant-btn.ant-btn-primary"
          ) as HTMLButtonElement;
          // let bfqxnobtn = document.querySelector(
          //   "body > div:nth-child(19) > div > div.ant-modal-wrap > div > div.ant-modal-content > div > div > div.ant-modal-confirm-btns > button:nth-child(1)"
          // ) as HTMLButtonElement;
          console.log("testDom", document.querySelector(
            "body > div:last-child div.ant-modal-confirm-btns > button.ant-btn.ant-btn-primary"
          ) as HTMLButtonElement);
          console.log("bfqxyesbtn", bfqxyesbtn);
          bfqxyesbtn.click();
          console.log(printAndCancel, 'printAndCancel')
          // 一下逻辑暂时不生效
          // if (printAndCancel) {
          //   setTimeout(() => {
          //     let bfqxyesbtn = document.querySelector(
          //       "body > div:nth-child(19) > div > div.ant-modal-wrap > div > div.ant-modal-content > div > div > div.ant-modal-confirm-btns > button.ant-btn.ant-btn-primary"
          //     ) as HTMLButtonElement;
          //     // let bfqxnobtn = document.querySelector(
          //     //   "body > div:nth-child(19) > div > div.ant-modal-wrap > div > div.ant-modal-content > div > div > div.ant-modal-confirm-btns > button:nth-child(1)"
          //     // ) as HTMLButtonElement;
          //     console.log("printAndCancel bfqxyesbtn", bfqxyesbtn);
          //     // bfqxyesbtn.click();
          //   }, 500);
          // }
        });
      });
    });

    observe1.observe(bfqxDom!, {
      childList: true,
    });
  }
  return true;
}

// 自定义一个js插入网页当中
function injectCustomjs() {
  let temp = document.createElement("script");
  // 制定一些全局方法，共网页内调用，与content.js互通消息
  temp.innerHTML = `window.startPrintWayBill=${startPrintWayBill};window.getFaHuoYiSetting=${injectGetFaHuoYiSetting};window.getFaHuoYiSetting();`;
  document.body.appendChild(temp);
  var timer: number = window.setInterval(function () {
    if (observerDom()) clearInterval(timer);
  }, 1000);
}

injectCustomjs();
