<script setup lang="ts">
import { message, type SelectProps } from "ant-design-vue";
import { ref, watch, onMounted } from "vue";
import { routeToSearch } from "@/router";
import * as searchHistoryService from "@/services/searchHistory.service"

const keyword = ref("");

const field = ref("TP");
const placeholder = ref("请输入文献主题")

const hotWords = ref(['建筑工程','工程设计','BIM'])

const onSearch = () => {
  const kwd = keyword.value.trim();
  if (kwd.length == 0) {
    message.warning("请输入查询关键词");
    return;
  }
  routeToSearch({ type: 'simple', kw: kwd, field: field.value });
}

const fieldOptions = ref<SelectProps['options']>([
  { value: 'TP', label: '主题' },
  { value: 'TI', label: '标题' },
  { value: 'AU', label: '作者' },
  { value: 'KW', label: '关键词' },
  { value: 'AB', label: '摘要' },
  { value: 'UN', label: '机构' },
]);

watch(field, (newValue) => {
  if (newValue == 'TI') {
    placeholder.value = "请输入文献标题"
  } else if (newValue == 'AU') {
    placeholder.value = "请输入文献作者"
  } else if (newValue == 'KW') {
    placeholder.value = "请输入文献关键词"
  } else if (newValue == 'AB') {
    placeholder.value = "请输入文献摘要"
  } else if (newValue == 'UN') {
    placeholder.value = "请输入文献机构"
  } else {
    placeholder.value = "请输入文献主题"
  }
});

onMounted(() => {
  searchHistoryService.getHoyKeyword(5).then((resp) => {
    const words: any = resp;
    for (let item of words) {
        var expression = item.expression;
        var _expression = expression.match(/\((.+)\)/g); 
        var index = hotWords.value.indexOf(RegExp.$1); 
        
        if (hotWords.value.length == 5) {
            break;
        }

        if (index == -1) {
          hotWords.value.push(RegExp.$1)
        }
    }
  })
  

})


</script>

<template>
  <div class="search-wrap">
    <h1>智能搜索</h1>
    <a-divider></a-divider>
    <a-row type="flex">
      <a-col>
        <a-select
          ref="select"
          v-model:value="field"
          style="width: 120px"
          :options="fieldOptions"
          size="large"
        ></a-select>
      </a-col>
      <a-col flex="1">
        <a-input-search
          v-model:value="keyword"
          :placeholder="placeholder"
          enter-button="搜&nbsp;&nbsp;索"
          size="large"
          @search="onSearch"
        />
      </a-col>
    </a-row>
    <a-row class="search-hotword">
      热门关键词：
      <span v-for="item in hotWords">
        {{item}}&nbsp;&nbsp;
      </span>

    </a-row>
  </div>
</template>

<style scoped lang="scss">
.search-wrap {
  width: 80%;
  margin: 0 auto;
  margin-top: 10%;

  h1 {
    font-size: 2rem;
    text-align: center;
  }

  .search-hotword{
    margin-top: 30px;
    > sapn{
      magin-left: 20px;
    }
  }
}
</style>
