<template>
    <view class="coupon">
        <view class="coupon__detail">
            <view class="coupon__detail__header">
                <view class="left">
                    <view class="title">{{ couponDetail.name }}</view>
                    <view class="date">{{ couponDetail.useTimeEnd }}到期</view>
                </view>
                <view class="right">
                    <view class="money">
                        <text>￥</text>
                        <text class="strong">{{ couponDetail.money }}</text>
                    </view>
                    <text class="condition">{{ condition(couponDetail) }}</text>
                </view>
            </view>
            <view class="coupon__detail__rule">
                <text class="sub_title">使用规则</text>
                <view class="content">
                    <view class="flex">
                        <text class="label">优惠券类型：</text>
                        <text class="flex-1">{{ parseUseGoodsType(couponDetail) }}</text>
                    </view>
                    <view class="flex">
                        <text class="label">领取说明：</text>
                        <text>每人限领{{ couponDetail.getNum }}张</text>
                    </view>
                    <view class="flex">
                        <text class="label">有效时间：</text>
                        <text>{{ parseTime(couponDetail) }}</text>
                    </view>
                    <view class="flex" v-show="couponDetail.useGoodsType !== 1">
                        <text class="label">使用限制：</text>
                        <text>{{ parseLimitContent(couponDetail) }}</text>
                    </view>
                </view>
            </view>
        </view>
        <view class="coupon__btn">
            <u-button class="manual" type="error" shape="circle" @click="handleManualCoupon"
                :disabled="isDisabled">立即领取</u-button>
        </view>
    </view>
</template>

<script setup lang='ts'>
import { apiCouponDetail } from '@/api/coupon';
import { onBackPress, onLoad, onUnload } from '@dcloudio/uni-app';
import { computed, reactive, ref, unref, toRaw } from 'vue';

interface CouponProp {
    name: string
    money: number
    getType: number //发放方式
    channelType: number //分销员/指定用户
    useGoodsType: number,//优惠券类型
    conditionType: number,//使用门槛
    sendTimeStart: number, //发放开始时间
    sendTimeEnd: number,//发放结束时间
    useTimeStart: string,//使用开始时间
    useTimeEnd: string,//使用结束时间
    sendTotal: number,
    sendTotalType: number//发放数量
    getNum: number, //领取数量
    status: number,//发放状态
    conditionMoney: number | string,//有门槛金额
    distributors: any[]//渠道选中分销员
    goodsCategoryDetailVos: any[],//品类券选中值
    goodsDetailVos: any[]//商品券选中列表
    isToggle?: boolean //是否展开
    goods: any[] //商品信息
    goodsCategories: any[] //品类信息
}
const couponId = ref()
const couponDetail = reactive<Partial<CouponProp>>({})
const count = ref(3) //x张优惠券
const num = ref(0)
const isDisabled = computed(() => couponDetail.getNum === 0)
const condition = computed(() => {
    return (row: Partial<CouponProp>) => {
        if (!Object.keys(row).length) return
        const { conditionType, conditionMoney } = row
        return conditionType === 1 ? '立减券' : `满${conditionMoney}可用`
    }
})
const parseTime = computed(() => {
    return (row: Partial<CouponProp>) => {
        if (!Object.keys(row).length) return
        const { useTimeStart, useTimeEnd } = row as CouponProp

        const [useTimeStartDate, useTimeStartHS] = useTimeStart.split(' ')
        const [useTimeEndDate, useTimeEndHS] = useTimeEnd.split(' ')

        const startText = useTimeStartHS.split(':').slice(0, -1).join(':')
        const endText = useTimeEndHS.split(':').slice(0, -1).join(':')

        return `${useTimeStartDate} ${startText}至${useTimeEndDate} ${endText}`
    }
})
const parseLimitContent = computed(() => {
    return (row: Partial<CouponProp>) => {
        if (!Object.keys(row).length) return
        const { useGoodsType, goodsCategories, goods } = toRaw(couponDetail) as CouponProp
        if (useGoodsType === 1) return
        const categoryNames = useGoodsType === 2
            ? transformGoods(goodsCategories, 'name')
            : transformGoods(goods, 'categoryName')
        return `仅可购买${categoryNames}商品`
    }
})
const useGoodsTypeMap: Record<number, string> = {
    1: '通用券',
    2: '品类券',
    3: '商品券'
}
const parseUseGoodsType = computed(() => {
    return (row: Partial<CouponProp>) => {
        const { useGoodsType } = row
        return useGoodsTypeMap[useGoodsType!]
    }
})
function transformGoods(goods: any[], field: string, separator = '、') {
    return goods.map(category => category[field]).join(separator)
}
onLoad((options) => {
    const { id } = options
    couponId.value = id
    fetchCouponDetail()
})
/**获取优惠券详情 */
const fetchCouponDetail = async () => {
    try {
        const res = await apiCouponDetail({ couponId: unref(couponId) })
        for (const key in res) {
            couponDetail[key] = res[key]
        }
    } catch (error) { }
}
/**领取后
 * 
 * 1、根据用户可领取张数
 * 2、领取后重新刷新详情页
 */
const handleManualCoupon = () => {
    couponDetail.getNum = couponDetail.getNum - 1
    uni.$u.toast(`优惠券已放到卡包中${couponDetail.getNum}`)
    /**
     * 1、有多张优惠券
     * 2、只有一张优惠券
     */
    // uni.navigateBack({
    //     delta: 1,
    //     success: () => {
    //         const pages = getCurrentPages()
    //         const prevPage = pages[pages.length - 1]
    //         prevPage.onLoad?.()
    //     }
    // })
}
onUnload(() => {
    uni.$emit('refresh', {})
})
</script>

<style lang="scss" scoped>
.coupon {
    display: flex;
    flex-direction: column;
    height: 100vh;

    .coupon__detail {
        height: calc(100% - 60px);
        overflow: auto;

        &__header {
            display: flex;
            background-color: #fff;
            margin: 20rpx;
            border-radius: 12rpx;

            .left {
                flex: 1;
                padding: 20rpx;
                line-height: 1.8;

                .title {
                    font-size: 36rpx;
                }

                .date {
                    color: #777;
                    font-size: 24rpx;
                }
            }

            .right {
                display: flex;
                flex-direction: column;
                justify-content: center;
                padding: 0 20rpx;
                height: 148rpx;
                border-left: 1px dashed #F1F2F2;

                .money {
                    color: #fc5531;

                    .strong {
                        font-size: 52rpx;
                        font-weight: 700;
                    }
                }

                .condition {
                    color: #777;
                    font-size: 28rpx;
                }
            }
        }

        &__rule {
            background-color: #fff;
            margin: 20rpx;
            padding: 30rpx;
            border-radius: 12rpx;

            .sub_title {
                font-size: 44rpx;
            }

            .content {
                margin-top: 20rpx;
                line-height: 60rpx;
                font-size: 13px;

                .label {
                    display: flex;
                    align-items: center;
                    width: 180rpx;

                    &::before {
                        content: '';
                        display: inline-block;
                        width: 8rpx;
                        height: 8rpx;
                        border-radius: 4rpx;
                        margin-right: 12rpx;
                        background-color: #000;
                    }
                }


            }
        }
    }

    .coupon__btn {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 120rpx;
        padding: 0 40rpx;
        background-color: #fff;

        .manual {
            height: 80rpx;
            width: 100%;
            text-align: center;
            line-height: 80rpx;
            color: #fff;
            border-radius: 999px;
            background-color: #fc5531;
        }
    }
}
</style>