<template>
    <view class="overflow-hidden relative"  v-if="diyComponent && diyComponent.skuList && Object.keys(diyComponent.skuList).length">
        <view v-if="diyStore.mode != 'decorate'" class="tab-bar-placeholder"></view>
        <view :style="warpCss" class="button-wrap w-[100%] flex justify-between box-border tab-bar z-10 items-center pl-[32rpx]" :class="{'!fixed left-0 bottom-0': diyStore.mode != 'decorate'}">
            <view class="flex items-center">
                <view v-if="diyComponent?.diyInfo.menuContent.includes('index')" class="flex flex-col justify-center items-center mr-[38rpx]" @click="redirect({ url: '/addon/seckill/pages/index', mode: 'reLaunch' })">
                    <view class="nc-iconfont nc-icon-shouyeV6xx11 text-[36rpx]"></view>
                    <text class="text-[20rpx]  whitespace-nowrap mt-[10rpx] ">首页</text>
                </view>
                <view v-if="diyComponent?.diyInfo.menuContent.includes('service')" class="flex flex-col justify-center items-center mr-[38rpx]" @click="servicesPopFn">
                    <text class="nc-iconfont text-[36rpx] nc-icon-kefuV6xx-1 text-[#303133]"></text>
                    <text class="text-[20rpx]  whitespace-nowrap mt-[10rpx]">客服</text>
                </view>
                <view v-if="diyComponent?.diyInfo.menuContent.includes('share')" class="flex flex-col justify-center items-center mr-[38rpx]"  @click="openShareFn">
                    <text class="nc-iconfont text-[36rpx] nc-icon-fenxiangV6xx text-[#303133]"></text>
                    <text class="text-[20rpx]  whitespace-nowrap mt-[10rpx]">分享</text>
                </view>
            </view>
            <template v-if="diyStore.mode == 'decorate'">
                <button v-if="diyComponent.diyInfo.isShowOriginalBuy" :style="originalBuyBtnStyle" 
                     class="btn-style flex-1 font-500">
                     {{diyComponent.diyInfo.originalBuyName}}
                </button>
                <button :style="buyBtnStyle" 
                    class="btn-style flex-1 font-500 text-[26rpx]"
                    @click="buyFn('buy_now')">{{diyComponent.diyInfo.buyName}}
                </button>
            </template>
            <template v-else>     
                <button v-if="diyComponent.diyInfo.isShowOriginalBuy" @click="buyFn('buy_now_single')" :style="originalBuyBtnStyle" 
                         class="btn-style font-500 flex-1"
                >{{diyComponent.diyInfo.originalBuyName}}
                </button>   
                <button v-if="isShowSingleSku && discountTime > 0 && diyComponent.seckill.status==1&&diyComponent.seckill_time.status==2" :style="buyBtnStyle" 
                    class="btn-style font-500 flex-1" @click="buyFn('buy_now')">{{diyComponent.diyInfo.buyName}}
                </button>
                <button v-else-if="diyComponent.seckill.status==0" :style="buyBtnStyle" class="btn-style font-500 flex-1 !bg-[#ccc]"
                >活动未开始
                </button>
                <button v-else-if="diyComponent.seckill.status==1&&diyComponent.seckill_time.status==0" :style="buyBtnStyle"
                        class="btn-style font-500 flex-1 !text-[#fff] !bg-[#ccc]">秒杀结束
                </button>
                <button v-else-if="diyComponent.seckill.status==1&&diyComponent.seckill_time.status==1" :style="buyBtnStyle"
                        class="btn-style font-500 flex-1 !text-[#fff] !bg-[#ccc]">即将开抢
                </button>
                <button v-else-if="!isShowSingleSku" class="btn-style flex-1 !text-[#fff] !bg-[#ccc]" :style="buyBtnStyle">已售罄</button>
            </template>
        </view>
        <online-service ref="onlineServiceRef" :data="config"></online-service>
        <!-- 装修时，防止点击 -->
        <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, computed, watch, onMounted, nextTick } from 'vue';
