<script setup lang="ts">
import { nextTick, onMounted, onUnmounted, reactive, ref, toRefs } from 'vue'
import { debounce } from 'lodash-es'
import { useRoute, useRouter } from 'vue-router'
import { deleteSearch, getSearchList, historySearch } from '@/api/search/search'
import { storage } from '@/utils/Storage'

const emit = defineEmits(['close'])

const value = ref('')
const showList = ref(false)
const historyList: any = ref([])
const handlerShowList = () => (showList.value = true)
const router = useRouter()
const route = useRoute()
const state = reactive({
  resultList: [],
}) as any

const { resultList } = toRefs(state)

const inputHandler = debounce((keyword) => {
  if (keyword)
    handlerSearch(keyword)
}, 500)

// 搜索
async function handlerSearch(value) {
  // 快捷键触发不做接口请求
  if(value === '/') return
  const res = await getSearchList({
    search: value,
  })
  if (res.code === 'OK') {
    state.resultList = [
      {
        title: '图检审批',
        path: 'worksheet',
        data: res.data.ai,
      },
      {
        title: '任务审批管理',
        path: 'task',
        data: res.data.preliminary,
      },
      {
        title: '任务终审管理',
        path: 'final',
        data: res.data.final,
      },
    ]
  }
}

function handlerHistory(name) {
  value.value = name
  handlerSearch(name)
}

// 删除历史记录
async function deleteHistory() {
  const res = await deleteSearch({})
  if (res.code === 'OK')
    historyList.value = []
}

// 获取历史搜索结果
async function getHistory() {
  const res = await historySearch({})
  if (res.code === 'OK')
    historyList.value = res.data
}
getHistory()

function goPath(item, id) {
  const desiredObject = item.data.find((item) => {
    return item.id === id
  })
  if (!storage.get('isSearch'))
    storage.set('isSearch', true, Date.now() + 30 * 60 * 1000)

  router.push({ name: item.path, query: { id, searchContent: desiredObject.name } })
  emit('close')
}

function highlightText(text, query) {
  if (!query)
    return text
  const regex = new RegExp(query, 'gi')
  const highlightedText = text.replace(regex, (match) => {
    return `<span style="color:#507AFD" class="highlight">${match}</span>`
  })

  return highlightedText
}
onMounted(() => {
  setTimeout(() => (value.value = ''))
  handlerShowList()
  handlerSearch('')
})
</script>

<template>
  <div class="input_wrap">
    <div class="ip_box">
      <img src="../../assets/images/IP.png" alt="">
    </div>
    <div class="input_box">
      <n-input
        v-model:value="value"
        placeholder="搜索任务ID、任务名称、提报人、拜访终端"
        placeholder-style="width:304px;height:22px;margin:17px 0 17px 12px;"
        style="font-size: 16px; font-weight: 500; color: #333333"
        type="text"
        @input="inputHandler"
        @mousedown="handlerShowList"
      >
        <template #prefix>
          <SvgIcon
            name="magnifying-1"
            width="21"
            height="20"
            style="margin: 10px 0 10px 4px"
          />
        </template>
      </n-input>
    </div>
    <div v-show="showList && (historyList.length || resultList.length)" class="list_box">
      <div
        v-if="historyList.length && !value"
        class="list_classfiy_item"
        style="border-bottom: 1px solid #e4e4e4"
      >
        <div class="list_title">
          历史搜索
        </div>
        <div class="flex history-list">
          <div class="tag-wrap">
            <div
              v-for="(item, index) of historyList"
              :key="index"
              class="tag"
              @click="handlerHistory(item.historyname)"
            >
              {{ item.historyname }}
            </div>
          </div>
          <SvgIcon
            class="icon-delete"
            name="delete-history"
            size="16"
            @click="deleteHistory"
          />
        </div>
      </div>
      <div
        v-for="(item, index) in resultList"
        :key="index"
        class="list_classfiy_item"
        :style="index === resultList.length - 1 ? '' : 'border-bottom:1px solid #e4e4e4'"
      >
        <div class="list_title">
          {{ item.title }}
        </div>
        <div
          v-for="(sitem, sindex) in item.data"
          :key="sindex"
          class="list_item"
          @click="goPath(item, sitem.id)"
        >
          <SvgIcon name="task-icon" size="16" style="margin-left: 16px" />
          <span class="name" v-html="highlightText(sitem.name, value)" />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.input_wrap {
  // width: 60%;
  width: 808px;
  position: absolute;
  top: 20%;
  left: 30%;
  box-shadow: none !important;

  .ip_box {
    z-index: 0;
    position: relative;
    left: calc(50% - 40px);
    top: 30px;

    img {
      width: 80px;
      height: 80px;
    }
  }

  .input_box {
    z-index: 1;
    background: #ffffff;
    border: 1px solid #507afd;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0px 12px 12px 0px rgba(80, 122, 253, 0.15), 0px 0px 0px 0.5px #d4e3fc;
    // width: 808px;
    // height: 56px;
  }

  .list_box {
    background: #fefefe;
    border: 1px dashed #f4f4f4;
    border-radius: 8px;
    box-shadow: 0px 12px 12px 0px rgba(80, 122, 253, 0.15);
    margin-top: 15px;
    padding: 8px 16px;
    width: 802px;
    height: 400px;
    .list_classfiy_item {
      margin-bottom: -2px;
      .list_title {
        font-size: 12px;
        font-family: PingFang SC, PingFang SC-Regular;
        font-weight: Regular;
        color: #999999;
        line-height: 17px;
        margin: 6px 0 12px 0;
        font-weight: 500;
      }

      .list_item {
        display: flex;
        flex-flow: row nowrap;
        align-items: center;
        margin: 16px 0;
      }
    }
  }
}

:deep(.n-input .n-input-wrapper) {
  margin: 8px;
}

.history-list {
  align-items: center;
  // 上面有margin-bottom:12;12+26=38
  padding: 26px 12px 12px 0;
}

.name {
  margin-left: 8px;
  cursor: pointer;
  font-weight: 500;
  color: #333333;
}

.tag-wrap {
  display: flex;
  align-items: center;
  flex: 1;
  overflow-y: hidden;
  overflow-x: auto;
  margin: 9px 0 9px 29px;

  .tag {
    font-weight: 500;
    padding: 0 12px;
    height: 22px;
    border: 1px solid #e4e7ed;
    border-radius: 12px;
    margin-right: 12px;
    font-size: 13px;
    font-family: PingFang SC, PingFang SC-Regular;
    font-weight: Regular;
    text-align: left;
    color: #666666;
    cursor: pointer;
  }
}

.icon-delete {
  cursor: pointer;
}

.highlight {
  color: #507afd;
}
</style>
