<script setup lang="ts">
import type { PropType } from "vue";
import type { SearchResultDoc } from "@/types/search.types";
import type { ResultMode } from "@/types/search.types";

const props = defineProps({
  data: {
    type: Object as PropType<SearchResultDoc>,
    required: true,
  },
  mode: {
    type: String as PropType<ResultMode>,
    default() { return 'detail' },
  }
});

function getAuthorAndUnit(scholar_name: string, unit_name: string) {
  let str = scholar_name
  if (unit_name) {
    str += ' ' + unit_name
  }
  return str
}

function highlight(name: string, content: string){
  if (props.data.highlight) {
    let highlight = JSON.parse(JSON.stringify(props.data.highlight));
    let reg = new RegExp('<em>(.*?)<\\/em>', 'g')
    let hlTitles: string[] = []
    let hlTitleOrigins: string[] = []

    if (highlight) {
      hlTitles = highlight[name] || highlight[name+'.exact']
      for (let index in hlTitles) {
        hlTitleOrigins[index] = hlTitles[index].replace(reg, '$1')
        content = content.replace(hlTitleOrigins[index], hlTitles[index])
      }
    }
  }
  return content;
}
</script>

<template>
  <div class="item-wrap">
    <h1>
      <RouterLink :to="'/detail/' + data.id" target="_blank">
        {{ data.title }}
      </RouterLink>
    </h1>
    <div class="metadata">
      <div>
        <span>作者：</span>
        <span v-for="(item, index) in data.unit_scholar" :key="index" class="author-item">
          {{ getAuthorAndUnit(item.scholar_name, item.unit_name) }}
        </span>
      </div>
      <div v-if="data.keywords.length > 0">关键词：<span v-html="highlight('keywords', data.keywords.join('，'))"></span></div>
      <div>
        <span>时间：{{ data.year }}</span>
        <span>，被引量：{{ data.cited }}</span>
      </div>
    </div>
    <p v-if="mode != 'brief'">摘要：<span v-html="highlight('abstract', data.abstract.replace('摘要：', ''))"></span></p>
  </div>
</template>

<style scoped lang="scss">

.item-wrap {
  padding: 5px;
  .metadata {
    padding-bottom: 5px;

    .author-item {
      margin-left: 1em;

      &:nth-child(2) {
        margin-left: 0;
      }
    }
  }
}
</style>
