<template>
	<view class="jnpf-users-select w-full">
		<selectBox v-model="innerValue"  :placeholder="placeholder" @openSelect="openSelect"
			:select-open="selectShow" :disabled="disabled" v-if="isInput" />
		<SelectPopup v-model="selectShow" :selectedData="selectedData" :hasSys="hasSys" @close="handleClose"
			@confirm="handleConfirm" />
	</view>
</template>

<script>
	import SelectPopup from './SelectPopup';
	import selectBox from '@/components/selectBox'
	import {
		getSelectedList
	} from '@/api/common'
	export default {
		name: 'jnpf-users-select',
		components: {
			SelectPopup,
			selectBox
		},
		props: {
			modelValue: {
				default: ''
			},
			isInput: {
				type: Boolean,
				default: true
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			hasSys: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				selectShow: false,
				innerValue: '',
				selectedData: [],
				multiple: true
			}
		},
		watch: {
			modelValue: {
				handler() {
					this.setDefault()
				},
				immediate: true
			},
		},
		methods: {
			setDefault() {
				if (!this.modelValue || !this.modelValue.length) return this.setNullValue();
				const ids = this.multiple ? this.modelValue : [this.modelValue];
				getSelectedList(ids).then((res) => {
					if (!this.modelValue || !this.modelValue.length) return this.setNullValue();
					const selectedData = res.data.list || []
					this.selectedData = selectedData
					this.innerValue = this.selectedData.map(o => o.orgNameTree).join();
				});
			},
			setNullValue() {
				this.innerValue = '';
				this.selectedData = [];
			},
			openSelect() {
				if (this.disabled) return
				this.selectShow = true
			},
			handleConfirm(selectedData, selectedIds) {
				if (!this.multiple) {
					this.$emit('update:modelValue', selectedIds[0])
					this.$emit('change', selectedIds[0], selectedData[0])
				} else {
					this.$emit('update:modelValue', selectedIds)
					this.$emit('change', selectedIds, selectedData)
				}
			},
			handleClose() {
				this.selectShow = false
			}
		}
	}
</script>