<template>
  <uv-popup ref="popupRef" mode="bottom" round="18rpx" z-index="9999">
    <view class="popupBox">
      <view class="popupBox_t">
        <view class="popupBox_t_l">
          <image
            class=""
            :src="skuValue.cover || details.coverImage"
            mode="aspectFill"
          ></image>
          <view class="popupBox_t_l_info">
            <view class="popupBox_t_l_info_price">
              <view
                class="popupBox_t_l_info_price_l"
                v-if="details.productPaymentMode == 1"
              >
                <text class="iconfont">&#xe669;</text>
                <text>{{ skuValue.exchangePoint }}</text>
              </view>
              <view class="popupBox_t_l_info_price_l" v-else>
                <rich-text :nodes="$mUtil.priceBigSmall(skuValue.salePrice)">
                </rich-text>
              </view>
              <!-- <text class="popupBox_t_l_info_price_r">￥80 </text> -->
              <!-- <text class="u-ml10">7.5折</text> -->
            </view>
            <view class="popupBox_t_l_info_stock"
              >库存 {{ skuValue.stock }} 件</view
            >
            <view class="popupBox_t_l_info_sku">{{ skuValue.skuSetName }}</view>
          </view>
        </view>
        <!-- <view class="popupBox_t_r iconfont">&#xe612;</view> -->
        <view>
          <uv-icon
            name="close-circle"
            color="#999999"
            size="28"
            @click="closePopup"
          ></uv-icon>
        </view>
      </view>
      <scroll-view scroll-y class="popupBox_sku_box">
        <view
          class="popupBox_sku"
          v-for="(item, index) in skuTable"
          :key="index"
        >
          <view class="popupBox_sku_item">
            <view class="popupBox_sku_item_lab">{{ item.head.name }}</view>
            <view class="popupBox_sku_item_list">
              <view
                :class="selectedObj[index] == v.id ? 'active' : ''"
                v-for="(v, i) in item.values || []"
                :key="i"
                @click="chonseSku(index, v.id)"
                >{{ v.name }}</view
              >
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="popupBox_num">
        <view class="popupBox_num_lab">购买数量</view>
        <view class="popupBox_num_inp">
          <!-- <view class="iconfont minus" @click="resNum">&#xe60b;</view>
              <view class="num">{{ add_num }}</view>
              <view class="iconfont plus-sign" @click="addNum">&#xe686;</view> -->
          <uv-number-box v-model="addNum"></uv-number-box>
        </view>
      </view>
      <view class="popupBox_btn">
        <button @click="addCart(1)">{{ btnName }}</button>
      </view>
    </view>
  </uv-popup>
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import { userShoppingCartAdd_Api } from "@/api/shop.js";
const emit = defineEmits(["updateShoppingCart"]);
const props = defineProps({
  skuTable: {
    type: Array,
    default: () => [],
  },
  details: {
    type: Object,
    default: () => ({}),
  },
});
const popupRef = ref(null);
const addNum = ref("1"); // 购买数量
const btnName = ref("加入购物车");
const skuTable = ref(props.details.skuTable || []); // 商品sku属性
const skuValue = ref({}); // 商品sku属性值
const selectedObj = ref({}); // 选中的sku属性值
const details = ref(props.details || {}); // 商品详情
const productSkuSetList = ref([]); // sku属性列表

watch(
  () => props.details,
  (newVal) => {
    details.value = newVal || {};
    if (newVal.productSkuSetList)
      productSkuSetList.value = newVal.productSkuSetList || [];
    skuTable.value = newVal.skuTable || [];
  }
);

watch(
  () => skuTable.value,
  (newVal) => {
    addNum.value = "1";
    let objs = [];
    newVal.forEach((v, i) => {
      objs.push(v.values[0].id || "");
    });
    selectedObj.value = [...objs];
    skuValueChange();
  }
);

// 商品规格选择
const chonseSku = (index, id) => {
  selectedObj.value[index] = id;
  skuValueChange();
};

const skuValueChange = () => {
  // skuValue.value[index] = id;
  let val = [...selectedObj.value];
  val = val.sort((a, b) => a - b);
  let ids = "_" + val.join("_") + "_";
  const objs = productSkuSetList.value.find((v) => v.skuHashCode == ids) || {};
  nextTick(() => {
    skuValue.value = objs || {};
  });
};

