<template>
    <view :style="warpCss" class="overflow-hidden relative" v-if="goodsList.length && !loading">
        <view class="flex justify-between items-center h-[84rpx] px-[24rpx]" :style="headCss">
            <view class="flex items-center">
                <view v-if="diyComponent.titleStyle.way == 'img' && diyComponent.titleStyle.imgUrl" class="flex items-center max-w-[180rpx] mr-[10rpx]" @click="diyStore.toRedirect(diyComponent.titleStyle.link)">
                    <image :src="img(diyComponent.titleStyle.imgUrl)" class="h-[34rpx] max-w-[100%]" mode="heightFix" />
                </view>
                <view v-else @click="diyStore.toRedirect(diyComponent.titleStyle.link)" :style="{ color : diyComponent.titleStyle.textColor, fontWeight : diyComponent.titleStyle.fontWeight,'font-size': (diyComponent.titleStyle.fontSize * 2) + 'rpx','font-style': diyComponent.titleStyle.fontStyle,whiteSpace: 'nowrap'}">
                    {{ diyComponent.titleStyle.text }}
                </view>
                <view class="mx-[10rpx] w-[2rpx] h-[22rpx] bg-[#fff]"></view>
                <view class="flex items-center">
                    <view class="flex items-center">
                        <template v-for="(item, index) in pintuanTotalData?.member_list.slice(0, 5)" :key="index">
                            <image v-if="item.member?.headimg" class="w-[35rpx] h-[35rpx] rounded-[50rpx] relative border-[2rpx] border-[#fff] border-solid box-border" :class="{'-ml-[16rpx]': index}" :src="img(item.member?.headimg)" @error="item.member.headimg = 'static/resource/images/default_headimg.png'" mode="aspectFill" />
                            <image v-else class="w-[35rpx] h-[35rpx] rounded-[50rpx] relative border-[2rpx] border-[#fff] border-solid box-border" :class="{'-ml-[16rpx]': index}" :src="img('static/resource/images/default_headimg.png')" mode="aspectFill" />
                        </template>
                    </view>
                    <view class="text-[#fff] text-[24rpx] flex items-center ml-[6rpx]" :style="{ color : diyComponent.subTitleStyle.textColor,'font-size': (diyComponent.subTitleStyle.fontSize * 2) + 'rpx'}">
                        <text> {{ pintuanTotalData?.num || 100 }}</text>
                        <text>人已拼成</text>
                    </view>
                </view>
            </view>
            <view class="flex-1 flex justify-end items-center">
                <view class="flex items-center" @click="diyStore.toRedirect(diyComponent.moreStyle.link)" :style="{ color : diyComponent.moreStyle.textColor,'font-size': (diyComponent.moreStyle.fontSize * 2) + 'rpx'}">
                    <text> {{ diyComponent.moreStyle.text }}</text>
                    <text class="!text-[22rpx] iconfont iconxiangyoujiantou"></text>
                </view>
            </view>
        </view>
        <view class="diy-shop-goods-list relative flex flex-wrap justify-between p-[20rpx] bg-[#fff]">
            <view class="w-full flex overflow-hidden" :class="{ 'mt-[20rpx]': index > 0 }"
                    v-for="(item,index) in goodsList" :key="index" @click="toDetail(item)">
                <view class="w-[240rpx] h-[240rpx] overflow-hidden" :style="{'borderRadius': diyComponent.goodsStyle.imgRounded * 2 + 'rpx'}">
                    <u--image width="240rpx" height="240rpx" :src="img(item.goods.cover_thumb_mid || '')"  model="aspectFill">
                        <template #error>
                            <image class="w-[240rpx] h-[240rpx] overflow-hidden" :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill" />
                        </template>
                    </u--image>
                </view>
                <view class="flex-1 flex flex-col ml-[20rpx] py-[6rpx] relative">
                    <view class="text-[28rpx] leading-[40rpx] text-[#303133] using-hidden mb-[10rpx]">
                        {{ item.goods.title }}
                    </view>
                    <view
                        class="self-start overflow-hidden h-[30rpx] border-[1px] border-[#FF9A9F] border-solid rounded-[8rpx] mb-[10rpx] flex leading-[normal]">
                        <view class="bg-[#FFE6E6] text-[#FF000D] text-[20rpx] h-[30rpx] leading-[30rpx] rounded-r-0 px-[8rpx] text-center">{{item.target_num}}人团</view>
                        <view class="text-[#FF000D] text-[20rpx] text-center leading-[30rpx] px-[10rpx]">已拼{{item.success_group_num || '0'}}份</view>
                    </view>
                    <view class="mt-auto flex justify-between items-center">
                        <view class="flex flex-col items-baseline">
                            <view class="h-full flex flex-col">
                                <view
                                    class="px-[10rpx] py-[6rpx] bg-[#FF0E1D] text-[#fff] text-[20rpx] inline-block rounded-[6rpx]">
                                    已省{{ subsidyFn(item) }}元</view>
                                <text class="iconfont iconxiajiantou leading-1 text-[#FF0E1D] mt-[2rpx] ml-[14rpx]"></text>
                            </view>
                            <view class="flex items-baseline leading-[1]">
                                <view
                                    class="font-bold text-[var(--price-text-color)] price-font block truncate max-w-[350rpx]">
                                    <text class="text-[24rpx] font-500 mr-[4rpx]">￥</text>
                                    <text class="text-[40rpx] font-500">{{ parseFloat(item.goods.show_price).toFixed(2).split('.')[0] }}</text>
                                    <text class="text-[24rpx] font-500">.{{ parseFloat(item.goods.show_price).toFixed(2).split('.')[1] }}</text>
                                </view>
                                <view class="ml-[6rpx] line-through text-[24rpx] text-[#999]">￥{{ parseFloat(item.goods.original_price).toFixed(2) }}</view>
                            </view>
                        </view>
                        <view
                        class="px-[18rpx] h-[50rpx] text-[24rpx] text-center flex items-center mt-[10rpx] ml-[auto]" :style="btnCss">{{ diyComponent.btnStyle.text }}</view>
                    </view>
                </view>
            </view>
            <mescroll-empty class="mt-[0]" v-if="!goodsList.length&& !loading" :option="{tip : '暂无商品，请看看其他商品吧！'}"></mescroll-empty>
        </view>
        <!-- 装修时，防止点击 -->
        <view v-if="diyStore.mode == 'decorate'" class="absolute z-10 top-0 right-0 bottom-0 left-0"></view>
    </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue';
