<!-- Dialog.vue -->
<template>
    <el-dialog :visible.sync="visible" @update:visible="handleUpdateVisible" :title="title + '职责目录'" :width="width"
        :before-close="beforeClose">

        <el-form inline :model="formData" label-width="" :label-position="'right'" :disabled="dialogTitle == '查看'"
            class="form-detail-inline" :rules="formRules" ref="ruleFormRef">
            <el-form-item label="所属机构名称" prop="agenciesName">
                <el-cascader v-model="formData.agenciesName" placeholder="请选择所属单位机构名称" :options="buildDepartmentOptions"
                    :props="{ value: 'id', label: 'directoryName', children: 'list' }" @change="agenciesNameChange" />
            </el-form-item>
            <el-form-item label="内设机构职责" prop="agenciesPrsponsibility">
                <el-input v-model="formData.agenciesPrsponsibility" :title="formData.agenciesPrsponsibility"
                    placeholder="请输入内设机构职责"></el-input>
            </el-form-item>
            <el-form-item label="职责事项" prop="matters">
                <el-input v-model="formData.matters" :title="formData.matters" placeholder="请输入职责事项"></el-input>
            </el-form-item>
            <el-form-item label="数据资源名称" prop="databasename">
                <el-input v-model="formData.databasename" :title="formData.databasename"
                    placeholder="请输入数据资源名称"></el-input>
            </el-form-item>
            <el-form-item label="职责类型" prop="type">
                <el-input v-model="formData.type" placeholder="请输入职责类型"></el-input>
            </el-form-item>
            <el-form-item label="职责目录编码" prop="code">
                <el-input v-model="formData.code" placeholder="提交后自动生成" disabled></el-input>
            </el-form-item>
            <el-form-item label="核心数据项" prop="database">
                <el-input v-model="formData.database" :title="formData.database" placeholder="请输入核心数据项"></el-input>
            </el-form-item>
            <el-form-item label="对应信息系统" prop="system">
                <!-- <el-input v-model="formData.system" :title="formData.system" placeholder="请输入对应信息系统" /> -->
                <el-select v-model="formData.system" placeholder="请选择系统架构">
                    <el-option v-for="item in systemOption" :key="item.id" :label="item.misProjectName"
                        :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="ps" class="textarea-row">
                <el-input v-model="formData.ps" :title="formData.ps" type="textarea" :rows="4" placeholder="请输入备注" />
            </el-form-item>
            <el-form-item label="变更原因" v-if="dialogTitle == '审核'" prop="agenciesName">
                <el-input :disabled="dialogTitle == '审核'" v-model="formData.agenciesName" placeholder="请输入变更原因" />
            </el-form-item>

            <!-- <template v-if="operationType == 'aduit'">
        <el-row>
          <el-col :span="12" class="two-form">
         
          </el-col>
          <el-col :span="12"></el-col>
          <el-col :span="7"></el-col>
        </el-row>
      </template> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取 消</el-button>
            <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { queryMisList, getDirectoryAllLevel } from '@/api/unified-resources/information-system/index.js'
