<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view
    v-if="loaded"
    class="Mall4j page-discount-package-detail"
  >
    <view class="main-prod">
      <view class="combo-prod-item">
        <view class="prod-info">
          <view class="info-row">
            <view class="btn">
              <label>
                <checkbox
                  :class="{'checked' : mainSpu.type===1 || mainSpu.checked}"
                  color="#FFFFFF"
                  :checked="mainSpu.type===1 || mainSpu.checked"
                  :disabled="mainSpu.type===1"
                />
              </label>
            </view>
            <view class="pic">
              <img-show
                :src="mainSpu.defaultSku.pic || mainSpu.pic"
                img-mode="aspectFit"
              />
            </view>
            <view class="opt">
              <view class="prod-name">
                {{ mainSpu.spuName }}
              </view>
              <view class="prod-sku-con">
                <text
                  :class="['prod-sku-text', mainSpu.defaultSku.skuName ? 'arrow' : '' ]"
                  @tap.stop="handleShowSkuPop(mainSpu)"
                >
                  {{ mainSpu.defaultSku.skuName || '' }}
                </text>
              </view>
              <view class="price-count">
                <view class="price">
                  <text class="symbol">
                    ￥
                  </text>
                  <text class="big-num">
                    {{ wxs.parsePrice(mainSpu.defaultSku.matchingPrice)[0] }}
                  </text>
                  <text class="small-num">
                    .{{ wxs.parsePrice(mainSpu.defaultSku.matchingPrice)[1] }}
                  </text>
                </view>
                <!-- 套装内的商品的数量 -->
                <view class="combo-count">
                  x {{ mainSpu.leastNum * comboNum }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="match-prod-con">
      <view
        v-for="(matchingProd, matchingProdIndex) in comboInfo.matchingSpus"
        :key="matchingProdIndex"
        class="combo-prod-item"
      >
        <view class="prod-info">
          <view class="info-row">
            <view class="btn">
              <label>
                <checkbox
                  :class="{'checked' : matchingProd.checked || matchingProd.required===1}"
                  color="#FFFFFF"
                  :value="matchingProd.comboSpuId.toString()"
                  :checked="matchingProd.checked || matchingProd.required===1"
                  :disabled="matchingProd.required===1"
                  @tap.stop="handleCheckProdItem(matchingProd, matchingProdIndex)"
                />
              </label>
            </view>
            <view
              v-if="matchingProd"
              class="pic"
            >
              <img-show
                :src="matchingProd.defaultSku.pic || matchingProd.pic"
                img-mode="aspectFit"
              />
            </view>
            <view class="opt">
              <view class="prod-name">
                {{ matchingProd.spuName }}
              </view>
              <view class="prod-sku-con">
                <text
                  :class="['prod-sku-text', matchingProd.defaultSku.skuName ? 'arrow' : '' ]"
                  @tap.stop="handleShowSkuPop(matchingProd)"
                >
                  {{ matchingProd.defaultSku.skuName || '' }}
                </text>
              </view>
              <view class="price-count">
                <view class="price">
                  <text class="symbol">
                    ￥
                  </text>
                  <text class="big-num">
                    {{ wxs.parsePrice(matchingProd.defaultSku.matchingPrice)[0] }}
                  </text>
                  <text class="small-num">
                    .{{ wxs.parsePrice(matchingProd.defaultSku.matchingPrice)[1] }}
                  </text>
                </view>
                <!-- 套装内的商品的数量 -->
                <view class="combo-count">
                  x {{ matchingProd.leastNum * comboNum }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="combo-footer">
      <view class="combo-price-reduce">
        <view class="combo-price">
          <text class="combo-price-title">
            套餐价:
          </text>
          <text
            class="price"
            decode
          >
            ￥
            <text class="big">
              {{ wxs.parsePrice(comboAmountInfo.matchingPrice)[0] }}.
            </text>{{ wxs.parsePrice(comboAmountInfo.matchingPrice)[1] }}
          </text>
        </view>
        <view class="combo-reduce">
          为您节省: ￥{{ wxs.parsePrice(comboAmountInfo.reduceAmount)[0] }}.{{ wxs.parsePrice(comboAmountInfo.reduceAmount)[1] }}
        </view>
      </view>
      <view class="btn-con">
        <view
          class="btn add-cart"
          @tap="handleShowComboInfo(0)"
        >
          加入购物车
        </view>
        <view
          class="btn buy-now"
          @tap="handleShowComboInfo(1)"
        >
          立即购买
        </view>
      </view>
    </view>

    <!-- 套餐整体信息弹窗 -->
    <view
      v-if="showComboInfo"
      class="pup-sku"
    >
      <view class="pup-sku-main">
        <view class="pup-sku-header">
          <view
            class="close"
            @tap="handleHideComboInfo"
          />
        </view>
        <view class="pup-sku-body">
          <!-- 商品 -->
          <scroll-view
            class="combo-prod-list"
            scroll-x
            :show-scrollbar="false"
          >
            <view
              v-if="mainSpu"
              class="pup-combo-item"
            >
              <view class="pup-combo-pic">
                <img-show
                  :src="mainSpu.defaultSku.pic || mainSpu.pic"
                  img-mode="aspectFit"
                />
              </view>
              <view class="pup-combo-name">
                {{ mainSpu.spuName }}
              </view>
              <view
                class="pup-combo-sku"
                @tap.stop="handleShowSkuPop(mainSpu)"
              >
                <view class="pup-combo-sku-text">
                  {{ mainSpu.defaultSku.skuName }}
                </view>
              </view>
            </view>
            <block
              v-for="(prodItem, prodIndex) in matchingSpus"
              :key="prodIndex"
            >
              <view
                v-if="prodItem.checked"
                class="pup-combo-item"
              >
                <view class="pup-combo-pic">
                  <img-show
                    :src="prodItem.defaultSku.pic || prodItem.pic"
                    img-mode="aspectFit"
                  />
                </view>
                <view class="pup-combo-name">
                  {{ prodItem.spuName }}
                </view>
                <view
                  class="pup-combo-sku"
                  @tap.stop="handleShowSkuPop(prodItem)"
                >
                  <view class="pup-combo-sku-text">
                    {{ prodItem.defaultSku.skuName || '' }}
                  </view>
                </view>
              </view>
            </block>
          </scroll-view>
          <!-- 数量 -->
          <view class="pup-sku-count">
            <view class="num-wrap">
              <view
                class="minus"
                @tap="onCountMinus"
              >
                <text class="row" />
              </view>
              <view class="text-wrap">
                <input
                  v-model="comboNum"
                  type="number"
                >
              </view>
              <view
                class="plus"
                @tap="onCountPlus"
              >
                <text class="row" />
                <text class="col" />
              </view>
            </view>
            <view class="count-name">
              套餐数量
            </view>
          </view>
        </view>
        <view class="pup-sku-footer">
          <view
            class="btn buy"
            @tap="handleComboInfoPopComfirm"
          >
            确定
          </view>
        </view>
      </view>
    </view>

    <!-- 套餐sku弹窗 -->
    <prod-sku-select
      v-if="showSkuPop && currentProdItem"
      :pic="currentProdItem.pic"
      :least-num="currentProdItem.leastNum"
      :sku-id="currentProdItem.defaultSku.skuId"
      :sku-name="currentProdItem.defaultSku.skuName"
      :activity-info="currentProdItem"
      :sku-list="currentProdItem.skuList"
      :is-main="currentProdItem.type===1"
      @set-sku="handleSetSku"
      @close-sku-pop="handleCloseSkuPop"
    />

    <!-- 提示弹窗 -->
    <pop-toast
      v-model:value="showtoastVal"
      :options="toastOp"
    />
  </view>
</template>

<script setup>
import Big from 'big.js'
const wxs = number()

const comboId = ref(0)
const shopId = ref(0)
onLoad((options) => {
  shopId.value = options.shopId
  comboId.value = options.comboId
  getComboDetailById()
})

/**
 * 弹窗提示
 */
// 弹窗提示
const showtoastVal = ref(false)
const toastOp = ref({})
const onShowToast = (op) => {
  showtoastVal.value = true
  toastOp.value = op
}
/**
 * 获取套餐详情
 */
// 套装信息
const comboInfo = ref({})
// 套装商品列表
const matchingSpus = ref([])
// 套装主商品
const mainSpu = ref({})
const loaded = ref(false)
const getComboDetailById = () => {
  const params = {
    url: '/tmerclub_marketing/ma/combo',
    data: {
      comboId: comboId.value
    },
    method: 'GET'
  }
  http.request(params).then(res => {
    comboInfo.value = res
    res.mainSpu.defaultSku = setDefaulProdSku(res.mainSpu.skuList, res.mainSpu.comboPrice)
    mainSpu.value = res.mainSpu
    res.matchingSpus.forEach(matchingPordItem => {
      matchingPordItem.checked = matchingPordItem.required === 1
      matchingPordItem.defaultSku = setDefaulProdSku(matchingPordItem.skuList, matchingPordItem.comboPrice)
    })
    matchingSpus.value = res.matchingSpus
    loaded.value = true
    setComboParam()
  }).catch(err => {
    if (err.code === 'A00001') {
      uni.showToast({
        title: err.msg,
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  })
}

/**
 * 初始化商品的默认sku
 */
const setDefaulProdSku = (skuList, comboPrice, ismainSpu) => {
  if (ismainSpu) {
    for (let i = 0; i < skuList.length; i++) {
      if (skuList[i].matchingPrice === comboPrice) {
        return skuList[i]
      }
    }
  } else {
    let defaultSku = null
    let flag = false
    for (let i = 0; i < skuList.length; i++) {
      if (comboPrice === skuList[i].matchingPrice && skuList[i].stocks) {
        defaultSku = skuList[i]
        flag = true
        break
      }
    }
    if (!flag && skuList.length) {
      defaultSku = skuList[0]
    }
    return defaultSku
  }
}

/**
 * 修改后重设商品的sku
 */
const { proxy } = getCurrentInstance()
const handleSetSku = (sku, isMain) => {
  if (isMain) {
    mainSpu.value.defaultSku = sku
    proxy.$forceUpdate()
  } else {
    const matchingProds = matchingSpus.value
    for (let i = 0; i < matchingProds.length; i++) {
      if (matchingProds[i].comboSpuId === sku.comboSpuId) {
        matchingProds[i].defaultSku = sku
        proxy.$forceUpdate()
        break
      }
    }
  }
  handleCloseSkuPop()
  setComboParam()
}

/**
 * 勾选/取选套装的商品
 */
const handleCheckProdItem = (matchingProd, matchingProdIndex) => {
  if (matchingProd.required) return
  const checked = matchingProd.checked
  const matchingSpusVal = matchingSpus.value
  matchingSpusVal[matchingProdIndex].checked = !checked
  setComboParam()
}

/**
 * 生成请求套餐金额的参数
 */
// 套装的数量
const comboNum = ref(1)
// 请求套餐价格的数据
const comboAmountParam = ref({})
const setComboParam = () => {
  const cartComboMatchSpuDTOS = []
  const matchingSkuIds = []
  matchingSpus.value.forEach(matchingProd => {
    if (matchingProd.checked) {
      cartComboMatchSpuDTOS.push({
        skuId: matchingProd.defaultSku.skuId,
        spuId: matchingProd.spuId,
        count: matchingProd.leastNum
      })
      matchingSkuIds.push(matchingProd.defaultSku.skuId)
    }
  })

  const comboAmountParamVal = {
    comboId: comboId.value,
    comboNum: comboNum.value,
    cartComboMatchSpuDTOS,
    matchingSkuIds,
    comboSpuId: mainSpu.value.comboSpuId,
    spuId: mainSpu.value.spuId,
    comboMainLeastNum: mainSpu.value.leastNum,
    skuId: mainSpu.value.defaultSku.skuId
  }
  comboAmountParam.value = comboAmountParamVal
  getComboAmount(comboAmountParamVal)
}

/**
 * 展示套装信息弹窗
 * @param {Number} openType: 0加入购物车  1立即购买
 */
// 套餐整体信息弹窗显隐
const showComboInfo = ref(false)
// 套餐购买方式: 0加入购物车 1立即购买
const comboBuyType = ref(0)
const handleShowComboInfo = (openType) => {
  showComboInfo.value = true
  comboBuyType.value = openType
}

/**
 * 关闭套装信息弹窗
 */
const handleHideComboInfo = () => {
  showComboInfo.value = false
}

/**
 * 减数量
 */
const onCountMinus = () => {
  const comboNumVal = comboNum.value
  if (comboNumVal > 1) {
    comboNum.value = comboNum.value - 1
  }
  setComboParam()
}

/**
 * 加数量
 */
const onCountPlus = () => {
  const comboNumVal = Number(comboNum.value)
  // 最小库存的商品
  if (comboNumVal < getMinStocksProd().defaultSku.stocks) {
    comboNum.value = comboNumVal + 1
  } else {
    onShowToast({
      title: getMinStocksProd().spuName + '库存不足',
      duration: 1000
    })
  }
  setComboParam()
}

/**
 * 最小库存的商品
 */
const getMinStocksProd = () => {
  const matchingSpusVal = matchingSpus.value.filter(el => el.checked)
  // 套餐内是否只有一个主商品
  const isOnlyMain = !matchingSpusVal.length
  let minStocksProd = {}
  if (isOnlyMain) {
    minStocksProd = mainSpu.value
  } else {
    minStocksProd = matchingSpusVal[0]
    matchingSpusVal.forEach(el => {
      if (el.defaultSku.stocks < minStocksProd.defaultSku.stocks) {
        minStocksProd = el
      }
    })
  }
  if (!isOnlyMain && mainSpu.value.defaultSku.stocks < minStocksProd.defaultSku.stocks) {
    minStocksProd = mainSpu.value
  }
  return minStocksProd
}

/**
 * 套装信息弹窗确认按钮
 */
const handleComboInfoPopComfirm = () => {
  if (comboNum.value < 1) {
    uni.showToast({
      title: '商品数量不能小于1',
      icon: 'none'
    })
    comboNum.value = 1
    return
  }
  if (comboBuyType.value) {
    util.checkAuthInfo(buyNow)
  } else {
    util.checkAuthInfo(addToCart)
  }
}

/**
 * 加入购物车
 */
const addToCart = () => {
  const paramData = JSON.parse(JSON.stringify({
    ...comboAmountParam.value,
    basketId: 0,
    shopId: shopId.value,
    count: comboNum.value
  }))
  paramData.cartComboMatchSpuDTOS.forEach(el => {
    el.count = el.count * paramData.comboNum
  })
  const params = {
    url: '/tmerclub_product/shop_cart/change_item',
    method: 'POST',
    data: paramData
  }
  http.request(params).then(() => {
    util.tapLog(2, { n: comboNum.value, sid: shopId.value, bid: paramData.spuId })
    uni.showToast({
      title: '加入购物车成功',
      icon: 'none'
    })
    handleHideComboInfo()
    uni.switchTab({
      url: '/pages/cart/cart'
    })
  }).catch(errMsg => {
    uni.showToast({
      title: errMsg.data || errMsg.msg,
      icon: 'none'
    })
    handleHideComboInfo()
  })
}

/**
 * 立即购买
 */
const buyNow = () => {
  // 最小库存的商品
  if (Number(comboNum.value) <= getMinStocksProd().defaultSku.stocks) {
    const paramData = JSON.parse(JSON.stringify({
      ...comboAmountParam.value,
      basketId: 0,
      shopId: shopId.value,
      count: comboNum.value
    }))
    paramData.cartComboMatchSpuDTOS.forEach(el => {
      el.count = el.count * paramData.comboNum
    })
    uni.setStorageSync('cloudShopCartItem', JSON.stringify(paramData))
    uni.redirectTo({
      url: '/package-user/pages/submit-order/submit-order?orderEntry=1'
    })
  } else {
    onShowToast({
      title: getMinStocksProd().spuName + '库存不足',
      duration: 1000
    })
  }
}

/**
 * 计算套餐金额
 */
// 套餐的价格信息
const comboAmountInfo = ref({})
const getComboAmount = () => {
  const comboAmountInfoVal = {
    matchingPrice: 0,
    price: 0,
    reduceAmount: 0
  }
  // 套餐总金额
  let comboTotal = new Big(0)
  // 套餐优惠总金额
  let comboReduceTotal = new Big(0)
  for (let i = 0; i < matchingSpus.value.length; i++) {
    const matchingProdItem = matchingSpus.value[i]
    if (matchingProdItem.checked) {
      comboTotal = comboTotal.plus(getTotalOrReduce(matchingProdItem, 'total'))
      comboReduceTotal = comboReduceTotal.plus(getTotalOrReduce(matchingProdItem, 'reduce'))
    }
  }
  comboTotal = comboTotal.plus(getTotalOrReduce(mainSpu.value, 'total'))
  comboReduceTotal = comboReduceTotal.plus(getTotalOrReduce(mainSpu.value, 'reduce'))

  comboAmountInfoVal.matchingPrice = Number(comboTotal.valueOf())
  comboAmountInfoVal.reduceAmount = Number(comboReduceTotal.valueOf())
  comboAmountInfo.value = comboAmountInfoVal
}

const getTotalOrReduce = (item, type) => {
  if (type === 'total') {
    return new Big(item.defaultSku.matchingPrice - 0).times(item.leastNum - 0)
  } else {
    return (new Big(item.defaultSku.priceFee - 0).minus(new Big(item.defaultSku.matchingPrice - 0))).times(item.leastNum - 0).valueOf()
  }
}

/**
 * 显示sku弹窗
 */
// sku弹窗显隐
const showSkuPop = ref(false)
// 当前操作的商品项
const currentProdItem = ref({})
const handleShowSkuPop = (item) => {
  currentProdItem.value = item
  showSkuPop.value = true
}

/**
 * 隐藏sku弹窗
 */
const handleCloseSkuPop = () => {
  showSkuPop.value = false
}

</script>

<style lang="scss" scoped>
 @use './discount-package-detail.scss';
</style>