// 加入购物车/立即购买
const addCart = (type = null) => {
  // console.log("加入购物车");
  if (btnName.value == "加入购物车") {
    let obj = {
      productId: details.value.productId,
      skuHashCode: skuValue.value.skuHashCode,
      skuSetName: skuValue.value.skuSetName,
      num: addNum.value || 1,
      effectiveStatus: 1,
      businessId: skuValue.value.businessId,
    };
    uni.showLoading({
      title: "加入购物车中...",
      mask: true,
    });
    userShoppingCartAdd_Api(obj)
      .then((res) => {
        uni.hideLoading();
        if (res.code == 200) {
          uni.showToast({
            title: "加入成功！",
            duration: 1500,
          });
          if (type == 1) {
            closePopup();
          }
          emit("updateShoppingCart");
        } else {
          uni.showToast({
            title: "加入失败！",
            duration: 1500,
          });
        }
      })
      .catch((err) => {
        // uni.hideLoading();
      });
  } else {
    // 立即购买
    // console.log("立即购买", skuValue.value);
    let dataJson = {
      shippingMethod: 0, //0物流，10自提
      createOrderDetailBos: [
        {
          skuHashCode: skuValue.value.skuHashCode,
          productNum: addNum.value || 1,
          productId: skuValue.value.productId,
        },
      ],
      marketingType: 0, //0无活动，1秒杀，2拼团
      orderType: 0,
      channelType: 5,
      exchange: details.value.productPaymentMode ? true : false,
      userUsePoint: true,
      businessId: skuValue.value.businessId,
    };
    if (type == 1) {
      closePopup();
    }
    uni.setStorageSync("dataJson", dataJson);
    uni.navigateTo({
      url: "/pages/surePay/surePay",
    });
  }
};

const closePopup = () => {
  addNum.value = "1";
  popupRef.value.close();
};

const open = (name, info = null) => {
  btnName.value = name;
  let detailsInfo = info || details.value || {};
  nextTick(() => {
    if (detailsInfo.singleSku) {
      skuValue.value = detailsInfo.productSkuSetList[0] || {};
    }
  });
  popupRef.value.open();
};

defineExpose({
  open,
});
</script>

<style lang="scss" scoped>
.popupBox {
  border-radius: 18rpx 18rpx 0rpx 0rpx;
  padding-top: 30rpx;
  overflow-y: auto;
  padding-bottom: 30rpx;

  .popupBox_t {
    padding: 0 30rpx 30rpx;
    display: flex;
    justify-content: space-between;
    .popupBox_t_l {
      display: flex;
      align-items: center;
      image {
        width: 200rpx;
        height: 200rpx;
        border-radius: 8rpx;
        overflow: hidden;
        margin-right: 20rpx;
        flex-shrink: 0;
      }
      .popupBox_t_l_info {
        .popupBox_t_l_info_price {
          display: flex;
          color: #999;
          font-size: 24rpx;
          align-items: baseline;
          .popupBox_t_l_info_price_l {
            font-size: 36rpx;
            color: #da4f4f;
          }
          .popupBox_t_l_info_price_r {
            text-decoration: line-through;
            margin-left: 15px;
          }
        }
        .popupBox_t_l_info_stock {
          color: #999;
          font-size: 24rpx;
          margin-top: 5rpx;
        }
        .popupBox_t_l_info_sku {
          font-size: 28rpx;
          color: #1a1a1a;
          margin-top: 25rpx;
        }
      }
    }
    .popupBox_t_r {
      color: #999;
      font-size: 50rpx;
    }
  }

  .popupBox_sku_box {
    max-height: 35vh;
  }

  .popupBox_sku {
    margin-top: 10rpx;
    .popupBox_sku_item {
      .popupBox_sku_item_lab {
        padding: 0 30rpx;
        font-size: 28rpx;
      }
      .popupBox_sku_item_list {
        padding: 0 30rpx;
        display: flex;
        flex-direction: row;
        align-items: center;
        margin-top: 20rpx;
        flex-wrap: wrap;
        > view {
          background-color: #f6f6f6;
          border: 1px solid #f6f6f6;
          padding: 12rpx 30rpx;
          margin-bottom: 24rpx;
          font-size: 24rpx;
          color: #1a1a1a;
          border-radius: 4px;
          margin-right: 10rpx;
        }
        > .active {
          background-color: #f2f5f4;
          border: 1px solid #eb5153;
          color: #eb5153;
          border-radius: 4px;
        }
      }
    }
  }
  .popupBox_num {
    display: flex;
    justify-content: space-between;
    padding: 0 30rpx;
    margin-top: 30rpx;
    .popupBox_num_lab {
      font-size: 28rpx;
    }
  }
  .popupBox_btn {
    padding: 0 30rpx;
    margin-top: 68rpx;
    button {
      width: 100%;
      height: 84rpx;
      background: #eb5153;
      border-radius: 43rpx;
      font-size: 30rpx;
      color: #ffffff;
      text-align: center;
      line-height: 84rpx;
    }
  }
}
</style>
