<template>
	<view class="jnpf-organize-select w-full">
		<selectBox v-model="innerValue" :placeholder="placeholder" @openSelect="openSelect" :select-open="selectShow"
			:disabled="disabled"  />
		<SelectPopup v-model="selectShow" :multiple="multiple" :selectedData="selectedData" @close="handleClose"
			@confirm="handleConfirm" :selectType="selectType" :ableIds="ableIds" />
	</view>
</template>

<script>
	import SelectPopup from './SelectPopup';
	import selectBox from '@/components/selectBox'
	import {
		getOrgSelectedList
	} from '@/api/common'
	export default {
		name: 'jnpf-organize-select',
		components: {
			SelectPopup,
			selectBox
		},
		props: {
			modelValue: {
				default: ''
			},
			placeholder: {
				type: String,
				default: '请选择'
			},
			disabled: {
				type: Boolean,
				default: false
			},
			multiple: {
				type: Boolean,
				default: false
			},
			selectType: {
				type: String,
				default: 'all'
			},
			ableIds: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				selectShow: false,
				innerValue: '',
				selectedData: [],
			}
		},
		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];
				getOrgSelectedList({
					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>