<template>
    <a-modal :open="modal.open" :title="modal.title" :width="800" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" :ok-text="okText" @ok="handleOk" @cancel="handleCancel">
        <a-spin :spinning="spining">
            <a-form ref="formRef" :model="formData" :rules="formRules">
                <a-card class="mb-8-2">
                    <a-row :gutter="12">
                        <a-col :span="24">
                            <a-form-item :label="'所属规则'" name="raffleId">
                                <a-select ref="select" v-model:value="formData.raffleId">
                                    <a-select-option v-for="item in listData" :value="item.id">{{
                                        item.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'奖品类型'" name="type">
                                <a-select ref="select" v-model:value="formData.type">
                                    <a-select-option v-for="item in lotteryTypes" :value="item.id">{{
                                        item.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'积分数'" name="point" v-if="formData.type==='point'">
                                <a-input-number :placeholder="'请输入积分数'" v-model:value="formData.point"
                                    style="width: 100%;"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'奖品名称'" name="name">
                                <a-input :placeholder="'请输入奖品名称'" v-model:value="formData.name"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'中奖数无限制'" name="">
                                <a-checkbox v-model:checked="numChecked"></a-checkbox>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'保底概率'" name="">
                                <a-checkbox v-model:checked="probabilityChecked"></a-checkbox>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'最大中奖数'" name="maxNum" v-if="!numChecked">
                                <a-input-number :placeholder="'请输入最大中奖数'" v-model:value="formData.maxNum"
                                    style="width: 100%;"></a-input-number>
                            </a-form-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-item :label="'中奖率'" name="probability" v-if="!probabilityChecked">
                                <a-input-number :placeholder="'请输入中奖率'" v-model:value="formData.probability"
                                    addon-after="%" style="width: 100%;"></a-input-number>
                            </a-form-item>
                        </a-col>

                        <a-col :span="24">
                            <a-form-item :label="'状态'" name="status">
                                <a-radio-group v-model:value="formData.status" :options="[
                                    { label: '启用', value: 'enabled' },
                                    { label: '停用', value: 'disabled' },
                                ]"></a-radio-group>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'奖品图片'">
                                <gx-upload v-model="formData.imgList" accept-types=".jpg,.png,.webp" :fileNumber="1" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-card>
            </a-form>
        </a-spin>
    </a-modal>
</template>

<script setup>
import { ref, h, onBeforeMount } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal, useSpining } from '@/hooks'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
import { spliceUrl } from "@/utils/util.js"
const emit = defineEmits(['ok'])
const { t } = useI18n() // 解构出t方法
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const { spining, showSpining, hideSpining } = useSpining()
const cancelText = ref(t('button.cancel'))
const okText = ref(t('button.confirm'))
const listData = ref([])
const lotteryTypes = ref([
    { id: 'point', name: '积分奖品' },
    { id: 'product', name: '实体奖品' },
    { id: 'none', name: '谢谢惠顾' },
])
const numChecked = ref(false)
const probabilityChecked = ref(false)
formRules.value = {
    type: { required: true, message: '请选择奖品类型' },
    name: { required: true, message: '请输入奖品名称' },
    maxNum: { required: true, message: '请输入最大中奖数' },
    point: { required: true, message: '请输入积分数' },
    probability: { required: true, message: '请中奖率', trigger: 'change' },
    status: [{ required: true, message: '请输入状态', trigger: 'change' }],
}
const getData = async () => {
    const { success, data, total } = await apis.raffles
        .getProjectList({
            pageSize: 99,
            page: 1,
        })
        .catch(() => {
            throw new Error()
        })
    if (config('http.code.success') === success) {
        listData.value = data.map(item => ({ id: item.id, name: item.title }))
    }
}
/**
 * 新建
 */
function handleCreate() {
    getData()
    showModal({
        type: 'create',
        title: '新增奖品',
    })
    formData.value.status = 'enabled'
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '编辑奖品',
    })
    try {
        showSpining()
        getData()
        const { data, success } = await apis.raffleProduct.getItem(record.id).catch()
        if (!success) {
            hideModal()
            return
        }
        hideSpining()
        formData.value = {
            ...data,
            probability: data.probability * 100,
            imgList: data.img ? [config('http.apiBasic') + data.img] : []
        }
        numChecked.value = data.maxNum < 0 ? true : false
        probabilityChecked.value = data.probability < 0 ? true : false
    } catch (error) {
        message.error({ content: error.message })
        hideSpining()
    }

}
/**
 * 确定
 */
function handleOk() {
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            const params = {
                ...formData.value,
                probability: probabilityChecked.value ? -1 : formData.value.probability / 100,
                img: formData.value.imgList && spliceUrl(formData.value.imgList[0]),
                maxNum: numChecked.value ? -1 : formData.value.maxNum,
            }
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.raffleProduct.createProject(params).catch((error) => {
                        console.log(error.message)
                        throw new Error(error)
                    })
                    break
                case 'edit':

                    result = await apis.raffleProduct.updateItem(formData.value.id, params).catch(() => {
                        console.log(error.message)
                        throw new Error(error)
                    })
                    break
            }
            hideLoading()
            if (config('http.code.success') === result?.success) {
                hideModal()
                emit('ok')
            }
        } catch (error) {
            message.error({ content: error.message })
            hideLoading()
        }
    })
        .catch((e) => {
            hideLoading()
        })
}

// 在 setup 中添加这些方法
const updateLabel = (index, value) => {
    formData.value.labels[index] = value;
};

const addLabel = () => {
    formData.value.labels.push('');
};

const removeLabel = (index) => {
    formData.value.labels.splice(index, 1);
};
/**
 * 取消
 */
function handleCancel() {

    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
    hideLoading()
}

defineExpose({
    handleCreate,
    handleEdit,
})

</script>

<style lang="less" scoped></style>