import { redirect, img } from '@/utils/common';
import useDiyStore from '@/app/stores/diy';
import { getPintuanComponentsGoods, getPintuanComponentsTotal } from '@/addon/pintuan/api/pintuan';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue'
import usePintuanIndexStore from '@/addon/pintuan/stores/index';

const props = defineProps(['component', 'index', 'value']);
const diyStore = useDiyStore();
const selectCategoryIndex = ref(1) // 当前选中的分类id
const goodsList = ref([]) // 商品列表
const pintuanIndexStore = usePintuanIndexStore()

const diyComponent = computed(() => {
    if (props.value) {
        return props.value;
    } else if (diyStore.mode == 'decorate') {
        return diyStore.value[props.index];
    } else {
         return props.component;
    }
})

// 组件框架样式
const warpCss = computed(() => {
    let style = '';
    style += 'position:relative;';
    if (diyComponent.value.componentStartBgColor && diyComponent.value.componentEndBgColor) style += `background:linear-gradient(${ diyComponent.value.componentGradientAngle },${ diyComponent.value.componentStartBgColor },${ diyComponent.value.componentEndBgColor });`;
    else style += 'background-color:' + (diyComponent.value.componentStartBgColor || diyComponent.value.componentEndBgColor) + ';';

    if (diyComponent.value.componentBgUrl) {
        style += `background-image:url('${ img(diyComponent.value.componentBgUrl) }');`;
        style += 'background-size: cover;background-repeat: no-repeat;';
    }

    if (diyComponent.value.topRounded) style += 'border-top-left-radius:' + diyComponent.value.topRounded * 2 + 'rpx;';
    if (diyComponent.value.topRounded) style += 'border-top-right-radius:' + diyComponent.value.topRounded * 2 + 'rpx;';
    if (diyComponent.value.bottomRounded) style += 'border-bottom-left-radius:' + diyComponent.value.bottomRounded * 2 + 'rpx;';
    if (diyComponent.value.bottomRounded) style += 'border-bottom-right-radius:' + diyComponent.value.bottomRounded * 2 + 'rpx;';
    return style;
})

