<template>
  <el-select
    v-model="selected"
    :placeholder="props.placeholder"
    :clearable="props.clearable"
    :disabled="props.disabled"
    filterable
    default-first-option
    :multiple="false"
    v-bind="attrs"
    @change="onChange"
  >
    <el-option
      v-for="item in optionList"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup lang="ts">
  import { ref, useAttrs, watch } from 'vue';
  import useSearch, { SelectType } from './search';

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

  type ValueType = number | Array<number> | null;

  const props = withDefaults(
    defineProps<{
      modelValue: ValueType;
      clearable?: boolean;
      disabled?: boolean;
      placeholder?: string;
      type: SelectType;
      params?: Record<string, any>;
    }>(),
    {
      clearable: true,
      disabled: false,
      placeholder: '请选择',
    }
  );
  const emit = defineEmits(['update:modelValue', 'change']);
  const attrs = useAttrs();

  const selected = ref<number | Array<number> | undefined>();
  const { optionList, search } = useSearch(props.type);
  search(props.params);

  const onChange = () => {
    const selectedData = optionList.value.filter(
      (item) => selected.value === item.value
    );
    emit('update:modelValue', selectedData[0].value || null);
    emit('change', selectedData[0]);
  };

  watch(
    () => props.params,
    (val, oldval) => {
      if (!val) return;

      if (JSON.stringify(val) !== JSON.stringify(oldval)) {
        search(val);
      }
    },
    {
      deep: true,
    }
  );

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