<template>
    <!-- 小型弹窗，用于完成，删除，保存等操作 -->
    <el-dialog class="l-dialog" :class="lDialog" :title="title" :visible.sync="dialogVisible" :showClose="true"
        :closeOnClickModal="false" @close="handleClose" :append-to-body="true">
        <div>
            <el-form :model="form" :rules="dynamicRules" ref="ruleForm" label-width="110px"
                :validate-on-rule-change="false">
                <el-form-item label="上级节点" prop="parentId">
                    <treeselect v-model="form.parentId" :options="treeDataList" placeholder="请选择上级节点" value-key="id"
                        @select="onParentSelect" noChildrenText="没有数据了" noOptionsText="没有数据了" noResultsText="没有搜索结果" />
                </el-form-item>
                <el-form-item :label="getFormLabel('contentName')" prop="contentName">
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" class="form-item" v-model="form.contentName" clearable show-word-limit
                        :placeholder="getFormPlaceholder('contentName')" maxlength="64"></el-input>
                </el-form-item>
                <el-form-item :label="getFormLabel('sort')" prop="sort">
                    <el-input-number v-model="form.sort" :min="0" :label="getFormPlaceholder('sort')" controls-position="right"
                        style="width: 100%;"></el-input-number>
                        <template>
                            <span style="color: #f00000;">{{sortTitle}}</span>
                        </template>
                </el-form-item>
            </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button class="clear-btn" @click="handleClose" :disabled="disabled">取消</el-button>
            <el-button type="primary" class="search-btn" :disabled="disabled"
                @click="submitForm('ruleForm')">确认</el-button>
        </span>
    </el-dialog>
