<template>
    <el-dialog :title="formData.id ? '编辑' : '创建'" :visible.sync="dialogVisible" width="1000px"
        custom-class="ele-dialog-form" :lock-scroll="false" @closed="handleClosed">
        <el-form :model="formData" ref="formRef" :rules="rules" label-width="100px">
            <el-row :gutter="15">
                <el-col :sm="12">
                    <el-form-item label="类型:" prop="type" v-if="!this.defaultType">
                        <el-select v-model="formData.type" placeholder="请选择类型" class="ele-fluid">
                            <el-option v-for="item in typeArr" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="标题:" prop="title">
                        <el-input v-model="formData.title" placeholder="请输入标题" clearable />
                    </el-form-item>
                    <el-form-item label="作者:" prop="author" v-if="!isSmartReply">
                        <el-input v-model="formData.author" placeholder="请输入作者" clearable />
                    </el-form-item>
                    <el-form-item label="状态:" prop="status">
                        <el-radio-group v-model="formData.status">
                            <el-radio :label="1">发布</el-radio>
                            <el-radio :label="2">不发布</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="排序:" prop="sort">
                        <el-input v-model="formData.sort" placeholder="请输入排序号" clearable />
                    </el-form-item>
                </el-col>
                <el-col :sm="12">
                    <el-form-item label="内容:" prop="content">
                        <tinymce-editor v-model="formData.content" :init="editorConfig" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <div slot="footer">
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="save">保存</el-button>
        </div>
    </el-dialog>
</template>

<script>
import TinymceEditor from '@/components/TinymceEditor'

export default {
    name: 'ArticleForm',
    components: { TinymceEditor },
    props: {
        defaultType: { type: [Number, String, Array], default: null },
        visible: { type: Boolean, default: false },
        defaultData: { type: Object, default: () => ({ status: 1, type: 1 }) },
    },
    data() {
        return {
            formData: Object.assign({}, this.defaultData),
            typeArr: [
                { id: 1, name: '文章资讯' },
                { id: 2, name: '注册协议' },
                { id: 3, name: '隐私政策' },
                { id: 4, name: 'VIP购买协议' },
                { id: 9, name: '智能问答' },
            ],
        }
    },
    computed: {
        // 弹窗显示状态（处理prop的双向绑定）
        dialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        },
        // 判断是否为智能问答类型
        isSmartReply() {
            // 处理 defaultType 可能是 Number、String 或 Array 的情况
            let currentType = this.defaultType || this.formData.type;
            if (Array.isArray(this.defaultType)) {
                // 如果是数组，使用第一个元素判断
                currentType = this.defaultType.length > 0 ? this.defaultType[0] : this.formData.type;
            }
            const b = currentType == 9;
            console.log('isSmartReply', b, this.defaultType)
            return b;
        },
        // 动态验证规则
        rules() {
            const baseRules = {
                title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
                type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
                content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
            };

            // 智能问答不需要验证作者
            if (!this.isSmartReply) {
                baseRules.author = [{ required: true, message: '请输入作者', trigger: 'blur' }];
            }

            return baseRules;
        },
        editorConfig() {
            return {
                menubar: false,
                skin_url: '/tinymce/skins/ui/oxide',
                content_css: '/tinymce/skins/content/default/content.css',
                height: 400,
            }
        },
    },
    watch: {
        defaultData(val) {
            this.formData = Object.assign({}, val)
        },
    },
    methods: {
        closeDialog() {
            this.$emit('update:visible', false);
        },
        handleClosed() {
            // 对话框关闭后重置表单
            this.resetForm();
        },
        resetForm() {
            if (this.$refs.formRef) {
                this.$refs.formRef.resetFields();
            }
            this.formData = Object.assign({}, this.defaultData);
        },
        save() {
            this.$refs.formRef.validate(valid => {
                if (!valid) return

                // 处理 defaultType 可能是 Number、String 或 Array 的情况
                let typeValue = this.formData.type;
                if (this.defaultType) {
                    if (Array.isArray(this.defaultType)) {
                        // 如果是数组，使用第一个元素
                        typeValue = this.defaultType.length > 0 ? Number(this.defaultType[0]) : this.formData.type;
                    } else {
                        typeValue = this.defaultType;
                    }
                }

                const loading = this.$loading({ lock: true })
                this.$http.post('/article/edit', { ... this.formData, type: typeValue })
                    .then(res => {
                        loading.close()
                        if (res.data.code === 0) {
                            this.$message.success(res.data.msg)
                            this.$emit('success')
                            this.closeDialog()
                        } else {
                            this.$message.error(res.data.msg)
                        }
                    })
                    .catch(e => {
                        loading.close()
                        this.$message.error(e.message)
                    })
            })
        },
    },
}
</script>

<style scoped>
.ele-dialog-form>>>.tox-tinymce {
    width: 100%;
}
</style>