import ColumnGroup from "antd/lib/table/ColumnGroup";
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",
        url: "*://*.fahuoyi.com/features/scanPrintingOld",
      },
      function (tabs) {
        console.log(tabs, "tabs11", message.value);
        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
                // 调试未打印已取消订单
                // message.value?.waybillNo ? 'ABC123111' : message.value?.orderNo
                // '1497851395913027966'
              }")`,
            });
            // 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('getPrintJS param:', param);
  let _ScanPrintSearchType = ScanPrintSearchType.WAYBILL_NO;
  // 调试未打印已取消订单
  // let _ScanPrintSearchType = ScanPrintSearchType.ORDER_ORIGINAL_ID;
  let _GetWaybillNoMethod = GetWaybillNoMethod.OLD;

  let _printId: string = param.list[0].printId;
  let _waybillTemplate: string = "0";
  console.log('getPrintJS param222:', param.list)
  // @ts-ignore
  param.list.forEach((item) => {
    if (item.wayCompanyId === param.wayCompanyId) {
      console.log('getPrintJS param333:', item);
      // (_waybillTemplate = item.waybillTemplateList[param?.platform ?? 0]),
      // platform// 平台编码，淘系及其他平台订单模板的为0，拼多多订单的为1，京东订单的为2，抖音订单为3
      // 如果param.platform为3，则当成2来处理
      console.log('getPrintJS param666:param.platform', param.platform);
      (_waybillTemplate = item.waybillTemplateList[param?.platform && param.platform===3?2: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"
}`;
  console.log('ConfigParams', ConfigParams)
  return ConfigParams;
}
