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

  https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j component-goods-waterfall">
    <view
      v-if="fieldData.categoryShow === 1"
      class="goods-recommend"
    >
      <scroll-view
        :scroll-x="true"
        class="category"
        :scroll-left="categoryScrollLeft"
        scroll-with-animation
      >
        <view
          v-for="(item, index) in categoryList"
          :key="index"
          class="category-item"
          :class="{active: selectedIndex === index}"
          @tap="switchCategory(index)"
        >
          {{ item.name }}
        </view>
      </scroll-view>
    </view>
    <view
      v-if="fieldData.size !== 1"
      class="goods-box"
    >
      <view
        v-for="(item, index) in nGoods"
        :key="index"
        class="goods-box-item"
      >
        <view
          v-for="(goodsItem, goodsIndex) in item"
          :key="goodsIndex"
          class="goods-item"
          @tap.stop="goodsFun(index, goodsIndex)"
        >
          <view
            class="goods-item-content"
            :class="{'goods-item-three':fieldData.size===3}"
          >
            <view
              class="goods-img"
              :class="{'goods-img-three':fieldData.size===3}"
              :style="{width: fieldData.size===3 ? 218 + 'rpx' : 305 + 'rpx', height: fieldData.size===3 ? 218 + 'rpx' : 305 + 'rpx'}"
            >
              <img-show
                :src="goodsItem.pic"
                img-mode="aspectFit"
                :img-style="{width:'100%',height:'100%'}"
              />
            </view>
            <view
              class="goods-box-info"
              :class="{'goods-box-info-three':fieldData.size===3}"
            >
              <view
                v-if="state.productName"
                class="goods-info-title"
                :class="{'goods-info-title-three':fieldData.size===3}"
              >
                {{ goodsItem.prodName }}
              </view>
              <view
                v-if="state.sellingPoint"
                class="goods-info-desc"
              >
                <text>{{ goodsItem.brief || '' }}</text>
              </view>
              <view
                v-if="state.price || state.buyBtn"
                class="goods-info-price  goods-cell-3"
                :class="{'goods-info-price-three':fieldData.size===3}"
              >
                <view
                  v-if="state.price"
                  class="price-info"
                >
                  <text class="symbol">
                    {{ `￥` }}
                  </text>
                  <text class="big-num">
                    {{ wxs.parsePrice(goodsItem.price)[0] }}
                  </text>
                  <text class="small-num">
                    {{ `.${wxs.parsePrice(goodsItem.price)[1]}` }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 一列 -->
    <view
      v-else
      class="goods-box-one"
    >
      <view
        v-for="(goodsItem, index) in nGoods[0]"
        :key="index"
        class="goods-one-column-item"
        @tap.stop="goodsFun(0, index)"
      >
        <view class="goods-img-one">
          <img-show :src="goodsItem.pic" />
        </view>
        <view class="goods-info-one">
          <view
            v-if="state.productName"
            class="goods-name-one"
          >
            {{ goodsItem.prodName }}
          </view>
          <view
            v-if="state.sellingPoint"
            class="goods-brief-one"
          >
            {{ goodsItem.brief || '' }}
          </view>
          <view
            v-if="state.price"
            class="goods-price-one"
          >
            <text class="symbol">
              ¥
            </text>
            <text class="big-num">
              {{ wxs.parsePrice(goodsItem.price)[0] }}
            </text>
            <text class="small-num">
              .{{ wxs.parsePrice(goodsItem.price)[1] }}
            </text>
          </view>
        </view>
      </view>
    </view>
    <!-- 空列表或加载全部提示 -->
    <empty-all-tips
      v-if="isLoaded"
      :is-empty="!goods.length"
      :is-all="isAll"
      :all-tips="$t('index.noMoreTips')"
    />
  </view>
</template>

<script setup>

const props = defineProps({
  fieldData: {
    type: Object,
    default: () => ({})
  },
  shopId: {
    type: [Number, String],
    default: 0
  },
  will: {
    // 需要获取的类型 默认首页
    type: String,
    default: 'home' // home 首页 ，feature 微页面  传 化名ID , goods 商品详情页，传商品ID ,ad 公共广告
  },
  isBottom: {
    type: Boolean,
    default: false
  }
})
const wxs = number()
const goods = ref([])
const nGoods = ref([])
const isAll = ref(false)
// 分类滚动栏横向滚动距离
const categoryScrollLeft = ref(0)
const state = reactive({
  // 显示状态
  productName: false,
  // 1
  sellingPoint: false,
  // 2
  price: false,
  // 3
  buyBtn: false // 4
})

watch(() => props.isBottom, (newVal) => {
  if (newVal) {
    getNextPage()
  }
})

onMounted(() => {
  const data = props.fieldData
  // 显示状态
  state.productName = data.showContent.find(x => x * 1 === 1)
  state.sellingPoint = data.showContent.find(x => x * 1 === 2)
  state.price = data.showContent.find(x => x * 1 === 3)
  state.buyBtn = data.showContent.find(x => x * 1 === 4)
  if (data.categoryShow === 1) {
    getPlatformCategoryList()
  } else {
    getData()
  }
})

/** 梳理数据 */
const carding = () => {
  nGoods.value = []
  const dataFieldPar = props.fieldData
  // 单独一列
  if (dataFieldPar.size === 1) {
    nGoods.value.push(goods.value)
    return
  }
  // 两列或三列
  const columnNum = dataFieldPar.size || 2
  let cur = 1
  const cellOne = []
  const cellTwo = []
  const cellThree = []
  goods.value.forEach((li, index) => {
    if (cur === 1) {
      cellOne.push(li)
    } else if (cur === 2) {
      cellTwo.push(li)
    } else if (cur === 3) {
      cellThree.push(li)
    }
    cur++
    if (cur > columnNum) {
      cur = 1
    }
    if (index === goods.value.length - 1) {
      nGoods.value.push(cellOne, cellTwo)
      if (cellThree.length) {
        nGoods.value.push(cellThree)
      }
    }
  })
}

// 处理升降序
const dealSortType = (type, status) => {
  let res = 0
  switch (type) {
    case 0:
      res = status === 0 ? 0 : 1
      break
    case 1:
      res = status === 0 ? 3 : 2
      break
    case 2:
      res = status === 0 ? 5 : 4
      break
  }
  return res
}

const current = ref(1)
const pages = ref(null)
// 触底加载下一页
const getNextPage = () => {
  if (pages.value > current.value) {
    isAll.value = false
    current.value = current.value + 1
    getData()
  } else {
    isAll.value = true
  }
}

const isLoaded = ref(false)
const categoryList = ref([])
const selectedIndex = ref(0)
let contentScrollW = 0
/**
 * 切换分类
 */
const switchCategory = (index) => {
  if (selectedIndex.value === index) {
    return
  }
  categoryScrollLeft.value = categoryList.value[index].left - contentScrollW / 2 + categoryList.value[index].width / 2 - 15
  selectedIndex.value = index
  current.value = 1
  isAll.value = false
  getData()
}

const getData = () => {
  http.request({
    url: '/mall4cloud_search/ua/search/renovation_page',
    method: 'GET',
    data: {
      shopId: Number(props.shopId) || '',
      pageNum: current.value,
      esRenovationSpuSort: dealSortType(props.fieldData.sortType, props.fieldData.sortStatus),
      esTimeRange: props.fieldData.timeType,
      primaryCategoryId: categoryList.value.length > 0 ? categoryList.value[selectedIndex.value].categoryId : '',
      showSpuType: 1, // 展示商品类型 0.展示指定的商品ids 1.展示瀑布流商品集合
      pageSize: 20,
      sort: 2
    }
  }).then((res) => {
    isLoaded.value = true
    const goodsPar = []
    res.list[0].spus.forEach(item => {
      goodsPar.push({
        prodName: item.spuName,
        status: item.spuStatus,
        price: item.priceFee,
        pic: item.mainImgUrl,
        brief: item.sellingPoint,
        prodId: item.spuId
      })
    })
    if (current.value === 1) {
      goods.value = goodsPar
      pages.value = res.pages
    } else {
      goods.value = goods.value.concat(goodsPar)
    }
    carding()
  })
}

/**
 * 获取平台分类
 */
const getPlatformCategoryList = () => {
  const params = {
    url: '/mall4cloud_product/ua/category/category_list',
    method: 'GET',
    data: {
      shopId: 0,
      parentId: 0
    }
  }
  http.request(params).then((res) => {
    categoryList.value = res.filter(item => item.status === 1)
    getData()
    getCategoryScrollWidth()
  })
}

// 分类滚动的总宽度
/**
 * 获取分类栏 scroll-view 滚动相关宽度
 */
const instance = getCurrentInstance() // 获取组件实例
const getCategoryScrollWidth = () => {
  nextTick(() => {
    const query = uni.createSelectorQuery().in(instance)
    query.select('.category').boundingClientRect(data => {
      // scroll-view 的宽度
      contentScrollW = data.width
    }).exec()
    query.selectAll('.category-item').boundingClientRect(data => {
      const dataLen = data.length
      for (let i = 0; i < dataLen; i++) {
        // scroll-view 各个分类项目的距离左边栏的距离
        categoryList.value[i].left = data[i].left
        // scroll-view 各个分类项目的宽度
        categoryList.value[i].width = data[i].width
      }
    }).exec()
  })
}

/**
 * 点击商品事件
 */
const goodsFun = (index, ItemIndex) => {
  const prodId = nGoods.value[index][ItemIndex].prodId || 0
  uni.navigateTo({
    url: '/pages/detail/detail?spuId=' + prodId
  })
}
</script>
<style lang="scss" scoped>
@use "index";
</style>
