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

<script>
	import SelectPopup from './SelectPopup';
	import selectBox from '@/components/selectBox'
	import {
		useBaseStore
	} from '@/store/modules/base'
	import {
		getGroupCondition
	} from '@/api/common'
	const baseStore = useBaseStore()
	export default {
		name: 'jnpf-group-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: [],
				allList: [],
			}
		},
		watch: {
			modelValue: {
				handler() {
					this.setDefault()
				},
				immediate: true
			},
			allList: {
				handler() {
					this.setDefault()
				},
				deep: true,
			},
		},
		created() {
			this.initData()
		},
		methods: {
			async initData() {
				this.allList = await baseStore.getGroupList()
			},
			setDefault() {
				if (!this.modelValue || !this.modelValue.length) return this.setNullValue();
				let selectedData = [];
				let val = this.multiple ? this.modelValue : [this.modelValue];
				for (let i = 0; i < val.length; i++) {
					inner: for (let j = 0; j < this.allList.length; j++) {
						if (this.allList[j].id === val[i]) {
							selectedData.push(this.allList[j])
							break inner
						}
					}
				}
				this.selectedData = selectedData
				this.innerValue = this.selectedData.map(o => o.fullName).join();
			},
			getOptions() {
				return new Promise((resolve, reject) => {
					if (this.selectType === 'custom') {
						const query = {
							ids: this.ableIds
						}
						getGroupCondition(query).then(res => {
							resolve(res.data || [])
						}).catch(error => {
							reject(error)
						})
					} else {
						baseStore.getGroupList().then(res => {
							resolve(res || [])
						})
					}
				})
			},
			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>