<!--
 * @Author: 王翠碧 1254597151@qq.com
 * @Date: 2023-05-27 15:44:47
 * @LastEditors: micky 1254597151@qq.com
 * @LastEditTime: 2023-12-25 16:58:35
 * @FilePath: \uniapp\src\pages\index\comp\sticky-category.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <view class="mt-3">
        <tabs
            :current="current"
            @change="handleChange"
            height="100"
            bar-width="60"
            :font-size="32"
            :barStyle="{ bottom: '0' }"
            activeColor="#2468f2"
            :isFixed="isFixed"
            :swipeable="false"
            :top="topheight"
            :itemWidth="tabsItemWidth"
        >
            <tab v-for="(item, i) in lists" :key="i" :name="item.categoryName"></tab>
            <view class="cate-container mt-[20rpx]">
                <view
                    v-for="(item, i) in lists"
                    :key="i"
                    :id="'category-item' + i"
                    class="category-item px-[20rpx]"
                >
                    <!-- <view class="text-center mt-[40rpx] mb-[20rpx] text-content text-base">
                        {{ item.categoryName }}
                    </view> -->
                    <div class="goods">
                        <block v-for="(item1, idx) in converItem(item.data)" :key="item1.id">
                            <view
                                class="goods-item"
                                @click="goPage(`/pages/goods/index?id=${item1.id}`)"
                            >
                                <view class="info-img">
                                    <u-image
                                        :src="item1.image"
                                        class="goods-image"
                                        width="100%"
                                        height="260"
                                        mode="aspectFill"
                                        border-radius="15"
                                    ></u-image>
                                </view>

                                <view class="info-column">
                                    <view style="text-align: left">
                                        <view
                                            class="goods-title overflow-ellipsis-line ellipsis-line1"
                                        >
                                            {{ item1.name }}
                                        </view>
                                    </view>
                                    <view class="flex justify-between items-center mt-[20rpx]">
                                        <view class="price-wrap text-lg">
                                            ¥
                                            <span class="price">{{ servicePrice(item1) }}</span>
                                        </view>
                                        <view class="text-sm normal" style="color: #b0aeae">
                                            <text class="font-bold">{{ item1.orderNum }}</text>
                                            人预约过
                                        </view>
                                    </view>
                                </view>
                            </view>
                        </block>
                    </div>
                </view>
            </view>
        </tabs>
    </view>
</template>

<script setup lang="ts">
import { ref, watch, nextTick, onMounted, getCurrentInstance, computed } from 'vue'
import { apiGoodsLists } from '@/api/store'
import { PriceEnum } from '@/enums/appEnums'
import { formatString } from '@/utils/util'
const props = withDefaults(
    defineProps<{
        top: number
        lists: any // 分类数据
        isFixed: boolean
    }>(),
    {
        top: 0,
        lists: [],
        isFixed: true
    }
)
const instance = getCurrentInstance() // 获取组件实例
const emit = defineEmits(['tabChange', 'backRefresh'])
const topheight = ref(0)
const converItem = computed(() => data => {
    if (!data) return
    return data.map(item => {
        const { price, minPrice, maxPrice } = item
        return {
            ...item,
            goodsPrice: price,
            priceRange: `${minPrice}-${maxPrice}`
        }
    })
})
const servicePrice = computed(() => item => {
    const { priceType, goodsPrice, priceRange } = item
    return priceType == PriceEnum.CUSTOMER_PRICE ? goodsPrice : formatString(priceRange)
})

const handleChange = async (e: any) => {
    emit('tabChange', topInstance.value[e] - 150)
}

interface listItem {
    data: []
    categoryId: ''
    categoryName: ''
    sliceNum: ''
}

watch(
    () => props.top,
    (nVal, oVal) => {
        topheight.value = nVal / (uni.upx2px(100) / 100)
    },
    { immediate: true }
)
watch(
    () => props.lists,
    async (nVal, oVal) => {
        const arr = nVal.reduce((crr: Promise<any>[], prev: listItem) => {
            crr.push(
                apiGoodsLists({
                    pageNo: 1,
                    pageSize: prev.sliceNum || 20,
                    categoryId: prev.categoryId
                })
            )
            return crr
        }, [])
        Promise.allSettled(arr).then(res => {
            res.map((item, index) => {
                if (item.status === 'fulfilled') {
                    props.lists[index].data = item.value.lists
                }
            })
        })
    },
    { immediate: true }
)

const tabsItemWidth = computed(() => {
    return (750 / props.lists.length).toString()
})

// 监听页面滚动，对应不同tab
const current = ref(0)

const topInstance = ref([])

const handleActive = (nVal: number) => {
    const index = topInstance.value.findIndex(distance => distance - nVal > 0)
    current.value = index + 1 > 0 ? index : topInstance.value.length - 1
}

onMounted(async () => {
    setTimeout(() => {
        const query = uni.createSelectorQuery().in(instance)
        query
            .selectAll('.category-item')
            .boundingClientRect(data => {
                topInstance.value = data.map(v => v.top)
            })
            .exec()
    }, 200)
})
const goPage = (url: string) => {
    uni.navigateTo({ url: url })
}

//截取当前数据到小数点后两位
const numFilter = (value: string) => {
    const realVal = parseFloat(value).toFixed(2)
    return realVal
}
defineExpose({
    handleActive
})
</script>

<style lang="scss" scoped>
:deep(.scroll-box) {
    display: flex;
}
.goods {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-column-gap: 20rpx;
    grid-row-gap: 20rpx;
    margin-bottom: 20rpx;
}
.goods-item {
    display: inline-block; //让每个子项可以方便换行
    // box-sizing: border-box;
    padding: 15rpx;
    border-radius: 10rpx;
    background-color: #fff;
    //box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    // margin-bottom: 20rpx;
    // width: 47%; //这样可以每行最多两个goods item

    .info-img {
        width: 100%;

        .goods-image {
            //图片质量选择器，选择最适合你的游戏图片质量的选择器
            width: 100%; //让图片可以整体显示在页面上
            //border-radius: 10rpx; //因为是 u-image 故需要传入参数变更圆角
        }
    }

    .info-column {
        text-align: left;
        padding-top: 20rpx;
        padding-left: 5rpx;

        .goods-title {
            font-size: 0.95rem;
            margin-bottom: 10rpx;
        }

        .goods-scribingPrice {
            font-size: 0.775rem;
            color: #808695;
            text-decoration: line-through;
        }

        .price-wrap {
            color: red;
        }
    }
}
</style>
