<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="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="24">
                            <a-form-item :label="'房刊标题'" name="title">
                                <a-input :placeholder="'请输入房刊标题'" v-model:value="formData.title"></a-input>
                            </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="pushAt">
                                <a-date-picker v-model:value="formData.pushAt" style="width: 100%;" />
                            </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="'封面'" name="imgList">
                                <gx-upload v-model="formData.imgList" accept-types=".jpg,.png,.webp" :fileNumber="1"
                                    @uploadSuccess="uploadSuccess" />
                            </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'
import { customersEnum, areaEnum } from "@/enums/useEnum"
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 rolesValue = ref([])
const roles = ref([])
const ceshi = ref('1222')
const editorContent = ref('')
const areaList = ref([])
const childOpen = ref(false)
const fileList = ref([])
const formArea = ref({ name: '', status: 'enabled' })
formRules.value = {
    name: { required: true, message: '请输入案场名称' },
    title: { required: true, message: '请输入房刊标题' },
    content: { required: true, message: '请输入内容' },
    imgList: { required: true, message: '请输入选择图片', trigger: 'change' },
    pushAt: { required: true, message: '请输入发布时间', trigger: 'change' },
    status: [{ required: true, message: '请选择状态', trigger: 'change' }],
    areaId: [{ required: true, message: '请选择所属区域', trigger: 'change' }]
}



/**
 * 新建
 */
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.houseArticles.getItem(record.id).catch()
        if (!success) {
            hideModal()
            return
        }
        hideSpining()
        formData.value = {
            name: data.name,
            title: data.title,
            id:data.id,
            status: data.status,
            areaId: data.areaId,
            pushAt: dayjs(data.pushAt),
            imgList: [config('http.apiBasic') + data.cover]
        }
        editorContent.value = decryptString(data.content)
        if (data.cover) {
            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() {
    // if (fileList.value.length === 0) return message.error('请上传图片')
    formRef.value.validateFields().then(async (values) => {
        try {
            showLoading()
            const params = {
                areaId:formData.value.areaId,
                name: formData.value.name,
                status: formData.value.status,
                title: formData.value.title,
                content: encryptString(editorContent.value),
                pushAt: formData.value.pushAt,
                cover: formData.value.imgList && spliceUrl(formData.value.imgList[0])
            }
            let result = null
            switch (modal.value.type) {
                case 'create':
                    result = await apis.houseArticles.createProject(params).catch((error) => {
                        throw new Error(error)
                    })
                    break
                case 'edit':
                    result = await apis.houseArticles.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()
        })
}
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 handleCancel() {
    hideModal()
}

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

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

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