<template>
  <el-select
    v-model="selected"
    filterable
    clearable
    :placeholder="props.placeholder"
    remote
    remote-show-suffix
    :remote-method="searchArchives"
    @change="change"
  >
    <el-option v-for="(item, idx) in options" :key="item.id" :value="item.id" :label="item.name">
      <div class="flex items-center justify-between">
        <span>{{ item.name }}</span>
        <el-tag type="info" class="ml-4">{{ item.id }}</el-tag>
      </div>
    </el-option>
  </el-select>
</template>

<script setup>
import { computed, nextTick, onMounted, ref } from "vue";
import { unique } from "@/utils";
import request from "@/api";
const props = defineProps({
  value: {
    type: String,
    default: ""
  },
  placeholder: {
    type: String,
    default: undefined
  },
  list: {
    type: Array,
    default: () => []
  },
  channelIds: {
    type: String,
    default: ""
  }
});
const emit = defineEmits(["input", "change"]);
const selected = computed({
  get() {
    return props.value;
  },
  set(val) {
    emit("input", val);
  }
});
const change = e => {
  emit(
    "change",
    e,
    options.value.find(v => v.id == e)
  );
  console.log(e);
};

const options = ref([]);
const searchArchives = async (q, init = false) => {
  if (!q && !init) return;
  options.value = [];
  const { data } = await request.get(`/archivesService/agency/archives/paginate`, {
    page: 1,
    pageSize: 100,
    keyword: q.trim(),
    channelIds: props.channelIds,
    needSubArchives: 1
  });
  const tmp = data.list
    .map(v => {
      v.familyIds = [v.id, ...(v.associatArchives || []).map(v3 => v3.id)];
      return v.associatArchives?.length
        ? [
            v,
            ...v.associatArchives.map(v2 => {
              v2.familyIds = [v.id, ...v.associatArchives.map(v3 => v3.id)];
              return v2;
            })
          ]
        : [v];
    })
    .flat();
  nextTick(() => {
    options.value = unique(tmp, "id");
    if (options.value[0]?.id && !init) {
      selected.value = options.value[0].id;
    }
  });
};

onMounted(() => {
  if (props.list && props.list.length) {
    options.value = props.list;
  } else {
    searchArchives("", true);
  }
});
</script>

<style lang="scss" scoped></style>
