import _ from 'lodash'
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: null,
    printServiceTimerCount: 0,
    printServiceTimerMaxCount: 10,
    showPrintNotService: false,
    localDevices: [],
    deviceNoteList: [],
    deviceLableList: [],
    labelList: [],
    printTimer: null,
    receiptList: [],
    receiptTimer: null,
    // 新增：其他打印任务队列与状态锁
    printQueue: [],
    isProcessing: false
  }),

  actions: {
    // 1. 添加任务到队列
    addToPrintQueue(task) {
      this.printQueue.push(task);
      if (this.log) console.log('任务已加入打印队列，当前队列长度:', this.printQueue.length);
      this.processPrintQueue(); // 尝试启动处理
    },
    // 2. 处理队列（递归执行）
    async processPrintQueue() {
      // 如果正在处理或队列为空，直接返回
      if (this.isProcessing || this.printQueue.length === 0) return;

      this.isProcessing = true;
      const currentTask = this.printQueue[0]; // 取出第一个任务

      try {
        if (this.log) console.log('开始执行打印任务:', currentTask);
        // 执行打印逻辑（参考你注释中的代码）
        await new Promise(resolve => setTimeout(resolve, 1500));
        ipcRenderer.send(currentTask.taskName, currentTask.data)
        if (this.log) console.log('任务执行成功');
      } catch (error) {
        console.error('打印任务执行失败:', error);
        // 失败时不移除任务，或者根据业务决定是否重试/丢弃
      } finally {
        // 无论成功失败，移除当前任务
        this.printQueue.shift();
        if (this.log) console.log('任务移除，剩余队列:', this.printQueue.length);

        // 标记为空闲，尝试处理下一个
        this.isProcessing = false;
        this.processPrintQueue();
      }
    },
    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.printType == "cash"
        );
        this.deviceLableList = res.records.filter(
          (item) => item.status && item.printType == "label"
        );
      } 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++;
          if (this.printServiceTimerCount >= this.printServiceTimerMaxCount) {
            this.isPrintService = false;
            this.showPrintNotService = true;
            clearInterval(this.printServiceTimer);
            this.printServiceTimer = null;
          }
        }
      }, 1000);
    },

    // 检查打印机是否可用
    checkPrinterAvailable(printer) {
      if (printer.connectionType === "局域网") {
        const ipReg = /^(\d{1,3}\.){3}\d{1,3}$/;
        return ipReg.test(printer.address);
      }

      if (printer.connectionType === "USB") {
        return this.localDevices.some(item => item.name === printer.address);
      }
      return false;
    },

    // 辅助方法：判断是否为特殊费用项（餐位费/打包费）
    isSpecialFeeItem(item) {
      // 可根据实际业务调整判断条件，比如通过名称/标识判断
      const specialNames = ["餐位费", "打包费"];
      // 条件：1. 无categoryId  2. 名称包含特殊费用关键词 或 标记了特殊标识
      return !item.categoryId && (item.isSpecialFee || specialNames.some(name => item.name?.includes(name)));
    },

    // 结算单
    async ORDER(data) {
      try {
        console.log('结算单===', data);
        // 筛选条件：状态启用 + 小票类型 + handoverSwitch=1 + 打印机可用 + 打印服务正常
        const validPrinters = this.deviceNoteList.filter(p => {
          return p.status
            && p.printType === "cash"
            && _.includes(p.printContentType.split(','), 'ORDER')
            && this.checkPrinterAvailable(p)
            && this.isPrintService;
        });

        if (validPrinters.length === 0) {
          console.log("结算单：无符合条件的可用打印机");
          return;
        }

        // 遍历符合条件的打印机打印
        validPrinters.forEach(printer => {
          const printData = {
            ...data,
            deviceId: printer.id,
            deviceName: printer.name,
            connectionType: printer.connectionType,
            printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
          };

          try {
            // 区分局域网和USB打印机
            if (printer.connectionType === "局域网") {
              this.addToPrintQueue({
                taskName: 'ORDER',
                data: JSON.stringify({
                  printerIp: printer.address,
                  orderData: printData
                })
              })
            } else {
              receiptPrint(printData);
            }
            console.log("✅ 打印结算单成功:", printer.address);
          } catch (error) {
            console.error("❌ 打印结算单失败:", printer.address, error);
          }
        });
      } catch (error) {
        console.log("结算单打印异常", error);
      }
    },
    // 客看单
    async GUEST_ORDER(data) {
      try {
        // 筛选条件：状态启用 + 小票类型 + handoverSwitch=1 + 打印机可用 + 打印服务正常
        const validPrinters = this.deviceNoteList.filter(p => {
          return p.status
            && p.printType === "cash"
            && _.includes(p.printContentType.split(','), 'GUEST_ORDER')
            && this.checkPrinterAvailable(p)
            && this.isPrintService;
        });

        if (validPrinters.length === 0) {
          console.log("结算单：无符合条件的可用打印机");
          return;
        }

        // 遍历符合条件的打印机打印
        validPrinters.forEach(printer => {
          const printData = {
            ...data,
            deviceId: printer.id,
            deviceName: printer.name,
            connectionType: printer.connectionType,
            printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
          };

          try {
            // 区分局域网和USB打印机
            if (printer.connectionType === "局域网") {
              this.addToPrintQueue({
                taskName: 'ORDER',
                data: JSON.stringify({
                  printerIp: printer.address,
                  orderData: printData
                })
              })
            } else {
              receiptPrint(printData);
            }
            console.log("✅ 打印客看单成功:", printer.address);
          } catch (error) {
            console.error("❌ 打印客看单失败:", printer.address, error);
          }
        });
      } catch (error) {
        console.log("客看单打印异常", error);
      }
    },
    // 预结算单
    async PRE_ORDER(data) {
      try {
        // 筛选条件：状态启用 + 小票类型 + handoverSwitch=1 + 打印机可用 + 打印服务正常
        const validPrinters = this.deviceNoteList.filter(p => {
          return p.status
            && p.printType === "cash"
            && _.includes(p.printContentType.split(','), 'PRE_ORDER')
            && this.checkPrinterAvailable(p)
            && this.isPrintService;
        });

        if (validPrinters.length === 0) {
          console.log("预结算单：无符合条件的可用打印机");
          return;
        }

        // 遍历符合条件的打印机打印
        validPrinters.forEach(printer => {
          const printData = {
            ...data,
            deviceId: printer.id,
            deviceName: printer.name,
            connectionType: printer.connectionType,
            printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
          };

          try {
            // 区分局域网和USB打印机
            if (printer.connectionType === "局域网") {
              this.addToPrintQueue({
                taskName: 'ORDER',
                data: JSON.stringify({
                  printerIp: printer.address,
                  orderData: printData
                })
              })
            } else {
              receiptPrint(printData);
            }
            console.log("✅ 打印预结算单成功:", printer.address);
          } catch (error) {
            console.error("❌ 打印预结算单失败:", printer.address, error);
          }
        });
      } catch (error) {
        console.log("预结算单打印异常", error);
      }
    },
    // 打印一菜一品厨房票
    ONLY_KITCHEN(data) {
      // 筛选条件：状态启用 + 小票类型 + handoverSwitch=1 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'ONLY_KITCHEN')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("打印一菜一品厨房票：无符合条件的可用打印机");
        return;
      }

      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {

        let cartsToPrint = data.carts; // 默认打印所有商品

        // 检查打印机是否配置了 categoryIds (假设 printer 对象上有此字段)
        if (printer.categoryIds) {
          // 将字符串 "617,616..." 分割成数组，并转为数字以便比较
          const allowedCategories = printer.categoryIds.split(',').map(id => Number(id));

          // 过滤商品：只保留 categoryId 在允许列表中的商品
          cartsToPrint = data.carts.filter(item => {
            return allowedCategories.includes(Number(item.categoryId));
          });
        }
        // --- 新增逻辑结束 ---

        // 可选：如果过滤后没有商品，可以选择不打印或打印空单，这里选择跳过
        if (cartsToPrint.length === 0) {
          console.log(`打印一菜一品厨房票：打印机 ${printer.name} 配置了分类，但当前订单无对应分类商品，跳过打印。`);
          return;
        }

        const printData = {
          ...data,
          carts: cartsToPrint, // 使用过滤后的商品列表覆盖原数据
          deviceId: printer.id,
          deviceName: printer.name,
          connectionType: printer.connectionType,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            this.addToPrintQueue({
              taskName: 'ONLY_KITCHEN',
              data: JSON.stringify({
                printerIp: printer.address,
                orderData: printData
              })
            })
          }
          // else {
          //   lodopPrintWork(printData);
          // }
          console.log("✅ 打印一菜一品厨房票成功:", printer.address);
        } catch (error) {
          console.error("❌ 打印一菜一品厨房票失败:", printer.address, error);
        }
      });
    },

    // 打印厨房整单
    ALL_KITCHEN(data) {
      // 筛选条件：状态启用 + 小票类型 + handoverSwitch=1 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'ALL_KITCHEN')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("打印厨房整单：无符合条件的可用打印机）");
        return;
      }

      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        // --- 新增逻辑开始：根据分类ID过滤商品 ---
        let cartsToPrint = data.carts; // 默认打印所有商品

        // 检查打印机是否配置了 categoryIds (假设 printer 对象上有此字段)
        if (printer.categoryIds) {
          // 将字符串 "617,616..." 分割成数组，并转为数字以便比较
          const allowedCategories = printer.categoryIds.split(',').map(id => Number(id));


          // 过滤商品：只保留 categoryId 在允许列表中的商品
          cartsToPrint = data.carts.filter(item => {
            return allowedCategories.includes(Number(item.categoryId));
          });
        }
        // --- 新增逻辑结束 ---

        // 可选：如果过滤后没有商品，可以选择不打印或打印空单，这里选择跳过
        if (cartsToPrint.length === 0) {
          console.log(`打印厨房整单：打印机 ${printer.name} 配置了分类，但当前订单无对应分类商品，跳过打印。`);
          return;
        }

        const printData = {
          ...data,
          carts: cartsToPrint, // 使用过滤后的商品列表覆盖原数据
          deviceId: printer.id,
          deviceName: printer.name,
          connectionType: printer.connectionType,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            this.addToPrintQueue({
              taskName: 'ALL_KITCHEN',
              data: JSON.stringify({
                printerIp: printer.address,
                orderData: printData
              })
            })
          }
          console.log("✅ 打印厨房整单成功:", printer.address);
        } catch (error) {
          console.error("❌ 打印厨房整单失败:", printer.address, error);
        }
      });
    },

    // ————————————————————————————————
    // 以下原有代码完全保留，仅优化格式和可读性
    // ————————————————————————————————
    checkLocalPrint(address) {
      const targetPrinter = this.localDevices.find(item => item.name === address);
      return !!targetPrinter?.name;
    },

    labelPrint(props) {
      const store = useUser();
      const validLabelPrinter = this.deviceLableList[0];

      if (!validLabelPrinter || !this.checkLocalPrint(validLabelPrinter.address)) {
        console.log("标签打印：未在本机查询到打印机");
        return;
      }

      const pids = validLabelPrinter.categoryList;
      let totalCount = 0;
      let currentCount = 0;

      // 先计算总打印数量
      props.carts.forEach(item => {
        if (pids.some(el => el === item.categoryId)) {
          totalCount += item.number;
        }
      });

      // 构建标签打印列表
      props.carts.forEach(item => {
        if (pids.some(el => el === item.categoryId)) {
          for (let i = 0; i < item.number; i++) {
            currentCount++;
            this.labelList.push({
              outNumber: props.outNumber,
              name: item.name,
              skuName: item.skuName,
              masterId: props.orderInfo.tableName,
              deviceName: validLabelPrinter.address,
              createdAt: dayjs(props.createdAt).format("YYYY-MM-DD HH:mm:ss"),
              isPrint: false,
              count: `${currentCount}/${totalCount}`,
              ticketLogo: store.shopInfo.ticketLogo,
            });
          }
        }
      });

      this.startLabelPrint();
    },

    startLabelPrint() {
      if (this.printTimer != null) return;

      this.printTimer = setInterval(() => {
        if (!this.labelList.length) {
          clearInterval(this.printTimer);
          this.printTimer = null;
          return;
        }

        const item = this.labelList[0];
        if (!item.isPrint) {
          ipcRenderer.send("printerTagSync", JSON.stringify(item));
          this.labelList[0].isPrint = true;
          this.labelList.splice(0, 1);
        }
      }, 2000);
    },

    // 打印交班小票（优化：1. 新增handoverSwitch=1才打印 2. 兼容局域网打印机）
    printWork(data) {
      // 筛选条件：状态启用 + 小票类型 + handoverSwitch=1 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'HANDOVER')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("交班小票：无符合条件的可用打印机（handoverSwitch≠1 或 打印机不可用）");
        return;
      }

      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          connectionType: printer.connectionType,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            ipcRenderer.send('printHandoverReceipt', JSON.stringify({
              printerIp: printer.address,
              handoverData: printData
            }));
          } else {
            lodopPrintWork(printData);
          }
          console.log("✅ 交班小票打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 交班小票打印失败:", printer.address, error);
        }
      });
    },

    printInvoice(data) {
      const validPrinter = this.deviceNoteList[0];
      if (!validPrinter || !this.checkLocalPrint(validPrinter.address)) {
        console.log("订单发票：未在本机查询到打印机");
        return;
      }

      data.deviceName = validPrinter.address;
      invoicePrint(data);
    },

    // 退款小票打印
    REFUND_ORDER(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'REFUND_ORDER')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("退单小票：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            // ipcRenderer.send('REFUND_ORDER', JSON.stringify({
            //   printerIp: printer.address,
            //   orderData: printData
            // }));
            this.addToPrintQueue({
              taskName: 'REFUND_ORDER',
              data: JSON.stringify({
                printerIp: printer.address,
                orderData: printData
              })
            })
          } else {
            refundPrint(printData);
          }
          console.log("✅ 退单小票打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 退单小票打印失败:", printer.address, error);
        }
      });
    },

    // 退菜小票打印
    RETURN_ORDER(data) {
      // 厨房退菜单
      this.REFUND_KITCHEN(data)

      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'RETURN_ORDER')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("退菜：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {

            const data = JSON.stringify({
              printerIp: printer.address,
              orderData: printData
            })

            // 用户退菜单
            this.addToPrintQueue({
              taskName: 'RETURN_ORDER',
              data: data
            })
          } else {
            refundPrint(printData);
          }
          console.log("✅ 退菜小票打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 退菜小票打印失败:", printer.address, error);
        }
      });
    },

    // 后厨-退菜单
    REFUND_KITCHEN(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'REFUND_KITCHEN')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("后厨-退菜单：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {

            const data = JSON.stringify({
              printerIp: printer.address,
              orderData: printData
            })

            // 厨房退菜单
            this.addToPrintQueue({
              taskName: 'REFUND_KITCHEN',
              data: data
            })
          } else {
            refundPrint(printData);
          }
          console.log("✅ 后厨-退菜单打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 后厨-退菜单打印失败:", printer.address, error);
        }
      });
    },

    // 商品销售数据
    PRODUCT_REPORT(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'PRODUCT_REPORT')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("商品销售数据：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            data.forEach(element => {
              this.addToPrintQueue({
                taskName: 'PRODUCT_REPORT',
                data: JSON.stringify({
                  printerIp: printer.address,
                  orderData: {
                    ...printData,
                    ...element
                  }
                })
              });
            });
          }
          //  else {
          //   refundPrint(printData);
          // }
          console.log("✅ 商品销售数据打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 商品销售数据打印失败:", printer.address, error);
        }
      });
    },

    // 经营日报
    DAY_REPORT(data) {
      console.log('print.DAY_REPORT', data);

      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'DAY_REPORT')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("经营日报：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            data.forEach(element => {
              this.addToPrintQueue({
                taskName: 'DAY_REPORT',
                data: JSON.stringify({
                  printerIp: printer.address,
                  orderData: {
                    ...printData,
                    ...element
                  }
                })
              });
            });
          }
          //  else {
          //   refundPrint(printData);
          // }
          console.log("✅ 经营日报打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 经营日报打印失败:", printer.address, error);
        }
      });
    },

    // 日结单
    DAY_ORDER(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'DAY_ORDER')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("日结单：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            data.forEach(element => {
              this.addToPrintQueue({
                taskName: 'DAY_ORDER',
                data: JSON.stringify({
                  printerIp: printer.address,
                  orderData: {
                    ...printData,
                    ...element
                  }
                })
              });
            });
          }
          //  else {
          //   refundPrint(printData);
          // }
          console.log("✅ 日结单打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 日结单打印失败:", printer.address, error);
        }
      });
    },

    // 储值单
    RECHARGE(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'RECHARGE')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("储值单：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            this.addToPrintQueue({
              taskName: 'RECHARGE',
              data: JSON.stringify({
                printerIp: printer.address,
                orderData: printData
              })
            });
          } else {
            refundPrint(printData);
          }
          console.log("✅ 储值单打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 储值单打印失败:", printer.address, error);
        }
      });
    },


    // 出入库单
    STOCK(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'STOCK')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("储值单：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            // ipcRenderer.send('STOCK', JSON.stringify({
            //   printerIp: printer.address,
            //   orderData: printData
            // }));
            this.addToPrintQueue({
              taskName: 'STOCK',
              data: JSON.stringify({
                printerIp: printer.address,
                orderData: printData
              })
            });
          } else {
            refundPrint(printData);
          }
          console.log("✅ 出入库单打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 出入库单打印失败:", printer.address, error);
        }
      });
    },


    // 盘点单
    STOCK_CHECK(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'STOCK_CHECK')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("盘点单：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            // ipcRenderer.send('STOCK_CHECK', JSON.stringify({
            //   printerIp: printer.address,
            //   orderData: printData
            // }));
            this.addToPrintQueue({
              taskName: 'STOCK_CHECK',
              data: JSON.stringify({
                printerIp: printer.address,
                orderData: printData
              })
            });
          } else {
            refundPrint(printData);
          }
          console.log("✅ 盘点单打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 盘点单打印失败:", printer.address, error);
        }
      });
    },

    // 排队取号
    CALL(data) {
      // 筛选条件：状态启用 + 小票类型 + 打印机可用 + 打印服务正常
      const validPrinters = this.deviceNoteList.filter(p => {
        return p.status
          && p.printType === "cash"
          && _.includes(p.printContentType.split(','), 'CALL')
          && this.checkPrinterAvailable(p)
          && this.isPrintService;
      });

      if (validPrinters.length === 0) {
        console.log("排队取号：无符合条件的可用打印机");
        return;
      }

      const store = useUser();
      // 遍历符合条件的打印机打印
      validPrinters.forEach(printer => {
        const printData = {
          ...data,
          deviceId: printer.id,
          deviceName: printer.name,
          printerName: printer.name,
          connectionType: printer.connectionType,
          shop_name: store.shopInfo.shopName,
          loginAccount: store.userInfo.name,
          printTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        };

        try {
          // 区分局域网和USB打印机
          if (printer.connectionType === "局域网") {
            // ipcRenderer.send('CALL', JSON.stringify({
            //   printerIp: printer.address,
            //   orderData: printData
            // }));
            this.addToPrintQueue({
              taskName: 'CALL',
              data: JSON.stringify({
                printerIp: printer.address,
                orderData: printData
              })
            });
          } else {
            refundPrint(printData);
          }
          console.log("✅ 排队取号打印成功:", printer.address);
        } catch (error) {
          console.error("❌ 排队取号打印失败:", printer.address, error);
        }
      });
    }
  },
});