<template>
  <el-select
    v-model="selected"
    :placeholder="placeholder"
    :clearable="clearable"
    :disabled="disabled"
    filterable
    v-bind="attrs"
    @change="onChange"
  >
    <template v-if="prefix" #prefix>
      <span style="padding-left: 12px">任务</span>
    </template>
    <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 { ElSelect, ElOption } from 'element-plus';

  defineOptions({
    name: 'SelectTask',
  });
  type ValueType = number | Array<number> | null;

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

  interface OptionListItem {
    value: number;
    label: string;
  }

  const selected = ref<number | Array<number> | undefined>();
  const optionList = ref<OptionListItem[]>([]);
  const search = () => {
    // TODO: get task list
    // optionList.value = [].map((item) => {
    //   return { ...item, value: item.id, label: item.name };
    // });
  };
  search(); // Initial load

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

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