<template>
    <div class="m-dataConsolidationDialogTree" @click.stop>
        <div class="tree-top">
            <el-input
                prefix-icon="el-icon-search"
                :placeholder="$t('cs.common.verification.verifyRequired', { verifyName: $t('cs.common.text.keyword') })"
                size="small"
                v-model="filterText"
                class="margin: 5px 10px;width: 90%;"
            ></el-input>
        </div>
        <el-tree
            :ref="treeRef"
            :empty-text="emptyText"
            :default-expanded-keys="defaultExpandedKeys"
            :expand-on-click-node="false"
            node-key="directoryId"
            :default-expand-all="defaultExpandAll"
            :highlight-current="true"
            :data="treeData"
            :load="loadNode"
            :lazy="lazy"
            :props="props"
            v-if="!searchTreeShow"
            @node-click="treeClick"
        >
            <span class="tree-slot" slot-scope="{ data }" :title="$t(data.directoryName)">
                <!-- 目录 -->
                <span class="flex-align-center">
                    <i class="el-icon-folder" style="margin-right: 5px" v-if="data.directoryType == 0"></i>
                    <i class="el-icon-setting" style="margin-right: 5px" v-if="data.directoryType == 1 || data.directoryType == 2"></i>
                    <span class="tree-slot-content">{{ $t(data.directoryName) }}</span>
                </span>
            </span>
        </el-tree>
    </div>
</template>
<script>
import CoreAPI from "../../Common/JS/CoreAPI";

const INITDIRECTORY = "null";

