<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-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="$t('pages.system.announcement.form.title')" name="title">
                            <a-input :placeholder="$t('pages.system.announcement.form.title.placeholder')"
                                v-model:value="formData.title"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item :label="$t('pages.system.announcement.form.content')" name="content">
                            <a-textarea v-model:value="formData.content"
                                :placeholder="$t('pages.system.announcement.form.content.placeholder')" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item :label="'所属区域'" name="areaId">
                            <a-select ref="select" v-model:value="formData.areaId" :placeholder="$t('pages.system.announcement.form.content.placeholder')">
                                <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="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="$t('pages.system.announcement.form.createdAt')"
                            name="createdAt">
                            <a-input
                                v-model:value="formData.createdAt"
                                :placeholder="$t('pages.system.announcement.form.createdAt.placeholder')" />
                        </a-form-item>
                    </a-col> -->
                </a-row>
            </a-card>
        </a-form>
    </a-modal>
</template>

<script setup>
import { areaEnum } from "@/enums/useEnum"
import { cloneDeep } from 'lodash-es'
import { ref } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import { message } from 'ant-design-vue'
import { useI18n } from 'vue-i18n'
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([])

formRules.value = {
    title: { required: true, message: t('pages.system.announcement.form.title.placeholder') },
    content: { required: true, message: t('pages.system.announcement.form.content.placeholder') },
    areaId: { required: true, message: '请选择区域'},
    status: { required: true, message: '请选择是否启用'},
}

/**
 * 请求角色
 */
getRole()

/**
 * 新建
 */
function handleCreate() {
    showModal({
        type: 'create',
        title: t('pages.system.announcement.add'),
    })
}
async function getRole() {
    const { success, data } = await apis.role.getRoleList().catch(() => {
        throw new Error()
    })
    if (!success) {
        return message.error('当前角色信息错误')
    }
    let roleArr = []
    if (data.length) {
        data.forEach((item) => {
            roleArr.push({
                label: item.name,
                value: item.id,
            })
        })
    }
    roles.value = roleArr
}
/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '修改公告信息',
    })
    const { data, success } = await apis.announcement.getNotices(record.id).catch()
    if (!success) {
        hideModal()
        return
    }
    let roles = []
    if (data.roles) {
        roles = formatArr(data.roles, 'edit')
    }

    data.roles = roles
    formRecord.value = data
    formData.value = cloneDeep(data)
}

/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()

                const params = {
                    ...values,
                    roles: formatArr(rolesValue.value),
                }
                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
}

/**
 * 取消
 */
function handleCancel() {
    hideModal()
}

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

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

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