<template>
  <view class="page-combine-detail-list">
    <view class="roll-area">
      <view class="content-box">
        <!-- 单商品 -->
        <view
          v-for="(prodItem,prodIdx) in combineSkuDetail.skuComboList"
          :key="prodIdx"
          class="single-prod"
          @tap="toProdDetail(prodItem)"
        >
          <view class="prod-img">
            <img-show
              :src="prodItem.imgUrl"
              img-mode="aspectFit"
            />
          </view>
          <view class="text-box">
            <view class="name">
              {{ prodItem.spuName }}
            </view>
            <view class="sku">
              <view
                v-if="prodItem.skuName"
                class="sku-text"
              >
                {{ prodItem.skuName }}
              </view>
            </view>

            <view class="price-box">
              <view class="count">
                ×{{ comboItemCount(prodItem.comboCount) }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="bottom-box">
        <view>
          <view class="sku">
            库存：{{ combineSkuDetail?.stock || 0 }}
          </view>
        </view>

        <view class="number-box">
          <view
            :class="['minus', comboCount <= 1 ? 'limit' : '']"
            @tap="onChangeNumber(-1)"
          />
          <input
            ref="prodNumberRef"
            v-model="comboCount"
            type="number"
            class="number"
            @blur="onProdNumberChange"
          >
          <view
            :class="['plus', comboCount >= combineSkuDetail?.stock ? 'limit' : '']"
            @tap="onChangeNumber(1)"
          />
        </view>
      </view>

      <view class="placeholder-bar" />
    </view>

    <view class="bottom-bar">
      <view class="price-box">
        <view class="title">
          销售价：
        </view>
        <view class="price">
          ￥
          <text class="big-num">
            {{ wxs.parsePrice(totalPrice)[0] }}
          </text>
          <text class="small-num">
            .{{ wxs.parsePrice(totalPrice)[1] }}
          </text>
        </view>
      </view>
      <view
        class="add-cart btn-box"
        @tap="onAddCart"
      >
        加入购物车
      </view>
      <view
        class="new-buy btn-box"
        @tap="onGoSubmit"
      >
        立即购买
      </view>
    </view>

    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-confirm="onPopConfirm"
      @handle-pop-cancel="onPopCancel"
    />
  </view>
</template>

<script setup>
import util from '@/utils/util'

const wxs = number()

const combineSkuDetail = ref({})
const spuId = ref(null)
const skuId = ref(null)
const comboCount = ref(1)
const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
onLoad((query) => {
  spuId.value = Number(query.spuId)
  skuId.value = Number(query.skuId)

  // 配送地址信息
  const isDeliveryAddrInfo = uni.getStorageSync('cloudDeliveryAddrInfo')
  if (isDeliveryAddrInfo) {
    deliveryAddrInfo.value = isDeliveryAddrInfo
  } else {
    onGetAddressList()
  }
  init()
})

const init = () => {
  onGetGoodDetail()
}

/**
 * 获取用户地址列表
 */
const onGetAddressList = () => {
  http.request({
    url: '/tmerclub_user/user_addr/list',
    method: 'GET',
    dontShowLogin: true,
    data: {}
  }).then(res => {
    for (const addr of res) {
      if (addr.isDefault) {
        deliveryAddrInfo.value = addr
        break
      }
    }
  }).catch(() => {})
}

const showPop = ref(false)
const popContent = ref({})
const deliveryAddrInfo = ref(null)// 当前配送地址信息
const goodDetail = ref({})
const onGetGoodDetail = () => {
  const userId = uni.getStorageSync('cloudToken') && uni.getStorageSync('cloudUserDetails') ? uni.getStorageSync('cloudUserDetails').userId : undefined
  http.request({
    url: '/tmerclub_product/ma/spu/prod_info',
    method: 'GET',
    withoutPrompting: true,
    data: {
      spuId: spuId.value,
      userId: userId || '',
      addrId: deliveryAddrInfo.value?.addrId || ''
    },
    selfLoading: true
  }).then((res) => {
    goodDetail.value = res
    combineSkuDetail.value = res.skus.find(item => item.skuId === skuId.value)
  }).catch((errMsg) => {
    showPop.value = true
    popContent.value.content = errMsg.msg ? errMsg.msg : '商品已下架'
    popContent.value.cancelText = '逛逛首页'
    popContent.value.confirmText = '搜索商品'
  })
}

/**
 * 提示弹窗确认
 */
const onPopConfirm = () => {
  showPop.value = false
  uni.navigateTo({ url: '/pages/search-page/search-page' })
}

/**
 * 提示弹窗取消
 */
const onPopCancel = () => {
  showPop.value = false
  uni.switchTab({ url: '/pages/index/index' })
}

const totalPrice = computed(() => {
  let num = comboCount.value
  if (num < 1) {
    num = 1
  } else if (num > combineSkuDetail.value?.stock) {
    num = combineSkuDetail.value?.stock
  } else {
    num = typeof num === 'string' ? Number(num.replace(/[^\d]/g, '')) : num
  }
  return goodDetail.value.priceFee * num || 0.01
})

/**
 * 修改商品数量
 */
const onChangeNumber = (num) => {
  let isProdNumber = parseInt(comboCount.value)
  if (num < 0) {
    // 点击数量-
    if (isProdNumber <= 1) {
      return
    } else {
      isProdNumber += num
    }
  } else {
    const stock = combineSkuDetail.value.stock
    // 普通商品
    if (isProdNumber >= stock) {
      uni.showToast({
        title: '库存不足',
        icon: 'none'
      })
      comboCount.value = stock || 1
    } else {
      isProdNumber += 1
    }
  }
  comboCount.value = isProdNumber
}

const onProdNumberChange = () => {
  if (comboCount.value < 1) {
    comboCount.value = 1
  } else if (comboCount.value > combineSkuDetail.value?.stock) {
    comboCount.value = combineSkuDetail.value?.stock
  } else {
    comboCount.value = typeof comboCount.value === 'string' ? Number(comboCount.value.replace(/[^\d]/g, '')) : comboCount.value
  }
}

const comboItemCount = (count) => {
  let num = comboCount.value
  if (num < 1) {
    num = 1
  } else if (num > combineSkuDetail.value?.stock) {
    num = combineSkuDetail.value?.stock
  } else {
    num = typeof num === 'string' ? Number(num.replace(/[^\d]/g, '')) : num
  }

  return count * num
}

const findSku = ref(true)
/**
 * 加入购物车按钮
 */
const onAddCart = () => {
  if (!findSku.value) {
    uni.showToast({
      title: '所选规格无货',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  const stock = combineSkuDetail.value.stock
  if (!stock) {
    uni.showToast({
      title: '库存不足',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  util.checkAuthInfo(() => {
    http.request({
      url: '/tmerclub_product/shop_cart/change_item',
      method: 'POST',
      data: {
        skuId: skuId.value,
        spuId: spuId.value,
        count: comboCount.value,
        oldSkuId: ''
      }
    }).then(() => {
      util.tapLog(2, {
        n: comboCount.value,
        sid: goodDetail.value.shopId,
        bid: spuId.value
      })
      uni.showToast({
        title: '加入购物车成功~',
        duration: 2000,
        icon: 'none'
      })
    })
  })
}

/**
 * 立即购买
 */
const onGoSubmit = () => {
  if (!findSku.value) {
    uni.showToast({
      title: '所选规格无货',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (comboCount.value > combineSkuDetail.value.stock) {
    uni.showToast({
      title: '库存不足',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  util.checkAuthInfo(() => {
    uni.setStorageSync(
      'cloudShopCartItem',
      JSON.stringify({
        count: comboCount.value,
        groupSkuId: undefined,
        seckillSkuId: undefined,
        seckillId: undefined,
        distributionUserId: Number(distributionUserId),
        shopId: goodDetail.value.shopId,
        skuId: skuId.value,
        spuId: spuId.value
      })
    )
    uni.navigateTo({
      url: '/package-user/pages/submit-order/submit-order?orderEntry=1&spuMold=2'
    })
  })
}

/**
 * 跳转商品详情
 */
const toProdDetail = (prodItem) => {
  uni.navigateTo({
    url: '/pages/detail/detail?spuId=' + prodItem.comboSpuId
  })
}
</script>

<style lang="scss" scoped>
@use "combine-detail-list";
</style>
