<script setup lang="ts">
import { ref, watch } from 'vue';
import request from '~/utils/request';
import App from '~/layout/app/index.vue';


const props = defineProps<{
  url?: string,
  to?: 'team' | 'grade' | 'class' | 'subject',
  modelValue?: string,
  modelName?: string,
  change?: (item: object | undefined) => void,
  fields?: [string, string],
  label?: (arg: any) => string,
  d?: {}
}>()
const emits = defineEmits(["update:modelValue", "update:modelName"])

const loading = ref(false)

const value = ref(props.modelValue)
const options = ref<{ name: string, value: string, origin?: {} }[]>((props.modelValue && props.modelName) ? [{
  name: props.modelName,
  value: props.modelValue
}] : [])

remoteMethod().then(() => {
  //

  // console.log('true :>> ', props.modelValue, props.modelName, options.value.find(({ value: val }) => val === props.modelValue));
  if (props.modelValue && props.modelName && !options.value.find(({ value: val }) => val === props.modelValue)) {
    // console.log('true :>> ', true);
    options.value.unshift({
      name: props.modelName,
      value: props.modelValue
    })
  }
})

function remoteMethod(keyword?: string) {
  loading.value = true
  return request({
    url: props.to ? `/jcxx/${props.to}/index` : props.url,
    data: {
      ...props.d,
      keyword,
      limit: 100,
    }
  }).then(({ data }) => {
    options.value = data.page_data.map((item: { [index: string]: string }) => ({
      value: item[props.fields ? props.fields[0] : props.to + '_id'],
      name: props.label ? props.label(item) : (item[props.fields ? props.fields[1] : props.to + '_name']),
      origin: item
    }))

    loading.value = false
  })
}



watch(
  () => value.value,
  (val) => {
    const item = options.value.find(({ value }) => value === val)
    emits("update:modelValue", val)
    emits("update:modelName", item?.name)
    props.change?.(item?.origin)
  }
)

watch(() => props.modelValue, (val) => {
  if (val === undefined) {
    value.value = undefined
  }
})
</script>



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

