<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="companyId">
                                <a-select v-model:value="formData.companyId" style="width: 100%">
                                    <a-select-option v-for="item of companyList" :value="item.id">{{ item.name
                                        }}</a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                          <a-col :span="12">
                            <a-form-item :label="'兑换数量'" name="maxNum">
                                <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="startAt">
                                <a-date-picker :placeholder="'请选择开始时间'"
                                    v-model:value="formData.startAt" style="width: 100%;" ></a-date-picker>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item :label="'结束时间'" name="endAt">
                                <a-date-picker :placeholder="'请选择结束时间'" v-model:value="formData.endAt" style="width: 100%;"></a-date-picker>
                            </a-form-item>
                        </a-col>
                      
                         <a-col :span="12">
                            <a-form-item :label="'是否每天'" name="isDaily">
                                 <a-radio-group v-model:value="formData.isDaily" :options="[
                                    { label: '是', value: true },
                                    { label: '否', value: false },
                                ]"></a-radio-group>
                            </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="'内容'">
                                <x-editor v-model="editorContent" :uploadHandler="uploadHandler" :height="300"></x-editor>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'礼品图片'">
                                <gx-upload v-model="formData.fileList" 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 { 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 { spliceUrl,decryptString,encryptString } from '@/utils/util'
const areaFormRef = ref()
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 companyList = ref([])
const editorContent=ref('')
formRules.value = {
    name: { required: true, message: '请输入礼品名称' },
    maxNum: { required: true, message: '请输入最大数量' },
    companyId: { required: true, message: '请选择案场',trigger:'change' },
    startAt: { required: true, message: '请选择开始时间',trigger:'change' },
    endAt: { required: true, message: '请选择结束时间',trigger:'change' },
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
}
onBeforeMount(async () => {
    const { success, data, total } = await apis.project
        .getProjectList({
            pageSize: 100,
            page: 1,
        })
        .catch(() => {
            throw new Error()
        })
    if (config('http.code.success') === success) {
        companyList.value = data.map(item => ({ id: item.id, name: item.name }))
    }
})


/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '新增礼品',
    })
    formData.value.status = 'enabled'
    formData.value.isDaily=true
}

/**
 * 编辑
 */
async function handleEdit(id) {
    showModal({
        type: 'edit',
        title: '编辑礼品',
    })
    try {
        showSpining()
        const { data, success } = await apis.houseProduct.getItem(id).catch()
        if (!success) {
            hideModal()
            return
        }
        hideSpining()
        editorContent.value=decryptString(data.content)
        formData.value = {
            ...data,
            startAt:dayjs(data.startAt),
            endAt:dayjs(data.endAt) 
        }
        if (data.img) {
            formData.value.fileList = [config('http.apiBasic') + data.img]
        }
    } catch (error) {
        message.error({ content: error.message })
        hideSpining()
    }

}
const uploadSuccess = (data) => {
    fileList.value.push(data)
}
/**
 * 确定
 */
function handleOk() {
    console.log(editorContent.value)
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            const params = {
               ...values,
               content:encryptString(editorContent.value),
               img:formData.value.fileList?spliceUrl(formData.value.fileList[0]):''
            }
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.houseProduct.createProject(params).catch((error) => {
                        throw new Error(error)
                    })
                    break
                case 'edit':
                    result = await apis.houseProduct.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() {
    hideModal()
}
const uploadHandler = async (file) => {
    const formData = new FormData();
    formData.append('file', file);
    const { data } = await apis.common.uploadImg(formData);
    return config('http.apiBasic') + data
}
/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
    hideLoading()
}

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

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