<template>
  <view class="page-association-goods">
    <view
      v-if="skuComboList && skuComboList.length > 0"
      class="list"
    >
      <checkbox-group @change="checkboxChange">
        <view
          v-for="(item, index) in skuComboList"
          :key="index"
          class="good-card"
        >
          <view
            v-if="isDel"
            class="checkbox-box"
          >
            <label class="check-box-label">
              <checkbox
                :checked="item.checked"
                color="#fff"
                :value="item.comboSkuId + ''"
                class="checkbox"
                @tap="onChoose(index)"
              />
            </label>
          </view>
          <view class="img-box">
            <img-show :src="item.imgUrl" />
          </view>
          <view class="info-box">
            <view class="name-and-price">
              <view class="name text-over-hide">
                {{ item.prodName }}
              </view>
              <view>￥{{ item.price }}</view>
            </view>
            <view class="specifications text-over-hide">
              {{ item.skuName }}
            </view>
            <view class="stock-and-num">
              <view>
                {{ $t('kuCun') }}{{ item.stock }}
              </view>
              <view class="num">
                <view>{{ $t('zuHeNeiShuLiang') }}</view>
                <view class="m-numSelector">
                  <view
                    :class="['minus', {'m-p-btn': item.comboCount===1, 'btn-disabled': item.comboCount===1}]"
                    @tap="onUpdateNum(-1, index, item.comboCount, 99999)"
                  />
                  <input
                    :value="item.comboCount"
                    type="number"
                    :disabled="prodStore.isStationProd"
                    @blur="onInputBlur($event, index, 99999)"
                  >
                  <view
                    class="plus"
                    :class="[{'m-p-btn': item.comboCount===99999, 'btn-disabled': item.comboCount===99999}]"
                    @tap="onUpdateNum(1, index, item.comboCount, 99999)"
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
      </checkbox-group>
    </view>

    <empty-tips
      v-else
      :tips-list="[$t('zanWuGuanLianXiang')]"
    />

    <view
      class="footer-bar"
    >
      <view class="total-info-box">
        <view class="total-info">
          <view class="combo-num">
            {{ $t('yiGuanLianSkucombolistlengthXiang').replace('[length]', skuComboList.length) }}
          </view>
          <view class="total-stock">
            {{ $t('heJiGongTongCangKuKuCunTotalstock').replace('[totalStock]', totalStock) }}
          </view>
        </view>
        <view
          v-if="skuComboList.length && warehouseStock === 0 && stationStock === 0"
          class="warming-tip"
        >
          {{ $t('tiShiDangQianGuanLianShangPinWuGongTongGongHuoCangKu') }}
        </view>
      </view>
      <view
        v-if="!isDel"
        class="btn-bar"
      >
        <button
          v-if="!prodStore.isStationProd"
          class="button btn-plain"
          @tap="onEdit"
        >
          {{ $t('guanLi') }}
        </button>
        <button
          v-if="!prodStore.isStationProd"
          class="button btn-plain"
          @tap="onSelectGoods"
        >
          {{ $t('guanLianShangPin') }}
        </button>
        <button
          class="button btn-primary"
          type="primary"
          @tap="onConfirm"
        >
          {{ $t('queDing') }}
        </button>
      </view>
      <view
        v-else
        class="btn-bar"
      >
        <view
          class="btn-radio"
        >
          <radio
            :checked="isAll"
            color="#082ba6"
            :disabled="!(skuComboList && skuComboList.length > 0)"
            @tap="selectAll"
          />
          {{ $t('quanXuan') }}
        </view>
        <button
          class="button text-btn"
          hover-class="none"
          @tap="isDel = !isDel"
        >
          {{ $t('tuiChuPiLiang') }}
        </button>
        <button
          class="button del"
          type="primary"
          @tap="onDel"
        >
          {{ $t('shanChu') }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>

const isDel = ref(false)
const skuIndex = ref(null)
const showProd = ref(false)
onLoad((options) => {
  showProd.value = options.showProd === 'true'
  skuIndex.value = Number(options.skuIndex)
  init()
})

onShow(() => {
  uni.setNavigationBarTitle({
    title: $t('guanLianShangPin')
  })
})

const skuComboList = ref([])
const prodStore = useProdStore()
const init = () => {
  const list = uni.getStorageSync('nowSkuComboList')
  if (list) {
    skuComboList.value = list
    uni.removeStorageSync('nowSkuComboList')
  } else {
    if (skuIndex.value || skuIndex.value === 0) {
      skuComboList.value = prodStore.dataForm.skuList[skuIndex.value]?.skuComboList || []
    } else {
      skuComboList.value = prodStore.dataForm.skuComboList || []
      skuComboList.value = prodStore.dataForm.skuComboList || []
    }
  }
  getTotalStock(skuComboList.value)
}

const isCommonWarehouse = ref(true)
const totalStock = ref(0)
let calcStockInfo = {}
const warehouseStock = ref(0)
const stationStock = ref(0)
const getTotalStock = (list) => {
  const reqSkuComboList = list.map(item => {
    return {
      skuId: item.skuId,
      comboSkuId: item.comboSkuId,
      comboCount: item.comboCount || 1,
      comboProdId: item.comboProdId
    }
  })
  const deliveryMode = JSON.stringify(prodStore.dataForm.deliveryMode)
  const paramData = {
    prodId: prodStore.dataForm.prodId,
    deliveryMode,
    skuList: [{
      skuComboList: reqSkuComboList
    }]
  }
  if (reqSkuComboList.length > 0) {
    http.request({
      url: '/sku/calculateStockBySkuIds',
      method: 'post',
      data: paramData
    }).then(({ data }) => {
      const skuInfo = data.skuList[0] || {}
      totalStock.value = skuInfo.stocks || 0
      warehouseStock.value = skuInfo.warehouseStock || 0
      calcStockInfo = skuInfo
      stationStock.value = skuInfo.stationStock || 0
      isCommonWarehouse.value = skuInfo.hasCommonStock
      skuComboList.value.forEach((item, index) => {
        item.stock = skuInfo.skuComboList[index].stock
        item.warehouseStock = skuInfo.skuComboList[index].warehouseStock
        item.stationStock = skuInfo.skuComboList[index].stationStock
      })
    })
  } else {
    totalStock.value = 0
    isCommonWarehouse.value = true
  }
}

const onUpdateNum = (num, index, nowVal, maxVal) => {
  if (showProd.value) return
  // 如果到达最小值或者最大值，就不再加减数量
  if ((nowVal === 1 && num === -1) || (nowVal === maxVal && num === 1)) return
  let count = skuComboList.value[index].comboCount + num
  if (count <= 0) {
    count = 1
  } else if (count > maxVal) {
    count = maxVal
  }
  skuComboList.value[index].comboCount = count
  getTotalStock(skuComboList.value)
}

const onInputBlur = (e, index, maxVal) => {
  let count = Number(e.detail.value.replace(/\D/g, ''))
  if (count < 1) {
    count = 1
  }
  if (count > maxVal) {
    count = maxVal
  }
  skuComboList.value[index].comboCount = count
  getTotalStock(skuComboList.value)
}

const onSelectGoods = () => {
  if (showProd.value) return
  uni.setStorageSync('nowSkuComboList', skuComboList.value)
  uni.navigateTo({
    url: '/package-prod/pages/select-goods/select-goods' + ((skuIndex.value || skuIndex.value === 0) ? ('?skuIndex=' + skuIndex.value) : '')
  })
}

const onEdit = () => {
  if (showProd.value) return
  skuComboList.value = skuComboList.value.map(item => {
    item.checked = false
    return item
  })
  isDel.value = true
}

let delList = []
const checkboxChange = (e) => {
  delList = e.detail.value
  if (delList.length > 0) {
    delList = delList.map(item => Number(item))
  }
}

const isAll = ref(false)
const onChoose = (index) => {
  skuComboList.value[index].checked = !skuComboList.value[index].checked

  isAll.value = !(skuComboList.value.some(i => i.checked === false))
}

const selectAll = () => {
  if (!(skuComboList.value && skuComboList.value.length > 0)) {
    isAll.value = false
    return
  }
  if (isAll.value) {
    skuComboList.value.forEach(item => {
      item.checked = false
    })
  } else {
    skuComboList.value.forEach(item => {
      item.checked = true
    })
  }
  isAll.value = !isAll.value
}

const onDel = () => {
  if (delList.length === 0 && !isAll.value) {
    uni.showToast({
      title: $t('qingXuanZeShangPin'),
      icon: 'none'
    })
    return
  }
  if (isAll.value) {
    skuComboList.value = []
    isAll.value = false
  } else {
    if (delList.length > 0) {
      delList.forEach(item => {
        skuComboList.value = skuComboList.value.filter(i => i.comboSkuId !== item)
      })
    }
  }
  delList = []
  getTotalStock(skuComboList.value)
}

const onConfirm = () => {
  if (skuIndex.value || skuIndex.value === 0) {
    prodStore.dataForm.skuList[skuIndex.value].skuComboList = skuComboList.value
    prodStore.dataForm.skuList[skuIndex.value].stocks = totalStock.value
    prodStore.dataForm.skuList[skuIndex.value].warehouseStock = calcStockInfo.warehouseStock || 0
    prodStore.dataForm.skuList[skuIndex.value].stationStock = calcStockInfo.stationStock || 0
    uni.redirectTo({
      url: '/package-prod/pages/specification-breakdown/specification-breakdown' + '?showProd=' + showProd.value
    })
  } else {
    prodStore.dataForm.skuComboList = skuComboList.value
    prodStore.dataForm.totalStocks = totalStock.value
    prodStore.dataForm.warehouseStock = calcStockInfo.warehouseStock || 0
    prodStore.dataForm.stationStock = calcStockInfo.stationStock || 0
    uni.redirectTo({
      url: '/package-prod/pages/post-prod/post-prod'
    })
  }
}

</script>

<style lang="scss" scoped>
@use "association-goods";
</style>
