<template>
    <view class="discount bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">
        <view class="fixed top-0 left-0 w-full z-10 text-[0]">
            <!-- #ifdef MP-WEIXIN -->
            <view class="absolute top-0 left-0 right-0 z-999">
                <top-tabbar :data="param" class="top-header" />
            </view>
            <!-- #endif -->
            <view v-if="config.active_desc" class="side-tab" :style="{top: topStyle}" @click="seckillPopup = true">
                <text class="iconfont iconjishibenV6xx !text-[#fff] icon"></text>
                <text class="desc">秒杀规则</text>
            </view>
            <image :src="img(config.adv_image)" mode="aspectFill" class="w-full" :style="{height: headStyle}" :show-menu-by-longpress="true" />
            <view class="relative w-full h-[110rpx] mt-[-40rpx] z-5" v-if="seckillList.length">
                <view class="rounded-tl-[24rpx] bg-[#F91106]  rounded-tr-[24rpx] h-[96rpx] absolute left-0 bottom-[1rpx]" :style="{ width:totalNavWidth *2 + 'rpx'}"></view>
                <scroll-view :scroll-x="true" class="h-[110rpx] rounded-tl-[24rpx] rounded-tr-[24rpx]" scroll-with-animation :scroll-into-view="'id' + (activeIndex-1 < 0 ? 0 :activeIndex-1)">
                    <view class="flex items-end h-[100rpx] mt-[10rpx]">
                        <view class="h-[100rpx] relative px-[20rpx] active-btn flex-shrink-0" v-for="(item,index) in seckillList" @click="navClick(item,index)" :id="'id' + index">
                            <view class="text-[#fff] px-[20rpx] text-center relative z-10" :class="{'pt-[12rpx]':item.status != 2,'pt-[10rpx]':item.status == 2,'relative left-[-15rpx]':item.status == 2 && index==0 }">
                               <template v-if="item.status != 2">
                                    <view class="text-[40rpx] leading-[40rpx] font-bold px-[10rpx] h-[39rpx] " :class="{'!text-[red]':active == item.id}">{{ item.start_time_format }}</view>
                                    <view class="flex justify-center mt-[5rpx]">
                                        <text class="text-[24rpx] flex-center mt-[6rpx]" :class="{'text-[red]':active==item.id}">{{ item.status_name }}</text>
                                    </view>
                               </template>
                               <template v-else>
                                    <view class="text-[32rpx] leading-[39rpx] font-bold px-[10rpx] h-[39rpx] flex items-center justify-center" :class="{'!text-[red]':active == item.id}">
                                        <image :src="img(active == item.id ?'addon/seckill/goods/icon.png' : 'addon/seckill/goods/icon1.png')" class="w-[32rpx] h-[32rpx] inline-block mr-[4rpx]" mode="widthFix" />
                                        <!-- <image :src="img(active == item.id ?'addon/seckill/goods/icon_title.png' : 'addon/seckill/goods/icon_title1.png')" class="w-[128rpx] h-[38rpx] inline-block" mode="widthFix" /> -->
                                        <text class="font-bold ml-[5rpx]">{{ item.name }}</text>
                                        <text class="font-bold ml-[5rpx]">{{ item.start_time_format }}</text>
                                    </view>
                                    <view class="flex items-center px-[10rpx] justify-center mt-[5rpx]">
                                        <text class="text-[22rpx] text-[#fff]" :class="{'!text-[#333]':active == item.id}">
                                            本场仅剩
                                        </text>
                                        <up-count-down class="text-[#fff] text-[28rpx] ml-[10rpx]" :time="item.countdown" format="DD:HH:mm:ss" @change="onChange">
                                            <view class="flex justify-center items-center h-[39rpx] gap-[6rpx]">
                                                <view class="text-[24rpx] flex items-center justify-center min-w-[32rpx] h-[32rpx] rounded-[6rpx]" :class="{'bg-[red] text-[#fff]':active == item.id, 'bg-[rgba(255,255,255,.4)] text-[#fff]':active != item.id}">
                                                    <text class="min-w-[30rpx] text-center" v-if="timeData.hours">{{ timeData.hours >= 10 ? timeData.hours : '0' + timeData.hours }}</text>
                                                    <text class="min-w-[30rpx] text-center" v-else>00</text>
                                                </view>
                                                <view :class="{'text-[red]':active == item.id}">:</view>
                                                <view class="text-[24rpx] flex items-center justify-center min-w-[32rpx] h-[32rpx] rounded-[6rpx]" :class="{'bg-[red] text-[#fff]':active == item.id, 'bg-[rgba(255,255,255,.4)] text-[#fff]':active != item.id}">
                                                    <text class="min-w-[30rpx] text-center">{{ timeData.minutes >= 10 ? timeData.minutes : '0' + timeData.minutes }}</text>
                                                </view>
                                                <view :class="{'text-[red]':active == item.id}">:</view>
                                                <view class="text-[24rpx] flex items-center justify-center min-w-[32rpx] h-[32rpx] rounded-[6rpx]" :class="{'bg-[red] text-[#fff]':active == item.id, 'bg-[rgba(255,255,255,.4)] text-[#fff]':active != item.id}">
                                                    <text class="min-w-[30rpx] text-center">{{ timeData.seconds < 10 ? '0' + timeData.seconds : timeData.seconds }}</text>
                                                </view>
                                            </view>
                                        </up-count-down>
                                    </view>
                               </template>     
                            </view>
                            <template v-if="active == item.id">
                                <image class="absolute bottom-[-2rpx] left-0 !h-[110rpx] w-full" :src="img(getNavBg(index))" />
                            </template>

                        </view>
                    </view>
                </scroll-view>
            </view>

        </view>

        <mescroll-body v-if="seckillList.length" ref="mescrollRef" :top="mescrollTop" @init="mescrollInit" :down="{ use: false }" @up="getSeckillTimeGoodsFn">
            <view class="relative bg-[#F6F6F6]">
                <view v-if="list.length && !loading" class="h-[200rpx] absolute left-0 right-0 top-0 seckill-list-head"></view>
                <view class="sidebar-margin py-[var(--top-m)] relative">
                    <template v-for="(item,index) in list" :key="index">
                    
                        <view class="bg-[#fff] p-[20rpx] flex rounded-[var(--rounded-big)]" :class="{'mb-[var(--top-m)]':index<list.length-1}" @click="toLink(item)">
                            <view class="w-[240rpx] h-[240rpx] rounded-[var(--goods-rounded-big)] overflow-hidden">
                                <u--image width="240rpx" height="240rpx" :radius="'var(--goods-rounded-big)'" :src="img(item.goods_cover_thumb_small ? item.goods_cover_thumb_small : '')" model="aspectFill">
                                    <template #error>
                                        <image class="rounded-[var(--goods-rounded-big)] overflow-hidden w-[240rpx] h-[240rpx]" :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill" />
                                    </template>
                                </u--image>
                            </view>

                            <view class="ml-[20rpx] flex-1 flex flex-col justify-between">
                                <view>
                                    <view class="text-[28rpx] leading-[1.4] multi-hidden">{{ item.name }}</view>
                                    <view class="flex items-center mb-[10rpx] justify-between text-[24rpx] mt-[10rpx] leading-[24rpx] text-[#999] mr-[10rpx]" v-if="item.sub_title">
                                        <view class="using-hidden">{{ item.sub_title }}</view>
                                    </view>
                                </view>
                                <view>
                                    <view class="flex items-center justify-between mb-[30rpx]">
                                        <view class="flex items-center flex-1 mb-[auto]" v-if="active_state == 2">
                                            <view class="w-[200rpx] line-progress relative">
                                                <!--  #ifdef H5 -->
                                                <view class="absolute right-[5rpx] top-[2rpx] z-3 !text-[14rpx] text-[#FF4040]">
                                                <!--  #endif -->
                                                <!--  #ifndef  H5 -->
                                                <view class="absolute right-[5rpx] top-[4rpx] z-3 !text-[14rpx] text-[#FF4040]">
                                                <!--  #endif -->   
                                                    <text class="">已抢{{ calculateNumPercentage(item) }}%</text>
                                                </view>
                                                <u-line-progress :percentage="calculateNumPercentage(item)" height="10" :showText="false" activeColor="#FFDDD4" inactiveColor="#fff">       
                                                </u-line-progress>
                                            </view>
                                        </view>
                                        <view v-if="item.defaultSku.sum_num >0" class="text-[24rpx] leading-[24rpx] text-[#999] ml-auto" >
                                            <view>限购{{item.defaultSku.sum_num}}{{ item.unit }}</view>
                                        </view>

                                    </view>
                                    <view class="flex items-end justify-between h-[66rpx] bg-[#FFF2EF] rounded-[12rpx] relative">
                                        <view class="bg-[#FFE167] rounded-t-[20rpx] rounded-br-[20rpx]  h-[30rpx] leading-[30rpx] text-[#666] text-[22rpx] absolute left-[0] top-[-20rpx] px-[10rpx]">
                                            <text class="text-[22rpx] line-through truncate">￥{{item.defaultSku.price}}</text>
                                        </view>
                                        <view class="text-[var(--price-text-color)] flex items-baseline pl-[16rpx] pb-[12rpx] w-[210rpx] truncate">
                                            <text class="text-[20rpx] whitespace-nowrap leading-[28rpx] ml-[4rpx] price-font">秒杀价</text>
                                            <text class="text-[24rpx] leading-[26rpx] font-500 mr-[4rpx] price-font">￥</text>
                                            <text class="text-[40rpx] leading-[40rpx] font-500 price-font">{{ parseFloat(item.defaultSku.seckill_price).toFixed(2).split('.')[0] }}.</text>
                                            <text class="text-[24rpx] leading-[28rpx] font-500 price-font">{{ parseFloat(item.defaultSku.seckill_price).toFixed(2).split('.')[1] }}</text>
                                        </view>
                                        <view v-if="active_state == 2" class="absolute top-0 right-0 rounded-r-[12rpx] h-full w-[142rpx] flex justify-end items-center text-[#fff] text-[26rpx] font-bold" :style="{ 'background-image': 'url(' + img('addon/seckill/goods/list_progress.png') + ')', 'background-size': 'auto 100%', 'background-repeat': 'no-repeat'}">
                                            <text class="pr-[15rpx]">立即抢</text>
                                        </view>
                                        <view v-if="active_state == 0" class="absolute top-0 right-0 rounded-r-[12rpx] w-[142rpx] text-[26rpx] h-full whitespace-nowrap flex justify-end items-center text-[#999] font-500" :style="{ 'background-image': 'url(' + img('addon/seckill/goods/list_end.png') + ')', 'background-size': 'auto 100%', 'background-repeat': 'no-repeat'}">
                                            <text class="pr-[15rpx]">已结束</text>
                                        </view>
                                        <view v-if="active_state == 1" class="absolute top-0 right-0 rounded-r-[12rpx] w-[142rpx] text-[26rpx] h-full whitespace-nowrap flex justify-end items-center text-[#fff] font-500" :style="{ 'background-image': 'url(' + img('addon/seckill/goods/list_not_started.png') + ')', 'background-size': 'auto 100%', 'background-repeat': 'no-repeat'}">
                                            <text class="pr-[15rpx]">未开始</text>
                                        </view>
                                        <image :src="img('addon/seckill/goods/list_center.png')" class="w-[33rpx] h-[66rpx] ml-[20rpx] absolute top-[0] right-[112rpx]" />
                                    </view>
                                </view>
                                
                                
                            </view>
                        </view>
                    </template>
                    <mescroll-empty v-if="!list.length && !loading" :option="{tip : '暂无商品，请看看其他商品吧！'}"></mescroll-empty>
                </view>
            </view>
        </mescroll-body>

        <view v-if="!seckillList.length && !loading" class="h-[calc(100vh-550rpx)]" :style="{'padding-top':mescrollTop}">
            <mescroll-empty :option="{tip : '暂无商品，请看看其他商品吧！','btnText': '去逛逛'}" @emptyclick="redirect({ url: '/addon/seckill/pages/index' })"></mescroll-empty>
        </view>
        <view @touchmove.prevent.stop>
            <u-popup :show="seckillPopup" @close="closeFn" mode="center" round="var(--rounded-big)">
                <view class="w-[570rpx] px-[32rpx] popup-common center">
                    <view class="title">秒杀规则</view>
                    <scroll-view :scroll-y="true" class="px-[30rpx] box-border max-h-[260rpx]">
                        <view class="text-[28rpx] leading-[40rpx] mb-[20rpx]">{{ config.active_desc }}</view>
                    </scroll-view>
                    <view class="btn-wrap !pt-[40rpx]">
                        <button class="primary-btn-bg w-[480rpx] h-[70rpx] text-[26rpx] leading-[70rpx] rounded-[35rpx] !text-[#fff] font-500" @click="seckillPopup = false">我知道了</button>
                    </view>
                </view>
            </u-popup>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, computed ,nextTick} from 'vue'
