import { defineStore } from "pinia";
import { ipcRenderer } from "electron";
import { useUser } from "@/store/user.js";
import dayjs from "dayjs";
import receiptPrint from "@/components/lodop/receiptPrint.js";
import lodopPrintWork from "@/components/lodop/lodopPrintWork.js";
import invoicePrint from "@/components/lodop/invoicePrint.js";
import refundPrint from "@/components/lodop/refundPrint.js";
import { printerList } from "@/api/account.js";
import { useSocket } from './socket.js';

export const usePrint = defineStore("print", {
  state: () => ({
    isPrintService: false, // 打印服务是否启动
    printServiceTimer: false, // 打印服务定时器
    printServiceTimerCount: 0, // 打印服务定时器计数
    printServiceTimerMaxCount: 10, // 打印服务定时器最大计数
    showPrintNotService: false, // 是否显示重启软件,
    localDevices: [], // 本地打印机列表
    deviceNoteList: [], // 添加的打印机
    deviceLableList: [], // 添加的打印机
    labelList: [], // 要打印的队列数据
    printTimer: null,
    receiptList: [], // 小票队列数据
    receiptTimer: null,
  }),
  actions: {
    // 获取本地打印机和已添加的可以用打印机列表
    async init() {
      // 获取本地打印机
      ipcRenderer.send("getPrintList");
      ipcRenderer.on("printList", (event, arg) => {
        this.localDevices = arg;
      });

      try {
        // 获取已添加的打印机
        const res = await printerList();
        this.deviceNoteList = res.records.filter(
          (item) => item.status && item.subType == "cash"
        );
        this.deviceLableList = res.records.filter(
          (item) => item.status && item.subType == "label"
        );
        console.log("打印队列初始化成功", {
          deviceNoteList: this.deviceNoteList,
          deviceLableList: this.deviceLableList,
        });
      } catch (error) {
        console.error("获取已添加的打印机列表失败", error);
      }

      // 检测打印服务是否启动
      this.checkPrintService();
    },
    // 检测打印组件服务是否启动
    checkPrintService() {
      this.printServiceTimer = setInterval(() => {
        if (
          typeof LODOP !== "undefined" &&
          LODOP.webskt &&
          LODOP.webskt.readyState == 1
        ) {
          // 准备好
          this.isPrintService = true;
          clearInterval(this.printServiceTimer);
          this.printServiceTimer = null;
        } else {
          this.printServiceTimerCount++;
          console.log("打印服务未启动", this.printServiceTimerCount);

          if (this.printServiceTimerCount >= this.printServiceTimerMaxCount) {
            // 超过最大次数
            this.isPrintService = false;
            this.showPrintNotService = true;
            clearInterval(this.printServiceTimer);
            this.printServiceTimer = null;
          }
        }
        console.log("打印服务是否启动：", this.isPrintService);
      }, 1000);
    },
    // 检查本地打印机是否能正常使用
    checkLocalPrint(address) {
      let print = "";
      for (let item of this.localDevices) {
        if (item.name == address) {
          print = item;
        }
      }

      if (!print.name) {
        return false;
      } else {
        return true;
      }
    },
    // 打印标签小票
    labelPrint(props) {
      const store = useUser();

      if (
        this.deviceLableList.length &&
        this.checkLocalPrint(this.deviceLableList[0].address)
      ) {
        let pids = this.deviceLableList[0].categoryList;
        let count = 0;
        let sum = 0;

        props.carts.map((item) => {
          if (pids.some((el) => el == item.categoryId)) {
            for (let i = 0; i < item.number; i++) {
              sum++;
            }
          }
        });

        props.carts.map((item) => {
          if (pids.some((el) => el == item.categoryId)) {
            for (let i = 0; i < item.number; i++) {
              count++;
              this.labelList.push({
                outNumber: props.outNumber,
                name: item.name,
                skuName: item.skuName,
                masterId: props.orderInfo.tableName,
                deviceName: this.deviceLableList[0].address,
                createdAt: dayjs(props.createdAt).format("YYYY-MM-DD HH:mm:ss"),
                isPrint: false,
                count: `${count}/${sum}`,
                ticketLogo: store.shopInfo.ticketLogo,
              });
            }
          }
        });

        console.log("this.labelList===", this.labelList);
        // return;

        // 执行打印操作
        this.startLabelPrint();
      } else {
        console.log("标签打印：未在本机查询到打印机");
      }
    },
    // 开始打印标签数据
    startLabelPrint() {
      if (this.printTimer != null) return;
      this.printTimer = setInterval(() => {
        let item = "";
        if (!this.labelList.length) {
          clearInterval(this.printTimer);
          this.printTimer = null;
        } else {
          item = this.labelList[0];
          if (!item.isPrint) {
            ipcRenderer.send("printerTagSync", JSON.stringify(item));
            this.labelList[0].isPrint = true;
            this.labelList.splice(0, 1);
          }
        }
      }, 2000);
    },
    // 添加小票打印队列数据
    pushReceiptData(props, isDevice = true) {
      // console.log("pushReceiptData===", props);
      if (!isDevice) {
        // 测试打印，无需校验本地打印机
        this.receiptList.push(props);
        this.startReceiptPrint();
      } else {
        if (
          this.deviceNoteList.length &&
          this.checkLocalPrint(this.deviceNoteList[0].address) &&
          this.isPrintService
        ) {
          const store = useUser();
          props.deviceId = this.deviceNoteList[0].id;
          props.deviceName = this.deviceNoteList[0].address;
          props.shop_name = store.shopInfo.shopName;
          props.loginAccount = store.userInfo.name;
          props.createdAt = dayjs(props.createdAt).format(
            "YYYY-MM-DD HH:mm:ss"
          );
          props.printTime = dayjs().format("YYYY-MM-DD HH:mm:ss");
          if (!props.orderInfo.masterId) {
            props.orderInfo.masterId = props.orderInfo.tableName;
          }
          props.orderInfo.outNumber = props.outNumber;
          if (!props.discountAmount) {
            props.discountAmount = props.amount;
          }

          this.receiptList.push(props);
          this.startReceiptPrint();
        } else {
          console.log("订单小票：未在本机查询到打印机");
        }
      }
    },
    // 开始打印小票
    async startReceiptPrint() {
      try {
        const socketStore = useSocket();
        const userStore = useUser();

        if (this.receiptTimer !== null) return;
        this.receiptTimer = setInterval(() => {
          if (!this.receiptList.length) {
            clearInterval(this.receiptTimer);
            this.receiptTimer = null;
          } else {
            receiptPrint(this.receiptList[0]);
            // 在这里触发已打印操作标记
            const data = {
              type: "cashier",
              operate_type: "order_print_status",
              table_code: this.receiptList[0].orderInfo.tableCode,
              account: userStore.shopInfo.account,
              print_status: "1",
              order_id: this.receiptList[0].orderInfo.id,
              print_id: this.receiptList[0].deviceId,
              shop_id: this.receiptList[0].orderInfo.shopId,
            }
            socketStore.ws.send(JSON.stringify(data));
            this.receiptList.splice(0, 1);
          }
        }, 2000);
      } catch (error) {
        console.log(error);
      }
    },
    // 打印交班小票
    printWork(data) {
      if (
        this.deviceNoteList.length &&
        this.checkLocalPrint(this.deviceNoteList[0].address)
      ) {
        data.deviceName = this.deviceNoteList[0].address;
        lodopPrintWork(data);
      } else {
        console.log("交班小票：未在本机查询到打印机");
      }
    },
    // 打印订单发票
    printInvoice(data) {
      if (
        this.deviceNoteList.length &&
        this.checkLocalPrint(this.deviceNoteList[0].address)
      ) {
        data.deviceName = this.deviceNoteList[0].address;
        invoicePrint(data);
      } else {
        console.log("订单发票：未在本机查询到打印机");
      }
    },
    // 打印退单小票
    printRefund(data) {
      if (
        this.deviceNoteList.length &&
        this.checkLocalPrint(this.deviceNoteList[0].address)
      ) {
        data.deviceName = this.deviceNoteList[0].address;
        refundPrint(data);
      } else {
        console.log("退单小票：未在本机查询到打印机");
      }
    },
  },
});