</template>
<script>
import _ from 'lodash'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getArchivalCatalogueTreeApi, addArchiveLeftApi, editArchiveLeftApi,geMaxSortApi } from '@/api/archivesManagement/index.js'
export default {
    name: "AddTreeData",
    props: ["width", "dataForm", "title", "disabled", "isAdd", "rowData"],
    components: { Treeselect },
    data() {
        return {
            lDialog: this.width > 500 ? "w700" : "w500",
            dialogVisible: true,
            isDisabled: true,
            form: {
                parentId: '',
                contentName: '',
                sort: 1,
            },
            loading: null,
            treeDataList: [],
            selectedParentLevel: null, // 保存选中父节点的层级
            geMaxSortApi,
            sortTitle:'',
            rules: {
                parentId: [
                    { required: true, message: '上级节点不能为空', trigger: 'change' }
                ],
                contentName: [
                    { required: true, message: '分类名称不能为空', trigger: 'blur' }
                ],
                sort: [
                    { required: true, message: '分类号不能为空', trigger: 'blur' }
                ],
            },
            errorObj: {
                contentName: '分类名称',
                sort: '分类号',
            },
        };
    },
    computed: {
        // 动态验证规则
        dynamicRules() {
            const isNonRootParent = this.form && this.form.parentId !== 0 && this.form.parentId !== undefined && this.form.parentId !== null;
            return {
                parentId: [
                    { required: true, message: '上级节点不能为空', trigger: 'change' }
                ],
                contentName: [
                    {
                        required: true,
                        message: isNonRootParent ? '案卷题名不能为空' : '分类名称不能为空',
                        trigger: 'blur'
                    }
                ],
                sort: [
                    {
                        required: true,
                        message: isNonRootParent ? '案卷排序号不能为空' : '分类号不能为空',
                        trigger: 'blur'
                    }
                ],
            };
        }
    },
    created() {
        this.initFormData();
    },
    methods: {
       async getMaxSort(value){
           const res = await geMaxSortApi({parentId:value});
           this.sortTitle = '当前已有最大排序为' + (res.data || 0);
        },
        /** 获取表单标签 */
        getFormLabel(field) {
            const isNonRootParent = this.form && this.form.parentId !== 0 && this.form.parentId !== undefined && this.form.parentId !== null;
            if (isNonRootParent) {
                if (field === 'contentName') {
                    this.errorObj.contentName = '案卷题名';
                    return '案卷题名';
                } else if (field === 'sort') {
                    this.errorObj.sort = '案卷排序号';
                    return '案卷排序号';
                }
            }
            if (field === 'contentName') {
                this.errorObj.contentName = '分类名称';
                return '分类名称';
            } else if (field === 'sort') {
                this.errorObj.sort = '分类号';
                return '分类号';
            }
            return '';
        },
        /** 获取表单占位符 */
        getFormPlaceholder(field) {
            const isNonRootParent = this.form && this.form.parentId !== 0 && this.form.parentId !== undefined && this.form.parentId !== null;
            if (isNonRootParent) {
                if (field === 'contentName') {
                    return '请输入案卷题名';
                } else if (field === 'sort') {
                    return '请输入案卷排序号';
                }
            }
            if (field === 'contentName') {
                return '请输入分类名称';
            } else if (field === 'sort') {
                return '请输入分类号';
            }
            return '';
        },
        /** 上级节点选择事件 */
        onParentSelect(selectedNode) {
            this.selectedParentLevel = selectedNode ? selectedNode.level : null;
            this.$nextTick(() => {
                if (this.$refs.ruleForm) {
                    this.$refs.ruleForm.clearValidate(['contentName', 'sort']);
                }
            });
            this.form.level = Number(selectedNode.level) + 1;
            this.getMaxSort(selectedNode.id);
        },
        /** 查找父节点层级 */
        findParentLevel(treeData, parentId) {
            for (const node of treeData) {
                if (node.id === parentId) {
                    this.selectedParentLevel = node.level;
                    return;
                }
                if (node.children && node.children.length > 0) {
                    this.findParentLevel(node.children, parentId);
                }
            }
        },
        /** 初始化表单数据 */
        async initFormData() {
            let value = 0;
            let treeId = this.isAdd === 'edit' && this.rowData ? this.rowData.id : null;
            await this.getLeftTreeList(treeId);
            if (this.isAdd === 'edit' && this.rowData) {
                // 编辑模式：填充表单数据
                this.form = {
                    id: this.rowData.id,
                    parentId: this.rowData.parentId || 0,
                    contentName: this.rowData.label || null,
                    sort: this.rowData.sort || 0,
                    level:this.rowData.level
                };
                value = this.rowData.parentId;
            } else {
                // 新增模式：重置表单
                this.form = {
                    parentId: this.rowData && this.rowData.id ? this.rowData.id : undefined,
                    contentName: null,
                    sort: 0,
                    level:this.rowData && this.rowData.level ? this.rowData.level : undefined
                };
                value = this.rowData.id;
            }
            

            // 如果是编辑模式，需要根据父节点ID找到对应的层级
            if (this.isAdd === 'edit' && this.form.parentId) {
                this.findParentLevel(this.treeDataList, this.form.parentId);
            }

            if(value){
                await this.getMaxSort(value);
            }
        },
        // 树数据过滤 - 支持无限层级转换，去除层级为3的数据
        convertToVueTree(data) {
            if (!data || !Array.isArray(data)) {
                return [];
            }

            return data.map(item => {
                // 如果当前节点层级为3，则跳过
                if (item.level === 3) {
                    return null;
                }

                const node = {
                    id: item.id,
                    label: item.contentName,
                    level: item.level
                };

                // 递归处理子节点
                if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                    const children = this.convertToVueTree(item.children);
                    // 过滤掉null值（层级为3的节点）
                    const filteredChildren = children.filter(child => child !== null);
                    // 只有当子节点不为空时才添加 children 属性
                    if (filteredChildren.length > 0) {
                        node.children = filteredChildren;
                    }
                }

                return node;
            }).filter(node => node !== null); // 过滤掉null值
        },
        // 获取左侧树列表
        async getLeftTreeList(value) {
            const res = await getArchivalCatalogueTreeApi({id:value})
            const transformedData = this.convertToVueTree(res.data)
            this.treeDataList = transformedData;
        },
        /*关闭弹窗 */
        handleClose() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
            /* setTimeout(() => {
                this.dialogVisible = true;
            }); */
        },
        /**确认弹窗 */
        sureBtnClick() {
            this.dialogVisible = false;
            this.$emit("closeDialog");
            /* setTimeout(() => {
                this.dialogVisible = true;
            }); */
        },
        /**重置表单*/
        reset() {
            this.form = {
                parentId: undefined,
                contentName: null,
                sort: null,
                level:null
            };
            this.resetForm("ruleForm");
        },
        handleReuslt(res) {
            this.$modal.msgSuccess(res.msg);
            this.reset();
            this.$emit('handleQuery');
            this.handleClose();
        },
        /**验证 */
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    // 显示遮罩层
                    this.loading = this.$loading({
                        lock: true,
                        text: "数据提交中，请稍候...",
                        background: 'rgba(0,0,0,0.5)',
                        target: this.$el.querySelector('.el-dialog') || document.body
                    })
                    let params = _.cloneDeep(this.form);
                    
                    if (this.isAdd === 'add') {
                        addArchiveLeftApi(params).then(res => {
                            this.loading.close();
                            if (res.code === 200) {
                                this.handleReuslt(res);
                            } else {
                                this.$modal.msgError(res.msg);
                            }
                        }).catch(error => {
                            this.loading.close();
                            this.$modal.msgError(this.errorMsg(error));
                        });
                    } else {
                        editArchiveLeftApi(params).then(res => {
                            this.loading.close();
                            if (res.code === 200) {
                                this.handleReuslt(res);
                            } else {
                                this.$modal.msgError(res.msg);
                            }
                        }).catch(error => {
                            this.loading.close();
                            this.$modal.msgError(this.errorMsg(error));
                        });
                    }
                }
            });
        },
        errorMsg(error) {
            const errorMessage = error.message;
            const errorArr = errorMessage.split('：');
            const errorObjData = errorArr.length > 1 ? JSON.parse(errorArr[1]) : '';
            if(errorObjData){
                return this.errorObj[errorObjData.paramName] + errorArr[0] + ':' + errorObjData.originalValue;
            }else{
                return errorMessage;
            }
            
        }
    }
};
</script>
<style lang="scss" scoped>
.w700 ::v-deep .el-dialog {
    width: 700px;
}

.w500 ::v-deep .el-dialog {
    width: 500px;
}

.w500 ::v-deep .el-dialog__header,
.w700 ::v-deep .el-dialog__header {
    // background: #eeeeee;

    .el-dialog__title {
        font-size: 16px;
    }
}

.yxq .el-range-separator {
    margin-right: 7px !important;
}

.el-date-editor--daterange.el-input__inner {
    width: 260px;
}

.form-item {
    width: 100%;
}

.select-style {
    display: flex;
    justify-content: space-between;
}
</style>