import DictionariesBehavior from "../../../../core/behavior/dictionaries.behavior";
import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import tickleBehavior, {
  getTickleContext,
} from "../../../../core/behavior/tickle.behavior";
import I18nBehavior from "../../../../i18n/behavior";
import { getOfflineTreatmentListMethod } from "../../request";
// module/order/pages/select-goods/select-goods.ts
Component({
  behaviors: [PageContainerBehavior, DictionariesBehavior, tickleBehavior,I18nBehavior],
  lifetimes: {
    attached() {
      const healthAnalysisReportId = wx.getStorageSync('healthAnalysisReportId'); 
      if(healthAnalysisReportId){
        this.getOfflineTreatmentList(healthAnalysisReportId);
      }
    },
  },
  data: {
    goodsList: [] as Array<{
      category: string;
      goods: Array<{
        id: string;
        name: string;
        description?: string;
        image: string;
        price: number;
        quantity: number;
        checked: boolean;
        badge?: string;
      }>;
    }>,
    selectAll: true,
    selectedCount: 0,
    totalPrice: 0,
    i18n: {
      orderText: {
        selectGoods: '选择',
        payMeant:'确认'
      }
    }
  },
  observers: {
    'goodsList': function () {
      this.calculateSummary();
    }
  },
  methods: {
    async getOfflineTreatmentList(healthAnalysisReportId: string) {
      const res = await getOfflineTreatmentListMethod(healthAnalysisReportId);
      const goodsList: any[] = [];
      Object.keys(res).forEach((categoryName: string) => {
        const categoryItems = res[categoryName] || [];
        if (categoryItems.length > 0) {
          const goods = categoryItems.map((item: any) => {
            return {
              id: item.id || '',
              name: item.name || '', //商品名称
              description: (() => {
                const dose = item?.cpFixedPricingRule?.convertDose ?? '';
                const unit = item?.cpFixedPricingRule?.convertUnit ?? '';
                return `${dose} ${unit}`;
              })(),
              image: item.itemImgSecond || '', //商品图片
              price: item.cpFixedPricingRule?.unitPrice || 0, //商品单价
              quantity: 1, //商品数量
              checked: true, //是否选中
            };
          });
          goodsList.push({
            category: categoryName,
            goods: goods,
          });
        }
      });
      this.setData({ goodsList });
      this.calculateSummary();
    },

    // 商品复选框变化
    onGoodsCheckChange(e: any) {
      const { categoryIndex, goodsIndex } = e.currentTarget.dataset;
      const checked = e.detail.checked;
      const goodsList = this.data.goodsList;
      const goods = goodsList[categoryIndex].goods[goodsIndex];

      goods.checked = checked;

      // 如果勾选且数量为0，设置为1
      if (checked && goods.quantity === 0) {
        goods.quantity = 1;
      }

      // 单价为0的商品，如果勾选，数量固定为1
      if (goods.price === 0) {
        if (checked) {
        goods.quantity = 1;
        } else {
          goods.quantity = 0;
        }
      }

      this.setData({ goodsList });
      this.calculateSummary();
    },

    // 全选变化
    onSelectAllChange(e: any) {
      const checked = e.detail.checked;
      const goodsList = this.data.goodsList.map(category => ({
        ...category,
        goods: category.goods.map(goods => ({
          ...goods,
          checked: checked,
          // 0元商品：选中时数量为1，未选中时数量为0
          // 非0元商品：选中时如果数量为0则设为1，否则保持原数量
          quantity: goods.price === 0 
            ? (checked ? 1 : 0)
            : (checked && goods.quantity === 0 ? 1 : goods.quantity)
        }))
      }));

      this.setData({
        goodsList,
        selectAll: checked
      });
      this.calculateSummary();
    },

    // 数量变化（加减按钮）
    onQuantityChange(e: any) {
      const { categoryIndex, goodsIndex, type } = e.currentTarget.dataset;
      const goodsList = this.data.goodsList;
      const goods = goodsList[categoryIndex].goods[goodsIndex];

      // 单价为0的商品数量固定为1（如果被选中）
      if (goods.price === 0) {
        // 0元商品数量固定为1，不允许通过按钮修改
            return;
      } else {
        // 非0价格商品的正常逻辑
        let newQuantity = goods.quantity;

        if (type === "plus") {
          newQuantity = goods.quantity + 1;
        } else if (type === "minus") {
          newQuantity = Math.max(0, goods.quantity - 1);
        }

        goods.quantity = newQuantity;

        // 如果数量为0，自动取消勾选
        if (newQuantity === 0) {
          goods.checked = false;
        } else if (!goods.checked) {
          // 如果数量大于0且未勾选，自动勾选
          goods.checked = true;
        }
      }

      this.setData({ goodsList });
      this.calculateSummary();
    },

    // 数量输入
    onQuantityInput(e: any) {
      const { categoryIndex, goodsIndex } = e.currentTarget.dataset;
      const goodsList = this.data.goodsList;
      const goods = goodsList[categoryIndex].goods[goodsIndex];

      // 单价为0的商品数量固定为1，不允许修改
      if (goods.price === 0) {
        // 保持数量为1
          goods.quantity = 1;
        this.setData({ goodsList });
        return;
      }

      const value = parseInt(e.detail.value) || 0;
        goods.quantity = Math.max(0, value);

      this.setData({ goodsList });
    },

    // 数量输入失焦
    onQuantityBlur(e: any) {
      const { categoryIndex, goodsIndex } = e.currentTarget.dataset;
      const goodsList = this.data.goodsList;
      const goods = goodsList[categoryIndex].goods[goodsIndex];

      // 单价为0的商品数量固定为1（如果被选中）
      if (goods.price === 0) {
        // 如果被选中，数量固定为1
        if (goods.checked) {
          goods.quantity = 1;
        } else {
          // 如果未选中，数量为0
          goods.quantity = 0;
        }
      } else {
        // 非0价格商品的逻辑
        if (goods.quantity === 0) {
          goods.checked = false;
        } else if (!goods.checked) {
          // 如果数量大于0且未勾选，自动勾选
          goods.checked = true;
        }
      }

      this.setData({ goodsList });
      this.calculateSummary();
    },

    // 计算汇总信息
    calculateSummary() {
      const goodsList = this.data.goodsList;
      let selectedCount = 0;
      let totalPrice = 0;
      let allChecked = true;

      goodsList.forEach((category: any) => {
        category.goods.forEach((goods: any) => {
          if (goods.checked && goods.quantity > 0) {
            selectedCount++; // 已选件数 = 选中的商品种类数
            totalPrice += goods.price * goods.quantity;
          }
          if (!goods.checked || goods.quantity === 0) {
            allChecked = false;
          }
        });
      });

      this.setData({
        selectedCount,
        totalPrice: totalPrice.toFixed(2),
        selectAll: allChecked
      });
    },

    // 结算
    onCheckout() {
      const goodsList = this.data.goodsList;
      // 过滤出选中的商品
      const selectedGoods = goodsList.map((category: any) => ({
        category: category.category,
        goods: category.goods.filter((goods: any) => goods.checked && goods.quantity > 0)
      })).filter((category: any) => category.goods.length > 0);

      if (selectedGoods.length === 0) {
        getTickleContext.call(this).showWarnMessage("请至少选择一件商品");
        return;
      }

      // 跳转到确认订单页面
      wx.setStorageSync('selectedGoods', selectedGoods);
      wx.setStorageSync('totalPrice', this.data.totalPrice);
      wx.navigateTo({
        url: `/module/order/pages/confirme-order/confirme-order`,
        fail: (err) => {
          getTickleContext.call(this).showWarnMessage(err.errMsg || "跳转失败");
        },
      });
    },

  }

});
