<template>
  <a-select
    :popup-visible="false"
    :fallback-option="false"
    :multiple="limit === 1 ? false : true"
    :allow-search="false"
    :allow-clear="allowClear"
    :placeholder="placeholder"
    @popup-visible-change="handleVisible"
    @remove="handleRemove"
    @clear="handleRemove"
    v-model="mySelectIds"
  >
    <a-option v-for="item of options" :key="item.id" :value="item.id" :label="item.name" />
  </a-select>
  <f-user-select-modal
    v-model:visible="modalVisible"
    :select-ids="mySelectIds"
    :limit="limit"
    :ignoreIds="ignoreIds"
    @change="handleChange"
    @user-list-change="handleUserListChange"
  ></f-user-select-modal>
</template>

<script setup lang="ts">
import { ref, watch, withDefaults } from 'vue'
import _ from 'lodash'
import FUserSelectModal from '../f-user-select-modal/index.vue'

const props = withDefaults(
  defineProps<{
    /**
     * 已选择
     */
    selectIds?: string[]
    /**
     * 忽略的ids
     */
    ignoreIds?: string[]
    /**
     * 最多可选几个
     */
    limit?: number

    allowClear?: boolean
    placeholder?: string
  }>(),
  {
    allowClear: true,
    selectIds: () => [],
    ignoreIds: () => [],
    placeholder: '请选择人员'
  }
)
const emit = defineEmits<{
  (event: 'change', val: string[]): void
}>()

const modalVisible = ref(false)
const handleVisible = () => {
  modalVisible.value = true
}

const mySelectIds = ref<string[]>([])
watch(
  () => props.selectIds,
  () => {
    mySelectIds.value = _.cloneDeep(props.selectIds || [])
  },
  {
    deep: true,
    immediate: true
  }
)

const options = ref<any[]>([])
const handleChange = (ids: string[], nodes: any[]) => {
  options.value = nodes
  mySelectIds.value = ids
  emit('change', ids)
}

const handleRemove = () => {
  emit('change', mySelectIds.value)
}

const handleUserListChange = (list: any[]) => {
  options.value = list
}
</script>

<style scoped></style>
