<template>
  <a-tree-select
    v-model="selected"
    :placeholder="placeholder"
    :allow-clear="clearable"
    :disabled="disabled"
    :data="optionList"
    :field-names="fieldNames"
    @change="onChange"
  >
  </a-tree-select>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { omit } from 'lodash';
  import { organizationList } from '@/api/base';
  import { OrgTreeItem, OrgItem } from '@/api/types/base';

  defineOptions({
    name: 'SelectOrg',
  });

  const props = defineProps<{
    modelValue: string;
    clearable?: boolean;
    disabled?: boolean;
    placeholder?: string;
    multiple?: boolean;
  }>();
  const emit = defineEmits(['update:modelValue', 'change']);

  const fieldNames = {
    key: 'id',
    title: 'name',
  };

  const selected = ref('');
  const optionList = ref<OrgTreeItem[]>([]);
  const search = async () => {
    optionList.value = [];
    const resData = await organizationList();
    optionList.value = resData || [];
  };
  search();

  const getDataByIds = (ids: string[]): OrgItem[] => {
    const datas: OrgItem[] = [];
    const getData = (list: OrgTreeItem[]) => {
      list.forEach((item) => {
        if (ids.includes(item.id)) {
          datas.push(omit(item, ['children']));
        }
      });
    };
    getData(optionList.value);
    return datas;
  };

  const onChange = () => {
    const selectedData = props.multiple
      ? getDataByIds(selected.value)
      : getDataByIds([selected.value]);
    emit('update:modelValue', selected.value);
    emit('change', props.multiple ? selectedData : selectedData[0]);
  };

  watch(
    () => props.modelValue,
    (val) => {
      selected.value = val;
    },
    {
      immediate: true,
    }
  );
</script>
