import _ from "lodash";
import dayjs from "dayjs";
import { defineStore } from "pinia";
import { ref, computed, nextTick } from "vue";
import { productPage, categoryList } from "@/api/product_new.js";
import { historyOrder, cancelOrder, rmPlaceOrder } from "@/api/order.js";
import { getLimitTimeDiscount, getDiscountActivity, getDiscountByUserId } from '@/api/market'
import { useUser } from "@/store/user.js";
import { useSocket } from "@/store/socket.js";
import useStorage from "@/utils/useStorage.js";
import { formatDecimal } from "@/utils/index.js";
import { shopUserDetail } from "@/api/account.js";
import { ElMessage } from "element-plus";

import {
  OrderPriceCalculator, limitUtils,
  BaseCartItem,
  BackendCoupon,
  ActivityConfig,
  OrderExtraConfig, MerchantReductionConfig, MerchantReductionType,
  GoodsType, FullReductionActivity
} from "ysk-utils";

const initialCostSummary = {
  finalPayAmount: 0,
  goodsRealAmount: 0,
  seatFee: 0,
  packFee: 0,
  totalDiscountAmount: 0,
  productCouponDeduction: 0,
  fullCouponDeduction: 0,
  pointDeductionAmount: 0,
  pointUsed: 0,
};