import { img, redirect, pxToRpx ,handleOnloadParams} from '@/utils/common';
import { getSeckillTime, getSeckillTimeGoods ,getSeckillConfig} from '@/addon/seckill/api/goods'
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue'
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue'
import useMescroll from '@/components/mescroll/hooks/useMescroll.js'
import { onLoad,onPageScroll, onReachBottom } from '@dcloudio/uni-app'
import { topTabar } from '@/utils/topTabbar'
import useSystemStore from "@/stores/system";

const systemStore = useSystemStore()
const topStyle = computed(() => {
    let style = pxToRpx(Number(systemStore.menuButtonInfo.height) + systemStore.menuButtonInfo.top + 8) + 30 + 'rpx;'
    return style
})
const headStyle = computed(() => {
    let isHeight = systemStore.menuButtonInfo.height && systemStore.menuButtonInfo.top
    let style = isHeight ? (pxToRpx(Number(systemStore.menuButtonInfo.height)) + pxToRpx(systemStore.menuButtonInfo.top) + pxToRpx(8) + 358) + 'rpx' : '490rpx'
    return style
})

const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom)
const seckillList = ref<Array<Object>>([])
const active = ref<number>(0)
const active_name = ref<String>('')
const active_state = ref<String>('')
const list = ref<Array<Object>>([]);
const loading = ref<boolean>(true);
  
