<template>
    <el-card class="!border-none" shadow="never">
        <el-page-header content="优惠券详情" @back="$router.back()" />
    </el-card>
    <el-card shadow="never" class="mt-4 card !border-none" :body-style="{ padding: '20px 0px' }">
        <el-form label-position="right" label-width="auto" :model="detailInfo" class="px-5 mt-6">
            <el-form-item label="优惠券名称：">{{ detailInfo.name }}</el-form-item>
            <el-form-item label="优惠券面值：">
                <span class="text-danger font-bold text-lg">￥{{ detailInfo.money }}</span>
            </el-form-item>
            <el-form-item label="发放方式：" class="couponWrap">
                <div>{{ parseGetType(detailInfo) }}</div>
                <div v-if="detailInfo.getType === DispatchEnum.CHANNEL_DISPATCH">
                    <el-auto-resizer>
                        <template #default="{ height, width }">
                            <el-table-v2
                                :columns="columnsGetType"
                                :data="parseChannel(detailInfo)"
                                :width="width"
                                :height="200"
                                fixed
                            >
                                <template #empty>
                                    <div class="flex items-center justify-center h-200">
                                        <el-empty />
                                    </div>
                                </template>
                            </el-table-v2>
                        </template>
                    </el-auto-resizer>
                </div>
            </el-form-item>
            <el-form-item label="优惠券类型：" class="couponWrap">
                <div>{{ useGoodsTypeMap[detailInfo.useGoodsType] }}</div>
                <!-- 品类券 -->
                <div v-if="detailInfo.useGoodsType === UseGoodsEnum.CATEGORY" class="core">
                    <el-tag
                        class="ml-2"
                        v-for="tag in detailInfo.goodsCategoryDetailVos"
                        :key="tag.id"
                    >
                        {{ tag.name }}
                    </el-tag>
                </div>
                <!-- 商品券 -->
                <div v-else-if="detailInfo.useGoodsType === UseGoodsEnum.CATEGOYR_PART">
                    <el-auto-resizer>
                        <template #default="{ height, width }">
                            <el-table-v2
                                :columns="columnsUseGoodsType"
                                :data="detailInfo.goodsDetailVos"
                                :width="width"
                                :height="200"
                                fixed
                            />
                        </template>
                    </el-auto-resizer>
                </div>
            </el-form-item>
            <el-form-item label="使用门槛：">{{ parseConditionType(detailInfo) }}</el-form-item>
            <el-form-item label="发放时间：">{{ parseTime(detailInfo, 'send') }}</el-form-item>
            <el-form-item label="使用时间：">{{ parseTime(detailInfo, 'use') }}</el-form-item>
            <el-form-item label="优惠券发放数量：">
                {{ parseDispatchCount(detailInfo) }}
            </el-form-item>
            <el-form-item label="用户可领取数量：">{{ detailInfo.getNum }}张</el-form-item>
            <el-form-item label="发放状态：">{{ parseStatus(detailInfo) }}</el-form-item>
        </el-form>
    </el-card>
</template>

<script setup lang="tsx">
import { ElAutoResizer } from 'element-plus'
import { useRequest } from '@/hooks/useFetchData'
import { getCouponDetailApi } from '@/api/application/coupon'
import {
    UseGoodsEnum,
    ChannelEnum,
    DispatchEnum,
    UseConditionEnum,
    DispatchCountEnum,
    getTypeMap,
    useGoodsTypeMap,
    conditionTypeMap,
    dispatchStatusMap,
    channelMap,
    channelfieldsMap,
    statusEnumMap
} from '@/enums/modeEnum'
import { timeFormat } from '@/utils/util'
import { parseCouponTime } from '@/utils/util'

interface CouponProp {
    name: string
    money: number
    getType: DispatchEnum //发放方式
    channelType: ChannelEnum //分销员/指定用户
    useGoodsType: UseGoodsEnum //优惠券类型
    conditionType: UseConditionEnum //使用门槛
    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[] //商品券选中列表
    [key: string]: any
}
const route = useRoute()
const id = route.query.id
const channel = route.query.channel as string
const detailInfo = reactive<Partial<CouponProp>>({}) as CouponProp

