<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"
      @clear="clearFun"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { userListUserApi, userQueryGroupApi, userQueryGroupDetailApi } from '@/api/system/user';
import { dataUseRate, dataUserRateSort } from '@/utils/common';

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

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  multiple: false,
  disabled: false,
  fitInputWidth: false,
  groupCode: 'SIMULATION_GROUP', // ALL所有人员，CID部门列表的部门编码
});
const listData = ref<any>([]);
const choseList = ref<any>([]);

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

watch(
  () => props.modelValue,
  (val: any) => {
    if (props.multiple) {
      choseList.value = val ? String(val).split(',') : [];
    } else {
      choseList.value = val;
    }
  },
  { deep: true, immediate: true }
);

onMounted(() => {
  initFun();
});

const initFun = () => {
  if (props.groupCode === 'ALL') {
    getAllUsersFun();
  } else {
    getAllGroupsFun();
  }
};

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

const getAllGroupsFun = () => {
  const params = {
    groupCode: props.groupCode,
    current: 1,
    size: 1,
  };
  userQueryGroupApi(params).then((res: any) => {
    if (res.code === 200) {
      if (res.data?.data[0]) {
        getGroupUsersFun(res.data?.data[0]?.id);
      }
    }
  });
};

const getGroupUsersFun = (id: string) => {
  const params = {
    id,
    current: 1,
    size: 9999,
  };
  userQueryGroupDetailApi(params).then((res: any) => {
    if (res.code === 200) {
      const { users } = res.data;
      const build = users.data?.map((item: any) => {
        return {
          ...item,
          value: item.userId,
          label: item.nickname || item.realName,
        };
      });
      listData.value = build;
      listData.value = dataUserRateSort('userId', build, 'user');
    }
  });
};

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);
        dataUseRate(item.userId, 'user');
      }
    });
    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;
        dataUseRate(item.userId, 'user');
        return true;
      }
    });
    emit('change', changeData);
  }
};

const clearFun = () => {
  emit('clear');
};
</script>

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