import { factoryContentUrls } from "../config";
import { StartPrint, Print } from "../types/index";
import { ScanPrintSearchType, GetWaybillNoMethod } from "../types/scanPrinting";
//     platform: PlatformCode,// 平台编码，淘系及其他平台订单模板的为0，拼多多订单的为1，京东订单的为2
const PlatfromsMap = new Map([
  [0, /.+:\/\/a.*\.fahuoyi.com\/scanPrinting\/index/],
  [1, /.+:\/\/pdd.*\.fahuoyi.com\/scanPrinting\/index/],
  [2, /.+:\/\/jd.*\.fahuoyi.com\/scanPrinting\/index/],
]);
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  console.log("onMessage", message);
  if (message.action === StartPrint) {
    // console.log("startPrint")
    // 通知fahuoyi的content开始点击
    // chrome.tabs.query(
    //   {
    //     url: "*://*.fahuoyi.com/scanPrinting/index",
    //   },
    //   function (tabs) {
    //     let exp = new RegExp(PlatfromsMap.get(message.value.platform)!, "i");

    //     console.log(tabs, "tabs66");
    //     tabs &&
    //       tabs.forEach((tab) => {
    //         if (exp.test(tab.url!)) {
    //           chrome.tabs.sendMessage(tab.id!, {
    //             action: Print,
    //             value: message.value,
    //           });
    //         }
    //       });
    //     // // sendResponse("")
    //     // if (tabs[0]) {
    //     //     chrome.tabs.sendMessage(tabs[0].id!, { action: Print, value: message.value })
    //     // }
    //   }
    // );
    chrome.tabs.query(
      {
        url: "*://*.fahuoyi.com/features/scanPrinting",
      },
      function (tabs) {
        console.log(tabs, "tabs11");
        tabs &&
          tabs.forEach((tab) => {
            chrome.tabs.sendMessage(tab.id!, {
              action: Print,
              value: message.value,
              js: `console.log(window["scan-printing-form"]);window["scan-printing-form"].config(${getPrintJS(
                message.value
              )});window["scan-printing-form"].searchAndPrint("${
                message.value?.waybillNo
                  ? message.value?.waybillNo
                  : message.value?.orderNo
              }")`,
            });
            // chrome.tabs.executeScript(tab.id!, {
            //   code: `console.log(window["scan-printing-form"]);window["scan-printing-form"].config(${getPrintJS(
            //     message.value
            //   )});`,
            // });
            // console.log(getPrintJS(message.value));
          });
      }
    );
  } else if (message.action === "sendNewWaybillNo") {
    // 从bg页面转发给厂家页面的content.js
    chrome.tabs.query(
      {
        url: factoryContentUrls,
      },
      function (tabs) {
        tabs &&
          tabs.forEach((tab) => {
            // chrome.tabs.sendMessage(tab.id!, message)
            const port = chrome.tabs.connect(tab.id!, {
              name: "sendNewWaybillNo",
            });
            port.onMessage.addListener(function (msg, port) {
              if (msg.action === "answer") {
                // console.log(msg, port, 'bg')
                port.disconnect();
              }
            });
            port.postMessage(message);
          });
      }
    );
    // let port = chrome.runtime.connect({ name: "bgSendMessage" })
    // port.postMessage(message)
  }
});
// chrome.runtime.onConnect.addListener(function (msg) {
//     console.log(msg, 'msgbg')
// })

function getPrintJS(param: any): string {
  console.log(param);
  let _ScanPrintSearchType = ScanPrintSearchType.WAYBILL_NO;
  let _GetWaybillNoMethod = GetWaybillNoMethod.OLD;

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

  if (param.waybillNo) {
    //旧单号
  } else {
    //新单号
    _ScanPrintSearchType = ScanPrintSearchType.ORDER_ORIGINAL_ID;
    _GetWaybillNoMethod = GetWaybillNoMethod.NEW;
  }
  let ConfigParams = `{
  /**
   * 扫描类型
   */
  searchType: "${_ScanPrintSearchType}",

  /**
   * 是否避免重复扫描打印
   */
  checkRepeatPrint: true,

  /**
   * 快递单模板id
   */
  waybillTemplateId: ${_waybillTemplate},

  /**
   * 打印机名称
   */
  printer: "${_printId}",

  /**
   * 发货人id
   */
  shippingAddressId: ${param.scanPrintingForm.shippingAddresses[0].id},

  /**
   * 是否打印成功后自动发货
   */
  autoShippingAfterPrint: ${param.isAutoEmit ? "true" : "false"},

  /**
   * 获取面单方式
   */
  getWaybillNoMethod: "${_GetWaybillNoMethod}",

  /**
   * 发货方式
   */
  shippingWay: "OFFLINE"
}`;
  return ConfigParams;
}
