<template>
	<div class="tree-choice">
		<el-input placeholder="输入名称搜索" v-model="filterText" style="margin-bottom: 10px"></el-input>
		<el-tree
			:data="dataList"
			node-key="id"
			default-expand-all
			:highlight-current="true"
			:expand-on-click-node="false"
			:filter-node-method="filterNode"
			ref="tree"
			@node-click="nodeClick"
			show-checkbox
			:default-checked-keys="checkeds"
			:props="{ disabled: () => true }"
		>
			<span class="custom-tree-node" slot-scope="{ data }">
				<span>{{ data.label }}</span>
			</span>
		</el-tree>
	</div>
</template>

<script>
	import { treeselect } from '@/api/system/dept.js'
	export default {
		model: {
			prop: 'modelValue',
			event: 'dataChange'
		},
		props: {
			modelValue: {
				type: Array,
				required: true
			}
		},
		data() {
			return {
				//搜索字段
				filterText: '',
				//拥有权限的id数组
				checkeds: [],
				//部门数据
				dataList: [],
				//选中的部门信息
				deptInfo: {}
			}
		},
		computed: {
			deptIds: {
				get() {
					return this.modelValue
				},
				set(val) {
					this.$emit('dataChange', val)
					this.$emit('click')
				}
			}
		},
		watch: {
			filterText(val) {
				this.$refs.tree.filter(val)
			}
		},
		created() {
			this.getDeptList()
		},
		methods: {
			//获取部门数据
			getDeptList() {
				treeselect().then((res) => {
					if (res.code === 200) {
						this.dataList = res.data
						this.checkeds = this.getDeptIds()
					}
				})
			},
			//搜索过滤节点
			filterNode(value, data) {
				if (!value) return true
				return data.label.indexOf(value) !== -1
			},
			//获取拥有的数据权限
			getDeptIds() {
				let ids = this.$store.state.user.dataPermissions
				if (ids.includes('*')) {
					return this.getAllIds(this.dataList)
				} else {
					return ids
				}
			},
			//节点点击
			nodeClick(data, node) {
				let ids = data.children && data.children.length ? this.getAllIds(data.children) : []
				ids.push(data.id)
				ids = ids.filter((item) => this.checkeds.includes(item))
				if (!ids.length) {
					return
				}
				this.deptIds = ids
				let deptNames = data.label
				let parent = node.parent
				while (parent.data.constructor === Object) {
					deptNames = parent.data.label + '\\' + deptNames
					parent = parent.parent
				}
				this.$emit('getDeptInfo', {
					deptId: data.id,
					deptName: data.label,
					deptNames
				})
			},
			//递归获取所有部门id
			getAllIds(parents) {
				if (!parents) return []
				let arrs = []
				parents.forEach((item) => {
					arrs.push(item.id)
					if (item.children && item.children.length) {
						arrs = [...arrs, ...this.getAllIds(item.children)]
					}
				})
				return arrs
			}
		}
	}
</script>

<style scoped lang="scss">
	.tree-choice {
		background-color: #fff;
		padding: 10px 10px;
		width: 280px;
		margin-right: 7px;
		flex-shrink: 0;
		height: 100%;
		overflow-y: auto;
	}
</style>
