"use strict";
const common_vendor = require("../../../common/vendor.js");
const common_assets = require("../../../common/assets.js");
const sheep_index = require("../../index.js");
const sheep_hooks_useGoods = require("../../hooks/useGoods.js");
const sheep_api_pay_wallet = require("../../api/pay/wallet.js");
require("../../api/index.js");
require("../../api/distri/score.js");
require("../../request/index.js");
require("../../config/index.js");
require("../../store/index.js");
require("../../store/app.js");
require("../../api/promotion/diy.js");
require("../../platform/index.js");
require("../../platform/provider/wechat/index.js");
require("../../platform/provider/wechat/miniProgram.js");
require("../../api/member/auth.js");
require("../../api/member/social.js");
require("../../api/member/user.js");
require("../../platform/provider/apple/index.js");
require("../../platform/share.js");
require("../../router/index.js");
require("../../hooks/useModal.js");
require("../../helper/index.js");
require("../../helper/test.js");
require("../../helper/digit.js");
require("../../api/member/signin.js");
require("../../helper/throttle.js");
require("../../url/index.js");
require("../../platform/pay.js");
require("../../api/pay/order.js");
require("../../store/user.js");
require("../../store/cart.js");
require("../../api/trade/cart.js");
require("../../api/trade/order.js");
require("../../api/promotion/coupon.js");
require("../../store/sys.js");
require("../../store/modal.js");
require("../../api/distri/share.js");
require("../../api/distri/team.js");
require("../../api/infra/file.js");
require("../../api/member/address.js");
require("../../api/member/point.js");
require("../../api/migration/app.js");
require("../../api/migration/chat.js");
require("../../api/migration/index.js");
require("../../api/migration/third.js");
require("../../api/pay/channel.js");
require("../../api/product/category.js");
require("../../api/product/comment.js");
require("../../api/product/favorite.js");
require("../../api/product/history.js");
require("../../api/product/spu.js");
require("../../api/promotion/activity.js");
require("../../api/promotion/article.js");
require("../../api/promotion/bargain.js");
require("../../api/promotion/combination.js");
require("../../api/promotion/rewardActivity.js");
require("../../api/promotion/seckill.js");
require("../../api/system/area.js");
require("../../api/system/voice.js");
require("../../api/trade/afterSale.js");
require("../../api/trade/brokerage.js");
require("../../api/trade/config.js");
require("../../api/trade/delivery.js");
require("../../config/zIndex.js");
require("../../util/index.js");
if (!Array) {
  const _easycom_su_number_box2 = common_vendor.resolveComponent("su-number-box");
  const _easycom_su_popup2 = common_vendor.resolveComponent("su-popup");
  (_easycom_su_number_box2 + _easycom_su_popup2)();
}
const _easycom_su_number_box = () => "../../ui/su-number-box/su-number-box.js";
const _easycom_su_popup = () => "../../ui/su-popup/su-popup.js";
if (!Math) {
  (_easycom_su_number_box + _easycom_su_popup)();
}
const _sfc_main = {
  __name: "s-select-sku",
  props: {
    goodsInfo: {
      type: Object,
      default() {
      }
    },
    show: {
      type: Boolean,
      default: false
    }
  },
  emits: ["change", "addCart", "buy", "close"],
  setup(__props, { emit: __emit }) {
    const emits = __emit;
    const props = __props;
    const userWallet = common_vendor.computed(() => sheep_index.sheep.$store("user").userWallet);
    const state = common_vendor.reactive({
      selectedSku: {},
      // 选中的 SKU
      currentPropertyArray: []
      // 当前选中的属性，实际是个 Map。key 是 property 编号，value 是 value 编号
    });
    const propertyList = sheep_hooks_useGoods.convertProductPropertyList(props.goodsInfo.skus);
    const skuList = common_vendor.computed(() => {
      let skuPrices = props.goodsInfo.skus;
      for (let price of skuPrices) {
        price.value_id_array = price.properties.map((item) => item.valueId);
      }
      return skuPrices;
    });
    function calcNums() {
      if (props.goodsInfo.highPrecision) {
        state.selectedSku.goods_num = parseInt(state.selectedSku.use_points / (state.selectedSku.highPrecisionPrice / 100));
      } else {
        state.selectedSku.goods_num = parseInt(state.selectedSku.use_points / sheep_hooks_useGoods.fen2yuan(state.selectedSku.price));
      }
    }
    async function useAllPonints() {
      const { code, data } = await sheep_api_pay_wallet.PayWalletApi.getDuserInfo();
      const userCanUsePoints = parseFloat(sheep_hooks_useGoods.points2point(data.integralDO.currentQuota));
      console.log(userCanUsePoints);
      state.selectedSku.use_points = parseInt(userCanUsePoints);
      calcNums();
    }
    function inputPoints(e) {
      const points = e.detail.value;
      console.log(typeof points);
      if (points == "") {
        return false;
      }
      const userCanUsePoints = parseFloat(sheep_hooks_useGoods.points2point(userWallet.value.integralDO.currentQuota));
      calcNums();
      common_vendor.nextTick$1(() => {
        state.selectedSku.use_points = parseInt(points);
        calcNums();
      });
      if (points <= 0) {
        sheep_index.sheep.$helper.toast("最低使用1积分");
        if (userCanUsePoints >= 1) {
          common_vendor.nextTick$1(() => {
            state.selectedSku.use_points = 1;
            calcNums();
          });
        } else {
          common_vendor.nextTick$1(() => {
            state.selectedSku.use_points = 0;
            calcNums();
          });
        }
      }
      if (points > userCanUsePoints) {
        sheep_index.sheep.$helper.toast("可用积分不足");
        common_vendor.nextTick$1(() => {
          state.selectedSku.use_points = parseInt(userCanUsePoints);
          calcNums();
        });
      }
    }
    common_vendor.watch(
      () => state.selectedSku,
      (newVal) => {
        emits("change", newVal);
      },
      {
        immediate: true,
        // 立即执行
        deep: true
        // 深度监听
      }
    );
    function onNumberChange(e) {
      if (e === 0)
        return;
      if (state.selectedSku.goods_num === e)
        return;
      state.selectedSku.goods_num = e;
    }
    function onAddCart() {
      if (state.selectedSku.id <= 0) {
        sheep_index.sheep.$helper.toast("请选择规格");
        return;
      }
      if (state.selectedSku.stock <= 0) {
        sheep_index.sheep.$helper.toast("库存不足");
        return;
      }
      emits("addCart", state.selectedSku);
    }
    async function onBuy() {
      if (props.goodsInfo.spuPayType == 2) {
        const { code, data } = await sheep_api_pay_wallet.PayWalletApi.getDuserInfo();
        const userCanUsePoints = parseFloat(sheep_hooks_useGoods.points2point(data.integralDO.currentQuota));
        if (userCanUsePoints < state.selectedSku.use_points) {
          sheep_index.sheep.$helper.toast("可用积分不足");
          return false;
        }
        if (state.selectedSku.goods_num < 1 || !state.selectedSku.use_points) {
          sheep_index.sheep.$helper.toast("输入金额少于可购买数量");
          return;
        }
        if (state.selectedSku.goods_num > state.selectedSku.stock) {
          state.selectedSku.use_points = (state.selectedSku.stock * sheep_hooks_useGoods.fen2yuan(state.selectedSku.price)).toFixed(2);
          state.selectedSku.goods_num = state.selectedSku.stock;
        }
      }
      if (state.selectedSku.id <= 0) {
        sheep_index.sheep.$helper.toast("请选择规格");
        return;
      }
      if (state.selectedSku.stock <= 0) {
        sheep_index.sheep.$helper.toast("库存不足");
        return;
      }
      emits("buy", state.selectedSku);
      state.selectedSku.use_points = 0;
    }
    function changeDisabled(isChecked = false, propertyId = 0, valueId = 0) {
      let newSkus = [];
      if (isChecked) {
        for (let price of skuList.value) {
          if (price.stock <= 0) {
            continue;
          }
          if (price.value_id_array.indexOf(valueId) >= 0) {
            newSkus.push(price);
          }
        }
      } else {
        newSkus = getCanUseSkuList();
      }
      let noChooseValueIds = [];
      for (let price of newSkus) {
        noChooseValueIds = noChooseValueIds.concat(price.value_id_array);
      }
      noChooseValueIds = Array.from(new Set(noChooseValueIds));
      if (isChecked) {
        let index = noChooseValueIds.indexOf(valueId);
        noChooseValueIds.splice(index, 1);
      } else {
        state.currentPropertyArray.forEach((currentPropertyId) => {
          if (currentPropertyId.toString() !== "") {
            return;
          }
          let index = noChooseValueIds.indexOf(currentPropertyId);
          if (index >= 0) {
            noChooseValueIds.splice(index, 1);
          }
        });
      }
      let choosePropertyIds = [];
      if (!isChecked) {
        state.currentPropertyArray.forEach((currentPropertyId, currentValueId) => {
          if (currentPropertyId !== "") {
            choosePropertyIds.push(currentValueId);
          }
        });
      } else {
        choosePropertyIds = [propertyId];
      }
      for (let propertyIndex in propertyList) {
        if (choosePropertyIds.indexOf(propertyList[propertyIndex]["id"]) >= 0) {
          continue;
        }
        for (let valueIndex in propertyList[propertyIndex]["values"]) {
          propertyList[propertyIndex]["values"][valueIndex]["disabled"] = noChooseValueIds.indexOf(
            propertyList[propertyIndex]["values"][valueIndex]["id"]
          ) < 0;
        }
      }
    }
    function getCanUseSkuList() {
      let newSkus = [];
      for (let sku of skuList.value) {
        if (sku.stock <= 0) {
          continue;
        }
        let isOk = true;
        state.currentPropertyArray.forEach((propertyId) => {
          if (propertyId.toString() !== "" && sku.value_id_array.indexOf(propertyId) < 0) {
            isOk = false;
          }
        });
        if (isOk) {
          newSkus.push(sku);
        }
      }
      return newSkus;
    }
    function onSelectSku(propertyId, valueId) {
      state.selectedSku.use_points = 0;
      let isChecked = true;
      if (state.currentPropertyArray[propertyId] !== void 0 && state.currentPropertyArray[propertyId] === valueId) {
        isChecked = false;
        state.currentPropertyArray.splice(propertyId, 1, "");
      } else {
        state.currentPropertyArray[propertyId] = valueId;
      }
      let choosePropertyId = [];
      state.currentPropertyArray.forEach((currentPropertyId) => {
        if (currentPropertyId !== "") {
          choosePropertyId.push(currentPropertyId);
        }
      });
      let newSkuList = getCanUseSkuList();
      if (choosePropertyId.length === propertyList.length && newSkuList.length) {
        newSkuList[0].goods_num = state.selectedSku.goods_num || 1;
        state.selectedSku = newSkuList[0];
      } else {
        state.selectedSku = {};
      }
      changeDisabled(isChecked, propertyId, valueId);
    }
    changeDisabled(false);
    common_vendor.onMounted(() => {
      if (propertyList.length == 1 && propertyList[0].values.length == 1) {
        onSelectSku(0, 0);
      }
    });
    return (_ctx, _cache) => {
      return common_vendor.e({
        a: state.selectedSku.picUrl || __props.goodsInfo.picUrl,
        b: common_vendor.t(__props.goodsInfo.name),
        c: __props.goodsInfo.spuPayType == 2
      }, __props.goodsInfo.spuPayType == 2 ? {
        d: common_assets._imports_0
      } : {}, {
        e: __props.goodsInfo.highPrecision
      }, __props.goodsInfo.highPrecision ? {
        f: common_vendor.t(common_vendor.unref(sheep_hooks_useGoods.fen2yuan6)(state.selectedSku.highPrecisionPrice || __props.goodsInfo.highPrecisionPrice))
      } : {
        g: common_vendor.t(common_vendor.unref(sheep_hooks_useGoods.fen2yuan)(state.selectedSku.price || __props.goodsInfo.price))
      }, {
        h: state.selectedSku.promotionFee >= 0 || __props.goodsInfo.promotionFee >= 0
      }, state.selectedSku.promotionFee >= 0 || __props.goodsInfo.promotionFee >= 0 ? {
        i: common_vendor.t(common_vendor.unref(sheep_hooks_useGoods.fen2yuan)(state.selectedSku.promotionFee || __props.goodsInfo.promotionFee))
      } : {}, {
        j: common_vendor.t(common_vendor.unref(sheep_hooks_useGoods.formatStock)("exact", state.selectedSku.stock || __props.goodsInfo.stock)),
        k: common_vendor.f(common_vendor.unref(propertyList), (property, k0, i0) => {
          return {
            a: common_vendor.t(property.name),
            b: common_vendor.f(property.values, (value, k1, i1) => {
              return {
                a: common_vendor.t(value.name),
                b: common_vendor.n({
                  "ui-BG-Main-Gradient": state.currentPropertyArray[property.id] === value.id
                }),
                c: common_vendor.n({
                  "disabled-btn": value.disabled === true
                }),
                d: value.id,
                e: value.disabled === true,
                f: common_vendor.o(($event) => onSelectSku(property.id, value.id), value.id)
              };
            }),
            c: property.id
          };
        }),
        l: __props.goodsInfo.spuPayType == 2
      }, __props.goodsInfo.spuPayType == 2 ? common_vendor.e({
        m: common_vendor.t(common_vendor.unref(sheep_hooks_useGoods.points2point)(userWallet.value.integralDO.currentQuota)),
        n: common_vendor.o(useAllPonints),
        o: __props.goodsInfo.spuPayType == 2
      }, __props.goodsInfo.spuPayType == 2 ? {
        p: common_assets._imports_0
      } : {}, {
        q: common_vendor.o([($event) => state.selectedSku.use_points = $event.detail.value, inputPoints]),
        r: !state.selectedSku.id,
        s: state.selectedSku.use_points
      }) : {
        t: common_vendor.o(($event) => onNumberChange($event)),
        v: common_vendor.o(($event) => state.selectedSku.goods_num = $event),
        w: common_vendor.p({
          min: 1,
          max: state.selectedSku.stock,
          step: 1,
          modelValue: state.selectedSku.goods_num
        })
      }, {
        x: common_vendor.o(() => {
        }),
        y: __props.goodsInfo.spuType && __props.goodsInfo.spuPayType == 1
      }, __props.goodsInfo.spuType && __props.goodsInfo.spuPayType == 1 ? {
        z: common_vendor.o(onAddCart),
        A: common_vendor.o(onBuy)
      } : common_vendor.e({
        B: __props.goodsInfo.spuPayType != 1 && !__props.goodsInfo.spuType
      }, __props.goodsInfo.spuPayType != 1 && !__props.goodsInfo.spuType ? {} : !__props.goodsInfo.spuType ? {} : {}, {
        C: !__props.goodsInfo.spuType,
        D: common_vendor.o(onBuy)
      }), {
        E: common_vendor.o(($event) => emits("close")),
        F: common_vendor.p({
          show: __props.show,
          round: "10"
        })
      });
    };
  }
};
const Component = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["__scopeId", "data-v-a43d1e2a"], ["__file", "D:/zx/mall-front-app/sheep/components/s-select-sku/s-select-sku.vue"]]);
wx.createComponent(Component);
