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

  https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j component-feature">
    <view
      v-for="(item, index) in list"
      :key="index"
    >
      <searchBar
        v-if="item.type === 'search'"
        :field-data="item.dataField"
        :shop-id="shopId"
        :page-scorll-top="pageScorllTop"
      />
      <image-ad
        v-if="item.type === 'imageAd' || item.type === 'hotArea'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <goods
        v-if="item.type === 'goods'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <notice
        v-if="item.type === 'notice'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <navigationClassification
        v-if="item.type === 'tabNav'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <titleText
        v-if="item.type === 'titleText'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <promotionalActivities
        v-if="item.type === 'promotionalActivities'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <goods-module-one
        v-if="item.type==='goodsModule1'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <goods-module-two
        v-if="item.type==='goodsModule2'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <goods-module-three
        v-if="item.type==='goodsModule3'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <goods-module-four
        v-if="item.type==='goodsModule4'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <goods-module-five
        v-if="item.type==='goodsModule5'"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
      <goods-waterfall
        v-if="item.type==='goodsWaterfall'"
        :is-bottom="isBottom"
        :field-data="item.dataField"
        :shop-id="shopId"
      />
    </view>
  </view>
</template>

<script setup>
import imageAd from './all-feature/image-ad/index.vue'
import goods from './all-feature/goods/index.vue'
import notice from './all-feature/notice/index.vue'
import navigationClassification from './all-feature/navigation-classification/index.vue'
import titleText from './all-feature/title-text/index.vue'
import promotionalActivities from './all-feature/promotional-activities/index.vue'
import searchBar from './all-feature/search-bar/index.vue'
import goodsModuleOne from './all-feature/goods-module-one/index.vue'
import goodsModuleTwo from './all-feature/goods-module-two/index.vue'
import goodsModuleThree from './all-feature/goods-module-three/index.vue'
import goodsModuleFour from './all-feature/goods-module-four/index.vue'
import goodsModuleFive from './all-feature/goods-module-five/index.vue'
import goodsWaterfall from './all-feature/goods-waterfall/index.vue'

const props = defineProps({
  isShowMicro: {
    type: Boolean,
    default: true
  },
  wid: {
    type: String,
    default: ''
  },
  pageLoad: {
    type: Boolean,
    default: false
  },
  pageId: {
    type: [Number, String],
    default: ''
  },
  shopId: {
    type: [Number, String],
    default: ''
  },
  pageScorllTop: {
    type: Number,
    default: 0
  }
})

const emit = defineEmits(['pageLoaded'])

const list = ref([])
let locking = false
const isBottom = ref(false)

onMounted(() => {
  nextTick(() => {
    getPageInfoById()
  })
})

/**
 * 请求页面数据
 */
const getPageInfoById = () => {
  list.value = []
  const params = {
    url: '/tmerclub_admin/ua/shop_renovation/get_renovation_by_id',
    method: 'GET',
    data: {
      renovationId: props.pageId
    }
  }
  if (props.pageId && props.shopId >= 0 && !locking) {
    locking = true
    http.request(params).then(async (res) => {
      locking = false
      if (!res) {
        // 没获取到数据，可能是对应id的页面被删了
        uni.showToast({
          title: '页面不存在！',
          icon: 'none',
          duration: 1200
        })
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          })
        }, 1500)
        return
      }
      const pageData = await matchproducts(JSON.parse((res.content)))
      list.value = pageData
      emit('pageLoaded', {
        detail: {
          homeStatus: res.homeStatus,
          code: 0,
          data: '已获取数据',
          title: pageData[0].dataField.title,
          bgImg: pageData[0].dataField.bgImg ? import.meta.env.VITE_APP_RESOURCES_URL + pageData[0].dataField.bgImg : '',
          textColor: pageData[0].dataField.textColor,
          bgType: pageData[0].dataField.bgType,
          bgColor: pageData[0].dataField.bgColor
        }
      })
    })
  }
}

