<template>
	<picker :range="userList" range-key="name" @change="bindPickerChangeUser" :value="indexUser">
		<view class="uni-input">{{userList[indexUser].name}}</view>
	</picker>
</template>
<script>
	import { getUserList } from '@/api/user.js'

	export default {
		name: 'UserSelector',
		props: {
			defaultVal: {
				type: Number,
				default: undefined
			}
		},
		data() {
			return {
				indexUser: 0,
				accountId: undefined,
				userList: [{ name: '' }],
				userSelObj: {}
			}
		},

		computed: {},
		watch: {
			defaultVal(val) {
				this.accountId = val
			}
		},
		created() {
			this.initUserListData()
		},
		mounted() {
			this.initUserListData()
		},
		methods: {
			// 初始化用户列表
			initUserListData() {
				getUserList().then((resp) => {
					const { code, data, msg } = resp
					if (code === 0) {
						this.userList = data
					} else {
						this.$message.error(msg)
					}
				}).catch((error) => {
					console.log(error)
				})
			},

			// 执行人选择
			handleSelectUser(data) {
				this.userList.forEach((node) => {
					if (node.children) {
						node.children.forEach((a) => {
							if (a.accountId === data) {
								this.setVal(a)
								return
							}
						})
					}
				})
			},

			// 返回值
			setVal(obj) {
				this.$emit('setUserInfo', obj)
			}
		}
	}
</script>
