<template>
		<view style="width: 100%;"
			@tap="open"
		>
			<u--input
				v-model="labels"
				suffixIcon="arrow-right"
				suffixIconStyle="color: #909399"
				disabled
				disabledColor="#ffffff"
				:placeholder="placeholder"
				border="none"
			></u--input>

			<u-action-sheet
				:show="show"
				@close="show = false"
			>
			<view class="cu-bar bg-white">
				<view class="action text-blue" @tap="show=false">取消</view>
				<view class="action text-green" @tap="selectUsers">确定</view>
			</view>
			<view>
				  <ly-tree :tree-data="data"
					:props="props" 
					node-key="id" 
					:checkOnClickNode ="true"
					:showRadio="showRadio"
					:show-checkbox ="showCheckBox"
					:checkOnlyLeaf = "checkOnlyLeaf"
					ref="userTree" />
			</view>
		</u-action-sheet>
	</view>
</template>

<script>
	import userService from "@/api/sys/userService"
	export default {
		data() {
			return {
				show: false,
				labels:'',
				data: [],
				treeList: []
			};
		},
		props: {
		    limit: Number,
		    value: String,
		    size: String,
			placeholder: {
			  type: String,
			  default: () => { return '请选择用户' }
			},
		    readonly: {
		      type: Boolean,
		      default: () => { return false }
		    },
			checkOnlyLeaf: {
		      type: Boolean,
		      default: () => { return false }
		    },
			showRadio: {
		      type: Boolean,
		      default: () => { return false }
		    },
			showCheckBox: {
			  type: Boolean,
			  default: () => { return true }
			},
		    disabled: {
		      type: Boolean,
		      default: () => { return false }
		    },
			props: {
				type: Object,
				default: () => {
					return {
						children: 'children',
						label: 'label'
					}
				}
			}
		  },
		mounted() {
			userService.treeData().then((data)=>{
				this.data = data
				this.setTreeList(this.data)
				let labelArra = []
				if(this.value){
					let keys = this.value.split(',')
					keys.forEach((id) => {
						this.treeList.forEach((node) => {
						  if (id === node.id) {
							labelArra.push(node.label)
						  }
						})
					 })
					this.labels = labelArra.join(',')
				}
			})
		},
		methods:{
			open () {
				this.show = true;
				if(this.value){
					this.$nextTick(()=>{
						let keys = this.value.split(',')
						this.$refs.userTree.setCheckedKeys(keys);
					})
				}
			},
			setTreeList (datas) { // 遍历树  获取id数组
			      for (var i in datas) {
			        this.treeList.push(datas[i])
			        if (datas[i].children) {
			          this.setTreeList(datas[i].children)
			        }
			      }
			    },
			selectUsers () {
				let ids = this.$refs.userTree.getCheckedNodes().filter((item)=>{
					return item.type === 'user'
				}).map((item)=>{
					return item.id
				}).join(",");
				let names = this.$refs.userTree.getCheckedNodes().filter((item)=>{
					return item.type === 'user'
				}).map((item)=>{
					return item.label
				}).join(",");
				this.labels = names
				this.$emit('input', ids)
				this.show = false
			}
		}
	}
</script>