import { getResponsibilityMsg, addResponsibility, updateResponsibility } from '@/api/unified-resources/job-directory/index.js'
import MyForm from "@/components/MyForm";
export default {
    name: "StandardDialog",
    components: {
        MyForm,
    },
    props: {
        value: {
            type: Boolean,
            default: false,
        },
        title: {
            type: String,
            default: "弹窗标题",
        },
        rowObj: {
            type: Object,
            default: {},
        },
        width: {
            type: String,
            default: "50%",
        },
    },
    data() {
        return {
            visible: this.value,
            dialogTitle: '',
            itemView: {},
            // 这是传递给表单组件的数据
            formData: {},
            isDisabled: false,
            buildDepartmentOptions: [],
            systemOption: [],
            formRules: {
                agenciesName: [{ required: true, message: '请输入所属机构名称', trigger: 'blur' }],
                agenciesPrsponsibility: [{ required: true, message: '请输入内设机构职责', trigger: 'blur' }],
                matters: [{ required: true, message: '请输入职责事项', trigger: 'blur' }],
                databasename: [{ required: true, message: '请输入职责事项', trigger: 'blur' }],
                type: [{ required: true, message: '请输入职责类型', trigger: 'blur' }],
                code: [{ required: true, message: '请输入职责目录编码', trigger: 'blur' }],
                database: [{ required: true, message: '请输入核心数据项', trigger: 'blur' }],
                system: [{ required: true, message: '请输入对应信息系统', trigger: 'blur' }]
            }
        };
    },
    watch: {
        value(newVal) {
            this.visible = newVal;
        },
        visible(newVal) {
            this.$emit("input", newVal);
        },
        title: {
            handler(newVal) {
                this.dialogTitle = newVal;
            },
            deep: true, // 深入监听
            immediate: true,
        },
        rowObj: {
            handler(newVal) {
                this.itemView = newVal;
            },
            deep: true, // 深入监听
            immediate: true,
        },
    },

    mounted() {
        this.getOrganizationalList()
        this.getTableListData()

        if (this.dialogTitle !== '新增') {
            getResponsibilityMsg({ id: this.itemView.id }).then(res => {
                if (+res.code === 200) {
                    this.getTableListData(res.data[0].agenciesName)
                    this.formData = res.data[0]
                    this.formData.agenciesName = res.data[0].agenciesName ? res.data[0].agenciesName?.split(',') : []

                }
            })
        } 

    },
    methods: {
        getOrganizationalList() {
            getDirectoryAllLevel({ type: '组织机构' }).then(res => {
                if (+res.code === 200) {
                    if (res.data === null) {
                        this.buildDepartmentOptions = []
                    } else {
                        this.removeListForLevel4(res.data[0].list)
                        this.buildDepartmentOptions = res.data[0].list
                    }
                }
            })
        },
        agenciesNameChange(value) {
            let str = value.join(',')
            this.getTableListData(str)
        },
        removeListForLevel4(data) {
            data.forEach(item => {
                // 如果是 level 4 的项，删除 list 属性
                if (item.level === '4') {
                    delete item.list;
                }
                // 如果当前项有子项（list），递归调用该函数
                if (item.list && item.list.length > 0) {
                    this.removeListForLevel4(item.list);
                }
            });
        },
        getTableListData(misProjectNameVal) {
            queryMisList({ pageNumber: 1, pageSize: 9999, belongDepartment: misProjectNameVal }).then(res => {
                if (res.data === null) {
                    this.systemOption = []
                } else {
                    this.systemOption = res.data
                }
            })
        },
        handleUpdateVisible(val) {
            this.visible = val;
        },
        beforeClose(done) {
            this.visible = false;
            this.$emit("before-close", done);
        },
        // 取消按钮处理方法
        handleCancel() {
            this.visible = false;
            this.$emit("cancel"); // 可以在父组件监听 'cancel' 事件
        },

        // 确定按钮处理方法
        async handleConfirm() {
            if (this.title === "新增") {
                this.formData.code = this.createRandomId()
            }
            // this.$refs.myFormComponent.validateForm();
            await this.$refs.ruleFormRef.validate((valid, fields) => {
                if (valid) {
                    // 校验通过，进行后续操作
                    console.log("表单校验通过，进行后续操作");
                    this.handleSave();
                } else {
                    this.$message.error("请完整填写表单");
                    console.log("表单校验失败");
                }
            })

        },

        handleSave() {

            let pForm = {}
            pForm = { ...this.formData }
            pForm.agenciesName = pForm.agenciesName ? pForm.agenciesName?.join(',') : ''
            if (this.title === "新增") {
                addResponsibility({ ...pForm }).then(res => {
                    if (+res.code === 200) {
                        this.$message.success(res.msg)
                        this.$emit("confirm");
                        this.handleCancel()
                    }
                })
            } else {
                updateResponsibility({ id: this.itemView.id, ...pForm }).then(res => {
                    if (+res.code === 200) {
                        this.$message.success(res.msg)
                        this.$emit("confirm");
                        this.handleCancel()
                    }
                })
            }
        },
        createRandomId() {
            let min = Math.pow(10, 14);
            let max = Math.pow(10, 15) - 1;
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
    },
};
</script>

<style scoped lang="scss">
/* 你可以根据需要为弹窗添加样式 */
</style>