import { ref, reactive, computed, toRefs, nextTick } from "vue";
// import { isArray, isObject } from "@/utils/is";
// import { cloneDeep, pick, get, omit, defaultsDeep } from "lodash-es";
// import { More, ArrowDown, ArrowRight } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useHiprinterStore } from "@/stores/modules/hiprinter";
import { Print } from "./interface/index";
import { useUserStore } from "@/stores/modules/user";
import { getPrintTemplate, savePrintTemplate } from "@/api/modules/print";
import { formatToDate } from "@/utils/dateUtil";

/**
 * @description 打印hooks
 * */
export const usePrint = (
  t: any,
  dwname: string | undefined,
  getSelectRecords: () => any,
  beforePrintCallback?: (data?: any) => boolean,
  printDataCallback?: (data: any) => any
) => {
  const state = reactive<Print.PrintStateProps>({
    /**
     * @description 打印编辑ref
     */
    printEditorRef: null,
    /**
     * @description 打印模版ref
     */
    printTemplateRef: null,
    printerListTpDropdownRef: null,
    activePrint: "",
    /**
     * @description 直接打印：明细设置记录
     */
    hiprinterStateList: [],
    /**
     * @description 直接打印：条码设置记录
     */
    hiprinterStateMx: [],
    printerTpList: []
  });

  const hiprinterStore = useHiprinterStore();
  const userStore = useUserStore();
  /**
   * @description 获取打印模块个性名称
   * @param name 额外名称
   */
  const getPrintDwname = (name = "") => {
    return dwname + name;
  };

  const toGetPrinterState = () => {
    state.hiprinterStateList = hiprinterStore.getPrinter(getPrintDwname(""));

    state.hiprinterStateMx = hiprinterStore.getPrinter(getPrintDwname("_mx"));
  };

  /**
   * @description 打印前，检测打印状态
   */
  const checkStatus = (callback: any) => {
    let checkData = true;
    beforePrintCallback && (checkData = beforePrintCallback());
    console.log("checkData :>> ", checkData);
    if (!checkData) return false;
    callback && callback();
  };

  /**
   * @description 打开打印
   */
  const openPrint = (name = "") => {
    state.activePrint = name ?? "";
    // 获取打印数据
    checkStatus(() => {
      state.printTemplateRef?.open({
        dwname: getPrintDwname(name)
      });
    });
  };

  const checkPrintTemplateList = (name = "", callback?: any) => {
    state.activePrint = name ?? "";
    console.log("checkPrintTemplateList name :>> ", name);
    // 获取打印数据
    checkStatus(async () => {
      let _key = getPrintDwname(name);
      // 获取打印模板
      state.printTemplateRef.getData(
        {
          dwname: _key
        },
        (data: any) => {
          state.printerTpList = data.list;

          if (callback) {
            callback();
          } else {
            nextTick(() => {
              console.log("checkPrintTemplateList data :>> ", data, state.printerListTpDropdownRef);
              state.printerListTpDropdownRef && state.printerListTpDropdownRef.handleOpen();
            });
          }
        },
        () => {
          state.printerTpList = [];

          if (callback) {
            callback();
          } else {
            nextTick(() => {
              state.printerListTpDropdownRef && state.printerListTpDropdownRef.handleOpen();
            });
          }
          ElMessage.warning("请管理员先设置打印模版");
        }
      );
    });
  };

  /**
   * @description 直接打开预览
   */
  const openPrintPriveiew = (name = "", data: any, direct = false) => {
    state.activePrint = name ?? "";
    // 获取打印数据
    checkStatus(async () => {
      let _key = getPrintDwname(name);

      if (state.printerTpList.length) {
        toPreviewPrintTemplate(data, _key, direct);
      } else {
        state.printTemplateRef?.open({
          dwname: _key
        });
      }
    });
  };

  /**
   * @description 预览:打印模板列表-预览
   */
  const toPreviewPrintTemplate = (data: any, key: string, directPrint: boolean = false) => {
    console.log("toEditPrintTemplate data :>> ", data, key, directPrint);
    let tem = data;
    if (typeof tem.content == "string") {
      tem.content = JSON.parse(tem.content);
    }
    let _record = getSelectRecords();
    let printData = {
      userInfo: userStore.userInfo,
      table: _record
    };

    let printerParams = hiprinterStore.getPrinter(key);
    if (printDataCallback) {
      printDataCallback({ data: printData, active: state.activePrint }).then((res: any) => {
        if (directPrint) {
          console.log("state.printEditorRef?.directPrint :>> ", typeof state.printEditorRef?.directPrint);
          state.printEditorRef?.directPrint(tem, res, tem.aliase, printerParams);
        } else {
          state.printEditorRef?.onlyPreview(tem, res, tem.aliase);
        }
      });
    } else {
      if (directPrint) {
        console.log("state.printEditorRef?.directPrint :>> ", typeof state.printEditorRef?.directPrint);
        state.printEditorRef?.directPrint(tem, printData, tem.aliase, printerParams);
      } else {
        state.printEditorRef?.onlyPreview(tem, printData, tem.aliase);
      }
    }
  };

  /**
   * @description 修改:打印模板列表页-修改/新增
   * @param data 打印模板
   */
  const toEditPrintTemplate = (data?: any) => {
    console.log("toEditPrintTemplate data :>> ", data);
    if (data && data.comid == 0) {
      // 系统模板,另存为
      data.aliase = "另存" + t(`business.dwname.${dwname}`) + "模版" + formatToDate();
      // 新增模版
      delete data.printid;
    }
    let tem = data ?? {
      aliase: "新建" + t(`business.dwname.${dwname}`) + "模版" + formatToDate(),
      dwname: dwname,
      content: {}
    };
    if (typeof tem.content == "string") {
      tem.content = JSON.parse(tem.content);
    }
    let _record = getSelectRecords();
    let printData = {
      userInfo: userStore.userInfo,
      table: _record
    };
    if (printDataCallback) {
      printDataCallback({ data: printData, active: state.activePrint }).then((res: any) => {
        console.log("res :>> ", res);
        state.printEditorRef?.open(tem, res);
      });
    } else {
      state.printEditorRef?.open(tem, printData);
    }
  };

  /**
   * @description 打印:打印模板列表-打印
   */
  const toPrintPrintTemplate = (data: any, callback: any, directPrint: boolean = false) => {
    console.log("toEditPrintTemplate data :>> ", data);
    let tem = data;
    if (typeof tem.content == "string") {
      tem.content = JSON.parse(tem.content);
    }
    let _record = getSelectRecords();
    let printData = {
      userInfo: userStore.userInfo,
      table: _record
    };

    let printerParams = hiprinterStore.getPrinter(dwname ?? "");
    if (printDataCallback) {
      printDataCallback({ data: printData, active: state.activePrint }).then((res: any) => {
        if (directPrint) {
          console.log("state.printEditorRef?.directPrint :>> ", typeof state.printEditorRef?.directPrint);
          state.printEditorRef?.directPrint(tem, res, tem.aliase, printerParams);
        } else {
          state.printEditorRef?.onlyPrint(tem, res, tem.aliase);
        }
        callback && callback();
      });
    } else {
      if (directPrint) {
        console.log("state.printEditorRef?.directPrint :>> ", typeof state.printEditorRef?.directPrint);
        state.printEditorRef?.directPrint(tem, printData, tem.aliase, printerParams);
      } else {
        state.printEditorRef?.onlyPrint(tem, printData, tem.aliase);
      }
      callback && callback();
    }
  };

  return {
    ...toRefs(state),
    toGetPrinterState,
    openPrint,
    openPrintPriveiew,
    toPreviewPrintTemplate,
    toPrintPrintTemplate,
    toEditPrintTemplate,
    checkPrintTemplateList
  };
};
