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


const props = defineProps({
  url: String,
  to: String,
  modelValue: String,
  modelName: String,
  change: Function,
  fields: Array,
  d: Object
})
const emits = defineEmits(["update:modelValue", "update:modelName"])

const loading = ref(true)

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]
})) : [])

remoteMethod().then(() => {
  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[idx],
        })
      }
    })
  }
})

function remoteMethod(keyword) {
  try {
    return request({
      url: props.to ? `/txwx/${props.to}/index` : props.url,
      data: {
        ...props.d,
        keyword,
        limit: 100,
      }
    }).then(({ data }) => {
      console.log('request data :>> ', data);
      options.value = 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
      }))
      if (loading.value) { loading.value = false }
    })
  } catch (error) {
    console.error(error);
  }
}



watch(
  () => value.value,
  (val) => {
    if (options.value.length > 0) {
      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(','));
      props.change?.(list)
    }
  }
)

watch(() => [props.modelValue, props.modelName], (val) => {
  value.value = val[0] ? val[0].split(',') : [];
  names.value = val[1] ? val[1].split(',') : [];
})
</script>





<template>
  <el-select class="w-full" v-model="value" filterable remote reserve-keyword clearable :remote-method="remoteMethod" :loading="loading" :key="loading" multiple collapse-tags>
    <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>

