<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="border-[0] border-t-[2rpx] border-solid border-[#f5f5f5] w-[100%] flex justify-between pl-[32rpx] pr-[4rpx] box-border tab-bar z-10 items-center" :class="{'fixed left-0 bottom-0': diyStore.mode != 'decorate'}">
            <view class="flex items-center">
                <view v-if="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="menuContent.includes('service')" class="flex flex-col justify-center items-center mr-[38rpx]" @click="servicesPopFn">
                    <!-- @click="redirect({ url: '/app/pages/member/contact' })" -->
                    <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="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>
                <!-- #ifdef MP-WEIXIN -->
                <!-- <view>
                    <nc-contact
                        :send-message-title="sendMessageTitle"
                        :send-message-path="sendMessagePath"
                        :send-message-img="sendMessageImg">
                        <view class="flex flex-col justify-center items-center mr-[38rpx]">
                            <text class="nc-iconfont nc-icon-kefuV6xx-1 text-[36rpx]"></text>
                            <text class="text-[20rpx] mt-[10rpx]">客服</text>
                        </view>
                    </nc-contact>
                </view> -->
                <!-- #endif -->
            </view>
            <template v-if="diyStore.mode == 'decorate'">
                <button v-if="diyComponent.isShowOriginalBuy" :style="originalBuyBtnStyle" 
                     class="flex-1 !h-[70rpx] font-500 primary-btn-bg !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border">
                     {{diyComponent.originalBuyName}}
                </button>
                <button :style="buyBtnStyle" 
                    class="flex-1 !h-[70rpx] font-500 text-[26rpx] !text-[#fff] primary-btn-bg !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border"
                    @click="buyFn('buy_now')">{{diyComponent.buyName}}
                </button>
            </template>
            <template class="flex flex-1" v-else>     
                <button v-if="diyComponent.isShowOriginalBuy" @click="buyFn('buy_now_single')" :style="originalBuyBtnStyle" 
                         class="flex-1 !h-[70rpx] font-500 text-[26rpx] !text-[#fff] primary-btn-bg !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border"
                >{{diyComponent.originalBuyName}}
                </button>   
                <button v-if="isShowSingleSku && discountTime > 0 && diyComponent.seckill.status==1&&diyComponent.seckill_time.status==2" :style="buyBtnStyle" 
                    class="flex-1 !h-[70rpx] font-500 text-[26rpx] !text-[#fff] primary-btn-bg !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border"
                    @click="buyFn('buy_now')">{{diyComponent.buyName}}
                </button>
                <button v-else-if="diyComponent.seckill.status==0"
                        class="flex-1 !h-[70rpx] font-500 text-[26rpx] !text-[#fff] !bg-[#ccc] !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border"
                >活动未开始
                </button>
                <button v-else-if="diyComponent.seckill.status==1&&diyComponent.seckill_time.status==0"
                        class="flex-1 !h-[70rpx] font-500 text-[26rpx] !text-[#fff] !bg-[#ccc] !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border"
                >秒杀结束
                </button>
                <button v-else-if="diyComponent.seckill.status==1&&diyComponent.seckill_time.status==1"
                        class="flex-1 !h-[70rpx] font-500 text-[26rpx] !text-[#fff] !bg-[#ccc] !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border"
                >即将开抢
                </button>
                <button v-else-if="!isShowSingleSku"
                        class="flex-1 !h-[70rpx] font-500 text-[26rpx] !text-[#fff] !bg-[#ccc] !m-0 !mr-[16rpx] leading-[70rpx] rounded-full remove-border"
                >已售罄
                </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: [{}]
        }
        return Object.assign({},obj,diyStore.value[props.index]);
    } else {
        emits('update:componentIsShow', true)
        return Object.assign({}, props.component, useSeckillGoodsDetailStore().goodsDetail);
    }
})

const warpCss = computed(() => {
    let style = '';
    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 buyBtnStyle = computed(() => {
    let style = '';
    if (diyComponent.value.buyStyle.startColor && diyComponent.value.buyStyle.endColor) style += `background:linear-gradient(${ diyComponent.value.buyStyle.gradientAngle },${ diyComponent.value.buyStyle.startColor },${ diyComponent.value.buyStyle.endColor });`;
    else style += 'background-color:' + (diyComponent.value.buyStyle.startColor || diyComponent.value.buyStyle.endColor) + ';';

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

    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.originalBuyStyle.startColor && diyComponent.value.originalBuyStyle.endColor) style += `background:linear-gradient(${ diyComponent.value.originalBuyStyle.gradientAngle },${ diyComponent.value.originalBuyStyle.startColor },${ diyComponent.value.originalBuyStyle.endColor });`;
    else style += 'background-color:' + (diyComponent.value.originalBuyStyle.startColor || diyComponent.value.originalBuyStyle.endColor) + ';';

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

    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) => {
    console.log("buy -- 购买 - button")
    useSeckillGoodsDetailStore().setGoodsDetail({isOpenSkuBuy: true, skuBuyType: type});
}

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

onMounted(() => {
    refresh();
    // 装修模式下刷新
    if (diyStore.mode == 'decorate') {
        watch(
            () => diyComponent.value,
            (newValue, oldValue) => {
                if (newValue && newValue.componentName == 'SeckillGoodsDetailBottom') {
                    nextTick(() => {
                        menuContent.value = (typeof diyComponent.value?.menuContent == 'object') ? diyComponent.value?.menuContent : diyComponent.value?.menuContent.split(',');
                    })
                }
            }
        )
    } else {
        refresh();
        initFn()
        getSeckillConfigFn()
    }
    // 商品限购
    goodsMaxBuy(diyComponent.value);
});

const menuContent = ref([])
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) 
    menuContent.value = (typeof diyComponent.value?.menuContent == 'object') ? diyComponent.value?.menuContent : diyComponent.value?.menuContent.split(',');

    // 活动进行中
    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 = () => {
    menuContent.value = (typeof diyComponent.value?.menuContent == 'object') ? diyComponent.value?.menuContent : diyComponent.value?.menuContent.split(',');
}
</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-top: 16rpx;
    padding-bottom: calc(constant(safe-area-inset-bottom) + 16rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 16rpx);
}
</style>
