<template>
    <a-modal :open="modal.open" :title="modal.title" :width="640" :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="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="concatName">
                                <a-input :placeholder="'请输入订单联系人'" v-model:value="formData.concatName"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'订单电话'" name="concatPhone">
                                <a-input :placeholder="'请输入订单电话'" v-model:value="formData.concatPhone"></a-input>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'排序'" name="sequence">
                                <a-input-number :placeholder="'请输入排序'" style="width: 100%;"
                                    v-model:value="formData.sequence"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'所需积分'" name="price">
                                <a-input-number :placeholder="'请输入所需积分'" style="width: 100%;"
                                    v-model:value="formData.price"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'已兑'" name="stock">
                                <a-input-number :placeholder="'请输入已兑数量'" style="width: 100%;"
                                    v-model:value="formData.stock"></a-input-number>
                            </a-form-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-item :label="'兑换数量上限'" name="maxNum">
                                <a-input-number :placeholder="'请输入兑换数量上限'" style="width: 100%;"
                                    v-model:value="formData.maxNum"></a-input-number>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'单人兑换次数上限'" name="canNum">
                                <a-input-number :placeholder="'请输入单人兑换次数上限'" style="width: 100%;"
                                    v-model:value="formData.canNum"></a-input-number>
                            </a-form-item>
                        </a-col>

                        <a-col :span="24">
                            <a-form-item :label="'详情'" name="details">
                                <x-editor v-model="editorContent" :uploadHandler="uploadHandler"
                                    :height="300"></x-editor>
                                <!-- <a-textarea :placeholder="'请输入详情'" v-model:value="formData.details" style="width: 100%;"
                                    :rows="4"></a-textarea> -->
                            </a-form-item>
                        </a-col>

                        <!-- <a-col :span="12">
                            <a-form-item :label="'是否热门'" name="isHot">
                                <a-radio-group v-model:value="formData.isHot" :options="[
                                    { label: '是', value: true },
                                    { label: '否', value: false },
                                ]"></a-radio-group>
                            </a-form-item>
                        </a-col> -->
                        <a-col :span="12">
                            <a-form-item :label="'所属区域'" name="areaId">
                                <a-select ref="select" v-model:value="formData.areaId">
                                    <a-select-option v-for="item in areaEnum.getAll()" :value="item.value">{{
                                        item.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'所属分类'" name="categoryId">
                                <a-select ref="select" v-model:value="formData.categoryId">
                                    <a-select-option v-for="item in categoryList" :value="item.value">{{
                                        item.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'权益到期时间'" name="expireAt">
                                <a-date-picker v-model:value="formData.expireAt"
                                    :show-time="{ format: 'YYYY-MM-DD HH:mm' }" format="YYYY-MM-DD HH:mm"
                                    style="width: 100%;" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'礼品有效期(天)'" name="expire">
                                <a-input-number :placeholder="'请输入礼品有效期'" style="width: 100%;"
                                    v-model:value="formData.expire"></a-input-number>
                            </a-form-item>
                        </a-col>

                        <a-col :span="12">
                            <a-form-item :label="'产品类别'" name="type">
                                <a-select v-model:value="formData.type" placeholder="请选择产品类别">
                                    <a-select-option v-for="value in typerEnum.getAll()" :key="value.value"
                                        :value="value.value">{{ value.name }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <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="'封面图'" name="fileList">
                                <gx-upload v-model="formData.fileList" accept-types=".jpg,.png,.webp" :fileNumber="1" />
                            </a-form-item>
                        </a-col>
                        <!-- <a-button type="primary" @click="handleCopy">复制</a-button> -->
                    </a-row>
                </a-card>
            </a-form>
        </a-spin>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, 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 dayjs from 'dayjs'
import GxUpload from '@/components/GxUpload/index.vue'
import { typerEnum, areaEnum } from "@/enums/useEnum"
import { spliceUrl, decryptString, encryptString } from "@/utils/util"
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 fileList = ref([])
const categoryList = ref([])
const editorContent = ref('')
formRules.value = {
    name: [{ required: true, message: '请输入权益名称' }],
    concatName: [{ required: true, message: '请输入订单联系人' }],
    concatPhone: [{ required: true, message: '请输入订单电话' }],
    price: [{ required: true, message: '请输入所需积分' }],
    sequence: [{ required: true, message: '请输入排序' }],
    stock: [{ required: true, message: '请输入已兑数量' }],
    maxNum: [{ required: true, message: '请输入兑换数量上限' }],
    canNum: [{ required: true, message: '请输入单人兑换次数上限' }],
    // details: [{ required: true, message: '请输入详情' }],
    isHot: [{ required: true, message: '请选择是否热门' }],
    areaId: [{ required: true, message: '请选择所属区域' }],
    expireAt: [{ required: true, message: '请选择权益到期时间' }],
    expire: [{ required: true, message: '请输入礼品有效期' }],
    type: [{ required: true, message: '请选择产品类别' }],
    status: [{ required: true, message: '请选择状态' }],
    fileList: [{ required: true, message: '请上传封面图', trigger: 'change' }],
    categoryId: [{ required: true, message: '请选择所属分类', trigger: 'change' }]
}
onBeforeMount(() => {
    formData.value.areaId = 1
    formData.value.isHot = true
    getCategory()
})
async function getCategory() {
    const { data, success } = await apis.equiteMgt.getCategory({ current: 1, pageSize: 99 }).catch()
    if (success) {
        console.log(data)
        categoryList.value = data.map(item => ({ value: item.id, name: item.name }))
    }
}
/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '新增',
    })
    // initData()
    formData.value.status = 'enabled'
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '编辑',
    })
    try {
        showSpining()
        const { data, success } = await apis.equiteMgt.getItem(record.id).catch()
        if (!success) {
            hideModal()
            return
        }
        hideSpining()
        formData.value = { ...data }
        formData.value.expireAt = data?.expireAt ? dayjs(data?.expireAt) : ''
        editorContent.value = data.details ? decryptString(data.details) : ''
        // editorContent.value = data.details
        if (data.cover && data.cover.length > 0) {
            formData.value.fileList = [data.cover].map(item => config('http.apiBasic') + item)
        }
    } catch (error) {
        message.error({ content: error.message })
        hideSpining()
    }

}
const uploadSuccess = (data) => {
    fileList.value.push(data)
}
// function handleCopy() {
//     formRef.value.validateFields().then(async (values) => {
//         try {
//             showLoading()
//             const params = {
//                 ...values,
//                 cover: spliceUrl(formData.value.fileList[0]),
//                 details: editorContent.value
//             }
//             let result = null
//             console.log(params)
//             result = await apis.equiteMgt.createProject(params).catch((error) => {
//                 throw new Error(error)
//             })
//             hideLoading()
//             if (config('http.code.success') === result?.success) {
//                 hideModal()
//                 emit('ok')
//             }
//         } catch (error) {
//             message.error({ content: error.message })
//             hideLoading()
//         }
//     })
//         .catch((e) => {
//             hideLoading()
//         })
// }
/**
 * 确定
 */
function handleOk() {
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            const params = {
                ...values,
                cover: spliceUrl(formData.value.fileList[0]),
                details: encryptString(editorContent.value),
            }
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.equiteMgt.createProject(params).catch((error) => {
                        throw new Error(error)
                    })
                    break
                case 'edit':
                    console.log(params)
                    result = await apis.equiteMgt.updateItem(formData.value.id, params).catch(() => {
                        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()
        })
}


/**
 * 取消
 */
function handleCancel() {
    formData.value.areaId = 1
    hideModal()
}
const onRangeChange = (value, dateString) => {
    console.log('value', value)
    console.log('Formatted Selected Time: ', dateString);
    formData.value.startAt = dayjs(dateString[0])
    formData.value.endAt = dayjs(dateString[1])
    console.log(formData.value)
};

/**
 * 关闭后
 */
function onAfterClose() {
    editorContent.value = ''
    resetForm()
    hideLoading()
}

defineExpose({
    handleCreate,
    handleEdit,
})
</script>

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