<template>
  <a-auto-complete
    v-bind="$attrs"
    :options="options"
    :allow-clear="true"
    @select="onSelect"
    @search="onSearch"
  />
</template>
<script lang="ts" setup>
  import { inject, ref, unref, watch } from 'vue';
  import { propTypes } from '/@/utils/propTypes';

  import { getDicDetailList } from '/@/api/system/dic';

  import { apiConfigFunc } from '/@/utils/event/design';

  const options = ref<{ value: string; label: string }[]>([]);

  const loading = ref(false);
  const isFirstLoad = ref(true);

  const emit = defineEmits(['update:value']);

  const props = defineProps({
    value: String,
    apiConfig: {
      type: Object,
    },
    staticOptions: {
      type: Array,
    },
    labelField: propTypes.string.def('label'),
    valueField: propTypes.string.def('value'),
    immediate: propTypes.bool.def(true),
    alwaysLoad: propTypes.bool.def(false),
    //数据来源 默认为空  如果不为空 则参数 api
    datasourceType: String,
  });

  const formModel = inject<any>('formModel', null);
  const isCamelCase = inject<boolean>('isCamelCase', false);
  watch(
    () => props.value,
    (val) => {
      unref(isFirstLoad) && fetch(val);
    },
    { deep: true },
  );

  async function fetch(_value?) {
    try {
      loading.value = true;
      let res: any = '';
      if (props.datasourceType) {
        if (props.datasourceType === 'dic') {
          res = await getDicDetailList;
        } else if (props.datasourceType === 'api') {
          res = await apiConfigFunc(props.apiConfig, isCamelCase, formModel);
        } else {
          options.value = props.staticOptions as { value: string; label: string }[];
        }
      }
      isFirstLoad.value = false;

      if (Array.isArray(res)) {
        options.value = !_value ? [] : mockVal(_value, res);
      }
    } catch (error) {
      loading.value = false;
    } finally {
      loading.value = false;
    }
  }
  const mockVal = (str: string, res) => {
    return res.filter((o) => {
      return o.value.indexOf(str);
    });
  };
  async function onSearch(value) {
    fetch(value);
  }

  async function onSelect(value) {
    emit('update:value', value);
  }
</script>