// 组件框架样式
const headCss = computed(() => {
    let style = '';
    style += 'position:relative;';
    if (diyComponent.value.headImgUrl) {
        style += `background-image:url('${ img(diyComponent.value.headImgUrl) }');`;
        style += 'background-size: cover;background-repeat: no-repeat;';
    }
    return style;
})

const navCss = computed(() => {
    const bgColor = diyComponent.value.headStyle.bgColor || '#fff'
    return {
        'backgroundColor': `${bgColor}`,
        '--active-text-color': `${diyComponent.value.headStyle.selectTextColor}`,
        '--text-color': `${diyComponent.value.headStyle.textColor}`
    }
})

const btnCss = computed(() => {
    let style = '';
    style += 'color:' + diyComponent.value.btnStyle.textColor +';';
    style += 'background-color:' + diyComponent.value.btnStyle.bgColor+';';
    if (diyComponent.value.btnStyle.startBgColor && diyComponent.value.btnStyle.endBgColor) style += `background:linear-gradient(to right, ${ diyComponent.value.btnStyle.startBgColor },${ diyComponent.value.btnStyle.endBgColor });`;
    else style += 'background-color:' + (diyComponent.value.btnStyle.startBgColor || diyComponent.value.btnStyle.endBgColor) + ';';
    style += 'border-radius:' + diyComponent.value.btnStyle.rounded * 2 + 'rpx;';
    return style;
})

const subsidyFn = (data: any) =>{
    let price = Number( data.goods.original_price - data.goods.show_price).toFixed(2)
    return Number(price)
}

// 切换商品分类，查询商品列表数据
const changeGoodsCategory = (item: any) => {
    // 装修模式禁止跳转
    if (diyStore.mode == 'decorate' || loading.value) return;
    selectCategoryIndex.value = item.id

    let obj = {}
    if(item.source == 'all'){
        obj = { source: 'all', num: item.num }
    }else{
        obj = { source: 'custom', pintuan_ids: item.pintuan_ids }
    }
    refreshGoodsList(obj)
}
const loading = ref(false)
const refreshGoodsList = (parameter: any) => {
    loading.value = true
    let data = {
        num: parameter.source == 'all' ? parameter.num : '',
        pintuan_ids: parameter.source == 'custom' ? parameter.pintuan_ids : ''
    }
    getPintuanComponentsGoods(data).then((res) => {
        goodsList.value = res.data
        setTimeout(() => {
            pintuanIndexStore.setPintuanComponentsLoad('pintuanList')
        }, 100);
        loading.value = false
    })
}

const pintuanTotalData = ref()
const getPintuanComponentsTotalFn = () => {
    getPintuanComponentsTotal().then((res) => {
        pintuanTotalData.value = res.data
     })
}

onMounted(() => {
    refresh();
    // 装修模式下刷新
    if (diyStore.mode == 'decorate') {
        pintuanTotalData.value = {
            num: 100,
            member_list:[
                {
                    member:{
                        headimg: ''
                    }
                },
                {
                    member:{
                        headimg: ''
                    }
                }
            ]
        }

        goodsList.value = [
            {
                goods: {
                    cover_thumb_mid: '',
                    title: '商品名称',
                    original_price: 500,
                    show_price: 200
                },
                target_num: 2,
                success_group_num: 100
            },
            {
                goods: {
                    cover_thumb_mid: '',
                    title: '商品名称',
                    original_price: 500,
                    show_price: 200
                },
                target_num: 2,
                success_group_num: 100
            }
        ]
    } else {
        changeGoodsCategory(diyComponent.value.list[0])
        getPintuanComponentsTotalFn()
    }
});

const refresh = () => {
    selectCategoryIndex.value = diyComponent.value.list[0].id
}

const toDetail = (item: any) => {
    if (diyStore.mode == 'decorate') return;
    uni.navigateTo({
        url: '/addon/pintuan/pages/goods/detail?pintuan_id=' + item.id
    })
}

</script>
<style lang="scss" scoped>
.category-item{
    position: relative;
    color: var(--text-color);
    &.active{
        color: var(--active-text-color);
        &::after{
            content: "";
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 8rpx;
            background-color: var(--active-text-color);
            border-top-left-radius: 12rpx;
            border-top-right-radius: 12rpx;
            border-bottom-left-radius: 2rpx;
            border-bottom-right-radius: 2rpx;
            bottom: 16rpx;
            box-shadow: 0 6rpx 10rpx -2rpx var(--active-text-color);
        }
    }
}
</style>
