<!--  -->
<template>
  <div>
    <Navbar style="min-width: 1184px;" @search="handleSearch" />
      <div v-if="goodList.length" class="default-width white-bgc my-3 pa-5" :loading="loading" style="border-radius: 5px;">
        <div class="goods-box">
          <v-card v-for="val in goodList" :key="val.id" class="goods-box-item" hover elevation="2" @click="handleClickGood(val)">
            <v-img :src="val.picUrl" width="100%" height="68%" cover></v-img>
            <div class="px-3 pt-3">
              <p class="ellipsis color-333">{{ val.name }}</p>
              <p class="color-999 ellipsis font-size-14 mt-1">{{ val.introduction }}</p>
              <div class="mt-1 d-flex justify-space-between">
                <div class="goods-box-item-price">￥{{ isArray(val.price) ? fen2yuan(val.price[0]) : fen2yuan(val.price) }}</div>
                <div class="font-size-15 mt-1" style="color: #c4c4c4">{{ salesAndStock(val) }}</div>
              </div>
            </div>
          </v-card>
        </div>
        <CtPagination :total="total" :page="page.pageNo" :limit="page.pageSize" @handleChange="handleChangePage"></CtPagination>
      </div>
      <Empty v-else class="default-width my-3" :elevation="false" :message=message ></Empty>
  </div>
</template>

<script setup>
defineOptions({name: 'mall-goodsList-index'})
import Navbar from '@/views/mall/components/navbar.vue'
import { useRoute } from 'vue-router'; const route = useRoute()
import { getGoodsList } from '@/api/mall/index'
import { isArray } from 'lodash-es'
import { formatSales, fen2yuan } from '@/hooks/web/useGoods'
import { ref, computed } from 'vue'

const page = ref({
  pageNo: 1,
  pageSize: 10
})

// 根据id获取商品列表
const loading = ref(false)
const total = ref(0)
const goodList = ref([])
const getData = async () => {
  const params = {
    ...page.value,
    keyword: keyword.value,
  }
  const { list, total: number } = await getGoodsList(params)
  goodList.value = list
  total.value = number || 0
}
getData()

// 分页
const handleChangePage = (e) => {
  page.value.pageNo = e
  getData()
}

const message = ref('')
const keyword = ref('')
// 关键字检索
const handleSearch = (val) => {
  keyword.value = val
  message.value = keyword.value ? `没有找到“${keyword.value}”相关商品` : '没有找到相关商品'
  getData()
}

// 格式化销量、库存信息
const salesAndStock = computed(() => (data) => {
  let text = []
  text.push(formatSales(undefined, data.salesCount))
  return text.join(' | ')
})

</script>
<style lang="scss" scoped>
.goods-box {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  &-item {
    height: 330px;
    width: calc((100% - 48px) / 5);
    margin: 0 12px 12px 0;
    &:nth-child(5n) {
      margin-right: 0;
    }
    &-price {
      color: #ff3000;
      font-size: 20px;
    }
  }
}
</style>
