<!--
 * @Descripttion: 树形选择器
 * @version: 1.1
 * @Author: sakuya
 * @Date: 2021年8月3日15:53:37
 * @LastEditors: sakuya
 * @LastEditTime: 2023年2月23日15:17:24
-->

<template>
	<div class="sc-tree-select">
		<el-tree-select v-model="defaultValue" :props="defaultProps" filterable default-expand-all lazy :load="loadNode" v-bind="$attrs" @node-click="nodeClick"></el-tree-select>
	</div>
</template>

<script>
	import config from "@/config/treeSelect";

	export default {
		emits: ["nodeClick", "finished"],
		props: {
			modelValue: null,
			apiObj: { type: Object, default: () => {} },
			apiKey: { type: String, default: "get" },
			isDept: { type: Boolean, default: false },
			isAllDept: { type: Boolean, default: false },
			parentTop: null
		},

		data() {
			return {
				defaultValue: null,
				treeList: [],
				defaultProps: {
					label: config.props.label,
					value: config.props.value,
					isLeaf: config.props.isLeaf
				}
			}
		},

		watch: {
			modelValue(val) {
				this.defaultValue = val;
			}
		},

		mounted() {
			if (this.isDept) this.defaultProps = Object.assign(this.defaultProps, config.deptProps);
			this.defaultValue = this.modelValue;
		},

		methods: {
			// 获取数据
			async loadNode({ level, data }, resolve) {
				if (this.apiObj) {
					if (level == 0) {
                        const res = await this.apiObj[this.apiKey]();
						this.treeList = config.parseData(res) || [];
                        
						if (this.isDept) {
                            if (this.isAllDept) resolve(this.treeList.filter(t => t.pid == 1 && t.deptType == "控股公司"));
                            else resolve(this.treeList.filter(t => t.deptId == this.$TOOL.data.get("USER_INFO").deptId));
                        } else resolve(this.treeList.filter(t => t.pid == 0));
						this.$emit("finished");
					} else resolve(this.treeList.filter(t => t.pid == data[this.defaultProps.value] && t.deptType == "控股公司"));
				} else resolve([]);
			},

			nodeClick(data) {
				this.$emit("update:modelValue", this.defaultValue);
				this.$emit("nodeClick", data);
			}
		}
	}
</script>

<style scoped>
.sc-tree-select {
  width: 100%;
}
</style>