const timeData = ref({});
// 定义 onChange 方法
const onChange = (e) => {
    timeData.value = e;
};

/********* 自定义头部 - start ***********/
const topTabarObj = topTabar()
let param = topTabarObj.setTopTabbarParam({ title: '限时秒杀' })
/********* 自定义头部 - end ***********/
let pageParameter = {};

onLoad((option: any) => {
    // #ifdef MP-WEIXIN
    // 处理小程序场景值参数
    option = handleOnloadParams(option);
    // #endif
    pageParameter = option;
})
const getSeckillTimeFn = () => {
    getSeckillTime().then((res: any) => {
        seckillList.value = res.data
        if (seckillList.value && seckillList.value.length) {
            seckillList.value.sort((a: any, b: any) => {
                return a.start_time - b.start_time
            })
        }
        calculateHeight();
        calculateNavWidth()
        if (seckillList.value && seckillList.value.length) {
            let tabData = seckillList.value[0]
            let activeIndex = 0
            seckillList.value.forEach((item: any,index: number) => {
                const now = new Date();

                // 提取当前的时、分、秒
                const hours = now.getHours();
                const minutes = now.getMinutes();
                const seconds = now.getSeconds();

                // 计算当天已过的总秒数（从00:00:00到现在）
                const currentTimeSeconds = hours * 3600 + minutes * 60 + seconds;
                item.countdown = (item.end_time - currentTimeSeconds) * 1000;
                if (item.status == 2) {
                    tabData = item
                    activeIndex = index                  
                }
            })
            if (pageParameter.time_id) {
                tabData = seckillList.value.find((item: any) => item.id == pageParameter.time_id) || tabData
                activeIndex = seckillList.value.findIndex((item: any) => item.id == pageParameter.time_id) || activeIndex
            }else if (seckillList.value.findIndex((item: any) => item.status === 2) === -1) {
                const now = new Date();
                const currentTimeSeconds = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds();
                
                let nearestItem: any = null;
                let nearestIndex = -1;
                let minTimeDiff = Infinity; // 初始化为无穷大，方便后续比较
                
                seckillList.value.forEach((item: any, index: number) => {
                    if (item.status === 1) { // 只处理即将开始的场次
                    // 计算距离开始的时间差（秒）
                    const timeDiff = item.start_time - currentTimeSeconds;
                    
                    // 如果时间差大于0（未来的时间），且比当前记录的最小时间差更小
                    if (timeDiff > 0 && timeDiff < minTimeDiff) {
                        minTimeDiff = timeDiff;
                        nearestItem = item;
                        nearestIndex = index;
                    }
                }
            });
                
                // 如果找到了最近的即将开始的场次，则选中它
                if (nearestItem) {
                    tabData = nearestItem;
                    activeIndex = nearestIndex;
                }
            }
            navClick(tabData,activeIndex)
        } else {
            loading.value = false
        }
    })
}

