<template>
  <z-paging
    ref="pagingRef"
    v-model="prodList"
    :paging-style="{'top': '0',background: '#f2f3f7'}"
    :default-page-size="12"
    :loading-more-custom-style="{paddingBottom: '200rpx'}"
    :empty-view-img="EmptyTipsUrl"
    :empty-view-img-style="{width: '400rpx', height: '220rpx'}"
    @query="queryData"
    @list-change="prodDataChange"
  >
    <view class="page-select-goods">
      <view class="top-bar">
        <view class="search-box">
          <view
            class="search-label"
            @tap="isProdName = !isProdName"
          >
            <view
              class="sku-name-con"
            >
              {{ isProdName ? $t('shangpin') : $t('fenlei') }}
            </view>
            <img
              style="width: 30rpx;"
              src="@/static/images/switch.png"
              alt
            >
          </view>
          <view
            v-if="isProdName"
            class="search-input"
          >
            <input
              class="uni-input"
              :placeholder="$t('qingShuRuShangPinMingCheng-0')"
              :value="params.prodName"
              @input="onInput"
              @confirm="onSearchData"
            >
          </view>
          <view
            v-else
            class="search-input"
          >
            <picker
              :value="selectedIndex"
              :range="categoryList"
              @change="onPickerChange"
            >
              <view class="uni-input">
                <text
                  v-if="!params.shopCategoryId"
                  class="placeholder"
                >
                  {{ $t('qingXuanZeDianPuFenLei') }}
                </text>
                <view
                  v-else
                  class="label"
                >
                  <text class="name">
                    {{ categoryList[selectedIndex] }}
                  </text>
                  <icon
                    type="clear"
                    size="15"
                    @tap.stop="onClearCategory"
                  />
                </view>
              </view>
            </picker>
          </view>
          <view
            class="search-icon"
            @tap="onSearchData"
          >
            <img
              src="@/static/images/search-prefix.png"
              alt
            >
          </view>
        </view>
      </view>
      <view class="list">
        <checkbox-group>
          <view
            v-for="(item, index) in prodList"
            :key="index"
            class="good-card"
          >
            <view class="info">
              <view
                class="checkbox-box"
              >
                <label class="check-box-label">
                  <checkbox
                    v-if="!isRefresh"
                    :checked="item.checked"
                    color="#fff"
                    class="checkbox"
                    :disabled="isMaxNum && !item.checked"
                    @tap="onChoose(index)"
                  />
                </label>
              </view>
              <view class="img-box">
                <img-show :src="item.pic" />
              </view>
              <view class="info-box">
                <view class="name-and-price">
                  <view class="name">
                    {{ item.prodName }}
                  </view>
                  <view
                    v-if="!item.skuList || item.skuList.length === 1"
                  >
                    ￥{{ item.price }}
                  </view>
                </view>
                <view class="specifications">
                  {{ item.skuName }}
                </view>
                <view class="stock-and-num">
                  <view>{{ $t('zongKuCun') }}{{ item.skuList.length === 1 ? item.skuList[0].stocks : countTotalStock(item.skuList) }}</view>
                </view>
              </view>
            </view>
            <view
              v-if="item.skuList && item.skuList.length > 1"
              class="specifications"
            >
              <specifications-list
                :combo-list="item.skuList"
                :is-max-num="isMaxNum"
                @on-choose="onChooseItem($event, index)"
              />
            </view>
          </view>
        </checkbox-group>
      </view>
      <view
        class="footer-bar"
      >
        <button
          class="button btn-plain"
          @tap="onCancel"
        >
          {{ $t('quXiao-0') }}
        </button>
        <button
          class="button"
          type="primary"
          @tap="onConfirm"
        >
          {{ $t('queDing') }}
        </button>
      </view>
    </view>
  </z-paging>
</template>

<script setup>
import SpecificationsList from '@/package-prod/components/specifications-list/specifications-list.vue'
import EmptyTipsUrl from '@/static/images/empty-tips.png'

const params = reactive({
  prodName: '',
  shopCategoryId: null
})

const skuIndex = ref(0)
onLoad((options) => {
  skuIndex.value = options.skuIndex
  // 拿到已选择的商品列表
  chooseList.value = uni.getStorageSync('nowSkuComboList')
  getCategoryList()
})

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

const prodList = ref([])

const categoryList = ref([])
let preCategoryList = []
// 获取店铺分类列表
const getCategoryList = () => {
  http.request({
    url: '/prod/category/listCategory',
    method: 'GET',
    data: {
      status: 1
    }
  }).then(({ data }) => {
    preCategoryList = data
    categoryList.value = data.map(i => i.categoryName)
  })
}

// 清除已选的分类信息
const onClearCategory = () => {
  params.shopCategoryId = null
  onSearchData()
}

