<template>
  <el-popover placement="bottom-start" :visible="isVisible" :width="props.width" ref="popoverRef"
              :trigger-keys="[]" style="height: 500px" popper-class="type-popper">
    <template #reference>
      <el-input
          ref="inputRef"
          v-model="keyword"
          :prefix-icon="Plus"
          :placeholder="props.placeholder"
          style="width: 100%;height: 100%"
          clearable
          @input="changeInput"
          class="no-border-input"
          :disabled="disabled"
          @focus="focus"
          @blur="handlerBlur"
          @click="changeInput"
      />
    </template>
    <div class="container" style="max-height: 300px">
      <el-table :data="searchList" max-height="300" @row-click="clickRow" :header-cell-style="{ backgroundColor: '#F1F5FB' }">
        <el-table-column
            v-for="(conf, index) in props.showConfig"
            :key="index"
            :label="conf.label"
            :prop="conf.prop"
            show-overflow-tooltip
        >
        </el-table-column>
        />
    </el-table>
    </div>
  </el-popover>

</template>

<script setup lang="ts">
import {ref, unref, computed, onMounted} from "vue";
import {post} from "@/utils/request.ts";
import {Plus} from "@element-plus/icons-vue";

const keyword = ref("");
const popoverRef = ref();
const inputRef = ref();

interface showConfig {
  prop: string;
  label: string;
}

const props = defineProps({
  requestApi: {
    type: String,
    default: ""
  },
  width: {
    type: Number,
    default: 800
  },
  showConfig: {
    type: Array as () => showConfig[],
    default: () => []
  },
  showHeader: {
    type: Boolean,
    default: true
  },
  placeholder: {
    type: String,
    default: ""
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

const searchList = ref<any>([]);

const changeInput = (inputStr: string) => {
  unref(popoverRef).popperRef?.delayHide?.()
  if (!props.requestApi || props.requestApi === "") {
    return;
  }
  post(props.requestApi, {keyword: keyword.value}).then((res: any) => {
    searchList.value = res
  });

};
const emit = defineEmits(['selectedCallBack', 'focus']);

const clickRow = (row: any) => {
  emit('selectedCallBack', row);
  popoverRef.value.hide();
  keyword.value = ""
};

const beforeShow = () => {
  if (searchList.value.length === 0) {
    popoverRef.value.hide();
  }
};
const isVisible = ref(false)
const focus = () => {
  isVisible.value = true
  changeInput("")
  emit('focus', true)
}
const handlerBlur = () => {
  isVisible.value = false
}
</script>

<style scoped lang="scss">
.no-border-input {
  :deep(.el-input__wrapper) {
    border: none !important;
    box-shadow: none !important;
  }

  :deep(.el-input__inner) {
    border: none !important;
    box-shadow: none !important;
  }

  &:hover {
    border: 1px solid #409eff !important;
  }
}
:deep(.el-table__cell) {
  padding: 0 4px;
  height: 36px;
}
</style>