<template>
    <el-select
        ref="selectOrgTree"
        class="dg-select"
        :style="{ width: width }"
        v-model="selectedNodeLabel"
        v-bind="$attrs"
        v-on="$listeners"
        :placeholder="placeholder"
        :filterable="filterable"
        :loadData="treeData"
        :loading="loading"
        :clearable="clearable"
        :defaultValue="defaultValue"
        style="width: 300px"
        @filter-change="handleFilterOrg"
        @clearSelect="handleClearSelect"
        @scroll-bottom="handleScrollBottom"
    >
        <dg-tree
            ref="tree"
            :key="key"
            :props="props"
            v-bind="treeProps"
            empty-text=""
            :lazy="lazy"
            :data="treeData"
            :render-after-expand="false"
            v-model="treeValue"
            radioType="all"
            @node-click="handleNodeClick"
        ></dg-tree>
    </el-select>
</template>

<script>
import ElSelect from "./select"
// import ElSelect from "./baseSelect";

import * as commonApi from "@/api/common"
export default {
    components: {
        ElSelect
    },

    props: {
        value: {
            type: String,
            default: ""
        },
        // 绑定值是否携带机构名称,如果为true，则value格式为${nodeKey}:orgName
        valueNeedName: {
            type: Boolean,
            default: false
        },
        nodeKey: {
            type: String,
            default: "code"
        },
        apiName: {
            type: String,
            default: "getOrgTree"
        },
        placeholder: {
            type: String,
            default: "请选择单位名称"
        },
        type: {
            type: String
        },
        // 是否支持查询
        filterable: {
            type: Boolean,
            default: true
        },
        // 是否默认选中根节点
        defaultSelectRoot: {
            type: Boolean,
            default: false
        },
        // 是否默认选中当前登录人机构
        defaultCurrentUserOrg: {
            type: Boolean,
            default: true
        },
        // 是否默认拼成条件去查询数据
        defaultSearch: {
            type: Boolean,
            default: true
        },
        name: String,
        // USER, TEMP
        mtType: {
            type: String,
            default: "USER"
        },
        clearable: {
            type: Boolean,
            default: true
        },
        // 查询时是否需要删除的数据
        needDeleted: {
            type: Boolean,
            default: false
        },
        // 查询时是否需要过滤管理范围
        needFilterMtAuth: {
            type: Boolean,
            default: true
        },
        defaultQueryOrg: Boolean,
        width: {
            type: String,
            default: "300px"
        },
        searchParams: {
            type: Object,
            default: () => {}
        }
    },
    data() {
        return {
            props: {
                value: this.nodeKey,
                label: "name",
                children: "children",
                isLeaf(data) {
                    return data.isParent !== true
                }
            },
            treeProps: {
                nodeKey: this.nodeKey,
                load: this.loadNode
            },
            searchForm: {
                name: "",
                mtType: "app",
                pageNum: 0,
                pageSize: 50
            },
            treeValue: "",
            data: [],
            lazy: true,
            treeData: [],
            key: 0,
            selectedNodeLabel: "",
            loading: true,
            defaultRoot: false,
            defaultValue: "",
            defaultReset: false
        }
    },

    computed: {
        hasSlots() {
            return this.$slots && this.$slots.default && this.$slots.default.length > 0
        }
    },
    watch: {
        treeValue(val) {
            if (val) {
                const { data } = this.$refs.tree.getNode(val)
                this.$refs.selectOrgTree.blur()
                this.selectedNodeLabel = data.name
                this.$refs.selectOrgTree.oldValue = data.name
                this.$emit("input", this.valueNeedName ? `${val}:${data.name}` : val)
            }
        },
        value: {
            immediate: true,
            handler(val) {
                if (!val) {
                    this.handleClearSelect()
                } else if (val && this.valueNeedName) {
                    this.selectedNodeLabel = this.value.split(":")[1]
                    this.defaultValue = this.selectedNodeLabel
                }
            }
        }
    },
    methods: {
        handleNodeClick(data, node, tree) {
            this.$emit("orgTreeValue", data[this.nodeKey], this.name)
            this.$emit("orgTreeNode", data)
        },
        loadNode(node, resolve) {
            this.getTree(node.level === 0 ? void 0 : node.data.id, resolve, node.level)
        },
        // 组织机构
        getTree(id, resolve, level) {
            const { apiName } = this
            let params = {
                id
            }
            if (this.type) {
                params["type"] = this.type
            }
            commonApi[apiName]({ ...params, ...this.searchParams })
                .then(res => {
                    // 默认选中根节点
                    if ((this.defaultSelectRoot || this.defaultRoot) && level === 0) {
                        this.treeValue = res[0][this.nodeKey]
                        this.selectedNodeLabel = res[0].name
                        this.$emit(
                            "input",
                            this.valueNeedName ? `${res[0][this.nodeKey]}:${res[0].name}` : res[0][this.nodeKey]
                        )
                        this.$emit("search", this.defaultSearch)
                    }
                    const resp = (res || []).map(item => {
                        return {
                            ...item,
                            name: item.deleted == "0" || !item.deleted ? item.name : item.name + "（已删除）"
                        }
                    })
                    return resolve(resp)
                })
                .catch(() => resolve([]))
        },
        handleChange(val) {
            this.$emit("submitTreeValue", val)
        },
        searchOrgTree() {},
        handleFilterOrg(val) {
            this.searchForm.keyword = $.trim(val)
            this.searchForm.pageNum = 0
            if (this.defaultReset === true) {
                this.key++
                this.defaultReset = false
            } else {
                if (this.searchForm.keyword) {
                    if (this.lazy === true) {
                        this.key++
                        this.lazy = false
                    }
                    this.getSearchTree()
                } else {
                    this.defaultReset = false
                    if (this.lazy === false) {
                        this.key++
                        this.lazy = true
                    }
                }
            }
        },
        handleClearSelect() {
            if (this.clearable) {
                this.treeValue = ""
                this.selectedNodeLabel = ""
                if (this.$refs.tree) {
                    this.$refs.tree.setCurrentKey(null)
                    this.$refs.tree.setRadioKeys([])
                }
                this.$emit("orgTreeValue", "", this.name)
                this.$emit("orgTreeNode", {})
                this.$emit("input", "")
                this.$emit("change", "")
            } else {
                if (this.defaultCurrentUserOrg) {
                    if (this.$refs.tree) {
                        this.$refs.tree.setCurrentKey(null)
                        this.$refs.tree.setRadioKeys([])
                    }
                    this.setDefaultCurrentUserOrg(false)
                    this.defaultValue = ""
                    this.defaultReset = true
                    this.lazy = true
                }
            }
        },
        handleScrollBottom() {
            if (!this.lazy && !this.isLast) {
                this.searchForm.pageNum++
                this.getSearchTree()
            }
        },
        // 查询
        getSearchTree() {
            this.loading = true
            let api = ""
            if (this.apiName == "roleAuthMtTree") {
                api = "roleAuthOrgSearch"
            } else {
                api = this.name == "govId" ? "govTreeMatch" : "treeMatch"
            }

            commonApi[api]({
                ...this.searchForm,
                needDeleted: this.needDeleted,
                needFilterMtAuth: this.needFilterMtAuth,
                ...this.searchParams
            }).then(res => {
                let { content, totalElements } = res.data
                content = content || []
                const _content = content.map(item => {
                    return {
                        ...item,
                        isParent: true,
                        name: item.fullName
                    }
                })
                if (this.searchForm.pageNum == 0) {
                    this.treeData = []
                }
                this.treeData = [...this.treeData, ..._content]
                this.isLast = this.treeData.length == totalElements
                this.loading = false
            })
        },
        // 设置当前登录人管理单位，默认为主单位
        setDefaultCurrentUserOrg(search) {
            // 单位名称： 当前登录人所属机构在管理范围内，则默认所属机构,反之默认根机构第一个
            const { deptId, securityOrgName, securityOrg, extendtions } = this.$store.state.user.info
            if (extendtions && (extendtions.haveCurrentOrgMt || extendtions.isAppAdmin == "1")) {
                const obj = {
                    code: securityOrg,
                    id: deptId,
                    name: securityOrgName
                }
                this.selectedNodeLabel = securityOrgName
                this.defaultValue = securityOrgName

                this.$emit("input", this.valueNeedName ? `${obj[this.nodeKey]}:${securityOrgName}` : obj[this.nodeKey])
                this.$emit("search", search)
            } else {
                this.defaultRoot = true
            }
        }
    },
    created() {
        if (this.defaultCurrentUserOrg) {
            this.setDefaultCurrentUserOrg(this.defaultSearch)
        }
    }
}
</script>
<style lang="scss" scoped></style>