const selectedIndex = ref(0)
const onPickerChange = (e) => {
  selectedIndex.value = e.detail.value
  params.shopCategoryId = preCategoryList[selectedIndex.value].categoryId
  onSearchData()
}

// 已选择合集
const chooseList = ref([])

const isProdName = ref(true)

const pagingRef = ref(null)
const queryData = (current, size) => {
  http.request({
    url: '/prod/prod/prodSkuPage',
    method: 'GET',
    data: {
      current,
      size,
      prodName: params.prodName ? params.prodName : null,
      shopCategoryId: params.shopCategoryId,
      mold: 0,
      status: 1,
      skuStatus: 1,
      preSellStatus: 0
    }
  }).then(({ data: res }) => {
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    pagingRef.value.complete(res.records)
  })
}

const isRefresh = ref(false)
// comboSkuId
const prodDataChange = (list) => {
  isRefresh.value = true
  prodList.value = list.map(item => {
    if (item.skuList && item.skuList.length > 0) {
      item.skuList.map(i => {
        i.checked = chooseList.value?.some(s => s.comboSkuId === i.skuId)
        return i
      })
    }
    item.checked = !(item.skuList.some(s => s.checked === false))
    return item
  })
  nextTick(() => {
    isRefresh.value = false
  })
}

const isMaxNum = computed(() => {
  return chooseList.value.length >= 10
})

// 判断选择数量是否达到最大值
const judgeMax = () => {
  if (chooseList.value.length >= 10) {
    uni.showToast({
      title: $t('zuiDuoXuanZe_10GeGuiGe'),
      icon: 'none'
    })
    return true
  } else {
    return false
  }
}

const onInput = (e) => {
  params.prodName = e.detail.value.trim()
}

const showClearIcon = ref(false)
const onSearchData = () => {
  if (params.prodName && params.prodName !== '') {
    showClearIcon.value = true
    pagingRef.value.reload()
  } else {
    params.prodName = ''
    showClearIcon.value = false
    pagingRef.value.reload()
  }
}

const onCancel = () => {
  uni.redirectTo({
    url: '/package-prod/pages/association-goods/association-goods'
  })
}

const countTotalStock = (skuList) => {
  let count = 0
  if (skuList && skuList.length > 0) {
    skuList.forEach(item => {
      count += item.stocks
    })
  }
  return count
}

const onChoose = (index) => {
  if (prodList.value[index].checked) {
    prodList.value[index].checked = false
    prodList.value[index].skuList.forEach(i => {
      // 删掉相关选择项
      chooseList.value = chooseList.value.filter(s => s.comboSkuId !== i.skuId)
    })
  } else {
    if (isMaxNum.value) return
    const item = prodList.value[index]

    for (let i = 0; i < item.skuList.length; i++) {
      const isMax = judgeMax()
      const val = item.skuList[i]
      if (isMax) {
        break
      }
      // 如果规格已存在数组中，则直接跳过
      if (chooseList.value.some(i => (i.comboSkuId === val.skuId && i.prodName === item.prodName))) continue
      const obj = {
        prodName: item.prodName,
        comboCount: 1,
        comboSkuId: val.skuId,
        comboProdId: item.prodId,
        skuName: val.skuName || '-',
        imgUrl: val.pic || item.pic,
        price: val.price,
        stock: val.stock || val.stocks,
        skuId: null,
        prodId: null
      }
      chooseList.value.push(obj)
    }
  }
  prodDataChange(prodList.value)
}

const onChooseItem = (skuId, index) => {
  const item = prodList.value[index]
  if (item.skuList && item.skuList.length > 0) {
    const sku = item.skuList.find(i => i.skuId === skuId)
    if (!sku) return
    if (sku.checked) {
      // 删掉相关选择项
      chooseList.value = chooseList.value.filter(s => s.comboSkuId !== sku.skuId)
    } else {
      if (isMaxNum.value) return
      const isMax = judgeMax()
      if (isMax) {
        return
      }
      const obj = {
        prodName: item.prodName,
        comboCount: 1,
        comboSkuId: sku.skuId,
        comboProdId: item.prodId,
        skuName: sku.skuName || '-',
        imgUrl: sku.pic || item.pic,
        price: sku.price,
        stock: sku.stock || sku.stocks,
        skuId: null,
        prodId: null
      }
      chooseList.value.push(obj)
    }
  }

  prodDataChange(prodList.value)
}

const onConfirm = () => {
  uni.setStorageSync('nowSkuComboList', chooseList.value)
  uni.redirectTo({
    url: '/package-prod/pages/association-goods/association-goods' + ((skuIndex.value || skuIndex.value === 0) ? ('?skuIndex=' + skuIndex.value) : '')
  })
}

</script>

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