getSeckillTimeFn()

// 获取秒杀配置信息
const config = ref<any>({})
const getSeckillConfigFn = () => {
    getSeckillConfig().then((res: any) => {
        config.value = res.data
    })
}
getSeckillConfigFn()
const seckillPopup = ref(false)
const closeFn = () => {
    seckillPopup.value = false
}
const activeIndex = ref(0)
const navClick = (item: any ,index:any) => {
    active.value = item.id
    active_name.value = item.status_name
    active_state.value = item.status
    activeIndex.value = index
    list.value = []
    getMescroll()?.resetUpScroll();
    uni.pageScrollTo({
        scrollTop: 0, //距离页面顶部的距离
        duration: 1
    });
}

const getSeckillTimeGoodsFn = (mescroll: any) => {
    if (seckillList.value.length == 0) return;

    loading.value = true;
    let data: object = {
        page: mescroll.num,
        limit: mescroll.size,
        id: active.value
    };

    getSeckillTimeGoods(data).then((res: any) => {
        let newArr = (res.data.data as Array<Object>).map((el: any) => {
            return el
        })
        //设置列表数据
        if (mescroll.num == 1) {
            list.value = []; //如果是第一页需手动制空列表
        }
        list.value = list.value.concat(newArr);
        mescroll.endSuccess(newArr.length);
        loading.value = false;
    }).catch(() => {
        loading.value = false;
        mescroll.endErr(); // 请求失败, 结束加载
    })
}
const toLink = (item: any) => {
    /*if (item.discount_status != 'active') {
        uni.showToast({ title: `活动${ item.discount_status_name }`, icon: 'none' })
        return;
    }*/
    redirect({ url: '/addon/seckill/pages/goods/detail', param: { sku_id: item.defaultSku.sku_id, time_id: active.value,seckill_id: item.seckill_id} })
}

