<template>
  <el-select class="w-full" v-loadmore="loadmore" v-model="value" filterable remote reserve-keyword clearable collapse-tags :remote-method="remoteMethod" popper-class="loadSelectPopper" :loading="loading" :multiple="multiple">
    <el-option v-for="item in options" :key="item.value" :label="item.name" :value="item.value">
      <slot :item="item.origin">
        {{ item.name }}
      </slot>
    </el-option>
  </el-select>
</template>

<script setup>
import { ref, watch } from 'vue';
import request from '~/utils/request';

const vLoadmore = {
  mounted: (el, binding) => {
    const SELECTWRAP_DOM = document.querySelector(".loadSelectPopper .el-select-dropdown .el-select-dropdown__wrap");
    SELECTWRAP_DOM.addEventListener('scroll', function (e) {
      const condition = this.scrollHeight - this.scrollTop <= this.clientHeight;
      if (condition) {
        binding.value()
      }
    })
  }
}

const props = defineProps({
  multiple: {
    type: Boolean,
    default: false,
  },
  url: String,
  modelValue: String,
  modelName: String,
  fields: [String, String],
  d: {}
})
const emits = defineEmits(["update:modelValue", "update:modelName"])

const loading = ref(false)
const currentPage = ref(1);
const total = ref(0);
const searchKey = ref("");

// const value = ref(props.modelValue ? props.modelValue.split(',') : [])
// const names = props.modelName ? props.modelName.split(',') : []

// const options = ref((value.value.length > 0) ? value.value.map((val, idx) => ({
//   value: val,
//   name: names[idx]
// })) : [])

const value = ref([]);
const names = ref([]);
const options = ref([]);

// initAna();
function initAna() {
  if (props.multiple) {
    value.value = props.modelValue ? props.modelValue.split(',') : [];
    names.value = props.modelName ? props.modelName.split(',') : [];
    // if (props.modelValue && props.modelName) {
    //   value.value.forEach((val, idx) => {
    //     if (!options.value.find((option) => val === option.value)) {
    //       options.value.unshift({
    //         value: val,
    //         name: names.value[idx],
    //       })
    //     }
    //   })
    // }
  } else {
    value.value = props.modelValue ? props.modelValue : "";
    names.value = props.modelName ? props.modelName : "";
    // if (props.modelValue && props.modelName) {
    //   if (!options.value.find((option) => value.value === option.value)) {
    //     options.value.unshift({
    //       value: value.value,
    //       name: names.value,
    //     })
    //   }
    // }
  }
}

init().then(() => {
  initAna();
})

function remoteMethod(keyword) {
  searchKey.value = keyword;
  currentPage.value = 1;
  options.value = [];
  init();
}

// init();
function init() {
  loading.value = true
  return request({
    url: props.to ? `/jcxx/${props.to}/index` : props.url,
    data: {
      ...props.d,
      keyword: searchKey.value,
      limit: 100,
      page: currentPage.value
    }
  }).then(({ data }) => {
    total.value = data.total_page;
    let arr = data.page_data.map((item) => ({
      value: item[props.fields ? props.fields[0] : props.to + '_id'],
      name: item[props.fields ? props.fields[1] : props.to + '_name'],
      origin: item
    }));
    options.value = [...options.value, ...arr];
    loading.value = false
  })
}

function loadmore() {
  currentPage.value++
  // 大于页码不请求了
  if (Number(currentPage.value) > Number(total.value)) {
    return
  }
  init();
}

watch(
  () => value.value,
  (val) => {
    if (typeof val == "object") {
      const list = val.map(v => options.value.find(({ value }) => value === v)).sort();
      emits("update:modelValue", list.map((i) => i?.value).join(','));
      emits("update:modelName", list.map((i) => i?.name).join(','));
    } else {
      const item = options.value.find(({ value }) => value === val)
      emits("update:modelValue", val)
      emits("update:modelName", item?.name)
    }
  }
)

// watch(() => props.modelValue, (val) => {
//   initAna();
// })
</script>

<style>
</style>