<template>
  <el-popover placement="bottom-start" :visible="isVisible" :width="props.width" ref="popoverRef"
              @before-enter="beforeShow" @hide="afterShow" popper-class="type-popper">
    <template #reference>
      <el-input v-model="keyword" style="width: 100%;height: 100%" @input="changeInput" :disabled="disabled"
                @click="changeInput"
                placeholder="诊断选择" ref="inputRef" @focus="focus" @blur="handleBlur"></el-input>
    </template>
    <div class="container" style="height: 300px">
      <el-scrollbar style="height: 300px">
        <table class="table" style="width: 100%; border-collapse: collapse;max-height: 50px">
          <!-- 表头 -->
          <thead>
          <tr class="table-title">
            <th
                v-for="item in showConfig"
                :key="item.prop"
                style="background-color: #f5f7fa; padding: 8px;"
            >
              {{ item.label }}
            </th>
          </tr>
          </thead>

          <!-- 表体 -->
          <tbody>
          <tr class="table-body"
              v-for="(item, index) in searchList"
              :key="index"
              @click="clickRow(item)"
              style="cursor: pointer; transition: background-color 0.2s;"
          >
            <td
                v-for="showItem in showConfig"
                :key="showItem.prop"
                style="vertical-align: middle; padding: 8px;"
            >
              {{ item[showItem.prop] }}
            </td>
          </tr>
          </tbody>
        </table>
      </el-scrollbar>

    </div>
  </el-popover>
</template>
<script setup lang="ts">
import {ref, unref, watch} from "vue";
import {post} from "@/utils/request.ts";
import {ElMessage} from "element-plus";

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

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

const props = defineProps({
  requestApi: {
    type: String,
    default: ""
  },
  width: {
    type: Number,
    default: 600

  },
  showConfig: {
    type: Array as () => showConfig[],
    default: () => []
  },
  showHeader: {
    type: Boolean,
    default: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})
const inputRef = ref();


const searchList = ref([]);
const changeInput = (inputStr: string) => {
  unref(popoverRef).popperRef?.delayHide?.()
  if (!props.requestApi || props.requestApi === "") {
    return
  }
  let tempList = keyword.value.split(",");
  let searchKeyword = tempList[tempList.length - 1];
  nameList.value = []
  selectList.value = selectList.value ? selectList.value.slice(0, tempList.length) : []
  let updateKeyword = false
  for (let i = selectList.value.length - 1; i >= 0; i--) {
    if (!tempList.includes(selectList.value[i].name)) {
      selectList.value.splice(i, 1);
      updateKeyword = true
    } else {
      nameList.value.push(selectList.value[i].name)
    }
  }
  if (updateKeyword) {
    keyword.value = nameList.value.length > 0 ? nameList.value.join(",") + "," : "";
  }
  post(props.requestApi, {keyword: searchKeyword}).then((res: any) => {
    searchList.value = res;
  })
}
const emit = defineEmits(['selectedCallBack', 'focus'])
const clickRow = (row: any) => {
  if (selectList.value && selectList.value.length >= 3) {
    ElMessage({
      message: '诊断最多三个',
      type: 'info',
    })
    return
  }

  if (selectList.value.some((item: any) => item.id == row.id)) {
    ElMessage({
      message: '诊断已存在',
      type: 'info',
    })
  } else {
    selectList.value.push(row)
    nameList.value.push(row.name)
    keyword.value = nameList.value.join(",") + ","
  }

  searchList.value = []
  popoverRef.value.hide()
}
const beforeShow = () => {
  // if (searchList.value.length === 0) {
  //   popoverRef.value.hide()
  // }
}
const afterShow = () => {
  if (nameList.value.length === 0) {
    keyword.value = ""
  } else {
    keyword.value = nameList.value.join(",") + ","
  }

}


const selectList = ref<any>()
const nameList = ref<any>([]);
watch(selectList, (newVal, oldVal) => {
  emit('selectedCallBack', newVal)
}, {deep: true});
const init = (list: any, nList: any) => {
  selectList.value = list;
  nameList.value = nList;
  keyword.value = nameList.value.join(",") + ","
}
const isVisible = ref(false);
const focus = () => {
  isVisible.value = true
  emit("focus", false)
}
const handleBlur = () => {
  isVisible.value = false
}
const clear = () => {
  selectList.value = []
  nameList.value = []
  keyword.value = ""
}
defineExpose({init, clear})
</script>
<style scoped lang="scss">
:deep(.el-table--small .el-table__cell) {
  padding: 0;
}

.table {
  th {
    background: none !important;
  }

  .table-title {
    height: 52px;
    font-weight: 500;
    font-size: 14px;
    color: #333333;
    font-style: normal;

    th {
      text-align: left;

      &:nth-child(1) {
        text-align: left;
        border-radius: 8px 8px 0 0;
        padding-left: 24px !important;
      }
    }
  }

  .table-body {
    height: 52px;
    font-weight: 500;
    font-size: 14px;
    color: #666666;
    font-style: normal;

    td {
      &:nth-child(1) {

        text-align: left;
        padding-left: 30px !important;
        white-space: nowrap; /* 防止文本换行 */
        overflow: hidden; /* 隐藏溢出的文本 */
        text-overflow: ellipsis; /* 显示省略号 */
      }
    }


    &:last-child {
      border-radius: 0 0 8px 8px;
    }

    &:hover {
      background-color: #4D6DE4;
      color: #fff;
    }
  }
}
table thead tr {
  background: #F5FAFF;;
}
</style>