<template>
  <el-select
    ref="LjSelectSelectRef"
    v-model="props.value"
    filterable
    remote
    reserve-keyword
    default-first-option
    automatic-dropdown
    remote-show-suffix
    v-bind="$attrs"
    :value-key="valueKey"
    :loading="loading"
    :no-match-text="noMatchText"
    :remote-method="remoteMethod"
    :popper-class="`lj-select__popper ${popperClass ? popperClass : ''}`"
    @focus="handleFocus"
    @change="handleSelect"
  >
    <template #label v-if="$slots?.label">
      <slot name="label"></slot>
    </template>
    <template #prefix>
      <slot name="prefix">
        <el-button type="primary" text bg class="pl-6 pr-6" size="small" :icon="Search" @click.stop="openModal"></el-button>
      </slot>
    </template>
    <template #header v-if="$slots?.header">
      <slot name="header" />
    </template>
    <slot name="default"></slot>
    <template #footer v-if="$slots?.footer">
      <slot name="footer" />
    </template>
  </el-select>
</template>

<script lang="ts" setup name="LjSelectorSelect">
import { ref } from "vue";
import { Search } from "@element-plus/icons-vue";

interface ProTableProps {
  value: any;
  loading: boolean;
  /**
   * @description 自定义远程搜索方法
   * @param params string  输入字段
   */
  remoteMethod: (params: any) => any;
  /**
   * @description 作为 value 唯一标识的键名，绑定值为对象类型时必填
   */
  valueKey: string;
  /**
   * @description 选择前的回调函数，返回false则不选择
   */
  beforeSelect?: (params: any) => boolean;
  noMatchText?: string;
  popperClass?: string;
}

// 默认值
const props = withDefaults(defineProps<ProTableProps>(), {
  beforeSelect: () => true,
  noMatchText: "暂无匹配数据"
});
const emit = defineEmits(["select", "update:value", "openModal", "focus"]);
const LjSelectSelectRef = ref();

const handleSelect = (item: any) => {
  console.log("LjSelectorSelect handleSelect 手动选 item :>> ", item);
  // if (item.disabled) {
  //   return;
  // }
  if (!props.beforeSelect(item)) {
    return;
  }
  emit("select", item);
};

const handleFocus = () => {
  emit("focus");
};

const openModal = (e: any) => {
  emit("openModal", e);
};

defineExpose({
  element: LjSelectSelectRef
});
</script>
