<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="rules" ref="ruleForm" label-width="110px">
                <el-form-item label="项目" prop="proId">
                    <el-select class="form-item" v-model="form.proId" filterable clearable placeholder="请选择项目" :disabled="isRead"
                        @change="handleProChange">
                        <el-option v-for="item in proList" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="移交时间" prop="transferTime">
                    <el-date-picker class="form-item" v-model="form.transferTime" placeholder="请选择移交时间" :disabled="isRead"
                        value-format="yyyy-MM-dd" type="date"></el-date-picker>
                </el-form-item>

                <el-form-item label="接收组织" prop="deptId">
                    <treeselect v-model="form.deptId" :options="treeDataList" placeholder="请选择接收组织" value-key="id"
                        :disable-branch-nodes="true" noChildrenText="没有数据了" noOptionsText="没有数据了"
                        noResultsText="没有搜索结果" :disabled="isRead"/>
                </el-form-item>
                <el-form-item label="移交问题" prop="transferIssue">
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 6 }" class="form-item"
                        v-model="form.transferIssue" clearable show-word-limit placeholder="请输入移交问题" maxlength="255" :disabled="isRead"></el-input>
                </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')" v-if="!isRead">确认</el-button>
        </span>

    </el-dialog>
</template>
<script>
import _ from 'lodash'
import {
    addTransferProblemApi,
    editTransferProblemApi,
    getProSelectApi,
} from '@/api/filesTransfer/issue'
import { getDeptSelectApi } from '@/api/select'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
    name: "IssueForm",
    props: ["width", "dataForm", "title", "disabled", "isAdd", "rowData"],
    dicts: ['data_class_type'],
    components: { Treeselect },
    data() {
        return {
            lDialog: this.width > 500 ? "w700" : "w500",
            dialogVisible: true,
            isDisabled: true,
            form: {
                proId: undefined,
                deptId: undefined,
                transferTime:undefined,
                transferIssue:null
            },
            treeDataList: [],
            proList: [],
            checkTreeData: [],
            loading: null,
            rules: {
                proId: [
                    { required: true, message: '请选择项目', trigger: 'change' }
                ],
                deptId: [
                    { required: true, message: '请选择接收组织', trigger: 'change' }
                ],
                transferIssue: [
                    { required: true, message: '请输入移交问题', trigger: 'blur' }
                ],
                transferTime: [
                    { required: true, message: '请选择移交时间', trigger: 'blur' }
                ],
            },
            errorObj: {
                transferIssue: '移交问题',
            },

        };
    },
    created() {
        this.initFormData();
    },
    computed: {
        isRead() {
            return this.isAdd === 'detail';
        }
    },
    methods: {
        /** 初始化表单数据 */
        async initFormData() {
            await getDeptSelectApi().then(res => {
                this.treeDataList = this.convertToVueTree(res.data);
            });
            await getProSelectApi().then(res => {
                this.proList = res.data;
            });


            if ((this.isAdd === 'edit' || this.isAdd === 'detail') && this.rowData) {
                // 编辑模式：填充表单数据
                this.form = {
                    id: this.rowData.id || null,
                    proId: this.rowData.proId || undefined,
                    deptId: this.rowData.deptId || undefined,
                    transferTime: this.rowData.transferTime || undefined,
                    transferIssue: this.rowData.transferIssue || null,
                };

            } else {
                // 新增模式：重置表单
                this.form = {
                    proId: undefined,
                    deptId: undefined,
                    transferTime: null,
                    transferIssue: null,
                };
            }
        },

        closeDialog() {
            this.isflag = false;
        },
        showColose() {
            this.isflag = false;
        },
        /*关闭弹窗 */
        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 = {
                proId: undefined,
                deptId: undefined,
                transferTime: null,
                transferIssue: 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);
                    // 获取单项工程名称
                    let proObj = this.proList.find(item => item.id === params.proId);
                    params.singleProName = proObj.name;
                    params.proName = proObj.proName;
                    // 获取接收组织名称
                    const obj = this.findNodeById(this.treeDataList, this.form.deptId);
                    params.deptName = obj?.label || '';
                    console.log(params);

                    if (this.isAdd === 'add') {
                        addTransferProblemApi(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 {
                        editTransferProblemApi(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));
                        });
                    }
                }
            });
        },
        // 树数据过滤 - 支持无限层级转换
        convertToVueTree(data, level = 1) {
            if (!data || !Array.isArray(data)) {
                return []
            }

            return data.map(item => {
                const node = {
                    id: item.deptId,
                    label: item.deptName,
                }

                if (item.children && Array.isArray(item.children) && item.children.length > 0) {
                    if (level < 3) {
                        const children = this.convertToVueTree(item.children, level + 1)
                        if (children.length > 0) node.children = children
                    }
                }

                return node
            })
        },
        findNodeById(nodes, id) {
            for (const node of nodes) {
                if (node.id === id) return node;
                if (node.children) {
                    const found = this.findNodeById(node.children, id);
                    if (found) return found;
                }
            }
            return null;
        },
        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>
