<template>
  <el-drawer
    v-loading="loading"
    v-model="showDrawer"
    title="全文搜索"
    direction="ttb"
    :before-close="handleClose"
    :size="searchResult.length > 0 ? '500px' : '200px'"
  >
    <div class="wrapper">
      <el-input
        v-model="keyword"
        @keyup.enter="onSearch"
        placeholder="请输入关键词进行全文搜索"
        clearable
      >
        <template #append>
          <el-button :icon="Search" @click="onSearch" />
        </template>
      </el-input>
      <div class="list">
        <div
          class="list-item"
          v-for="value in searchResult"
          :key="value.book_id"
          @click="handleLocatePage(value.page_num)"
        >
          <div v-html="value.text" class="line-clamp-3"></div>
          <el-tag type="primary" class="pageNum"
            >第{{ value.page_num }}页</el-tag
          >
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script lang="ts" setup>
import { searchText } from "@/api";
import { Search } from "@element-plus/icons-vue";
/* props */
/* emit */
const $emit = defineEmits(["locatePage"]);
/* data */
const showDrawer = ref(false);
const keyword = ref("");
const loading = ref(false);
const searchResult = ref([]);
/* computed */
/* methods */

function show() {
  showDrawer.value = true;
}
function handleClose() {
  showDrawer.value = false;
}

async function onSearch() {
  console.log(keyword.value);
  try {
    loading.value = true;
    const params = { q: keyword.value };
    const res = await searchText(params);
    const { results } = res;
    searchResult.value = results.map((item) => {
      return {
        ...item,
        url: import.meta.env.VITE_API_BASE_URL + "/static/" + item.url,
      };
    });
  } catch (error) {
    console.log(error);
  }
}

function handleLocatePage(param) {
  $emit("locatePage", param);
  showDirectory.value = false;
}

defineExpose({
  show,
});
</script>
<style lang="scss" scoped>
.list {
  padding: 20px 0;
  height: 300px;
  overflow: auto;
  .list-item {
    padding: 20px;
    font-size: 14px;
    color: #666;
    border-bottom: 1px solid #eee;
    display: flex;
    cursor: pointer;

    &:hover {
      background-color: #eee;
    }
  }
}

:deep(.el-drawer__body) {
  height: 500px;
}

.wrapper {
  padding: 0 50px;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  word-wrap: break-word;
  word-break: break-all;
}
</style>
