<template>
    <view class="card flex mt-[20rpx]" :class="{ 'gray': isGray(item!) }">
        <view class="card__top">
            <view class="card__left overflow-hidden">
                <!-- 领取次数多张 -->
                <slot name="count"></slot>
                <text class="font-bold text-xl name truncate">{{ item!.name }}</text>
                <text>{{ couponDesc(item!) }}</text>
                <text class="useTime">{{ timeText }}{{ parseTime(item) }}</text>
                <!-- 详细信息 -->
                <block>
                    <view
                        class="detail"
                        v-if="isVisibleCouponDetail(item!)"
                        @click="handleToggle(item!)"
                    >
                        <text>详细信息</text>
                        <text :class="['icon', { 'active': item!.isToggle }]"></text>
                    </view>
                    <view class="placeholder" v-else></view>
                </block>
                <slot name="selection"></slot>
            </view>
            <view class="card__right" :class="{ default: slots.selection }">
                <text>
                    ￥
                    <text class="money">{{ item!.money }}</text>
                </text>
                <text class="label">{{ couponCondition(item!) }}</text>
                <!-- 已使用/已过期 -->
                <slot name="status"></slot>
                <!-- 立即使用 -->
                <slot name="use" :row="item"></slot>
                <!-- 立即领取 -->
                <slot name="manual"></slot>
                <slot name="expiringSoon"></slot>
            </view>
        </view>
        <!-- 详细信息内容 -->
        <view class="card__bottom" v-show="item!.isToggle">
            <view v-if="slots.manual">领取说明：{{ '每人限领' + item!.getNum }}张</view>
            <view v-if="slots.manual">有效期截至时间：{{ item!.useTimeEnd }}</view>
            <view v-if="isLen(item!)">使用限制：{{ parseDetailLabel(item!) }}</view>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { PropType, computed, unref, useSlots } from 'vue'
import {
    CouponEnum,
    UseConditionEnum,
    conditions,
    useGoodsTypeMap,
    CouponCountMap,
    CouponStatusEnum,
    showExpiringSoonDays
} from '@/enums/appEnums'

interface CouponProp {
    name: string
    money: number
    getType: number //发放方式
    channelType: number //分销员/指定用户
    useGoodsType: number //优惠券类型
    conditionType: number //使用门槛
    sendTimeStart: string //发放开始时间
    sendTimeEnd: string //发放结束时间
    useTimeStart: string //使用开始时间
    useTimeEnd: string //使用结束时间
    sendTotal: number
    sendTotalType: number //发放数量
    getNum: number //领取数量
    status: number //发放状态
    conditionMoney: number | string //有门槛金额
    distributors: any[] //渠道选中分销员
    goodsCategoryDetailVos: any[] //品类券选中值
    goodsDetailVos: any[] //商品券选中列表
    isToggle?: boolean //是否展开
    goodsCategories: any[] //品类信息
    goods: any[] //商品信息
    useStatus: number //使用状态
}

const props = defineProps({
    item: Object as PropType<CouponProp>,
    default: () => ({}),
    activeTabName: String
})
const slots = useSlots()

const couponDesc = computed(() => (row: CouponProp) => generateCouponText(row))
/**无门槛：立减 有门槛：满x元可用 */
const couponCondition = computed(() => (row: CouponProp) => {
    const { conditionType, conditionMoney } = row
    return conditionType === UseConditionEnum.NO_CONDITION ? '立减券' : `满${conditionMoney}可用`
})
const isLen = computed(() => (row: CouponProp) => {
    const { goodsCategories, goods } = row
    return goodsCategories.length >= 1 || goods.length >= 1
})
/**
 * 1、通用券不需要
 * 2、useStatus：1需要
 */