import { redirect, img } from '@/utils/common';
import useDiyStore from '@/app/stores/diy';
import useMemberStore from '@/stores/member'
import useSeckillGoodsDetailStore from '@/addon/seckill/stores/goodsDetail'
import { getSeckillConfig } from '@/addon/seckill/api/goods'
import onlineService from '@/components/online-service/online-service'


const props = defineProps(['component', 'index', 'value', 'global']);
const diyStore = useDiyStore();
const emits = defineEmits(['loadingFn', 'update:componentIsShow']); //商品数据加载完成之后触发
const sendMessageTitle = ref('')
const sendMessagePath = ref('')
const sendMessageImg = ref('')
const discountTime = ref(0)

// 会员信息
const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)

const diyComponent = computed(() => {
    if (diyStore.mode == 'decorate') {
        const obj = {
            skuList: [{}]
        }
        emits('update:componentIsShow', true)
        return Object.assign({},{diyInfo:diyStore.value[props.index]},obj);
    } else {
        emits('update:componentIsShow', true)
        return Object.assign({}, {diyInfo:props.component}, useSeckillGoodsDetailStore().goodsDetail);
    }
})

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

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

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

// 立即购买按钮
const buyBtnStyle = computed(() => {
    let style = '';
    // 活动开始采用后台设置的背景颜色和文字颜色
    if(diyStore.mode == 'decorate' || (isShowSingleSku.value && discountTime.value > 0 && diyComponent.value.seckill.status==1&&diyComponent.value.seckill_time.status==2)){
        if (diyComponent.value.diyInfo.buyStyle.startColor && diyComponent.value.diyInfo.buyStyle.endColor) style += `background:linear-gradient(${ diyComponent.value.diyInfo.buyStyle.gradientAngle },${ diyComponent.value.diyInfo.buyStyle.startColor },${ diyComponent.value.diyInfo.buyStyle.endColor });`;
        else style += 'background-color:' + (diyComponent.value.diyInfo.buyStyle.startColor || diyComponent.value.diyInfo.buyStyle.endColor) + ';';

        if (diyComponent.value.diyInfo.buyStyle.textColor) style += 'color:' + diyComponent.value.diyInfo.buyStyle.textColor+';';
    }
    if (diyComponent.value.diyInfo.buyStyle.fontSize) style += 'font-size:' + diyComponent.value.diyInfo.buyStyle.fontSize * 2 + 'rpx !important;';

    if (diyComponent.value.goods_type == 'real' || (diyComponent.value.goods_type == 'virtual' && diyComponent.value.virtual_receive_type != 'verify')){
        style += 'width:200rpx !important;';
    }else{
        style += 'width:400rpx !important;';
    }
    return style;
})


// 原价购买按钮
const originalBuyBtnStyle = computed(() => {
    let style = '';
    if (diyComponent.value.diyInfo.originalBuyStyle.startColor && diyComponent.value.diyInfo.originalBuyStyle.endColor) style += `background:linear-gradient(${ diyComponent.value.diyInfo.originalBuyStyle.gradientAngle },${ diyComponent.value.diyInfo.originalBuyStyle.startColor },${ diyComponent.value.diyInfo.originalBuyStyle.endColor });`;
    else style += 'background-color:' + (diyComponent.value.diyInfo.originalBuyStyle.startColor || diyComponent.value.diyInfo.originalBuyStyle.endColor) + ';';

    if (diyComponent.value.diyInfo.originalBuyStyle.textColor) style += 'color:' + diyComponent.value.diyInfo.originalBuyStyle.textColor+' !important;';
    if (diyComponent.value.diyInfo.originalBuyStyle.fontSize) style += 'font-size:' + diyComponent.value.diyInfo.originalBuyStyle.fontSize * 2 + 'rpx !important;';

    if (diyComponent.value.goods_type == 'real' || (diyComponent.value.goods_type == 'virtual' && diyComponent.value.virtual_receive_type != 'verify')){
        style += 'width:200rpx !important;';
    }else{
        style += 'width:400rpx !important;';
    }
    return style;
})

