import _ from "lodash";
import { defineStore } from "pinia";
import { useUser } from "@/store/user.js";
import { usePrint } from "@/store/print.js";
import useStorage from "@/utils/useStorage";
import ReconnectingWebSocket from "reconnecting-websocket";
import { useGoods } from "@/store/goods.js";
import { ElMessage } from "element-plus";
import { getOrderByIdAjax, commOrderPrintData } from "@/utils/index.js";
import { printData } from '@/api/print.js'

export const useSocket = defineStore("socket", {
  state: () => ({
    online: false, // 在线状态
    ws: null, // websocket实例
    heartbeatTimer: null, // 心跳计时器
    orderList: [],
    orderListTimer: null,
    log: false,
    isPrinting: false,
    // 新增：其他打印任务队列与状态锁
    printQueue: [],
    isProcessing: false
  }),
  actions: {
    // 计算订单中所有菜品的总价总和
    calcAllCartsTotalSum(cartObj) {
      // 初始化总和为0
      let totalSum = 0;
      // 遍历原始对象的所有键（0、1、2...）
      Object.keys(cartObj).forEach(key => {
        const carts = cartObj[key] || [];
        // 累加当前分类下的菜品总价（num × unitPrice）
        carts.forEach(item => {
          const num = Number(item.num) - Number(item.returnNum) || 0; // 防错：非数字转0
          const unitPrice = Number(item.unitPrice) || 0;
          totalSum += num * unitPrice;
        });
      });
      return totalSum; // 返回所有菜品的总价总和
    },
    // 1. 添加任务到队列
    addToPrintQueue(task) {
      this.printQueue.push(task);
      if (this.log) console.log('任务已加入打印队列，当前队列长度:', this.printQueue.length);
      this.processPrintQueue(); // 尝试启动处理
    },
    // 2. 处理队列（递归执行）
    async processPrintQueue() {
      const printStore = usePrint();

      // 如果正在处理或队列为空，直接返回
      if (this.isProcessing || this.printQueue.length === 0) return;

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

      try {
        if (this.log) console.log('开始执行打印任务:', currentTask);

        const isOrderPrint = ['GUEST_ORDER', 'PRE_ORDER', 'ORDER', 'RETURN_ORDER', 'REFUND_ORDER', 'ALL_KITCHEN', 'ONLY_KITCHEN', 'REFUND_KITCHEN',]

        console.log('currentTask===', currentTask);

        if (_.includes(isOrderPrint, currentTask.printType)) {
          // 订单相关打印，调用对应接口获取数据
          const data = await getOrderByIdAjax(currentTask.orderId);

          console.log('订单相关打印，调用对应接口获取数据===', data);

          switch (currentTask.printType) {
            case 'ORDER':
              // 打印订单小票
              printStore.ORDER(commOrderPrintData(data));
              // 打印标签小票
              printStore.labelPrint(commOrderPrintData(data));
              break;
            case 'PRE_ORDER':
              // 打印预订单小票
              data.originAmount = this.calcAllCartsTotalSum(data.detailMap)

              if (data.seatAmount > 0 && data.dineMode == 'dine-in') {
                data.originAmount += data.seatAmount
              }
              let packFee = 0

              data.cartList.forEach(item => {
                if (item.packNumber > 0 && (item.num - item.returnNum) >= item.packNumber) {
                  packFee += (item.num - item.returnNum) * item.packAmount
                }
              })

              if (packFee > 0) {
                data.originAmount += packFee
                data.packFee = packFee
              }

              printStore.PRE_ORDER(commOrderPrintData({ ...data, isBefore: true }));
              break;
            case 'GUEST_ORDER':
              // 打印客看单
              data.detailMap = _.at(data.detailMap, data.placeNum);

              let amout = 0
              data.detailMap.flat().forEach(item => {
                amout += item.num * item.unitPrice
              });

              data.originAmount = amout

              if (data.placeNum == 1 && data.dineMode == 'dine-in') {
                data.originAmount += data.seatAmount
              }

              if (data.packFee > 0) {
                data.originAmount += data.packFee
              }

              printStore.GUEST_ORDER(commOrderPrintData({ ...data, isGuest: true, isBefore: false }));
              break;
            case 'ALL_KITCHEN':
              // 打印整单厨房票
              if (data.payMode == 'after-pay') {
                // 后付费订单，只打印当前下单商品的整单厨房票
                data.detailMap = _.at(data.detailMap, data.placeNum);
                printStore.ALL_KITCHEN(commOrderPrintData({ ...data, isGuest: true, isNotPrint: true }));
              } else {
                printStore.ALL_KITCHEN(commOrderPrintData({ ...data, isNotPrint: true }));
              }
              // console.log('打印整单厨房票.data', data);
              break;
            case 'ONLY_KITCHEN':
              // 打印一菜一品厨房票
              if (data.payMode == 'after-pay') {
                // 后付费订单，只打印当前下单的一菜一品厨房票
                data.detailMap = _.at(data.detailMap, data.placeNum);
                const orderInfo = commOrderPrintData({ ...data, isGuest: true, isNotPrint: true });
                orderInfo.carts.forEach(item => {
                  const ONLY_KITCHEN_DATA = {
                    ...orderInfo,
                    carts: [item]
                  }
                  printStore.ONLY_KITCHEN(ONLY_KITCHEN_DATA);
                })
              } else {
                data.cartList.forEach(item => {
                  const ONLY_KITCHEN_DATA = {
                    ...data.orderData,
                    cartList: [item],
                    isNotPrint: true
                  }
                  printStore.ONLY_KITCHEN(commOrderPrintData(ONLY_KITCHEN_DATA));
                })
              }
              break;
            case 'RETURN_ORDER':
              // 打印退菜小票
              const socketData = JSON.parse(currentTask.data);
              // console.log('打印退菜小票.socketData', socketData);

              let cartList = _.compact(
                _.map(data.cartList, (cartItem) => {
                  // 找到对应项
                  const taskItem = _.find(socketData, (t) => cartItem.id == t.id);

                  // 找到就返回带 num 的对象
                  if (taskItem) {
                    return {
                      ...cartItem,
                      num: taskItem.num,
                      returnNum: 0,
                      payAmount: taskItem.num * cartItem.price
                    };
                  }

                  // 没找到返回 undefined，会被 _.compact 过滤掉
                  return null;
                })
              );

              data.cartList = cartList;

              // console.log('打印退菜小票.data', data);

              printStore.RETURN_ORDER(commOrderPrintData({ ...data, isRefundDish: true }));
              break;
            case 'REFUND_ORDER':
              // 打印退单小票
              {
                const socketData = JSON.parse(currentTask.data);
                // console.log('打印退菜小票.socketData', socketData);

                let cartList = _.compact(
                  _.map(data.cartList, (cartItem) => {
                    // 找到对应项
                    const taskItem = _.find(socketData, (t) => cartItem.id == t.id);

                    // 找到就返回带 num 的对象
                    if (taskItem) {
                      return {
                        ...cartItem,
                        num: taskItem.num,
                        returnNum: 0,
                        payAmount: taskItem.num * cartItem.price
                      };
                    }

                    // 没找到返回 undefined，会被 _.compact 过滤掉
                    return null;
                  })
                );

                data.cartList = cartList;
                data.payAmount = currentTask.amount;
                // console.log('打印退单小票.data', data);

                printStore.REFUND_ORDER(commOrderPrintData({ ...data, isRefundDish: true }));
              }
              break;
            default:
              break;
          }
        } else {
          // 执行打印逻辑（参考你注释中的代码）
          const res = await printData({
            shopId: currentTask.shopId,
            dataId: currentTask.dataId,
            type: currentTask.printType
          });

          console.log('printData.res===', res);

          if (printStore[currentTask.printType]) {
            printStore[currentTask.printType](JSON.parse(res.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();
      }
    },
    // 关闭ws
    close() {
      if (this.log) console.log("关闭ws");
      this.online = false;
      this.ws.close(1000);
      this.ws = null;
      this.clearHeartBeat();
    },
    wsReconnect: _.throttle(
      function () {
        if (this.ws.readyState == ReconnectingWebSocket.OPEN) return;
        this.ws.reconnect();
        // console.log("11111");
      },
      2000,
      { leading: true, trailing: false }
    ),
    cartInit() {
      const store = useUser();
      const goodsStore = useGoods();

      this.ws.send(
        JSON.stringify({
          type: "cashier",
          account: `cashier_${store.shopInfo.id}`,
          operate_type: "init",
          shop_id: store.shopInfo.id,
          table_code:
            goodsStore.tableInfo.tableCode || useStorage.get("tableCode"),
        })
      );
    },
    // 初始化
    init(wsUrl = import.meta.env.VITE_API_WSS) {
      return new Promise((resolve, reject) => {
        const store = useUser();
        const printStore = usePrint();
        const goodsStore = useGoods();

        if (!store.shopInfo.id) return;

        printStore.init();

        if (this.ws == null) {
          if (this.log) console.log("创建新的ws连接");

          const protocols = []; // 可选的子协议数组
          const options = {
            // 自动重新连接的选项（可选）
            connectionTimeout: 1000,
            maxRetries: 100,
          };
          this.ws = new ReconnectingWebSocket(wsUrl, protocols, options);
        } else {
          if (this.log) console.log("重新连接ws");
          this.wsReconnect();
        }

        this.ws.addEventListener("open", (event) => {
          if (this.log) console.log("wss连接成功");
          this.online = true;
          // 清除心跳
          this.clearHeartBeat();
          if (this.log) console.log(this);
          this.cartInit();
          this.startheartbeat();

          resolve()
        });

        this.ws.addEventListener("message", async (e) => {
          let data = JSON.parse(e.data);
          if (data.operate_type == "init") {
            // console.log("接收消息", data);
            if (!goodsStore.tableInfo.tableCode) {
              useStorage.set("tableCode", data.table_code);
            }
            goodsStore.getCartList(data.data);
          }

          this.ws.send(
            JSON.stringify({
              type: "receipt",
              msg_id: data.msg_id,
            })
          );

          if (data.data_type == "cart") {
            if (data.status == 1) {
              // 返回成功状态
              switch (data.operate_type) {
                case "add":
                  // 添加购物车商品
                  {
                    // console.log('socket终极操作数据.add===', data.data);
                    const cartItem = goodsStore.cartList.find(item => item.id == data.data.id) || { number: 0 }
                    // console.log('socket终极操作数据.cartItem===', cartItem);
                    let arr = []
                    goodsStore.orderList.forEach(item => {
                      arr.push(...item.goods)
                    })
                    const isExist = _.some(arr, item => Number(item.productId) === data.data.product_id)

                    if (data.data.number == 1 && data.data.number > cartItem.number) {
                      if (isExist) {
                        ElMessage({
                          type: 'warning',
                          message: '该商品已下单过，请确认是否重复',
                          duration: 4000
                        })
                      }
                    }
                    goodsStore.successAddCart(data.data);
                  }
                  break;
                case "edit":
                  {
                    // 编辑购物车商品
                    // console.log('socket终极操作数据.edit===', data.data);

                    const cartItem = goodsStore.cartList.find(item => item.id == data.data.id)

                    // console.log('socket终极操作数据.cartItem===', cartItem);

                    let arr = []
                    goodsStore.orderList.forEach(item => {
                      arr.push(...item.goods)
                    })
                    const isExist = _.some(arr, item => Number(item.productId) === data.data.product_id)

                    if (data.data.number == 2 && data.data.number > cartItem.number) {
                      if (isExist) {
                        ElMessage({
                          type: 'warning',
                          message: '该商品已下单过，请确认是否重复',
                          duration: 4000
                        })
                      } else {
                        ElMessage({
                          type: 'warning',
                          message: '购物车已有该商品，请确认是否重复',
                          duration: 4000
                        })
                      }
                    }

                    goodsStore.successEditCart(data.data);
                  }
                  break;
                case "del":
                  // 删除购物车商品
                  if (data.type && data.type == "bc") {
                    goodsStore.successDeleteCartItem(data.data);
                  } else {
                    goodsStore.successDeleteCartItem();
                  }
                  break;
                case "cleanup":
                  // 清空购物车
                  if (
                    data.data.table_code == goodsStore.orderListInfo.tableCode &&
                    !data.type
                  )
                    return;
                  goodsStore.successClearCart();
                  break;
                case "batch":
                  // 整单打包
                  this.cartInit();
                  break;
                case "rottable":
                  // 转桌
                  useStorage.set("tableCode", data.data.new_table_code);
                  goodsStore.successClearCart();
                  goodsStore.historyOrderAjax(data.data.new_table_code);
                  this.cartInit();
                  break;
                case "clearOrder":
                  // 清空订单或删除订单
                  goodsStore.historyOrderAjax(data.data.table_code);
                  break;
                case "bulk_edit":
                  // 限时折扣更新
                  // goodsStore.updateGoodsList();
                  break;
                default:
                  break;
              }
            } else {
              if (data.type == "no_suit_num") {
                let product = goodsStore.cartList[goodsStore.cartActiveIndex];
                ElMessage.error(
                  `${product.product_name}库存不足，已删除，请选择其他商品`
                );
                goodsStore.operateCart(product, "del");
              } else {
                ElMessage.error(data.msg || "操作失败");
              }
            }
          } else if (data.data_type == "order") {
            this.addToPrintQueue(JSON.parse(data.data));
            return;

            goodsStore.successClearCart();
            goodsStore.historyOrderAjax(data.data.table_code);
            this.cartInit();

            this.addToPrintQueue(data.data);

            // 收到订单消息，打印订单小票
            let orderInfo = data.data.split("_");
            let orderId = orderInfo[0]; // 订单ID
            let orderModel = orderInfo[1]; // 订单类型
            let orderStatus = orderInfo[2]; // 订单ID_先付后付(1先付0后付)_订单状态 0未完成 1完成_第几次下单 
            let placeNum = orderInfo[3]; // 下单次数

            let printList = useStorage.get("printList") || [];

            if (goodsStore.orderListInfo.tableCode) {
              goodsStore.historyOrderAjax(goodsStore.orderListInfo.tableCode);
            }

            // 防止重复打印
            if (!printList.some((el) => el == orderId) && orderStatus == 1) {
              printList.push(orderId);
              useStorage.set("printList", _.uniq(printList));

              this.orderList.push(orderId);
              this.startPrintInterval();
            }

            // 防止重复打印客看单
            if (orderStatus == 0) {
              getOrderByIdAjax(orderId).then(res => {
                let originOrderInfo = res
                originOrderInfo.detailMap = _.at(originOrderInfo.detailMap, placeNum);

                console.log('originOrderInfo', originOrderInfo);

                let amout = 0
                originOrderInfo.detailMap.flat().forEach(item => {
                  amout += item.num * item.unitPrice
                });

                originOrderInfo.originAmount = amout

                if (originOrderInfo.placeNum == 1 && originOrderInfo.dineMode == 'dine-in') {
                  originOrderInfo.originAmount += originOrderInfo.seatAmount
                }

                if (originOrderInfo.packFee > 0) {
                  originOrderInfo.originAmount += originOrderInfo.packFee
                }

                printStore.pushReceiptData(commOrderPrintData({ ...originOrderInfo, isGuest: true, isBefore: false }));
              }).catch(err => {
                console.log(err);
              })
            }
          } else if (data.data_type == "product_update") {
            // 商品更新
            this.updateGoods();
          } else if (data.data_type == 'other_print') {
            // 其他打印集合 data.data = {"shopId":148,"dataId":27,"printType":"STOCK"}
            // 用const res = printData({ shopId: shopId, dataId: dataId, type: printType })
            // 获取到数据后调用goodsStore[data.data.printType](JSON.parse(res.data))
            console.log('other_print===', data.data);
            this.addToPrintQueue(data.data);
          }
        });

        this.ws.addEventListener("error", () => {
          if (this.log) console.log("WebSocket连接发生错误");
          this.online = false;
          this.clearHeartBeat();
          reject('WebSocket连接发生错误')
        });

        this.ws.addEventListener("error", (e) => {
          if (this.log) console.log("ws关闭了", e);
          this.online = false;
          this.clearHeartBeat();
        });
      })
    },
    updateGoods: _.throttle(function () {
      const goodsStore = useGoods();
      goodsStore.updateGoodsList();
    }, 1000),
    // 启动心跳连接
    startheartbeat() {
      this.heartbeatTimer = setInterval(() => {
        if (this.log) console.log("发送心跳");
        this.ws.send(JSON.stringify({ type: "ping_interval", set: "cashier" }));
      }, 10000);
    },
    // 清除心跳
    clearHeartBeat() {
      // 清除心跳
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    },
    // 打印队列开始执行
    startPrintInterval() {
      if (this.isPrinting) return; // 如果正在打印，直接返回
      this.isPrinting = true; // 标记为正在打印
      let printTime = 2000; // 定时器
      const printStore = usePrint();
      const printNextOrder = async () => {
        try {
          if (!this.orderList.length) {
            this.isPrinting = false; // 订单处理完，标记为不在打印
            return;
          }
          const orderInfo = await getOrderByIdAjax(this.orderList[0]);
          if (orderInfo.status == "done") {
            // 打印订单小票
            printStore.pushReceiptData(commOrderPrintData(orderInfo));
            // 打印标签小票
            printStore.labelPrint(commOrderPrintData(orderInfo));
          }
          this.orderList.splice(0, 1);
          // 递归调用打印下一个订单
          setTimeout(printNextOrder, printTime);
        } catch (error) {
          console.log(error);
          // 发生错误时继续尝试下一个订单
          // this.orderList.splice(0, 1);
          setTimeout(printNextOrder, printTime);
        }
      };
      // 开始打印第一个订单
      printNextOrder();
    },
  },
});
