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


const props = defineProps<{
  url: string,
  modelValue?: string,
  modelName?: string,
  change?: (item: object | undefined) => void,
  d?: {},
  myProps?:{},
}>()
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
// }] : [])
// console.log('value :>> ', value.value);

type TOptionItem = {
  label: string,
  value: string,
  children?: TOptionItem[]
}
const options = ref<TOptionItem[]>([])

remoteMethod()
// .then(() => {
//   if (props.modelValue && props.modelName && !options.value.find(({ value: val }) => val === props.modelValue)) {
//     options.value.unshift({
//       name: props.modelName,
//       value: props.modelValue
//     })
//   }
// })

function remoteMethod(keyword?: string) {
  loading.value = true
  return request({
    url: props.url,
    data: {
      ...props.d,
      keyword,
    }
  }).then(({ data }) => {
    options.value = data.tree_data.flat()
    console.log('options :>> ', options.value);
    loading.value = false
  })
}



// watch(
//   () => value.value,
//   (val) => {
//     console.log('cascader val :>> ', val, theRef.value.getCheckedNodes());
//     // const item = options.value.find(({ value }) => value === val)

//     // emits("update:modelValue", val?.at(-1))
//     // emits("update:modelName", item?.name)
//     // props.change?.(item?.origin)
//   }
// )

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

const theProps = ref({
  emitPath: false,
  ...props.myProps
})

const handleChange = (val?:string) => {
  // console.log('object :>> ',  theRef.value.getCheckedNodes());
  if (val) {
    const { value, text } = theRef.value.getCheckedNodes()[0]
    emits("update:modelValue", value)
    emits("update:modelName", text)
  } else {
    emits("update:modelValue", undefined)
    emits("update:modelName", undefined)
  }

}



const theRef = ref()
</script>



<template>
  <!-- remote :remote-method="remoteMethod"-->
  <el-cascader ref="theRef" class="w-full" v-model="value" :options="options" filterable reserve-keyword clearable
    :loading="loading" :props="theProps" @change="handleChange" />
</template>