const mescrollTop = ref('')
const calculateHeight = () => {
    let isHeight = systemStore.menuButtonInfo.height && systemStore.menuButtonInfo.top
    mescrollTop.value = isHeight ? (pxToRpx(Number(systemStore.menuButtonInfo.height)) + pxToRpx(systemStore.menuButtonInfo.top) + pxToRpx(8) + 358) + (seckillList.value.length ? 70 : 0) + 'rpx' : (seckillList.value.length ? '560rpx' : '490rpx')
}
const calculateNumPercentage = (item: any) => {
    const percentage = (item.defaultSku.order_num / item.defaultSku.sum_stock) * 100 || 0;
    // 确保返回字符串类型的两位小数
    return percentage.toFixed(2); 
}
const getNavBg = (index) => {
    if (index === 0) return 'addon/seckill/goods/nav-left.png'
    if (index === seckillList.value.length - 1 && isFullNav.value) return 'addon/seckill/goods/nav-right.png'
    if (index === seckillList.value.length - 1 && !isFullNav.value) return 'addon/seckill/goods/nav-center.png'
    return 'addon/seckill/goods/nav-center.png'
}

const isFullNav = ref(false) 
const totalNavWidth = ref(0)
// 计算导航项总宽度
const calculateNavWidth = () => {
    nextTick(() => {
        if (seckillList.value.length == 0) return; // 如果没有数据，则不执行
        const query = uni.createSelectorQuery()
        query.selectAll('.active-btn').boundingClientRect((rects) => {
            if (rects && rects.length > 0) {
                const screenWidth = systemStore.systemInfo.windowWidth; // 屏幕宽度
                // 计算总宽度（包含间距）
                const totalWidth = rects.reduce((sum, rect) => sum + rect.width, 0)          
                isFullNav.value = totalWidth > screenWidth;
                totalNavWidth.value = isFullNav.value ? totalWidth : screenWidth;
            } else {
                console.error('获取导航项宽度失败')
            }
        }).exec()
    });
}
</script>

<style lang="scss" scoped>
.active {
    padding: 0 14rpx;
    line-height: 34rpx;
    border-radius: 29rpx;
    background: linear-gradient(94deg, var(--primary-color) 0%, var(--primary-color) 99%), #EF000C;
}
.seckill-list-head {
    background: linear-gradient(180deg, #FFFEFB 40%, #F6F6F6 100%);
}
.line-progress{
    border:2rpx solid #FF4040 !important;
    border-radius:20rpx !important;
}
</style>
