<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <el-page-header :content="route.query.id ? '编辑优惠券' : '新增优惠券'" @back="$router.back()" />
        </el-card>

        <el-card class="!border-none mt-[15px]" shadow="never">
            <div class="font-medium mb-7">基本信息</div>
            <el-form ref="formRef" :model="formData" label-width="150px" :rules="rules">
                <el-form-item label="优惠券名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请填写优惠券名称" class="w-[360px]" maxlength="25" show-word-limit></el-input>
                </el-form-item>
                <el-form-item label="优惠券面值" prop="money">
                    <el-input v-model="formData.money" placeholder="请填写优惠券面值" class="w-[360px]" maxlength="8"></el-input>
                </el-form-item>

                <el-form-item label="发放方式" prop="getType">
                    <div>
                        <el-radio-group v-model="formData.getType">
                            <el-radio v-for="option in optionMap.dispatchMethodOptions" :key="option.value" :label="option.value">
                                {{ option.label }}
                            </el-radio>
                        </el-radio-group>
                        <div class="form-tips">
                            用户领取：后台发放后需要用户领取；系统赠送：后台直接发送给用户券包中；渠道派发：后台发放给指定用户或推广员
                        </div>
                        <!-- 渠道派发 -->
                        <div v-show="formData.getType === DispatchEnum.CHANNEL_DISPATCH">
                            <el-radio-group v-model="channel">
                                <el-radio v-for="option in optionMap.channelOptions" :key="option.value" :label="option.value">
                                    {{ option.label }}
                                </el-radio>
                            </el-radio-group>
                            <el-form-item label="" prop="userList">
                                <channel-select-user v-model="formData.userList">
                                    <template #popup>
                                        <el-button type="primary">选择赠送对象</el-button>
                                    </template>
                                </channel-select-user>
                            </el-form-item>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="优惠券类型" prop="useGoodsType">
                    <div>
                        <div>
                            <el-radio-group v-model="formData.useGoodsType">
                                <el-radio v-for="option in optionMap.goodsOptions" :key="option.value" :label="option.value">
                                    {{ option.label }}
                                </el-radio>
                            </el-radio-group>
                        </div>
                        <!-- 品类券 -->
                        <div v-show="formData.useGoodsType === UseGoodsEnum.CATEGORY">
                            <el-form-item label="选择商品的品类" prop="serviceCategory">
                                <el-select
                                    placeholder="请选择商品品类"
                                    multiple
                                    collapse-tags
                                    collapse-tags-tooltip
                                    v-model="formData.serviceCategory"
                                >
                                    <el-option v-for="item in categoryLists" :key="item.id" :label="item.name" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </div>
                        <!-- 商品券 -->
                        <div v-show="formData.useGoodsType === UseGoodsEnum.CATEGOYR_PART">
                            <el-form-item label="" prop="goodsList">
                                <good-select v-model="formData.goodsIds" v-model:selectData="formData.goodsList">
                                    <template #popup>
                                        <el-button type="primary">选择服务</el-button>
                                    </template>
                                </good-select>
                            </el-form-item>
                        </div>
                    </div>
                </el-form-item>

                <el-form-item label="使用门槛" prop="conditionType">
                    <div>
                        <div>
                            <el-radio-group v-model="formData.conditionType">
                                <el-radio v-for="option in optionMap.conditionOptions" :key="option.value" :label="option.value">
                                    {{ option.label }}
                                </el-radio>
                            </el-radio-group>
                            <!-- 有门槛 -->
                            <el-form-item
                                label=""
                                prop="conditionMoney"
                                class="w-[360px]"
                                v-show="formData.conditionType === UseConditionEnum.CONDITION"
                            >
                                <el-input v-model="formData.conditionMoney" maxlength="8">
                                    <template #append>元</template>
                                </el-input>
                                <span class="form-tips">注：填写最低消费金额</span>
                            </el-form-item>
                        </div>
                    </div>
                </el-form-item>

                <!-- 渠道派发给指定用户不可见 -->
                <el-form-item label="发放时间" prop="sendTimeStart" v-if="sendTimeCondition">
                    <div>
                        <daterange-picker
                            class="w-[385px]"
                            type="datetimerange"
                            format="YYYY-MM-DD HH"
                            :isDisabledDate="true"
                            :isDisabledHours="true"
                            v-model:startTime="formData.sendTimeStart"
                            v-model:endTime="formData.sendTimeEnd"
                        />
                    </div>
                </el-form-item>

                <el-form-item label="使用时间" prop="useTimeStart">
                    <div>
                        <daterange-picker
                            class="w-[385px]"
                            type="datetimerange"
                            format="YYYY-MM-DD HH"
                            :isDisabledDate="true"
                            :isDisabledHours="true"
                            v-model:startTime="formData.useTimeStart"
                            v-model:endTime="formData.useTimeEnd"
                        />
                    </div>
                </el-form-item>

                <!-- 系统赠送、渠道派发给指定用户 不可见 -->
                <el-form-item label="发放数量" prop="sendTotalType" v-show="formData.getType !== DispatchEnum.SYSTEM_GIVE">
                    <div v-if="channelCondition">
                        <span>{{ formData.userList[channel]?.length || 0 }}张</span>
                    </div>
                    <div v-else>
                        <el-radio-group v-model="formData.sendTotalType">
                            <el-radio v-for="option in optionMap.dispatchCountOptions" :key="option.value" :label="option.value">
                                {{ option.label }}
                            </el-radio>
                        </el-radio-group>
                        <!-- 限量 -->
                        <el-form-item label="" prop="dispatchCount" v-if="formData.sendTotalType === DispatchCountEnum.COUNT">
                            <el-input v-model.number="formData.dispatchCount" maxlength="9">
                                <template #append>张</template>
                            </el-input>
                        </el-form-item>
                    </div>
                </el-form-item>

                <!-- 系统赠送、渠道派发给指定用户 只能领取一张 -->
                <el-form-item label="用户可领取数量" prop="getNum">
                    <div class="w-[240px]">
                        <el-input v-model.number="dispatchCount" :disabled="isDisabledGetCount" maxlength="4">
                            <template #append>张</template>
                        </el-input>
                    </div>
                </el-form-item>

                <!-- 渠道派发给指定用户状态只允许启用 -->
                <el-form-item label="发放状态" prop="status">
                    <el-radio-group v-model="formData.status" :disabled="isDisabledStatus || notAvailableSend">
                        <el-radio v-for="option in optionMap.statusOptions" :key="option.value" :label="option.value">
                            {{ option.label }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
    <footer-btns v-perms="['auth:coupon:save']">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
    </footer-btns>
</template>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import GoodSelect from '@/components/good-select/index.vue'
import ChannelSelectUser from '@/components/channel-select-user/index.vue'
import { useRequest } from '@/hooks/useFetchData'
import { useCommon } from '@/hooks/useCommon'
import { CHANNEL_INJECTION_KEY } from '@/config/symbol'
import { getCoupondetail as getCouponDetail, addCoupon } from '@/api/application/coupon'
import { DispatchEnum, ChannelEnum, UseGoodsEnum, UseConditionEnum, DispatchCountEnum } from '@/enums/modeEnum'
import { optionMap } from '@/config/status'
import { deepClone, toast } from '@/utils/util'
import {
    validateMoney,
    validateUserList,
    validateServiceCategory,
    validateGoodsList,
    valdiateConditionMoney,
    validateDispatchCount,
    validateGetNum,
    validateSendTime,
    validateUseTime
} from '@/utils/validate'

const formData: any = ref({
    id: '',
    name: '', //名称
    money: '', //面值
    getType: 1, //发放方式
    useGoodsType: 1, //优惠券类型
    conditionType: 1, //使用门槛
    sendTimeStart: '', //发放开始时间
    sendTimeEnd: '', //发放结束时间
    useTimeStart: '', //使用开始时间
    useTimeEnd: '', //使用结束时间
    sendTotal: 1,
    getNum: 1, //领取数量
    status: 1, //发放状态
    conditionMoney: '', //有门槛金额
    dispatchCount: '', //限量张数
    sendTotalType: 1, //发放数量
    useTimeType: 1,
    useTime: '',
    getNumType: 1,
    useGoodsIds: [],
    userIds: [],
    userList: [], //渠道选中用户
    serviceCategory: [], //品类券选中值
    goodsList: [] //商品券选中列表
})
const channel = ref(1) //渠道

/**渠道派发给指定用户不可见发放时间 */
const sendTimeCondition = computed(
    () =>
        unref(formData).getType !== DispatchEnum.CHANNEL_DISPATCH ||
        (unref(formData).getType === DispatchEnum.CHANNEL_DISPATCH && channel.value === ChannelEnum.DISTBUTOR)
)
/**渠道派发给指定用户 */
const channelCondition = computed(() => unref(channel) === ChannelEnum.USER && unref(formData).getType === DispatchEnum.CHANNEL_DISPATCH)
const condition = computed(() => unref(formData).getType === DispatchEnum.SYSTEM_GIVE || channelCondition.value)
/**系统赠送、渠道派发给指定用户 只能领取1张优惠券 */
const dispatchCount = computed({
    get: () => unref(formData).getNum,
    set: val => {
        unref(formData).getNum = val
    }
})
/**系统赠送、渠道派发给指定用户 禁用 */
const isDisabledGetCount = computed(() => condition.value)
/** 渠道派发给指定用户 禁用*/
const isDisabledStatus = computed(() => channelCondition.value)

const { categoryLists, fetchCategoryList } = useCommon()
fetchCategoryList()

const route = useRoute()
const router = useRouter()

const formRef = ref<FormInstance>()
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
    money: [
        { required: true, message: '请输入优惠券面额', trigger: 'blur' },
        {
            validator: (...args) => validateMoney(args, getField(['conditionType', 'conditionMoney'])),
            trigger: 'blur'
        }
    ],
    userList: {
        validator: (...args) => validateUserList(args, getField('getType'), channel.value),
        trigger: 'blur'
    },
    serviceCategory: {
        validator: (...args) => validateServiceCategory(args, getField('useGoodsType')),
        trigger: 'change'
    },
    goodsList: {
        validator: (...args) => validateGoodsList(args, getField('useGoodsType')),
        trigger: 'blur'
    },
    conditionMoney: {
        validator: (...args) => valdiateConditionMoney(args, getField(['conditionType', 'money'])),
        trigger: 'blur'
    },
    dispatchCount: {
        validator: (...args) => validateDispatchCount(args, getField(['sendTotalType', 'getType'])),
        trigger: 'blur'
    },
    getNum: [
        { required: true, message: '请输入用户可领取数量', trigger: 'blur' },
        {
            validator: (...args) => validateGetNum(args, getField(['sendTotalType', 'dispatchCount'])),
            trigger: 'blur'
        }
    ],
    sendTimeStart: [
        {
            validator: (...args) => validateSendTime(args, getField(['sendTimeStart', 'sendTimeEnd', 'useTimeStart', 'useTimeEnd'])),
            trigger: 'change'
        },
        { required: true, message: '请选择发放时间' }
    ],
    useTimeStart: [
        {
            validator: (...args) => validateUseTime(args, getField(['useTimeStart', 'useTimeEnd', 'sendTimeStart', 'sendTimeEnd'])),
            trigger: 'change'
        },
        { required: true, message: '请选择使用时间' }
    ]
})

