<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">
                    <div>
                        <el-input
                            :disabled="route.query.detail == 'true'"
                            v-model="formData.name"
                            placeholder="请输入优惠券名称"
                            class="w-[360px]"
                        ></el-input>
                    </div>
                </el-form-item>
                <el-form-item label="发放数量" prop="send_total">
                    <div>
                        <div class="flex">
                            <el-input
                                v-model="formData.send_total"
                                placeholder="请输入每日发放数量"
                                class="w-[360px]"
                                :disabled="
                                    formData.send_total_type == 1 || route.query.detail == 'true'
                                "
                            ></el-input>
                            <el-checkbox
                                :disabled="route.query.detail == 'true'"
                                label="不限数量"
                                v-model="formData.send_total_type"
                                :true-label="1"
                                :false-label="2"
                                class="ml-2"
                            />
                        </div>
                        <div class="form-tips">
                            编辑进行中的优惠券，发放总量只能增加不能减少，请谨慎设置。最多1000000张
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="使用时间" prop="use_time_type">
                    <div>
                        <div>
                            <el-radio-group
                                v-model="formData.use_time_type"
                                :disabled="route.query.detail == 'true' || formData.status == 2"
                            >
                                <el-radio :label="1">固定日期</el-radio>
                                <el-radio :label="2">领券当日起</el-radio>
                                <el-radio :label="3">领券次日起</el-radio>
                            </el-radio-group>
                        </div>
                        <div v-if="formData.use_time_type == 1">
                            <daterange-picker
                                class="w-[385px]"
                                v-model:startTime="formData.use_time_start"
                                v-model:endTime="formData.use_time_end"
                                :disabled="route.query.detail == 'true' || formData.status == 2"
                            />
                        </div>
                        <div class="w-[240px]" v-if="formData.use_time_type == 2">
                            <el-input
                                v-model="formData.use_time"
                                :disabled="route.query.detail == 'true' || formData.status == 2"
                            >
                                <template #append>天内可用</template>
                            </el-input>
                        </div>
                        <div class="w-[240px]" v-if="formData.use_time_type == 3">
                            <el-input
                                v-model="formData.use_time"
                                :disabled="route.query.detail == 'true' || formData.status == 2"
                            >
                                <template #append>天内可用</template>
                            </el-input>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </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="money">
                    <div>
                        <el-input
                            :disabled="route.query.detail == 'true' || formData.status == 2"
                            v-model="formData.money"
                            placeholder="请输入"
                            class="w-[360px]"
                        ></el-input>

                        <div class="form-tips">面额需大于0元，支持两位小数</div>
                    </div>
                </el-form-item>
                <el-form-item label="领取方式" prop="get_type">
                    <div>
                        <el-radio-group
                            v-model="formData.get_type"
                            :disabled="route.query.detail == 'true' || formData.status == 2"
                        >
                            <el-radio :label="1">用户领取</el-radio>
                            <el-radio :label="2">系统赠送</el-radio>
                        </el-radio-group>

                        <div class="form-tips">
                            用户领取：指用户自行领取；系统赠送：指通过后台给某个用户发放
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="使用门槛" prop="condition_type">
                    <div>
                        <div>
                            <el-radio-group
                                v-model="formData.condition_type"
                                :disabled="route.query.detail == 'true' || formData.status == 2"
                            >
                                <el-radio :label="1">无门槛</el-radio>
                                <el-radio :label="2">订单满</el-radio>
                            </el-radio-group>
                            <div class="w-[240px]" v-if="formData.condition_type == 2">
                                <el-input
                                    v-model="formData.condition_money"
                                    :disabled="route.query.detail == 'true' || formData.status == 2"
                                >
                                    <template #append>元可使用</template>
                                </el-input>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="领取次数">
                    <div>
                        <div>
                            <el-radio-group
                                v-model="formData.get_num_type"
                                :disabled="route.query.detail == 'true' || formData.status == 2"
                            >
                                <el-radio :label="1">不限领取</el-radio>
                                <el-radio :label="2">限制领取</el-radio>
                                <el-radio :label="3">每天限制领取</el-radio>
                            </el-radio-group>
                            <div
                                class="w-[240px]"
                                v-if="formData.get_num_type == 3 || formData.get_num_type == 2"
                            >
                                <el-input
                                    v-model="formData.get_num"
                                    :disabled="route.query.detail == 'true' || formData.status == 2"
                                >
                                    <template #append>张</template>
                                </el-input>
                            </div>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item label="使用范围" prop="use_goods_type">
                    <div>
                        <div>
                            <el-radio-group
                                v-model="formData.use_goods_type"
                                :disabled="route.query.detail == 'true' || formData.status == 2"
                            >
                                <el-radio :label="1">全场通用</el-radio>
                                <el-radio :label="2">指定商品可用</el-radio>
                                <el-radio :label="3">指定商品不可用</el-radio>
                            </el-radio-group>
                        </div>
                        <div v-if="formData.use_goods_type !== 1">
                            <div>
                                <el-button
                                    type="primary"
                                    @click="handleselect"
                                    :disabled="route.query.detail == 'true' || formData.status == 2"
                                    >选择商品</el-button
                                >
                                已选择{{ goodslists?.length || 0 }}件商品
                                <el-button
                                    link
                                    type="primary"
                                    @click="handleclearAll"
                                    :disabled="route.query.detail == 'true' || formData.status == 2"
                                    >清空</el-button
                                >
                            </div>
                            <div class="w-[800px]">
                                <el-table size="large" class="mt-[14px]" :data="goodslists">
                                    <el-table-column label="商品信息">
                                        <template #default="{ row }">
                                            <div class="flex items-center">
                                                <el-avatar
                                                    :src="row.image"
                                                    style="height: 60px; min-width: 60px"
                                                />

                                                <el-tooltip
                                                    :content="row.name"
                                                    placement="top-start"
                                                >
                                                    <div class="ml-[10px] text_hidden">
                                                        {{ row.name }}
                                                    </div>
                                                </el-tooltip>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="商品分类" prop="category_name" />
                                    <el-table-column label="商品价格" prop="sell_price">
                                        <template #default="{ row }">
                                            ￥{{ row.sell_price }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" prop="sn">
                                        <template #default="{ row }">
                                            <el-button
                                                :disabled="
                                                    route.query.detail == 'true' ||
                                                    formData.status == 2
                                                "
                                                type="primary"
                                                link
                                                @click="handleclear(row.id)"
                                                >移除</el-button
                                            >
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
        </el-card>
        <selectpopup
            v-if="showselect"
            ref="selectRef"
            @close="showselect = false"
            @success="handleselected"
            :selected="goodslists"
        ></selectpopup>
    </div>
    <footer-btns v-perms="['']">
        <el-button type="primary" @click="handleSubmit">保存</el-button>
    </footer-btns>
</template>
<script lang="ts" setup>
import Selectpopup from './component/selectgoods.vue'
import { useDictOptions } from '@/hooks/useDictOptions'
import feedback from '@/utils/feedback'
import useAppStore from '@/stores/modules/app'
import type { FormInstance, FormRules } from 'element-plus'
import { getCoupondetail, addCoupon, editCoupon } from '@/api/application/coupon'
// import { getGoodLists } from '@/api/goods'
import { usePaging } from '@/hooks/usePaging'
const appStore = useAppStore()
const route = useRoute()
const router = useRouter()
const formData: any = ref({
    id: '',
    name: '',
    money: '',
    condition_type: 1,
    condition_money: '',
    send_total_type: 1,
    send_total: '',
    use_time_type: 1,
    user_time_start: '',
    use_time_end: '',
    use_time: '',
    get_type: 1,
    get_num_type: 1,
    get_num: '',
    use_goods_type: 1,
    use_goods_ids: []
})
//表单校验
const formRef = ref<FormInstance>()
const validatetotal = (rule: any, value: any, callback: any) => {
    if (!value && formData.value.send_total_type == 2) {
        return callback(new Error('请输入每日发放数量'))
    }
    if (value > 1000000) {
        callback(new Error('超过最大数量1000000张'))
    }
    if (value < 0) {
        callback(new Error('发放数量需大于0'))
    }
}
const rules = reactive<FormRules>({
    name: [
        {
            required: true,
            message: '请输入优惠券名称',
            trigger: ['blur', 'change']
        }
    ],
    send_total: [
        {
            validator: validatetotal,
            required: true,

            // message: '请输入每日发放数量',
            trigger: ['blur', 'change']
        }
    ],
    use_time_type: [
        {
            required: true,
            message: '请选择使用时间',
            trigger: ['blur', 'change']
        }
    ],
    money: [
        {
            required: true,
            message: '请输入优惠券面额',
            trigger: ['blur', 'change']
        }
    ],
    get_type: [
        {
            required: true,
            message: '请选择领取方式',
            trigger: ['blur', 'change']
        }
    ],
    condition_type: [
        {
            required: true,
            message: '请选择使用门槛',
            trigger: ['blur', 'change']
        }
    ],
    use_goods_type: [
        {
            required: true,
            message: '请选择使用范围',
            trigger: ['blur', 'change']
        }
    ]
})
const getData = async () => {
    if (!route.query.id) return
    const res = await getCoupondetail({ id: route.query.id })

    formData.value = res
    formData.value.use_goods_ids = res.use_goods_ids.split(',')
    goodslists.value = res.goods
}
getData()
//展开选择商品框
const showselect = ref(false)
const selectRef = shallowRef<InstanceType<typeof Selectpopup>>()
const handleselect = async () => {
    showselect.value = true
    await nextTick()
    selectRef.value?.open()
}
const goodslists = ref([])
const handleselected = (val: any) => {
    showselect.value = false
    goodslists.value = val
    formData.value.use_goods_ids = val.map((item: any) => {
        return item.id
    })
}

const handleclearAll = () => {
    ;(goodslists.value = []), (formData.value.use_goods_ids = [])
}
const handleclear = (id: any) => {
    goodslists.value = goodslists.value.filter((item: any) => {
        return item.id != id
    })
    formData.value.use_goods_ids = formData.value.use_goods_ids.filter((item: any) => {
        return item.id != id
    })
}
//保存
const handleSubmit = async () => {
    await formRef.value?.validate()

    if (route.query.id) {
        await editCoupon(formData.value)
    } else {
        await addCoupon(formData.value)
    }

    router.back()
}
</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);
}
</style>
