<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" :label-col="{ style: { width: '90px' } }">
                <a-card class="mb-8-2">
                    <a-row :gutter="24">
                        <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="createdAt">
                                <a-date-picker v-model:value="formData.createdAt" placeholder="请选择发布时间"
                                    style="width: 100%;" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="排序" name="sequence">
                                <a-input-number v-model:value="formData.sequence" style="width: 100%;" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'状态'" name="status">
                                <a-radio-group v-model:value="formData.status" :options="announcementStatus.getAll()" disabled></a-radio-group>
                            </a-form-item>
                        </a-col>
                         <a-col :span="24">
                            <a-form-item :label="'公告简介'" name="desc">
                                <a-textarea v-model:value="formData.desc" ></a-textarea>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'公告内容'" name="content">
                                <x-editor v-model="formData.content" :uploadHandler="uploadHandler" :height="350"></x-editor>
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item :label="'公告封面'" name="cover">
                                <gx-upload  v-model="formData.cover" :fileNumber="1"></gx-upload>
                            </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 } 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 { announcementStatus } from '@/enums/index'
import {spliceUrl} 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 cancelText = ref(t('button.cancel'))
const okText = ref(t('button.confirm'))
const rolesValue = ref([])
const roles = ref([])
const { spining, showSpining, hideSpining } = useSpining()
formRules.value = {
    title: { required: true, message: '请输入标题' },
    desc: { required: true, message: '请输入简介' },
    content: { required: true, message: '请输入内容' },
    sequence: { required: true, message: '请选择排序' },
    status: { required: true, message: '请选择是否启用' },
    createdAt: { required: true, message: '请选择创建时间' },
    cover:{required: false, message: '请上传封面'}
}

/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: '新增',
    })
    formData.value.status = 1
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    try {
        showModal({ type: 'edit', title: '修改公告信息' })
        showSpining()
        const { data, success } = await apis.announcement.getNotices(record.id).catch()
        if (!success) {
            hideModal()
            return
        }
        hideSpining()
        formData.value = { ...data }
        formData.value.createdAt = dayjs(data.createdAt)
        formData.value.cover=formData.value.cover?[config('http.apiBasic')+formData.value.cover]:[]
    } catch (error) {
        message.error(error.message)
    }

}

/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                const params = {
                    ...values,
                    cover:formData.value.cover?spliceUrl(formData.value.cover[0]):'',
                    status:1
                } 
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.announcement.createNotices(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        result = await apis.announcement.updateNotices(formData.value.id, params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === result?.success) {
                    hideModal()
                    emit('ok')
                    message.success(modal.value.type === 'create' ? '创建成功' : '更新成功')
                }
            } catch (error) {
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}

/**
 * 对权限组 过数据格式
 */
function formatArr(data, type = '') {
    const rolesArr = []
    data.forEach((item) => {
        roles.value.forEach((r) => {
            if (type === 'edit') {
                if (item.role_id === r.value) {
                    rolesArr.push({
                        value: item.role_id,
                        label: r.label,
                    })
                    return
                }
            } else if (r.value === item) {
                rolesArr.push({
                    role_id: item,
                    role_name: r.label,
                })
                return
            }
        })
    })
    return rolesArr
}
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>