/**显示详细信息 */
const isVisibleCouponDetail = computed(() => (row: CouponProp) => {
    return unref(isLen)(row) || slots.manual
})
/**已使用、已过期可见 */
const isGray = computed(() => {
    return (row: CouponProp) => {
        const { useStatus } = row
        return (
            useStatus === CouponEnum.ALIPAY ||
            useStatus === CouponEnum.OVERDUE ||
            props.activeTabName == CouponCountMap.notAvailableCount
        )
    }
})
const parseTime = computed(() => {
    return (row: any) => {
        const { useTimeStart, useTimeEnd } = row
        // const [useTimeStartDate] = useTimeStart.split(' ')
        // const [useTimeEndDate] = useTimeEnd.split(' ')

        return `${parseSingleTime(useTimeStart)} 至 ${parseSingleTime(useTimeEnd)}`
    }
})
const parseSingleTime = (t: string) => {
    if (!t) return
    try {
        const [day, time] = t.split(' ')
        let hour = time.split(':')[0]
        hour.startsWith('0') ? (hour = hour.replace('0', '')) : ''
        return `${day} ${hour}时`
    } catch {}
    return t
}
const parseDetailLabel = computed(() => {
    /**品类券：仅可购买指定xx商品 商品券：仅可购买xx部分商品 */
    return (row: CouponProp) => {
        const { goodsCategories, useGoodsType, goods } = row
        if (!unref(isVisibleCouponDetail) || useGoodsType === 1) return
        const catrgoryNames =
            useGoodsType === 2 ? transformGoods(goodsCategories) : transformGoods(goods)
        const text = useGoodsType === 2 ? `指定${catrgoryNames}` : `${catrgoryNames}`
        return `仅可购买${text}服务`
    }
})
const timeText = computed(() => (slots.manual ? '领取时间：' : '有效期：'))
const showExpiringSoon = computed(() => {
    return (row: CouponProp) => {
        const { useTimeEnd, useStatus } = row
        const currentTime = new Date().getTime()
        const endTime = Date.parse(useTimeEnd)
        const daysDifference = Math.abs(endTime - currentTime) / (60 * 60 * 24 * 1000)
        return daysDifference <= showExpiringSoonDays && useStatus == CouponStatusEnum.AVALIABLE
    }
})

/**切换显示详细信息 */
const handleToggle = (item: CouponProp) => {
    item.isToggle = !item.isToggle
}

function transformGoods(goods: any[], separator = '、') {
    return goods.map(category => category.name).join(separator)
}

/*优惠券类型+有门槛/优惠券类型+无门槛*/
function generateCouponText(row: any) {
    const { useGoodsType, conditionType, conditionMoney, money } = row
    const flag = conditions.some(
        condition =>
            condition.useGoodsType === useGoodsType && condition.conditionType === conditionType
    )
    if (!flag) return
    const condition =
        conditionType === UseConditionEnum.NO_CONDITION
            ? `消费立减${money}`
            : `满${conditionMoney}减${money}`
    return `${useGoodsTypeMap[useGoodsType]}服务${condition}元`
}
</script>

<style lang="scss" scoped>
.card {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    box-shadow: 0 8rpx 20rpx 0 $white4;
    margin: 30rpx;
    overflow: hidden;

    &__top {
        display: flex;
        position: relative;

        .card__left {
            flex: 1;
            display: flex;
            flex-direction: column;
            line-height: 1.8;
            background-color: $white;
            padding: 0 20rpx 20rpx;
            border-radius: 12rpx;
            position: relative;

            .name {
                margin-top: 34rpx;
            }

            .useTime {
                font-size: 21rpx;
            }

            .detail {
                color: $gray2;
                font-size: 20rpx;
                display: flex;
                justify-content: space-between;
                align-items: center;

                .icon {
                    width: 20rpx;
                    height: 20rpx;
                    background-color: $gray2;
                    border-radius: 999px;
                    position: relative;

                    &::before {
                        content: '';
                        width: 6rpx;
                        height: 6rpx;
                        border-left: 1px solid $white;
                        border-bottom: 1px solid $white;
                        position: absolute;
                        left: 50%;
                        top: 50%;
                        transform: translate(-50%, -50%) rotate(-45deg);
                    }

                    &.active {
                        &::before {
                            transform: translate(-50%, -50%) rotate(135deg);
                        }
                    }
                }
            }

            .placeholder {
                height: 36rpx;
            }
        }

        .card__right {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            // justify-content: center;
            text-align: center;
            background-image: linear-gradient(to left, $blue3 0%, $blue4 100%);
            color: $white;
            // background-image: linear-gradient(45deg, #FEF4F0 0%, #ffdde1 100%);
            // color: #fc5531;
            // padding: 20rpx 30rpx;
            padding-top: 44rpx;
            width: 90px;
            border-radius: 12rpx;

            .money {
                font-size: 44rpx;
            }

            &::before {
                content: '';
                position: absolute;
                top: -10rpx;
                left: -10rpx;
                width: 20rpx;
                height: 20rpx;
                background-color: $white1;
                border-radius: 100%;
            }

            &::after {
                content: '';
                position: absolute;
                bottom: -10rpx;
                left: -10rpx;
                width: 20rpx;
                height: 20rpx;
                background-color: $white1;
                border-radius: 100%;
                z-index: 1;
            }

            .label {
                font-size: 24rpx;
            }

            &.default {
                justify-content: center;
                padding-top: 0;
            }
        }
    }

    &__bottom {
        width: 100%;
        padding: 12rpx 20rpx;
        border-top: 1px solid $white3;
        background-color: $white;
        box-sizing: border-box;
        font-size: 20rpx;
        line-height: 1.8;
        color: $gray2;
        z-index: 2;
    }

    &.gray {
        filter: grayscale(1);
        opacity: 0.7;
    }
}
</style>
