<template>
    <view :style="warpCss" class="overflow-hidden relative p-[24rpx]" v-if="diyComponent && diyComponent.goods && Object.keys(diyComponent.goods).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.goods.title }}
                    </view>
                    <view class="text-[24rpx] text-[#999] leading-[30rpx] using-hidden mb-[20rrpx]">
                        {{ diyComponent.goods.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">拼团价</text>
                            <text class="text-[28rpx] font-500 mr-[4rpx]">￥</text>
                            <text class="text-[46rpx] font-500">{{ Number(goodsPrice).toFixed(2).split('.')[0] }}</text>
                            <text class="text-[28rpx] font-500">.{{ Number(goodsPrice).toFixed(2).split('.')[1] }}</text>
                        </view>
                        <view class="text-[#999999] ">
                            <text class="text-[24rpx] mr-[6rpx] font-500 price-font">原价</text>
                            <text class="text-[28rpx] leading-[36rpx]">￥{{ diyComponent.goods.original_price }}</text>
                        </view>
                    </view>
                </view>
            </view>
            <view v-if="diyComponent.diyInfo.dividerLine.isShow" class="goods-divider">

                 <!-- {{ img('addon/pintuan/xux.svg') }} -->
            </view>
            <!-- <image
                :src="img('addon/pintuan/xux.svg')"
                mode="scaleToFill"
                class="goods-divider"
            /> -->
            
            <view class="flex flex-col mb-[26rpx] mt-[40rpx]" :class="{'mt-[30rpx]': !diyComponent.diyInfo.dividerLine.isShow}" v-if="diyComponent.refund_type_name && diyComponent.diyInfo.serviceConfig.includes('guarantee')">
                <view class="text-[red] text-[30rpx] 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] mt-[35rpx]" v-if="diyComponent.expire_desc">
                <view class="text-[red] text-[30rpx] 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.desc && diyComponent.diyInfo.serviceConfig.includes('instructions')">
                <view class="text-[red] text-[30rpx] font-bold mb-[20rpx]">购买须知</view>
                <u-parse v-if="diyStore.mode != 'decorate'" :content="diyComponent.desc" :tagStyle="{img: 'vertical-align: top;width:100%;',p:'overflow: hidden;word-break:break-word;' }"></u-parse>
                <text v-else class="text-[28rpx]">{{ diyComponent.desc }}</text>
            </view>

            <button v-if="diyComponent.diyInfo.buyBtn.isShow" class="mt-[40rpx] 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, timeTurnTimeStamp } from '@/utils/common';
import useDiyStore from '@/app/stores/diy';
import usePintuanGoodsDetailStore from '@/addon/pintuan/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 = {
            goods: {
                pintuan_price: '100.00',
                original_price: '200.00',
                title: '标题',
                sub_title: '副标题',
                desc: '购买须知'
            },
            refund_type_name: '随时退', 
            expire_desc: '购买之后10天有效'
        }
        return Object.assign({}, {diyInfo: diyStore.value[props.index]}, obj);
    } else {
        return Object.assign({}, {diyInfo: props.component}, usePintuanGoodsDetailStore().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.desc && 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.goods.pintuan_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
})

// 根据结束时间判断isSingle的值
const isSingle = computed(() => {
    if (!diyComponent.value.end_time) return 1;
    
    const endTime = new Date(diyComponent.value.end_time.replace(/-/g, '/'));
    const now = new Date();
    
    // 如果当前时间在结束时间之前，isSingle为0，否则为1
    return now < endTime ? 0 : 1;
});

const buyFn = () => {
     let type = ''
    if(isShowSingleSku.value && discountTime.value > 0 && diyComponent.value.status=='process'){
        type = 'buy_now'
    }else{
        type = 'buy_now_single'
    }
    usePintuanGoodsDetailStore().setGoodsDetail({isOpenSkuBuy: true, skuBuyType: type, isSingle: isSingle.value});
}

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

const discountTime = ref(0)
const initFn = () => {
   // 获取当前时间
   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 = (timeTurnTimeStamp(diyComponent.value.end_time) - currentTimeSeconds) * 1000;
}


// 判断单规格库存是否为0
const isShowSingleSku = computed(() => {
    let isSingleSpec = false // 是否为单规格，true：多规格，false：单规格
    diyComponent.value.goods.sku_list.forEach((item: any, index: any) => {
        if (item.sku_spec_format) {
            isSingleSpec = true
        }
    })

    // 单规格，库存为0，显示已售罄
    if (!isSingleSpec && diyComponent.value.goods.stock <= 0) {
        return false;
    } else if (!isSingleSpec && diyComponent.value.goods.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>
.goods-divider{
    position: relative;
    height: 2rpx;
    border: 0;
    // border-bottom: 4rpx dashed  var(--separation-line-color);
    background: linear-gradient(to right, var(--separation-line-color) 50%, transparent 50%);
    background-size: 15rpx 2rpx; /* 调整这里的数值来控制虚线间距，第一个值控制虚线段和间隔的总长度 */

    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>
