<!-- 发布公告 -->
<template>
    <el-dialog :title="`${ editType == 'add' ? '发布' : '编辑' }公告`" v-model="visible" width="1150px" destroy-on-close>
        <el-form ref="bulletinFormRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="选择栏目：" prop="columnValue">
                <SelectDict placeholder="请选择栏目" v-model="form.columnValue" dictCode="bulletin_column"></SelectDict>
            </el-form-item>
            <el-form-item label="公告标题：" prop="title">
                <el-input v-model="form.title" placeholder="请输入公告标题" />
            </el-form-item>
            <el-form-item label="接收人员：" prop="ownerBy">
                <el-radio-group v-model="form.bulletinType" style="margin-bottom: 5px" @change="changeType">
                    <el-radio :value="1" label="全体员工"></el-radio>
                    <el-radio :value="2" label="指定人员"></el-radio>
                </el-radio-group>
                <SelectUser v-model="form.noticeUserIdList" multiple v-if="form.bulletinType == 2"></SelectUser>
            </el-form-item>
            <el-form-item label="公告详情：" prop="content">
                <ckeditor class="template_ckeditor" @sendContnet="getContent" :content="form.content"></ckeditor>
            </el-form-item>
            <el-form-item label="上传附件：" class="form-item">
                <Upload :isTips="false" v-model="form.fileIds" :resourceList="fileList" @uploadStatus="uploadStatus" />
            </el-form-item>
            <el-form-item label="其他设置：" prop="taskContent">
                <el-checkbox v-model="form.isTalk" :true-value="1" :false-value="2">允许评论</el-checkbox>
            </el-form-item>
            <el-form-item label="提醒方式：">
                <SelectDict
                    type="checkbox"
                    disabledItem="site"
                    :selectedFirst="editType == 'add'"
                    v-model="remindModels"
                    dictCode="task_remind_mode"
                ></SelectDict>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button :loading="buttonLoading" :disabled="fileLoading" type="primary" @click="submitForm">提交</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { addBulletin, updateBulletin, getBulletin } from '@/api/system/bulletin';
    import { BulletinForm, BulletinQuery } from '@/api/system/bulletin/types';
    import { useDictCache } from '@/hooks/web/useDict'
    import ckeditor from '@/components/ckeditor/index.vue'
    import useUserStore from '@/store/modules/user';
    const { queryDictDetailByCodes } = useDictCache(['task_remind_mode','bulletin_column'])
    queryDictDetailByCodes()

    const emits = defineEmits(['refresh'])

    const getContent = (val: string) => {
        form.value.content = val
    }

    const visible = ref(false)
    const buttonLoading = ref(false)

    const fileList = ref([])
    const bulletinFormRef = ref<ElFormInstance>();
    const remindModels = ref([])
    const initFormData: BulletinForm = {
        id: undefined,
        title: '',
        content: '',
        columnValue: '',
        noticeUserIdList: [],
        noticeUserIds: '',
        isTalk: 1,
        remindMode: '',
        fileIds: [],
        files: undefined,
        bulletinType: 1
    }

    const data = reactive<PageData<BulletinForm, BulletinQuery>>({
        form: { ...initFormData },
        rules: {
            columnValue: [
                { required: true, message: "请选择栏目", trigger: "change" }
            ],
            title: [
                { required: true, message: "公告标题不能为空", trigger: "change" }
            ],
            content: [
                { required: true, message: "公告详情不能为空", trigger: "blur" }
            ]
        }
    });

    const { form, rules } = toRefs(data);

    const editType = ref('')
    const { userInfo } = useUserStore();
    const open = (type, id) => {
        reset();
        editType.value = type
        fileList.value = []
        if(id) {
            getBulletin(id, userInfo.id).then(res => {
                if(res.success) {
                    let datas = res.result
                    fileList.value = datas.files || []
                    setTimeout(() => {
                        form.value.content = datas.content
                        Object.assign(form.value, datas)
                        remindModels.value = res.result.remindMode?.split(',')
                        form.value.noticeUserIdList = form.value.noticeUserIds ? form.value.noticeUserIds.split(',') : []
                        delete form.value.files
                    }, 100)
                }
            })
        }
        visible.value = true
    }

    const changeType = () => {
        form.value.noticeUserIdList = []
        form.value.noticeUserIds = ''
    }

    const fileLoading = ref(false)
    const uploadStatus = (type) => {
        if(type == 'loading') {
            fileLoading.value = true
        } else {
            fileLoading.value = false
        }
    }

    const submitForm = () => {
        bulletinFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                let params = JSON.parse(JSON.stringify(form.value))
                params.remindMode = remindModels.value.join(',')
                params.noticeUserIds = params.noticeUserIdList.join(',')
                buttonLoading.value = true;
                let request = editType.value == 'edit' ? updateBulletin : addBulletin
                await request(params).finally(() => buttonLoading.value = false);
                ElMessage.success((editType.value == 'add' ? '新增' : '编辑') + "成功");
                reset()
                visible.value = false
                emits('refresh')
            }
        });
    }

    const cancel = () => {
        reset();
        visible.value = false
    }

    /** 表单重置 */
    const reset = () => {
        form.value = { ...initFormData };
        bulletinFormRef.value?.resetFields();
    }

    defineExpose({
        open
    })
</script>

<style lang="scss" scoped>
    :deep(.sle-user-el-input) {
        margin-top: 5px;
    }
</style>