// 匹配商品
const matchproducts = async (arr) => {
  const res = await searchGoodsMessage(arr)
  if (!res) return arr
  res.forEach(item => {
    if (item.spuActivity) {
      if (item.spuActivity.groupActivity) {
        item.activityPrice = item.spuActivity.groupActivity.price
      }
      if (item.spuActivity.sekillActivitySpuVO) {
        item.activityPrice = item.spuActivity.sekillActivitySpuVO.seckillPrice
      }
    }
  })
  arr.forEach(item => {
    if (item.type === 'goods') { // 商品列表(这里是进行一个筛选)
      const goodsParams = {
        prodName: 'spuName',
        status: 'spuStatus',
        price: 'priceFee',
        pic: 'mainImgUrl',
        brief: 'sellingPoint'
      }
      item.dataField.goods = handleScreenGoods(item.dataField.goods, res, 'prodId', goodsParams)
    } else if (item.type === 'promotionalActivities') { // 促销活动
      const promoParams = {
        prodName: 'spuName',
        prodType: 'spuType',
        status: 'spuStatus',
        price: 'activityPrice',
        groupNumber: 'groupNumber',
        pic: 'mainImgUrl',
        brief: 'sellingPoint',
        oriPrice: 'priceFee',
        activityStatus: 'activityStatus',
        activityPrice: 'activityPrice'
      }
      item.dataField.prodIds = handleScreenGoods(item.dataField.prodIds, res, 'prodId', promoParams)
    } else if (item.type === 'goodsModule1') { // 商品模块1
      item.dataField.leftConfig.goodsList = handleScreenGoods(item.dataField.leftConfig.goodsList, res, 'id')
      item.dataField.rightConfig.goodsList = handleScreenGoods(item.dataField.rightConfig.goodsList, res, 'id')
    } else if (item.type === 'goodsModule3' || item.type === 'goodsModule4' || item.type === 'goodsModule5') { // 商品模块3 4 5
      item.dataField.goodsList = handleScreenGoods(item.dataField.goodsList, res, 'id')
    }
  })
  return arr
}

// 查询商品信息
const searchGoodsMessage = (arr) => {
  let goodsArr = []
  arr.forEach(item => {
    if (item.type === 'goods') { // 商品信息
      item.dataField.goods.forEach(v => {
        goodsArr.push(v.prodId)
      })
    } else if (item.type === 'promotionalActivities') { // 促销和活动
      item.dataField.prodIds.forEach(v => {
        goodsArr.push(v.prodId)
      })
    } else if (item.type === 'goodsModule1') { // 商品模块1
      item.dataField.leftConfig.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
      item.dataField.rightConfig.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goodsModule3') { // 商品模块3
      item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goodsModule4') { // 商品模块4
      item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goodsModule5') { // 商品模块5
      item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    }
  })
  goodsArr = Array.from(new Set(goodsArr))
  if (!goodsArr.length) return
  return new Promise((resolve) => {
    http.request({
      url: '/tmerclub_search/ua/search/renovation_page',
      method: 'GET',
      data: {
        spuIds: uni.getStorageSync('cloudAppType') === 1 ? goodsArr.toString() : goodsArr,
        showSpuType: 0, // 展示商品类型 0.展示指定的商品ids 1.展示瀑布流商品集合
        pageNum: 1,
        pageSize: goodsArr.length,
        getDelete: 1
      }
    }).then((res) => {
      res.list[0].spus.forEach(item => {
        if (item.spuActivity && item.spuActivity.groupActivity) {
          item.groupNumber = item.spuActivity.groupActivity.groupNumber
        }
      })
      resolve(res.list[0].spus)
    })
  })
}

// 筛选商品回显 currentArr: 表示当前装修的商品，backReturnArr: 表示根据现有id查询后端返回的商品
const handleScreenGoods = (currentArr, backReturnArr, type, otherParams) => {
  let params
  if (otherParams) {
    params = {
      ...otherParams
    }
  } else {
    params = {
      name: 'spuName', // 商品名称
      prodType: 'spuType', // 商品类型
      status: 'spuStatus', // 商品状态
      price: 'priceFee', // 商品价格
      imgs: 'mainImgUrl', // 商品图片
      orignPrice: 'marketPriceFee', // 商品原价
      description: 'sellingPoint' // 商品描述
    }
  }
  const arr = []
  for (let i = 0; i < currentArr.length; i++) {
    for (let j = 0; j < backReturnArr.length; j++) {
      if (currentArr[i][type] === backReturnArr[j].spuId) {
        for (const key in params) {
          currentArr[i][key] = backReturnArr[j][params[key]]
        }
        currentArr[i].spuType = currentArr[i].spuType || backReturnArr[j].spuType
        arr.push(currentArr[i])
      }
    }
  }
  return arr
}

// 下拉页面触底
const getNextPage = () => {
  isBottom.value = true
  setTimeout(() => {
    isBottom.value = false
  }, 100)
}
defineExpose({ getNextPage })
</script>
<style lang="scss" scoped>
@use "feature";
</style>