//保存
const handleSubmit = () => {
    formRef.value?.validate(async valid => {
        if (!valid) return
        const [sendTimeStartDate, sendTimeStartTime] = unref(formData).sendTimeStart.split(' ')
        const [sendTimeEndDate, sendTimeEndTime] = unref(formData).sendTimeEnd.split(' ')
        const [useTimeStartDate, useTimeStartTime] = unref(formData).useTimeStart.split(' ')
        const [useTimeEndDate, useTimeEndTime] = unref(formData).useTimeEnd.split(' ')

        // const useHour = useTimeStartTime === useTimeEndTime ? '59' : '00'
        const userList = unref(formData).userList[channel.value!]
        const data = {
            ...formData.value,
            useTimeStart: `${useTimeStartDate} ${useTimeStartTime}:00:00`,
            useTimeEnd: `${useTimeEndDate} ${useTimeEndTime}:00:00`,
            appendIds: userList ? userList.map((user: any) => user.id) : [],
            goodsCategoryIds: unref(formData).serviceCategory,
            goodsIds: unref(formData).goodsIds,
            channelType: unref(channel),
            sendTotal: unref(formData).dispatchCount
        }

        if (unref(sendTimeCondition)) {
            // let senHour = sendTimeStartTime === sendTimeEndTime ? '59' : '00'
            Object.assign(data, {
                sendTimeStart: `${sendTimeStartDate} ${sendTimeStartTime}:00:00`,
                sendTimeEnd: `${sendTimeEndDate} ${sendTimeEndTime}:00:00`
            })
        }
        console.log(data)

        const { runFn } = useRequest({
            apiFn: addCoupon,
            onSuccess: () => {
                toast('创建优惠券成功', 'success')
                router.back()
            },
            onError: () => {}
        })
        runFn(data)
    })
}
/**获取表单值 */
function getField(fields: string | string[]) {
    if (Array.isArray(fields)) {
        return fields.map(field => unref(formData)[field])
    } else {
        return unref(formData)[fields]
    }
}

