<template>
    <el-dialog
        :model-value="visible"
        :title="title"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="handleCancel"
        :width="width"
    >
        <el-form
            v-if="isShowSearch"
            :model="searchForm"
            ref="searchFormRef"
            :inline="true"
            label-width="auto"
        >
            <!-- 指定分销员、指定用户 -->
            <el-form-item v-for="search in searchParam" :key="search.field" :label="search.label">
                <el-select
                    v-model="searchForm[search.field]"
                    placeholder="请选择"
                    class="ls-input"
                    clearable
                >
                    <el-option
                        v-for="option in search.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="getLists">搜索</el-button>
                <el-button @click="resetParams">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="pager.lists" height="500">
            <el-table-column
                v-for="column in columns"
                :key="column.prop"
                :property="column.prop"
                :label="column.label"
            >
                <template #default="{ row }">
                    <!-- slot -->
                    <template v-if="column.slot">
                        <el-switch
                            v-model="row.status"
                            :active-value="1"
                            :inactive-value="2"
                            :before-change="() => handleStatusChange(row, getLists, 'inner')"
                            :disabled="disabledStatus(row)"
                        />
                    </template>
                    <!-- 操作 -->
                    <template v-else-if="column.prop === 'operation'">
                        <el-button type="primary" link @click="handleDelete(row)">删除</el-button>
                    </template>
                    <!-- 使用状态 -->
                    <template v-else-if="column.extract">
                        <span>{{ useStatusMap[row.useStatus] }}</span>
                    </template>
                    <!-- 普通文本 -->
                    <span v-else>{{ parseText(row, column.prop) }}</span>
                </template>
            </el-table-column>
        </el-table>
        <div class="flex justify-end mt-4">
            <el-config-provider :locale="zhCn">
                <pagination v-model="pager" @change="getLists" />
            </el-config-provider>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { usePaging } from '@/hooks/usePaging'
import { useCommon } from '@/hooks/useCommon'
import {
    getCouponListsByChannel,
    getCouponByUser,
    delCouponByDistributor
} from '@/api/application/coupon'
import feedback from '@/utils/feedback'
import { parseEmpty } from '@/utils/util'
import { ChannelEnum, DispatchEnum } from '@/enums/modeEnum'
import { useStatusMap } from '@/enums/modeEnum'
import { optionMap } from '@/config/status'

const props = defineProps({
    title: { type: String, default: '' },
    visible: { type: Boolean, default: true },
    width: { type: [Number, String], default: '50%' },
    onCancel: { type: Function, default: () => {} },
    onConfirm: { type: Function, default: () => {} },
    getType: { type: Number, default: 1 },
    channelType: { type: [Number, String], default: '' },
    id: { type: Number, default: 0 },
    name: { type: String, default: '' }
})
const handleCancel = () => {
    props.onCancel()
}

const getType = computed(() => props.getType)
const channel = computed(() => props.channelType)
const couponId = computed(() => props.id)
const couponName = computed(() => props.name)
const condition = computed(() => unref(getType) === DispatchEnum.CHANNEL_DISPATCH)
const field = computed(() =>
    !unref(condition) ? '' : unref(channel) === ChannelEnum.DISTBUTOR ? 'distributor' : 'user'
)
const isShowSearch = computed(() => unref(getType) !== DispatchEnum.USER_RECEIVE)
const parseText = computed(() => {
    return (row: any, prop: string) => {
        return !unref(field) ? parseEmpty(row, prop) : parseEmpty(row[unref(field)], prop)
    }
})

const dispatchMap: Record<number, any> = {
    [DispatchEnum.USER_RECEIVE]: {
        search: [],
        api: () => getCouponByUser,
        columns: [
            { prop: 'userName', label: '用户账号' },
            { prop: 'mobile', label: '手机号码' },
            { prop: 'createTime', label: '领取时间' },
            { prop: 'allCouponCount', label: '领取数量' },
            { prop: 'useCouponCount', label: '已使用数量' }
        ]
    },
    [DispatchEnum.CHANNEL_DISPATCH]: {
        [ChannelEnum.DISTBUTOR]: {
            search: [{ label: '发放状态', field: 'status', options: optionMap.statusOptions }],
            api: () => getCouponListsByChannel,
            columns: [
                { prop: 'name', label: '分销员名称' },
                { prop: 'distNum', label: '分销员ID' },
                { prop: 'status', label: '发放状态', slot: true },
                { prop: 'operation', label: '操作' }
            ]
        },
        [ChannelEnum.USER]: {
            search: [{ label: '使用状态', field: 'status', options: optionMap.useStatusOptions }],
            api: () => getCouponListsByChannel,
            columns: [
                { prop: 'username', label: '用户账号' },
                { prop: 'mobile', label: '手机号码' },
                { prop: 'status', label: '使用状态', extract: true }
            ]
        }
    }
}
function generateContent() {
    const map = dispatchMap[unref(getType)]

    /**表格参数 */
    const searchForm = reactive<Record<string, any>>({
        couponId: unref(couponId),
        channelType: unref(getType) !== DispatchEnum.CHANNEL_DISPATCH ? '' : unref(channel)
    })
    const searchParam = unref(condition) ? map[unref(channel)].search : map['search']
    searchParam.forEach(item => {
        searchForm[item.field] = ''
    })
    /**api */
    const api = unref(condition) ? map[unref(channel)].api() : map['api']()

    /**生成表格columns */
    const columns = unref(condition) ? map[unref(channel)].columns : map['columns']
    return {
        searchParam,
        searchForm,
        api,
        columns
    }
}
const { searchForm, searchParam, api, columns } = generateContent()

const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: api,
    params: searchForm
})
onMounted(getLists)

const { handleStatusChange } = useCommon()

/**分销员删除 */
const handleDelete = async (row: any) => {
    const {
        id,
        distributor: { name }
    } = row
    try {
        await feedback.confirm(
            `此操作不可逆，确定删除分销员【${name}】所持有的【${unref(couponName)}】优惠券？`
        )
        await delCouponByDistributor({ ids: [id] })
        feedback.msgSuccess('删除成功')
        getLists()
    } catch (error) {}
}
// 发放时间：18:00-19:00， 根据当前时间判断是否可以滑动
// 未到发放时间停用且无法滑动
// 过了发放时间停用且无法滑动
// 发放期间
const now = new Date().getTime()
const disabledStatus = computed(function () {
    return function (row) {
        const { sendTimeStart, sendTimeEnd } = row
        if (Object.keys(row).length) {
            return now < Date.parse(sendTimeStart) || now > Date.parse(sendTimeEnd) ? true : false
        }
    }
})
</script>
<style scoped></style>
