<template>
  <div class="comp-content">
    <el-select-v2
      class="select"
      v-model="choseList"
      :options="listData"
      :placeholder="disabled ? '' : '请选择'"
      filterable
      clearable
      :collapse-tags="multiple"
      :disabled="disabled"
      :multiple="multiple"
      :fit-input-width="fitInputWidth"
      @change="changeFun"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { userQueryGroupDetailApi } from '@/api/system/user';

interface Props {
  modelValue: string;
  multiple?: boolean;
  disabled?: boolean;
  fitInputWidth?: boolean;
  groupId?: string;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  multiple: false,
  disabled: false,
  fitInputWidth: false,
  groupId: '',
});
const listData = ref<any>([]);
const choseList = ref<any>([]);

const emit = defineEmits(['update:modelValue', 'change']);

watch(
  () => props.modelValue,
  (val: any) => {
    if (props.multiple) {
      choseList.value = val ? val.split(',') : [];
    } else {
      choseList.value = val;
    }
  },
  { deep: true, immediate: true }
);
watch(
  () => props.groupId,
  () => {
    if (props.groupId) {
      // 更新数据
      getlistDataFun();
    } else {
      listData.value = [];
    }
  },
  { deep: true, immediate: true }
);

// onMounted(() => {
//   getlistDataFun();
// });

const getlistDataFun = () => {
  const params = {
    current: 1,
    size: 9999,
    id: props.groupId,
  };
  userQueryGroupDetailApi(params).then((res: any) => {
    if (res.code === 200) {
      const build = res.data.users.data.map((item: any) => {
        return {
          ...item,
          value: item.userId,
          label: item.nickname,
        };
      });
      listData.value = build;
    }
  });
};

const changeFun = () => {
  if (props.multiple) {
    const ids = choseList.value.join(',');
    emit('update:modelValue', ids);
    const changeData: any[] = [];
    listData.value.forEach((item: any) => {
      if (choseList.value.includes(String(item.userId))) {
        changeData.push(item);
      }
    });
    emit('change', changeData);
  } else {
    emit('update:modelValue', choseList.value);
    let changeData: any = {};
    listData.value.some((item: any) => {
      if (choseList.value === String(item.userId)) {
        changeData = item;
        return true;
      }
    });
    emit('change', changeData);
  }
};
</script>

<style lang="scss" scoped>
.comp-content {
  width: 100%;
  .select {
    width: 100%;
  }
}
</style>