// 商品限购
const maxBuy = ref(-1);
const goodsMaxBuy = (data: any = {}) => {
    // 限购 - 是否开启限购
    if (data.is_limit && userInfo.value && data.stock > 0) {
        if (data.max_buy) {
            let max_buy = 0;
            if (data.limit_type == 1) { //单次限购
                max_buy = data.max_buy;
            } else { // 单人限购
                let buyVal = data.max_buy - (data.has_buy || 0);
                max_buy = buyVal > 0 ? buyVal : 0;
            }

            if (max_buy > data.stock) {
                maxBuy.value = data.stock
            } else if (max_buy <= data.stock) {
                maxBuy.value = max_buy;
            }
        }
    }
}

// 判断单规格库存是否为0
const isShowSingleSku = computed(() => {

    let isSingleSpec = false // 是否为单规格，true：多规格，false：单规格
    diyComponent.value.skuList.forEach((item: any, index: any) => {
        if (item.sku_spec_format) {
            isSingleSpec = true
        }
    })

    // 单规格，库存为0，显示已售罄
    if (!isSingleSpec && diyComponent.value.defaultSku.seckill_stock <= 0) {
        return false;
    } else if (!isSingleSpec && diyComponent.value.defaultSku.seckill_stock > 0) {
        // 单规格，库存大于0，可以购买
        return true;
    }
    return true;
})

const buyFn = (type: any) => {
    useSeckillGoodsDetailStore().setGoodsDetail({isOpenSkuBuy: true, skuBuyType: type});
}

/************* 分享海报-start **************/
const openShareFn = () => {
    useSeckillGoodsDetailStore().setGoodsDetail({isOpenSharePoster: true});
}
/************* 分享海报-end **************/

onMounted(() => {
    refresh();
    // 装修模式下刷新
    if (diyStore.mode == 'decorate') {
        watch(
            () => diyComponent.value,
            (newValue, oldValue) => {
                if (newValue && newValue.diyInfo && newValue.diyInfo.componentName == 'SeckillActivityGoodsDetailBottom') {
                    nextTick(() => {

                    })
                }
            }
        )
    } else {
        refresh();
        initFn()
        getSeckillConfigFn()
    }
    // 商品限购
    goodsMaxBuy(diyComponent.value);
});

const initFn = () => {
    sendMessageTitle.value = diyComponent.value.name
    sendMessagePath.value = '/addon/seckill/pages/goods/detail?sku_id=' + diyComponent.value.sku_id;
    if (diyComponent.value.type) {
        sendMessagePath.value += '&type=' + diyComponent.value.type;
    }
    sendMessageImg.value = img(diyComponent.value.goods_cover_thumb_mid) 

    // 活动进行中
    if (diyComponent.value.seckill.status == 1) {
        // 场次秒杀中
        if (diyComponent.value.seckill_time.status == 2) {
            // 秒杀倒计时
            // 获取当前时间
            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;
            discountTime.value = (diyComponent.value.seckill_time.end_time - currentTimeSeconds) * 1000;
            // 处理负数情况（如果当前时间已超过结束时间，剩余时间为0）
            if (discountTime.value < 0) {
                discountTime.value = 0;
            }
        } else if (diyComponent.value.seckill_time.status == 1) {
            // 场次即将开始
            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;
            discountTime.value = (diyComponent.value.seckill_time.start_time - currentTimeSeconds) * 1000;
            // 处理负数情况（如果当前时间已超过结束时间，剩余时间为0）
            if (discountTime.value < 0) {
                discountTime.value = 0;
            }
        }

    }
}

const config = ref({})
const getSeckillConfigFn = () => {
    getSeckillConfig().then((res: any) => {
        config.value = res.data
    })
}
const onlineServiceRef = ref()
const servicesPopFn = ()=>{
    onlineServiceRef.value?.open()
}

const refresh = () => {
}
</script>
<style lang="scss" scoped>
.tab-bar-placeholder {
    padding-bottom: calc(constant(safe-area-inset-bottom) + 100rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 100rpx);
}
.tab-bar {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
}
.btn-style{
    height: 100rpx;
    border-radius: 0 !important;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 36rpx !important;
}
.button-wrap{
   box-shadow: 0 4rpx 12rpx rgba(0,0,0,.3); 
}
</style>
