import { onMounted, ref, reactive, toRefs, provide, watch, computed } from "vue";
import { hiprint, autoConnect, disAutoConnect } from "vue-plugin-hiprint";
import { TYPE, useToast, POSITION } from "vue-toastification";
import ToastErrCopy from "@/components/ToastWidget/ToastErrCopy/index.vue";
import dayjs from "dayjs";
import { isArray } from "@/utils/is";
import { HiprintState } from "@/stores/interface/index";

/**
 * @description 打印hooks常量
 */
interface printStateProps {
  /**
   * @description 打印模版
   */
  hiprintTemplate: any;
  /**
   * @description 打印数据
   */
  printData: any;
}

interface showPreviewParams {
  hTemplate: any;
  pData: any;
  width?: string | number;
  sTitle?: string;
}

/**
 * @description 页面按钮权限
 * */

/**
 * @description hiprint打印hooks
 * @param {Function} t i18n
 * @param {Function} reqCallback 调用浏览器打印，点击时触发回调; 注意：1，无论打印成功与否; 2，直接打印的成功时间不会触发
 * @param {Function} successCallback 直接打印:发送成功触发回调，不会触发浏览器回调（reqCallback）
 * @param {Function} failCallback 直接打印:发送失败触发回调，不会触发浏览器回调（reqCallback）
 * */