export default {
    props: ["directoryId", "root", "activeName"],
    data() {
        return {
            //首页左侧树相关配置属性
            treeData: [],
            filterText: "", // 左侧树输入框值
            props: {
                isLeaf: "isLeaf"
            },
            node: null,
            resolve: null,
            currentNode: "", // 选中对象id
            lazy: true,
            searchTreeShow: false,
            defaultExpandAll: false,
            defaultExpandedKeys: [INITDIRECTORY],
            treeRef: "moveTree",
            emptyText: this.$t("cs.common.text.noData"),
            searchTreeKey: [],
            searchInitTree: [],
            searchInitPid: "",
            INITROOTDIRECTORY: [
                {
                    directoryId: INITDIRECTORY,
                    directoryName: vm.$t("cs.exchange.DataConsolidation.rootDirectory"),
                    directoryType: "0",
                    isLeaf: false,
                    children: []
                }
            ],
            currentNodeData: {} // 选中对象数据
        };
    },
    methods: {
        //目录点击
        treeClick(data) {
            const _this = this;
            _this.$nextTick(() => {
                let t = setTimeout(() => {
                    // 点击之后保存点击对象
                    _this.currentNode = data.directoryId;
                    _this.currentNodeData = data;
                    _this.$refs[_this.treeRef].setCurrentKey(_this.currentNode ? _this.currentNode : null);
                    clearTimeout(t);
                    _this.$emit("treeClickHandler", _this.currentNodeData);
                });
            });
        },
        //目录懒加载
        loadNode(node, resolve) {
            const _this = this;
            _this.node = node;
            _this.resolve = resolve;
            if (node.level === 0 && _this.root) {
                return resolve(INITROOTDIRECTORY);
            }
            if (node.level >= 1 || !_this.root) {
                var postData = {
                    sortModels: [{ fieldName: "order", sortType: 0 }],
                    filterModel: {
                        filterGroupModel: [
                            {
                                filterFields: [
                                    {
                                        operationType: node.data.directoryId ? 20 : 100,
                                        fieldType: 10,
                                        fieldName: "parent_id",
                                        fieldValue: node.data.directoryId
                                    }
                                ],
                                logicType: 0
                            }
                        ]
                    },
                    lazyLoad: true,
                    systemId: _this.activeName
                };
                CoreAPI.getMenuFrameRouteTree(postData).then(
                    res => {
                        _this.emptyText = _this.$t("cs.common.text.noData");
                        _this.setResData(res);
                        if (_this.currentNode) {
                            setTimeout(function () {
                                _this.$refs[_this.treeRef].setCurrentKey(_this.currentNode ? _this.currentNode : null);
                            }, 0);
                        }
                        resolve(res);
                    },
                    rej => {
                        _this.$message({
                            type: "error",
                            message: rej.msg
                        });
                    }
                );
            }
            resolve([]);
        },
        // 重置树的状态配置,一般用于懒加载与全加载状态切换
        resultTreeSearchTreeShow(lazy, defaultExpandAll) {
            let _this = this;
            _this.searchTreeShow = true;
            _this.$nextTick(() => {
                _this.lazy = lazy;
                _this.defaultExpandAll = defaultExpandAll;
                _this.searchTreeShow = false;
                setTimeout(() => {
                    // 保持选中
                    _this.$refs[_this.treeRef].setCurrentKey(_this.currentNode ? _this.currentNode : null);
                });
            });
        },
        //获取树data
        getDirectoryTreeData(filterText) {
            const _this = this;
            _this.searchFnc = setTimeout(function () {
                var postData = {
                    sortModels: [{ fieldName: "order", sortType: 0 }],
                    filterModel: {
                        filterGroupModel: [
                            {
                                filterFields: [
                                    {
                                        operationType: 10,
                                        fieldType: 10,
                                        fieldName: "code",
                                        fieldValue: filterText ? filterText.trim() : ""
                                    }
                                ],
                                logicType: 0
                            }
                        ]
                    },
                    lazyLoad: false,
                    systemId: _this.activeName
                };
                CoreAPI.getMenuFrameRouteTree(postData).then(res => {
                    _this.emptyText = _this.$t("cs.common.text.noResult");
                    _this.setResData(res);
                    let treeData = _this.root ? DataCenter.Methods.deepCopy(INITROOTDIRECTORY) : [];
                    if (res.length == 0) {
                        treeData = [];
                    } else {
                        treeData = _this.root ? DataCenter.Methods.deepCopy(INITROOTDIRECTORY) : [];
                        if (_this.root) {
                            res.forEach(ele => {
                                treeData[0].children.push(ele);
                            });
                        } else {
                            res.forEach(ele => {
                                treeData.push(ele);
                            });
                        }
                    }
                    _this.treeData = treeData;
                    setTimeout(() => {
                        _this.resultTreeSearchTreeShow(false, true);
                    });
                });
            }, 500);
        },
        //处理接口返回的参数 拼装成当前需要的参数名儿等
        setResData(data) {
            if (Array.isArray(data)) {
                data.forEach(item => {
                    let obj = { directoryType: 1, directoryOrder: null, isLeaf: !item.isChildren };
                    ({ id: obj.directoryId, code: obj.directoryName, parentId: obj.parentDirectoryId, children: obj.children } = item);
                    item = Object.assign(item, obj);
                    if (item.children && item.children.length > 0) {
                        this.setResData(item.children);
                    }
                });
            } else {
                let obj = { directoryType: 1, directoryOrder: null, isLeaf: !data.isChildren };
                ({ id: obj.directoryId, code: obj.directoryName, parentId: obj.parentDirectoryId, children: obj.children } = data);
                data = Object.assign(data, obj);
            }
        },
        //遍历树
        forTree(list, parentId) {
            for (let i = 0; i < list.length; i++) {
                let item = list[i];
                if (parentId == item.id) {
                    this.searchInitPid = item.parentId;
                    return;
                }
                if (item.children?.length > 0) {
                    this.forTree(item.children, parentId);
                }
            }
        },
        // 搜索树展开节点
        getSerachTreeKey(parentId) {
            const _this = this;
            if (!parentId) return;

            _this.searchTreeKey.unshift(parentId);
            _this.searchInitPid = "";
            _this.forTree(_this.searchInitTree, parentId);
            if (_this.searchInitPid) {
                _this.getSerachTreeKey(_this.searchInitPid);
            }
        },
        //获取最新的展开父级集合
        getNewExtendList() {
            return new Promise((resolve, reject) => {
                var postData = {
                    sortModels: [{ fieldName: "order", sortType: 0 }],
                    filterModel: null,
                    lazyLoad: false,
                    systemId: this.activeName
                };
                CoreAPI.getMenuFrameRouteTree(postData)
                    .then(res => {
                        this.searchInitTree = res;
                        this.getSerachTreeKey(this.directoryId);
                        resolve();
                    })
                    .catch(err => {
                        CloudServiceCommon.Log.debug(err);
                        reject();
                    });
            });
        }
    },
    created() {
        if (this.directoryId == "" || !this.directoryId) {
            this.currentNode = "";
        }
        this.currentNode = this.directoryId;
        this.getNewExtendList().then(() => {
            this.defaultExpandedKeys = this.defaultExpandedKeys.concat(this.searchTreeKey);
            this.resultTreeSearchTreeShow(true);
        });
    },
    watch: {
        //input 快捷查询树结构
        filterText: function (val) {
            const _this = this;
            clearTimeout(_this.searchFnc);
            if (!val) {
                _this
                    .getNewExtendList()
                    .then(() => {
                        _this.defaultExpandedKeys = _this.defaultExpandedKeys.concat(_this.searchTreeKey);
                        _this.resultTreeSearchTreeShow(true);
                    })
                    .catch(() => {
                        _this.defaultExpandedKeys = _this.defaultExpandedKeys.concat(_this.searchTreeKey);
                        _this.resultTreeSearchTreeShow(true);
                    });
                return;
            }
            _this.getDirectoryTreeData(val);
        }
    }
};
</script>
<style lang="less">
.m-dataConsolidationDialogTree {
    width: 100%;
    height: 100%;
    .el-tree {
        flex-direction: column;
        display: flex;
        height: calc(100% - 42px);
        font-weight: normal;
        overflow-x: auto;
    }
}
</style>