/**选择渠道券 */
const selectObj = ref<Record<number, any[]>>({})
const handleSelectionChange = (val: any) => {
    selectObj.value[unref(channel)] = deepClone(val)
}
/**选择品类券后，再选择商品券并点击确定，需清除上次操作选择的数据 */
watch(
    () => unref(formData).goodsList,
    val => {
        if (val.length && formData.value.serviceCategory.length) {
            formData.value.serviceCategory = []
        }
    }
)
/**选择商品券后，再选择品类券，需清除上次操作选择的数据 */
watch(
    () => unref(formData).serviceCategory,
    val => {
        if (val.length && formData.value.goodsList.length) {
            formData.value.goodsIds = []
            formData.value.goodsList = []
        }
    }
)
/**切换发放方式，关联用户领取数量 */
watch(
    () => unref(condition),
    (val: boolean) => {
        dispatchCount.value = val ? 1 : ''
    }
)
/**切换使用门槛，清除上次操作数据 */
watch(
    () => unref(formData).conditionType,
    val => {
        if (val === UseConditionEnum.NO_CONDITION && formData.value.conditionMoney) {
            formData.value.conditionMoney = ''
        }
    }
)
/**切换发放数量，清除上次操作数据 */
watch(
    () => unref(formData).sendTotalType,
    val => {
        if (val === DispatchCountEnum.NO_COUNT && formData.value.dispatchCount) {
            formData.value.dispatchCount = ''
        }
    }
)
/**切换优惠券类型，清除上次操作数据 */
watch(
    () => unref(formData).useGoodsType,
    val => {
        if (val === UseGoodsEnum.ALL && formData.value.serviceCategory.length) {
            formData.value.serviceCategory = []
        } else if (val === UseGoodsEnum.ALL && formData.value.goodsList.length) {
            formData.value.goodsIds = []
            formData.value.goodsList = []
        }
    }
)
/**先选择用户领取输入参数后，切换到渠道派发时需要清除上一次数据 */
watch(
    () => unref(channelCondition),
    () => {
        if (unref(formData).sendTimeStart) {
            formData.value.sendTimeStart = ''
            formData.value.sendTimeEnd = ''
            formData.value.useTimeStart = ''
            formData.value.useTimeEnd = ''
        }
    }
)

let notAvailableSend = ref(false)
/** 发放时间大于当前时间，发放状态默认为停用，且不可编辑 */
watch(
    () => unref(formData).sendTimeStart,
    () => {
        const currentTime = new Date().getTime()
        if (Date.parse(unref(formData).sendTimeStart + ':00:00') > currentTime) {
            formData.value.status = 2
            notAvailableSend.value = true
        } else {
            formData.value.status = 1
            notAvailableSend.value = false
        }
    }
)
provide(CHANNEL_INJECTION_KEY, {
    channel,
    categoryLists,
    selectObj,
    handleSelectionChange
})
</script>
<style lang="scss" scope>
.preview {
    width: 375px;
    box-sizing: border-box;
    flex: none;
    height: 722px;
    border: 1px solid hsla(0, 0%, 89.8%, 0.898039);
    display: flex;
    flex-direction: column;
}

.title {
    background: #f5f8ff;
    height: 40px;
    border-bottom: 1px solid hsla(0, 0%, 89.8%, 0.898039);
}

.el-time-spinner__wrapper {
    width: 100% !important;
}

.el-scrollbar:nth-child(2) {
    display: none;
}
.el-input__inner {
    line-height: 32px;
}
</style>