const parseChannel = computed(() => {
    return (detailInfo: CouponProp) => {
        const { channelType } = detailInfo
        return detailInfo[channelfieldsMap[channelType]]
    }
})
const parseConditionType = computed(() => {
    return (detailInfo: Partial<CouponProp>) => {
        const { conditionType, conditionMoney } = detailInfo
        const text = conditionTypeMap[conditionType!]
        return conditionType === UseConditionEnum.NO_CONDITION
            ? `${text}`
            : `${text}${conditionMoney}元`
    }
})
const parseTime = computed(() => {
    return (detailInfo: CouponProp, type: string) => {
        const {
            sendTimeStart,
            sendTimeEnd,
            useTimeStart,
            useTimeEnd,
            channelType,
            getType,
            createTime
        } = detailInfo
        const obj: Record<string, string[]> = {
            send: [sendTimeStart, sendTimeEnd],
            use: [useTimeStart, useTimeEnd]
        }
        const [startTime, endTime] = obj[type]
        if (startTime && endTime) {
            return `${parseCouponTime(startTime)} 至 ${parseCouponTime(endTime)}`
        } else if (channelType === 2 && getType === 3) {
            return createTime || '--'
        }
        return '--'
    }
})

const parseDispatchCount = computed(() => {
    return (detailInfo: Partial<CouponProp>) => {
        const { sendTotalType, sendTotal } = detailInfo
        return !sendTotalType
            ? '--'
            : sendTotalType === DispatchCountEnum.NO_COUNT
            ? '不限量'
            : `${sendTotal}张`
    }
})
const parseStatus = computed(() => {
    return (detailInfo: CouponProp) => {
        const { status } = detailInfo
        return statusEnumMap[status]
    }
})
const parseGetType = computed(() => {
    return (detailInfo: CouponProp) => {
        const { getType, channelType } = detailInfo
        return getType !== DispatchEnum.CHANNEL_DISPATCH
            ? `${getTypeMap[getType]}`
            : `${getTypeMap[getType]}-指定${channelMap[channelType]}`
    }
})
const columnFields: Record<string, any> = {
    GetType: {
        [ChannelEnum.DISTBUTOR]: {
            name: '分销员名称',
            distNum: '分销员ID'
        },
        [ChannelEnum.USER]: {
            nickname: '用户名称',
            username: '用户账号',
            mobile: '电话号码'
        }
    },
    UseGoodsType: {
        name: '服务名称',
        categoryName: '服务分类'
    }
}
function generateColumns(type: string | number) {
    const fields = type === 'GetType' ? columnFields[type][channel] : columnFields[type]
    return Object.keys(fields).map(key => {
        return {
            key: `${key}`,
            dataKey: `${key}`,
            title: fields[key],
            width: 150,
            cellRenderer: ({ cellData }: any) => {
                return <span>{cellData === '' ? '--' : cellData}</span>
            }
        }
    })
}

function generateData(columns: any[], tempData: any[]) {
    return Array.from(tempData).map((item, rowIndex) => {
        return columns.reduce(
            (rowData, column) => {
                rowData[column.dataKey] = item[column.dataKey]
                return rowData
            },
            {
                id: `${rowIndex}`,
                parentId: null
            }
        )
    })
}
const columnsGetType = generateColumns('GetType')
const columnsUseGoodsType = generateColumns('UseGoodsType')
// const data = generateData(columnsGetType, detailInfo.users)

/**获取优惠券详情 */
const getCouponDetail = () => {
    const { runFn } = useRequest({
        apiFn: getCouponDetailApi,
        onSuccess: (result: Record<string, any>) => {
            Object.keys(result).forEach(key => {
                detailInfo[key] = result[key]
            })
        }
    })
    runFn({ id })
}
onMounted(getCouponDetail)
</script>
<style lang="scss" scoped>
.couponWrap {
    :deep(.el-form-item__content) {
        display: block;

        .core {
            border: 1px solid #dedede;
            padding: 10px 5px;
        }
    }
}

:deep(.el-table-v2__empty) {
    height: 100%;

    .h-200 {
        height: inherit;
    }
}
</style>