// 商品store + 购物车store
export const useGoods = defineStore("goods", {
  state: () => ({
    remark: "", // 订单备注 
    showVipPrice: 0,
    allSelected: 0, // 是否整单打包
    vipUserInfo: {}, // 会员信息
    tableInfo: {
      name: "",
      num: "",
      tableCode: "",
    }, // 台桌信息
    cartActiveIndex: 0, // 购物车激活索引,
    isCartInit: false,
    payType: "cart", // 结算类型，cart 购物车结算 table 桌台结算 order 订单结算,
    cartList: [], // 购物车列表
    // 购物车信息,
    cartInfo: {
      costSummary: {
        ...initialCostSummary
      }
    },
    goodsName: "", // 商品名称,
    categoryIndex: useStorage.get("categoryIndex") || 0, // 商品分类索引,
    categoryList: [], // 商品分类列表
    originCategoryList: [], // 原始商品分类列表,
    goodsListLoading: false, // 商品列表加载状态
    goodsList: [], // 商品列表
    originGoodsList: [], // 原始商品列表
    orderList: [], // 订单列表
    orderListInfo: "", // 历史订单信息
    cartType: "cart", // cart order
    cartOrderItem: "",
    pendingList: useStorage.get("pendingList") || [],
    fullReductionActivities: '', // 满减活动配置信息
    limitDiscountRes: null, // 限时折扣
    newUserDiscount: null // 新客立减
  }),
  actions: {
    // 选择会员
    async selectUser(user) {
      const store = useUser()
      this.vipUserInfo = { ...user, isMemberPrice: store.shopInfo.isMemberPrice }

      if (store.shopInfo.isMemberPrice && this.vipUserInfo.isVip) {
        this.showVipPrice = 1
      }

      await this.updateGoodsList()

      this.calcCartInfo()
    },
    // 清除会员信息
    async clearVipUserInfo() {
      // console.log('清除会员信息');

      this.vipUserInfo = {};
      this.showVipPrice = 0;

      await this.updateGoodsList()

      this.calcCartInfo()
    },
    // 清除历史订单
    async clearHistoryOrder() {
      try {
        await cancelOrder({
          shopId: this.orderListInfo.shopId,
          orderId: this.orderListInfo.id,
        });
      } catch (error) {
        console.log("清除历史订单失败", error);
      }
      this.operateCart(
        { table_code: this.orderListInfo.tableCode },
        "clearOrder"
      );
      this.historyOrderAjax(this.orderListInfo.tableCode);
    },
    // 删除某一次订单
    async deleteHistoryOrder(placeNum = null) {
      try {
        if (!placeNum) return;
        await rmPlaceOrder({
          shopId: this.orderListInfo.shopId,
          orderId: this.orderListInfo.id,
          placeNum: placeNum,
        });
      } catch (error) {
        console.log("删除某一次订单", error);
      }
      this.operateCart(
        { table_code: this.orderListInfo.tableCode },
        "clearOrder"
      );
      this.historyOrderAjax(this.orderListInfo.tableCode);
    },
    // 清除所有商品信息
    clearAllGoods() {
      this.categoryIndex = 0;
      this.categoryList = [];
      this.originCategoryList = [];
      this.goodsListLoading = false;
      this.goodsList = [];
      this.originGoodsList = [];
      this.orderList = [];
      this.orderListInfo = "";

      useStorage.del("printList");
      useStorage.del("updateFlag");
      useStorage.del("tableCode");
    },
    // 恢复挂单
    async recoverPending(item) {
      let socket = useSocket();

      if (this.cartList.length || this.orderList.length) {
        this.pendingCart();
      }

      if (item.orderId) {
        await this.historyOrderAjax(item.tableCode);
      }

      let pendingList = useStorage.get("pendingList");
      let index = pendingList.findIndex(
        (val) => val.tableCode == item.tableCode
      );

      pendingList.splice(index, 1);
      useStorage.set("pendingList", pendingList);
      this.pendingList = useStorage.get("pendingList");
      useStorage.set("tableCode", item.tableCode);
      socket.cartInit();
    },
    // 开始挂单
    pendingCart() {
      let cart = this.cartList;
      let order = this.orderList;

      if (cart.length || order.length) {
        let pendingList = useStorage.get("pendingList") || [];
        pendingList.push({
          tableCode: cart[0].table_code || this.orderListInfo.tableCode,
          productName: [
            ...cart.map((item) => item.product_name),
            ...order
              .map((item) => item.goods)
              .flat()
              .map((item) => item.product_name),
          ].join("、"),
          orderId: order.length && this.orderListInfo.id,
          totalAmount: this.cartInfo.totalAmount,
          pendingAt: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        });

        useStorage.set("pendingList", pendingList);
        this.pendingList = useStorage.get("pendingList");
        useStorage.del("tableCode");
      }
    },
    // 选中订单中的商品
    selectOrderItem(index = null, i) {
      this.orderList.map((item) => {
        item.goods.map((val) => {
          val.active = false;
        });
      });

      if (index !== null) {
        this.selectCartItemHandle();

        this.cartType = "order";
        if (this.orderList.length) {
          if (!this.orderList[index].goods[i].active) {
            this.orderList[index].goods[i].active = true;
          } else {
            this.orderList[index].goods[i].active = false;
          }
          this.cartOrderItem = this.orderList[index].goods[i];
        }
      }
    },
    // 选中购物车商品
    selectCartItemHandle(index = null) {
      this.cartList.map((val) => {
        val.active = false;
      });
      if (index !== null) {
        this.selectOrderItem();

        this.cartType = "cart";
        this.cartActiveIndex = index;

        if (this.cartList.length) {
          this.cartList[index].active = true;
        }
      }
    },
    // 手动选择台桌
    selectTable(tableInfo = {}) {
      const socket = useSocket();

      this.tableInfo = tableInfo;
      this.isCartInit = false;
      // 选择台桌后将购物车初始化
      socket.cartInit();
      if (this.tableInfo.tableCode) {
        this.historyOrderAjax(this.tableInfo.tableCode);
      } else {
        this.orderList = [];
        this.orderListInfo = "";
      }
    },
    // 获取订单列表
    async historyOrderAjax(tableCode = "", orderId = "") {
      try {
        if (!tableCode && !orderId) return;

        const store = useUser();
        const res = await historyOrder({
          tableCode: tableCode,
          orderId: orderId,
        });

        if (res) {
          if (res.userId) {
            const userInfo = await shopUserDetail({
              userId: res.userId,
            });
            if (userInfo.id) {
              this.vipUserInfo = userInfo;

              if (userInfo.isVip && store.shopInfo.isMemberPrice) {
                this.showVipPrice = 1;
              }

              await this.updateGoodsList()
            }
          }

          this.orderListInfo = res;

          let arr = [];
          for (let key in res.detailMap) {
            arr.push({
              orderNum: key,
              goods: res.detailMap[key].map((item) => {
                return this.comleteOrderInfo(item);
              }),
            });
          }
          this.orderList = arr;
          // console.log("this.orderList===2222", this.orderList);

          if (this.orderListInfo.tableCode && this.orderListInfo.tableName) {
            this.tableInfo = {
              tableCode: this.orderListInfo.tableCode,
              name: this.orderListInfo.tableName,
              num: this.orderListInfo.seatNum
            }
          }
        } else {
          this.orderList = [];
          this.orderListInfo = "";
        }
        this.calcCartInfo();
      } catch (error) {
        console.log(error);
      }
    },
    // 初始化商品
    async initGoods() {
      await this.getCategoryList();
      await this.getGoodsList();

      let tableCode = useStorage.get("tableCode");
      if (tableCode) {
        await this.historyOrderAjax(tableCode);
      }
    },
    // 切换商品分类
    async setCategoryIndex(index) {
      this.categoryIndex = index;
      useStorage.set("categoryIndex", index);

      if (index == 0) {
        await this.getGoodsList();
        this.goodsList = _.chunk(
          this.originGoodsList.filter((item) => item.isSale),
          12
        );
      } else if (this.categoryList[index].id == "off_sale") {
        // 筛选已下架的商品
        this.goodsList = _.chunk(
          this.originGoodsList.filter((item) => item.isSale == 0),
          12
        );
      } else {
        // 除了全部，其他只做本地筛选
        this.goodsList = _.chunk(
          this.originGoodsList.filter(
            (item) =>
              item.categoryId == this.categoryList[this.categoryIndex].id &&
              item.isSale
          ),
          12
        );
      }

      this.updateGoodsNumber();
    },
    filterCategoryGoods(id) { },
    // 根据商品名字模糊查询商品列表
    filterNameGoods(name) {
      this.goodsList = _.chunk(
        this.originGoodsList.filter((item) => item.name.includes(name)),
        12
      );

      this.updateGoodsNumber();
    },
    // 获取商品分类列表
    async getCategoryList() {
      try {
        const res = await categoryList();
        this.originCategoryList = [...res];
        this.categoryList = res;
        this.categoryList.unshift({
          name: "全部",
          id: "",
        });
        this.categoryList.push({
          name: "已下架",
          id: "off_sale",
        });
      } catch (error) {
        console.log(error);
      }
    },
    // 获取商品列表/更新商品列表
    async getGoodsList() {
      try {
        const socket = useSocket();
        const store = useUser()

        this.goodsListLoading = true;
        const res = await productPage({
          categoryId:
            this.categoryList[this.categoryIndex].id == "off_sale"
              ? ""
              : this.categoryList[this.categoryIndex].id,
          name: this.goodsName,
        });

        this.originGoodsList = await productPage();

        // 获取限时折扣
        this.limitDiscountRes = await getLimitTimeDiscount({ shopId: store.shopInfo.id })

        // 获取满减活动
        this.fullReductionActivities = await getDiscountActivity({ shopId: store.shopInfo.id })

        // 新客立减
        if (this.vipUserInfo.id) {
          this.newUserDiscount = await getDiscountByUserId({
            shopId: store.shopInfo.id,
            shopUserId: this.vipUserInfo.id,
            orderId: this.orderListInfo.id || ''
          })
        }

        if (socket.ws == null) {
          await socket.init();
          if (this.limitDiscountRes !== null) {
            this.operateCart({ data: this.limitDiscountRes }, 'time_discount_save')
          }
        }

        const chunkNum = 12

        // 将数组分割成每页12个
        this.goodsList = _.chunk(res, chunkNum);

        let index = useStorage.get("categoryIndex") || 0;
        if (index == 0) {
          this.goodsList = _.chunk(
            this.originGoodsList.filter((item) => item.isSale),
            chunkNum
          );
        } else if (this.categoryList[index].id == "off_sale") {
          // 筛选已下架的商品
          this.goodsList = _.chunk(
            this.originGoodsList.filter((item) => item.isSale == 0),
            chunkNum
          );
        } else {
          // 除了全部，其他只做本地筛选
          this.goodsList = _.chunk(
            this.originGoodsList.filter(
              (item) =>
                item.categoryId == this.categoryList[this.categoryIndex].id &&
                item.isSale
            ),
            chunkNum
          );
        }

        this.goodsList.forEach(val => {
          val.forEach((item, index) => {
            // console.log('this.goodsList.index', index);
            // console.log('this.goodsList.item', item);
            // console.log('this.goodsList.limitDiscountRes', this.limitDiscountRes);
            // console.log('this.goodsList.store.shopInfo', store.shopInfo);
            // console.log('this.goodsList.this.vipUserInfo', this.vipUserInfo);
            // console.log('this.goodsList.this.vipUserInfo', JSON.stringify(this.vipUserInfo));
            // console.log('this.goodsList.this.canUseLimitTimeDiscount', limitUtils.canUseLimitTimeDiscount(item,
            //   this.limitDiscountRes,
            //   store.shopInfo,
            //   this.vipUserInfo, 'id'));


            item.showMore = false;
            item.orderCount = 0;
            item.memberPrice = item.lowMemberPrice
            item.salePrice = item.lowPrice
            item.time_dicount_mode = this.limitDiscountRes
            item.is_time_discount = limitUtils.canUseLimitTimeDiscount(item,
              this.limitDiscountRes,
              store.shopInfo,
              this.vipUserInfo, 'id') ? 1 : 0
            item.time_discount_price = limitUtils.returnPrice({
              goods: { ...item },
              shopInfo: store.shopInfo,
              limitTimeDiscountRes: this.limitDiscountRes,
              shopUserInfo: this.vipUserInfo,
              idKey: 'id'
            })
          })
        })
        // console.log('this.goodsList===', this.goodsList);
      } catch (error) {
        console.log(error);
      }
      setTimeout(() => {
        this.goodsListLoading = false;
      }, 500);
    },
    // 获取购物车列表，数据必须由长链接返回
    async getCartList(arr) {
      try {
        const store = useUser();

        let numCount = 0;
        let packCount = 0;

        arr.map((val, index) => {
          if (val.product_type == "weight") {
            numCount++;
          } else {
            numCount += +val.number;
          }
          packCount += +val.pack_number;
          val = this.completeGoodsInfo(val);
          val.active = false;
          if (!this.isCartInit && index == 0) {
            val.active = true;
          }
        });

        if (
          store.shopInfo &&
          store.shopInfo.eatModel.includes("take-out") &&
          packCount > 0 &&
          packCount == numCount
        ) {
          this.allSelected = 1;
        } else {
          this.allSelected = 0;
        }

        this.cartList = arr;
        this.isCartInit = true;

        // if (
        //   this.tableInfo.tableCode &&
        //   store.shopInfo.registerType == "after"
        // ) {
        //   await this.historyOrderAjax(this.tableInfo.tableCode);
        // }
        this.calcCartInfo();
        // console.log("getCartList.cartList===", this.cartList);
      } catch (error) {
        console.log("getCartList===", error);
      }
    },
    // 更新商品列表的角标
    updateGoodsNumber() {
      let arr = [
        ...this.cartList,
        ...this.orderList
          .map((item) => item.goods)
          .flat()
          .map((item) => {
            item.discount_sale_amount = item.discountSaleAmount;
            item.discount_sale_note = item.discountSaleNote;
            item.is_print = item.isPrint;
            item.is_gift = item.isGift;
            item.is_temporary = item.isTemporary;
            return item;
          }),
      ];

      this.goodsList.map((item) => {
        item.map((val) => {
          val.number = 0;
          arr.map((cart) => {
            if (val.id == cart.product_id) {
              val.number += +cart.number - (cart.returnNum || 0);
            }
          });
        });
      });

      // console.log("updateGoodsNumber===", this.goodsList);
    },
    // 添加商品到购物车
    addCart(params) {
      console.log("添加商品到购物车===", params);
      const store = useUser()

      let tableCode = "";
      if (this.tableInfo.tableCode) {
        tableCode = this.tableInfo.tableCode;
      } else {
        if (this.cartList.length) {
          tableCode = this.cartList[0].table_code;
        } else {
          tableCode = useStorage.get("tableCode");
        }
      }

      let pack_number = 0;
      if (params.type == "weight") {
        pack_number = 1;
      } else {
        pack_number = params.number;
      }
      const sendData = {
        table_code: tableCode,
        product_id: params.productId || "",
        sku_id: params.id || "",
        number: params.number || 1,
        pack_number: this.allSelected ? pack_number : 0,
        is_gift: params.is_gift || 0,
        is_temporary: params.is_temporary || 0,
        discount_sale_amount: params.discount_sale_amount || 0,
        discount_sale_note: params.discount_sale_note || 0,
        is_print: 1,
        is_wait_call: 0,
        remark: params.remark || "",
        product_name: params.product_name || "",
        sku_name: params.sku_name || "",
        pro_group_info: params.pro_group_info || [],
        goods_type: params.goods_type || "",
        product_type: params.type,
        is_time_discount: limitUtils.canUseLimitTimeDiscount(params, this.limitDiscountRes, store.shopInfo, this.vipUserInfo, 'productId') ? 1 : 0
      };

      console.log('sendData', sendData);
      this.operateCart(sendData);
    },
    // 购物添加成功
    successAddCart(goodsInfoItem) {
      if (this.cartList.length) {
        for (let i = 0; i < this.cartList.length; i++) {
          if (
            this.cartList[i].product_id == goodsInfoItem.product_id &&
            this.cartList[i].id == goodsInfoItem.id
          ) {
            this.cartList[i] = this.completeGoodsInfo({
              active: this.cartList[i].active,
              ...goodsInfoItem,
            });

            this.calcCartInfo();
            return;
          }
        }
        this.cartList.push(this.completeGoodsInfo({ ...goodsInfoItem }));
      } else {
        this.cartList.push(this.completeGoodsInfo({ ...goodsInfoItem }));
      }

      // 给第一个商品添加选中效果
      if (this.cartList.length == 1) {
        this.selectCartItemHandle(0);
      }

      this.calcCartInfo();
    },
    // 成功编辑购物车商品
    successEditCart(data) {
      this.successAddCart(data);
    },
    // 补全商品信息
    completeGoodsInfo(item) {
      const store = useUser()

      // console.log('补全商品信息===', item);
      if (item.is_temporary) {
        item.salePrice = item.discount_sale_amount
        return item;
      } else {
        let flag = false;
        this.originGoodsList.map((val) => {
          if (val.id == item.product_id) {
            flag = true;
            let sku = val.skuList.find((sku) => sku.id == item.sku_id || sku.id == item.skuId);

            // console.log('sku===', sku);


            let group_text = "";
            if (val.type == "package" && item.pro_group_info) {
              group_text = JSON.parse(item.pro_group_info)
                .flat()
                .map((item) => item.goods)
                .flat()
                .map((item) => item.proName)
                .join("、");
            }

            item.lowPrice = sku.salePrice;
            item.number = +item.number
            item.num = +item.number
            item.salePrice = sku.salePrice;
            item.memberPrice = sku.memberPrice;
            item.product_name = val.name;
            item.sku_name = sku && sku.specInfo;
            item.suitNum = sku.suitNum;
            item.group_type = val.groupType;
            item.goods_type = val.type;
            item.skuList = val.skuList;
            item.selectSpecInfo = val.selectSpecInfo;
            item.group_text = group_text;
            item.packFee = val.packFee;
            item.unitName = val.unitName;
            item.stockNumber = val.stockNumber;
            item.isStock = val.isStock;
            item.is_time_discount = limitUtils.canUseLimitTimeDiscount(val, this.limitDiscountRes, store.shopInfo, this.vipUserInfo) ? 1 : 0
            item.time_discount_price = limitUtils.returnPrice({
              goods: { ...item },
              shopInfo: store.shopInfo,
              limitTimeDiscountRes: this.limitDiscountRes,
              shopUserInfo: this.vipUserInfo,
            })
          }
        });

        if (!flag) {
          console.log("该商品不存在，已删除", item);
          this.operateCart(item, "del");
        }
        return item;
      }
    },
    // 补全历史订单列表商品信息
    comleteOrderInfo(item) {
      // console.log('补全订单列表商品信息');
      const store = useUser()

      this.originGoodsList.map((val) => {
        if (val.id == item.productId) {
          let sku = val.skuList.find((sku) => sku.id == item.skuId);

          let group_text = "";
          if (val.type == "package" && item.pro_group_info) {
            group_text = JSON.parse(item.proGroupInfo)
              .flat()
              .map((item) => item.proName)
              .join("、");
          }

          item.product_id = item.productId;
          item.sku_name = sku && sku.specInfo;
          item.group_type = val.groupType;
          item.goods_type = val.type;
          item.skuList = val.skuList;
          item.selectSpecInfo = val.selectSpecInfo;
          item.group_text = group_text;
          item.packFee = item.packAmount;
          item.unitName = val.unitName;
          item.lowPrice = sku.salePrice;
          item.salePrice = sku.salePrice;
        }
        item.pack_number = item.packNumber;
        item.product_name = item.productName;
        item.number = item.num;
        item.is_temporary = item.isTemporary;
        item.discount_sale_amount = item.discountSaleAmount
        item.is_gift = item.isGift
        item.is_time_discount = limitUtils.canUseLimitTimeDiscount(item, this.limitDiscountRes, store.shopInfo, this.vipUserInfo, 'productId') ? 1 : 0
        item.isTimeDiscount = limitUtils.canUseLimitTimeDiscount(item, this.limitDiscountRes, store.shopInfo, this.vipUserInfo, 'productId') ? 1 : 0
        item.time_discount_price = limitUtils.returnPrice({
          goods: { ...item },
          shopInfo: store.shopInfo,
          limitTimeDiscountRes: this.limitDiscountRes,
          shopUserInfo: this.vipUserInfo,
        })
      });
      return item;
    },
    // 删除购物车商品
    deleteCartItem() {
      this.operateCart(
        {
          table_code: this.cartList[0].table_code,
          id: this.cartList[this.cartActiveIndex].id,
        },
        "del"
      );
    },
    // 删除购物车回执操作
    successDeleteCartItem(data = null) {
      if (data && data.id) {
        let index = this.cartList.findIndex(
          (val) => val.product_id == data.product_id
        );
        this.cartList.splice(index, 1);
      } else {
        this.cartList.splice(this.cartActiveIndex, 1);
      }

      this.selectCartItemHandle(
        this.cartActiveIndex == 0 ? 0 : this.cartActiveIndex - 1
      );
      this.calcCartInfo();
    },
    // 清空购物车
    clearCart() {
      let tableCode = "";
      if (this.tableInfo.tableCode) {
        tableCode = this.tableInfo.tableCode;
      } else {
        if (this.cartList.length) {
          tableCode = this.cartList[0].table_code;
        }
      }
      this.operateCart({ table_code: tableCode }, "cleanup");
    },
    // 商品更新后，需要对购物车、订单进行更新
    async updateGoodsList() {
      // console.log('选择用户后更新所有===', this.vipUserInfo);
      const socket = useSocket();
      const store = useUser()

      await this.getCategoryList();
      await this.getGoodsList();

      // console.log('选择用户后更新所有.cartList===', this.cartList);
      // console.log('选择用户后更新所有.cartList===', this.orderList);

      if (this.cartList.length || this.orderList.length) {
        let data = {
          cart: this.cartList.map(item => {
            return {
              id: item.id,
              is_time_discount: limitUtils.canUseLimitTimeDiscount(item, this.limitDiscountRes, store.shopInfo, this.vipUserInfo, 'product_id') ? 1 : 0
            }
          }),
          history: this.orderList
            .map((item) => item.goods)
            .flat().map(item => {
              return {
                id: item.id,
                is_time_discount: limitUtils.canUseLimitTimeDiscount(item, this.limitDiscountRes, store.shopInfo, this.vipUserInfo, 'productId') ? 1 : 0
              }
            })
        }
        this.operateCart({ data }, 'bulk_edit')
      }
      // await socket.cartInit();
    },
    // 清空购物车回执操作
    async successClearCart() {
      this.cartList = [];
      this.cartInfo = {
        costSummary: { ...initialCostSummary }
      };
      this.orderList = [];
      this.orderListInfo = "";

      // 存在真实台桌，需要拉取历史订单
      if (this.tableInfo.name) {
        await this.historyOrderAjax(this.tableInfo.tableCode);
      } else {
        this.calcCartInfo();
      }

      // 清空商品列表的角标
      if (!this.cartList.length && !this.orderList.length) {
        this.updateGoodsNumber();
      }

      this.updateGoodsList()
    },
    // 下单成功清除购物车，重新加载订单
    async updateOrderList() {
      await this.historyOrderAjax(this.cartList[0].table_code);
      this.cartList = [];
      this.calcCartInfo();
    },
    // 计算购物车信息
    calcCartInfo(opts = {}) {
      const defaultOptions = {
        pointsPerYuan: 0, // 积分换算规律
        maxDeductionAmount: 0, // 最大抵扣
        userPoints: 0, // 使用积分数量
        newUserDiscount: this.newUserDiscount, // 新客立减
        fixedAmount: 0, // 商家减免
        backendCoupons: [], // 已选择的优惠券
      };

      const options = {
        ...defaultOptions,
        ...opts
      }

      const store = useUser();

      const shopInfo = ref(store.shopInfo) || {
        isMemberPrice: 0,
        isTableFee: 1,
      };

      const consumeDiscount = ref({});

      //商品数据Map
      const goodsMap = this.originGoodsList

      var getAllGoodsList = () => {
        console.log('this.cartList===', this.cartList);
        const currentGoods = (this.cartList).map(item => {
          return {
            ...this.completeGoodsInfo(item),
            discountSaleAmount: item.discount_sale_amount
          }
        });

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

        const giftGoods = [].map(this.completeGoodsInfo);
        // 扁平化历史订单商品
        const oldOrderGoods = this.orderList
          .map((item) => item.goods)
          .flat()
          .map(this.comleteOrderInfo);
        if (this.payType == 'table' || this.payType == 'order') {
          return [...giftGoods, ...oldOrderGoods];
        } else {
          return [...currentGoods, ...giftGoods, ...oldOrderGoods];
        }
      }

      // 合并所有商品列表
      const allGoods = ref(getAllGoodsList() || [])

      // 就餐类型 'dine-in' | 'take-out'
      let dinnerType = ref(this.allSelected ? "take-out" : "dine-in");

      // 餐位费
      const seatFeeConfig = ref({
        pricePerPerson: store.shopInfo.tableFee,
        personCount: this.allSelected ? 0 : this.tableInfo.num,
        isEnabled: !store.shopInfo.isTableFee,
      });

      console.log('seatFeeConfig', seatFeeConfig.value);

      //积分规则
      const pointDeductionRule = ref({
        pointsPerYuan: options.pointsPerYuan,
        maxDeductionAmount: options.maxDeductionAmount,
      });

      const userPoints = ref(options.userPoints);

      // 初始配置：默认无减免（固定金额 0 元）
      const merchantReductionConfig = ref({
        type: "fixed_amount",
        fixedAmount: options.fixedAmount,
      });


      console.log('this.newUserDiscount', this.newUserDiscount);


      // 订单额外配置
      const orderExtraConfig = computed(() => ({
        // 引用扩展后的商家减免配置
        merchantReduction: merchantReductionConfig.value,
        additionalFee: 0,
        pointDeductionRule: pointDeductionRule.value,
        seatFeeConfig: seatFeeConfig.value,
        currentStoreId: store.shopInfo.shopId,
        userPoints: userPoints.value,
        isMember: this.showVipPrice,
        memberDiscountRate: 1,
        fullReductionActivities: this.fullReductionActivities !== null ? [this.fullReductionActivities] : [],
        currentDinnerType: dinnerType.value,
        limitTimeDiscount: this.limitDiscountRes,
        shopUserInfo: this.vipUserInfo,
        newUserDiscount: this.newUserDiscount !== null ? this.newUserDiscount.amount : '', //新客立减
      }));

      // 营销活动列表
      const activityList = [];

      // 优惠券列表
      const backendCoupons = ref(options.backendCoupons);

      // 商品加入购物车顺序
      const cartOrder = ref({});

      // 订单费用汇总

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


      const orderCostSummary = {
        allGoods: allGoods.value,
        costSummary: OrderPriceCalculator.calculateOrderCostSummary(
          allGoods.value,
          dinnerType.value,
          backendCoupons.value,
          activityList.value,
          orderExtraConfig.value,
          cartOrder.value,
          new Date()
        ),
      };

      console.log("orderCostSummary===", orderCostSummary);
      this.cartInfo = orderCostSummary
      return orderCostSummary;
    },
    // 购物车操作
    operateCart(data, operate_type = "add") {
      const socket = useSocket();
      const store = useUser();

      console.log(`购物车操作${operate_type}===`, data);
      if (socket.online) {
        socket.ws.send(
          JSON.stringify({
            type: "cashier",
            shop_id: store.shopInfo.id,
            account: store.userInfo.id,
            operate_type: operate_type,
            ...data,
          })
        );
      } else {
        console.log("离线操作");
      }
    },
    // 判断订单是否锁单
    isOrderLock(data, operate_type = "search_pay_lock") {
      return new Promise((resolve, reject) => {
        const socket = useSocket();
        this.operateCart(data, operate_type);
        socket.ws.addEventListener("message", (e) => {
          let data = JSON.parse(e.data);
          if (data.operate_type == "search_pay_lock") {
            if (data.status == 0) {
              ElMessage({
                message: "其他用户正在支付该订单，请稍后再试！",
                type: "warning",
              });
              reject();
            } else {
              resolve();
            }
          } else {
            if (data.status == 1) {
              resolve();
            } else {
              reject();
            }
          }
        });
      });
    },
  },
});