export const useHiPrintPlugin = (
  t: any,
  reqCallback?: (data?: any) => any, // 调用浏览器打印，点击时触发回调，无论打印成功与否，直接打印的成功时间不会触发
  successCallback?: (data?: any) => any, // 直接打印成功触发回调，不会触发浏览器回调
  failCallback?: (data?: any) => any
) => {
  const state = reactive<printStateProps>({
    hiprintTemplate: null,
    printData: null
  });

  const toast = useToast();

  /**
   * @description 打印机列表
   */
  const printerList = computed(() => {
    console.log("hiprint.hiwebSocket.getPrinterList() :>> ", hiprint.hiwebSocket.getPrinterList());
    return hiprint.hiwebSocket.getPrinterList();
  });

  const setPrintTemplate = (template: any, pData: any, title = ""): showPreviewParams => {
    let printTem = new hiprint.PrintTemplate({
      template: template.content,
      fontList: [
        { title: "微软雅黑", value: "Microsoft YaHei" },
        { title: "黑体", value: "STHeitiSC-Light" },
        { title: "思源黑体", value: "SourceHanSansCN-Normal" },
        { title: "王羲之书法体", value: "王羲之书法体" },
        { title: "宋体", value: "SimSun" },
        { title: "华为楷体", value: "STKaiti" },
        { title: "cursive", value: "cursive" }
      ],
      dataMode: 1 // 1:getJson 其他：getJsonTid 默认1
      // history: true // 是否需要 撤销重做功能
    });

    const newDate = dayjs().format("YYYY-MM-DD HH:mm");
    if (isArray(pData)) {
      pData.forEach((item: any) => {
        item.printDate = newDate;
      });
    } else {
      pData.printDate = newDate;
    }

    console.log("setPrintTemplate pData :>> ", pData);
    console.log("setPrintTemplate printTem :>> ", printTem);
    console.log("{ :>> ", {
      hTemplate: printTem,
      pData: pData,
      width: printTem.getPanel().width,
      sTitle: title
    });

    return {
      hTemplate: printTem,
      pData: pData,
      width: printTem.getPanel().width,
      sTitle: title
    };
  };

  // const init = () => {
  //   if (!hiprint.hiwebSocket.opened) {
  //     //   try {
  //     console.log("start init :>> ");
  //     // hiPrintPlugin.install(Vue);

  //     autoConnect((status: any, msg: any) => {
  //       if (status) {
  //         console.log("init success :>> ");
  //       } else {
  //         console.log("init fail msg :>> ", msg);
  //         disAutoConnect();
  //       }
  //     });
  //     //   } catch (error) {
  //     //     console.log("useHiPrint init error :>> ", error);
  //     //   }
  //   }
  // };

  const toDefaultPrint = (pData: any) => {
    state.hiprintTemplate.print(
      pData,
      {},
      {
        callback: () => {
          console.log("toDefaultPrint hooks callback");
          reqCallback && reqCallback(pData);
        }
      }
    );
  };
  /**
   * 直接打印方法，调用打印插件electron-hiprint
   * @param param 打印参数
   * @param ifShowTips
   */
  const toDirectPrint = (printerParams?: HiprintState.printerParams, ifShowTips: boolean = false) => {
    // state.hiprintTemplate = hTemplate;
    // const printerList = state.hiprintTemplate.getPrinterList();
    console.log("toDirectPrint hiprint :>> ", hiprint);
    // const printerList = hiprint.hiwebSocket.getPrinterList();
    // const clientInfo = state.hiprintTemplate.getClientInfo();
    console.log("toDirectPrint printerList :>> ", printerList);
    console.log("toDirectPrint state.printData :>> ", state.printData);
    console.log("toDirectPrint printerParams :>> ", printerParams);
    if (printerList.value && printerList.value.length) {
      state.hiprintTemplate.print2(state.printData, printerParams, {
        callback: () => {
          console.log("callback");
          reqCallback && reqCallback();
          // emit("printCallback", state.printData);
          // loadingPrinter.value = false;
          // dialogVisible.value = false;
        }
      });
      // state.hiprintTemplate.print(state.printData, printerParams, {
      //   callback: () => {
      //     console.log("callback");
      //     // emit("printCallback", state.printData);
      //     // loadingPrinter.value = false;
      //     // dialogVisible.value = false;
      //   }
      // });
      state.hiprintTemplate.on("printSuccess", (data: any) => {
        console.log("打印任务：发送成功");
        toast.success(
          {
            component: ToastErrCopy,
            props: {
              type: "success",
              title: "发送成功",
              message: "打印任务"
            }
          },
          {
            icon: false,
            timeout: 4000,
            closeButton: false,
            toastClassName: "longjoe-toast"
          }
        );
        successCallback && successCallback(state.printData);
      });
      state.hiprintTemplate.on("printError", (data: any) => {
        console.log("打印任务：发送失败");
        toast.error(
          {
            component: ToastErrCopy,
            props: {
              type: "error",
              title: "发送失败",
              message: "打印任务"
            }
          },
          {
            icon: false,
            timeout: 4000,
            closeButton: false,
            toastClassName: "longjoe-toast"
          }
        );
        failCallback && failCallback(data);
      });
    } else {
      toast.error(
        {
          component: ToastErrCopy,
          props: {
            type: "info",
            title: "操作提示",
            message: "未查找到打印机，请确保与设备保持链接"
          }
        },
        {
          icon: false,
          timeout: 4000,
          closeButton: false,
          toastClassName: "longjoe-toast"
        }
      );
    }
  };

  /**
   * 默认打印按钮（含有直接打印逻辑）
   * @param params 打印参数
   * @param pData
   */
  const toPrintOfDefaultBtn = (
    { hTemplate, pData, width = "210" }: showPreviewParams,
    printerParams: HiprintState.printerParams = {}
  ) => {
    /** 1.判断是否有开启插件
     * 是：直接打印
     * 否：弹出预览界面
     */
    console.log("toPrintOfDefaultBtn hiprint :>> ", hiprint);

    if (!hiprint.hiwebSocket.opened) {
      // 重连
      hiprint.hiwebSocket.reconnect();
    }

    console.log("hiprint :>> ", hiprint);
    console.log("hiprint.hiwebSocket :>> ", hiprint.hiwebSocket);

    console.log("hiprint.hiwebSocket :>> ", hiprint.hiwebSocket);
    console.log("hiprint.hiwebSocket.opened :>> ", hiprint.hiwebSocket.opened);

    console.log("toPrintOfDefaultBtn printerParams :>> ", printerParams);
    if (hiprint.hiwebSocket.opened) {
      state.hiprintTemplate = hTemplate;
      state.printData = pData;

      toDirectPrint(printerParams, false);
    } else {
      toast(
        {
          component: ToastErrCopy,
          props: {
            type: "info",
            title: t("sys.print.clientNotConnect"),
            message: `连接【${hiprint.hiwebSocket.host}】失败！<br>请确保目标服务器已<a href="https://gitee.com/CcSimple/electron-hiprint/releases" target="_blank"> 下载 </a> 并 <a href="hiprint://"> 运行 </a> 打印服务！`
          }
        },
        {
          position: POSITION.TOP_RIGHT,
          icon: false,
          timeout: 5000,
          closeButton: false,
          toastClassName: "longjoe-toast"
        }
      );
    }
  };

  // onMounted(() => {
  //   init();
  // });

  const hiprintDisConnect = () => {
    disAutoConnect();
  };

  return {
    ...toRefs(state),
    printerList,
    setPrintTemplate,
    hiprintDisConnect,
    toPrintOfDefaultBtn,
    toDefaultPrint,
    toDirectPrint
  };
};
