<template>
    <view :style="warpCss" class="overflow-hidden relative p-[24rpx]" v-if="diyComponent && diyComponent.skuList && Object.keys(diyComponent.skuList).length">
        <view :style="componentCss">
            <view class="flex overflow-hidden">
                <image v-if="diyComponent.goods_cover_thumb_mid" class="w-[220rpx] h-[220rpx] rounded-[10rpx]"
                        :src="img(diyComponent.goods_cover_thumb_mid)" :mode="'aspectFill'"
                        @error="diyComponent.goods_cover_thumb_mid='static/resource/images/diy/shop_default.jpg'"/>
                <image v-else class="w-[220rpx] h-[220rpx] rounded-[var(--rounded-mid)]" :src="img('static/resource/images/diy/shop_default.jpg')" :mode="'aspectFill'"/>

                <view class="flex-1 flex flex-col ml-[20rpx] py-[6rpx]">
                    <view class="text-[30rpx] text-[#333] leading-[40rpx] multi-hidden mb-[10rpx]">
                        {{ diyComponent.name }}
                    </view>
                    <view class="text-[24rpx] text-[#999] leading-[30rpx] using-hidden mb-[20rrpx]">
                        {{ diyComponent.sub_title }}
                    </view>
                    <view class="mt-auto flex items-baseline flex-wrap mt-[auto]">
                        <view class="text-[var(--price-text-color)] price-font flex items-baseline mr-[10rpx]">
                            <text class="text-[24rpx] font-500 mr-[4rpx]">秒杀价￥</text>
                            <text class="text-[40rpx] font-500">{{ Number(goodsPrice).toFixed(2).split('.')[0] }}</text>
                            <text class="text-[24rpx] font-500">.{{ Number(goodsPrice).toFixed(2).split('.')[1] }}</text>
                        </view>
                        <view class="text-[#999999]">
                            <text class="text-[20rpx] mr-[6rpx]">原价</text>
                            <text class="text-[24rpx] line-through leading-[36rpx]">￥{{ diyComponent.defaultSku.price
                                }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <view v-if="diyComponent.diyInfo.dividerLine.isShow" class="goods-divider"></view>
            <view class="flex flex-col mb-[26rpx]" :class="{'mt-[30rpx]': !diyComponent.diyInfo.dividerLine.isShow}" v-if="diyComponent.refund_type_name && diyComponent.diyInfo.serviceConfig.includes('guarantee')">
                <view class="text-[red] text-[36rpx] font-bold mb-[20rpx]">服务保障</view>
                <view class="flex items-center">
                    <text class="iconfont icontuihuoV6mm !text-[28rpx] pt-[4rpx] mr-[10rpx]"></text>
                    <text class="text-[28rpx]">{{ diyComponent.refund_type_name }}</text>
                </view>
            </view>
            <view class="flex flex-col mb-[26rpx]" v-if="diyComponent.expire_desc">
                <view class="text-[red] text-[36rpx] font-bold mb-[20rpx]">核销码</view>
                <view class="flex items-center">
                    <text class="iconfont iconhexiao !text-[30rpx] pt-[4rpx] mr-[10rpx]"></text>
                    <text class="text-[28rpx]">{{ diyComponent.expire_desc }}</text>
                </view>
            </view>
            <view class="flex flex-col" v-if="diyComponent.seckill.seckill_remark && diyComponent.diyInfo.serviceConfig.includes('instructions')">
                <view class="text-[red] text-[36rpx] font-bold mb-[20rpx]">购买须知</view>
                <u-parse v-if="diyStore.mode != 'decorate'" :content="diyComponent.seckill.seckill_remark" :tagStyle="{img: 'vertical-align: top;width:100%;',p:'overflow: hidden;word-break:break-word;' }"></u-parse>
                <text v-else class="text-[28rpx]">{{ diyComponent.seckill.seckill_remark }}</text>
            </view>

            <button v-if="diyComponent.diyInfo.buyBtn.isShow" class="mt-[26rpx] h-[80rpx] text-[32rpx] flex items-center justify-center" :style="buyBtnStyle" @click="buyFn()">{{ diyComponent.diyInfo.buyBtn.text }}</button>
            <!-- 装修时，防止点击 -->
            <view v-if="diyStore.mode == 'decorate'" class="absolute z-10 top-0 right-0 bottom-0 left-0"></view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { img } from '@/utils/common';
import useDiyStore from '@/app/stores/diy';
import useSeckillGoodsDetailStore from '@/addon/seckill/stores/goodsDetail'

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

const diyComponent = computed(() => {
    if (diyStore.mode == 'decorate') {
        const obj = {
            skuList: [{}],
            seckill: {
                seckill_remark: '购买须知'
            },
            refund_type_name: '随时退', 
            expire_desc: '购买之后10天有效',
            name: '标题', 
            sub_title: '副标题', 
            defaultSku: {
                price: '100.00',
                seckill_show_price: '10.00'
            }
        }
        return Object.assign({}, {diyInfo: diyStore.value[props.index]}, obj);
    } else {
        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 isShowTemplate = ref(false);
const isGoodsPropertyTemp = () => {
    isShowTemplate.value = false;
    if (
        (diyComponent.value.seckill?.seckill_remark && diyComponent.value?.diyInfo.serviceConfig.includes('instructions')) ||
        (diyComponent.value.refund_type_name && diyComponent.value?.diyInfo.serviceConfig.includes('guarantee')) ||
        (diyComponent.value.expire_desc) ||
        diyStore.mode == 'decorate'
        ) {
        isShowTemplate.value = true;
    }
    emits('update:componentIsShow', isShowTemplate.value)
}


// 商品价格
const goodsPrice = computed(() => {
    return diyComponent.value.defaultSku.seckill_show_price;
})

const buyBtnStyle = computed(() => {
    let style = '';
    style += 'border-radius:' + diyComponent.value.diyInfo.buyBtn.rounded * 2 + 'rpx;';
    style += 'background-color:' + diyComponent.value.diyInfo.buyBtn.bgColor + ';'; 
    style += 'color:' + diyComponent.value.diyInfo.buyBtn.textColor + ';'; 
    style += 'font-size:' + diyComponent.value.diyInfo.buyBtn.fontSize * 2 + 'rpx;'; 
    return style
})

const buyFn = () => {
    let type = ''
    if(isShowSingleSku.value && discountTime.value > 0 && diyComponent.value.seckill.status==1&&diyComponent.value.seckill_time.status==2){
        type = 'buy_now'
    }else{
        type = 'buy_now_single'
    }
    useSeckillGoodsDetailStore().setGoodsDetail({isOpenSkuBuy: true, skuBuyType: type});
}

onMounted(() => {
    refresh()
    // 装修模式下刷新
    if (diyStore.mode == 'decorate') {
        isGoodsPropertyTemp()
    } else {
        watch(
            () => diyComponent.value,
            (newValue, oldValue) => {
                if (newValue && newValue.diyInfo?.componentName && newValue.diyInfo.componentName == 'SeckillActivityGoodsDetailGoodsInfo') {
                    isGoodsPropertyTemp()
                }
            },
            { immediate: true }
        )
        initFn()
    }
});

const discountTime = ref(0)
const initFn = () => {
   // 活动进行中
   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;
            }
        }

    } 
}


// 判断单规格库存是否为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 refresh = () =>{
    
}
const componentCss = computed(() => {
    return {
        '--separation-line-color': diyComponent.value.diyInfo.dividerLine.color || '#FF0000'
    }
})

</script>
<style lang="scss" scoped>
.card-template{
    background-color: transparent !important;
    border-radius: 0 !important;
}
.goods-divider{
    position: relative;
    height: 2rpx;
    border: 0;
    border-bottom: 4rpx dashed  var(--separation-line-color);
    margin: 28rpx 0;
    &::after{
        content: '';
        position: absolute;
        top: 50%;
        left: -37rpx;
        transform: translateY(-50%);
        width: 26rpx;
        height: 26rpx;
        background-color: var(--separation-line-color);
        border-radius: 50%;
    }
    &::before{
        content: '';
        position: absolute;
        top: 50%;
        right: -37rpx;
        transform: translateY(-50%);
        width: 26rpx;
        height: 26rpx;
        background-color: var(--separation-line-color);
        border-radius: 50%;
    }
}
</style>
