<template>
  <div v-if="showStatistics" class="statistics">
    <div class="history">{{ isHistory ? '搜索历史' : '搜索结果' }}</div>
    <Icon class="delete-btn" name="delete" size="40" @click="tapDeleteIcon"></Icon>
  </div>
  <div :class="['words_data', { pop_words_data: isPopUp }]">
    <div v-if="isLoading && !scrollLoading" :class="['loading', { pop_loading: isPopUp }]">
      <Icon name="global_loading" loading :size="80"></Icon>
    </div>
    <template v-else>
      <!-- 搜索历史 -->
      <template v-if="isHistory">
        <div v-if="isHistoryEmpty" class="empty">
          <Empty type="learn" content="暂无搜索历史" size="320"></Empty>
        </div>
        <div v-else>
          <div :class="['result_words', { pop_result_words: isPopUp }]" @scroll="pageScroll">
            <div
              v-for="(i, index) in historyList"
              :key="index"
              :class="['word', { pop_word: isPopUp }]"
              @click="tapWordDetails(i, 0)"
            >
              <text class="english">{{ i.wordSpell }}</text>
              <div class="chinese chinese2">
                <div v-for="(item, idx) in i?.meaningSimpleListNew" :key="idx" class="chinese-box">
                  <span v-for="(i2, subidx) in item.typeAbbr" :key="subidx" class="span">
                    {{ i2 }}
                  </span>

                  <div class="abbr">{{ item.znDesc }}</div>
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="showHistoryMore && historyTotal > resultListNumer"
            :class="['more', { pop_more: isPopUp }]"
            @click="tapLoadMore"
          >
            <span>查看更多</span>
            <Icon name="down" size="48"></Icon>
          </div>
        </div>
      </template>
      <!-- 搜索结果 -->
      <template v-else>
        <div v-if="isSearchEmpty" name="empty">
          <div :class="['empty', { pop_empty: isPopUp }]">
            <Empty type="search" :size="isPopUp ? 120 : 320"></Empty>
          </div>
        </div>
        <div v-else>
          <div :class="['result_words', { pop_result_words: isPopUp }]" @scroll="pageScroll">
            <div
              v-for="(i, index) in resultList"
              :key="index"
              :class="['word', { pop_word: isPopUp }]"
              @click="tapWordDetails(i, 1)"
            >
              <span class="english">{{ i.wordSpell }}</span>
              <div class="chinese chinese2">
                <div v-for="(item, idx) in i?.meaningSimpleListNew" :key="idx" class="chinese-box">
                  <span v-for="(i2, subidx) in item.typeAbbr" :key="subidx" class="span">
                    {{ i2 }}
                  </span>
                  <div class="abbr">{{ item.znDesc }}</div>
                </div>
              </div>
            </div>
          </div>
          <div
            v-if="showSearchMore && resultTotal > resultListNumer"
            :class="['more', { pop_more: isPopUp }]"
            @click="tapLoadMore"
          >
            <span>查看更多</span>
            <Icon name="down" size="48"></Icon>
          </div>
        </div>
      </template>
    </template>
  </div>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import type { SearchHistory, SearchResult } from '../interface'
import dictionariesApi from '@/api/subject/dictionaries'
import { dialog } from '@/components/mj/mj-dialog'

withDefaults(
  defineProps<{
    showStatistics?: boolean
    isPopUp?: boolean // 是否是弹窗格式
  }>(),
  {
    showStatistics: true,
    isPopUp: false,
  },
)
const emits = defineEmits(['searchEmpty', 'selectedWord'])
const OSS_URL = import.meta.env.VITE_OSS_URL
const bg = `url(${OSS_URL}/urm/dictionaries_cutting_line.svg)`

const keyWord = ref<string>('')
const isLoading = ref(true)
const isSearchEmpty = ref(false)
const isHistoryEmpty = ref(false)
const isHistory = ref<boolean>(true) // true-搜索历史 false-搜索结果
const historyTotal = ref<number>(0)
const resultTotal = ref<number>(0)
const historyList = ref<SearchHistory[]>([]) // 搜索历史
const resultList = ref<SearchResult[]>([]) // 搜索结果
const showHistoryMore = ref<boolean>(true)
const showSearchMore = ref<boolean>(true)
const loadingTimer = ref<any>()
const resultListNumer = 5
const scrollLoading = ref(false)
const isScrollLoading = ref(false) // 触底加载状态

const pageData = ref({
  historyPage: {
    size: 10,
    current: 1,
  },
  wordPage: {
    size: 10,
    current: 1,
  },
})
defineExpose({
  tapSearch,
  onSearchInput,
  onConfirmInput,
})

// 搜索
function tapSearch(val: any) {
  keyWord.value = val.value
  onConfirmInput(val)
}

function onSearchInput(val: any) {
  keyWord.value = val.value
  resultTotal.value = 0
  historyTotal.value = 0
  if (keyWord.value) {
    isHistory.value = false
    resultList.value = []
    fetchSearchResult({ size: resultListNumer, current: 1 }, val.value)
  } else {
    isHistory.value = true
    fetchHistoryData()
  }
}
async function onConfirmInput(val: any) {
  keyWord.value = val.value

  if (resultList.value.length <= 0) {
    emits('searchEmpty')
  }
  await fetchSearchResult({ size: resultListNumer, current: 1 }, val.value)
  for (let i in resultList.value) {
    let go = resultList.value[i].completeFlag
    if (go) {
      let saveHistory = {
        wordId: resultList.value[i].wordId,
        searchValue: val.value,
        stageState: 1,
        wordSpell: resultList.value[i].wordSpell,
        wordZnDesc: resultList.value[i].wordZnDesc,
      }
      emits('selectedWord', {
        id: resultList.value[i].wordId,
        spell: resultList.value[i].wordSpell,
      })
      await dictionariesApi.addSearchHistoryApi(saveHistory)
      keyWord.value = ''
      isHistory.value = true
      fetchHistoryData()
    } else {
      isSearchEmpty.value = true
    }
  }
}
// 删除icon
function tapDeleteIcon() {
  dialog.show({
    content: '确定要清空历史搜索吗?',
    ok: async () => {
      await dictionariesApi.deleteSearchHistoryApi()
      fetchHistoryData()
    },
  })
}

// 单词详情
async function tapWordDetails(i: any, type: number) {
  let saveHistory = {
    wordId: i.wordId,
    searchValue: keyWord.value,
    stageState: 1,
    wordSpell: i.wordSpell,
    wordZnDesc: i.wordZnDesc,
  }
  emits('selectedWord', {
    id: i.wordId,
    spell: i.wordSpell,
  })
  if (type === 1) {
    await dictionariesApi.addSearchHistoryApi(saveHistory)
  }
  keyWord.value = ''
  isHistory.value = true
  fetchHistoryData()
}

// 查看更多
async function tapLoadMore() {
  if (isHistory.value) {
    pageData.value.historyPage.size = 20
    await fetchHistoryData(pageData.value.historyPage)
    pageData.value.historyPage.size = 10
    showHistoryMore.value = false
    pageData.value.historyPage.current++
  } else {
    pageData.value.wordPage.size = 20
    await fetchSearchResult(pageData.value.wordPage, keyWord.value)
    pageData.value.wordPage.size = 10
    showSearchMore.value = false
    pageData.value.wordPage.current++
  }
}
// 获取搜索历史
async function fetchHistoryData(page: anyObj = { size: resultListNumer, current: 1 }) {
  showHistoryMore.value = true
  isHistoryEmpty.value = false
  isLoading.value = true
  const res: any = await dictionariesApi.getSearchHistoryApi({ ...page, stageState: 1 })
  if (res.data.code === 200) {
    historyTotal.value = res.data.data.totalRows
    historyList.value = res.data.data.rows
    toolsFN(historyList.value)
    isHistoryEmpty.value = historyList.value.length === 0 ? true : false
    loadingTimer.value = setTimeout(() => {
      isLoading.value = false
      scrollLoading.value = false
    }, 100)
  }
  pageData.value.historyPage.current = 1
}
// 搜索结果
async function fetchSearchResult(page: anyObj, keyword = '') {
  showSearchMore.value = true
  isSearchEmpty.value = false
  isLoading.value = true
  const res: any = await dictionariesApi.searchWordApi({ ...page, keyword })
  if (res.data.code === 200) {
    resultTotal.value = res.data.data.totalRows
    resultList.value = res.data.data.rows
    toolsFN(resultList.value)

    isSearchEmpty.value = resultList.value.length === 0 ? true : false
    loadingTimer.value = setTimeout(() => {
      isLoading.value = false
      scrollLoading.value = false
    }, 100)
  }

  pageData.value.wordPage.current = 1
}

function toolsFN(arr: any[]) {
  for (const par of arr || []) {
    if (par.meaningSimpleList !== null) {
      par.meaningSimpleList = par.meaningSimpleList.reverse()
    }
    par.meaningSimpleListNew = []
    let num = 0
    for (const item of par.meaningSimpleList || []) {
      num = num + item.znDesc.length
      if (num < 25 && par.meaningSimpleList.length > 1 && num + item.znDesc.length < 25) {
        par.meaningSimpleListNew.push(item)
      } else {
        par.meaningSimpleListNew[0] = item
        par.meaningSimpleListNew.length = 1
      }

      item.typeAbbr = (item.typeAbbr || '').split('/')
    }
  }
}

// 滚动加载

async function pageScroll(e: any) {
  // return

  if (isScrollLoading.value) return
  // 滚动条滚动时，距离顶部的距离
  const scrollTop = e.target.scrollTop
  // 可视区的高度
  const windowHeight = e.target.clientHeight
  // 滚动条的总高度
  const scrollHeight = e.target.scrollHeight
  // 当滚动条滚动到底部 并且 当前数据小于总数时进行翻页
  if (
    scrollTop + windowHeight >= scrollHeight - 50 &&
    (isHistory.value
      ? pageData.value.historyPage.current < historyTotal.value
      : pageData.value.wordPage.current < resultTotal.value)
  ) {
    isScrollLoading.value = true
    if (isHistory.value) {
      const res: any = await dictionariesApi.getSearchHistoryApi({
        ...pageData.value.historyPage,
      })
      if (res.data.code === 200) {
        historyTotal.value = res.data.data.totalPage
        toolsFN(res.data.data.rows)
        historyList.value = historyList.value.concat(res.data.data.rows)
      }
      pageData.value.historyPage.current++

      isScrollLoading.value = false
    } else {
      const res: any = await dictionariesApi.searchWordApi({
        ...pageData.value.wordPage,
        keyword: keyWord.value,
      })
      if (res.data.code === 200) {
        resultTotal.value = res.data.data.totalPage
        toolsFN(res.data.rows)
        resultList.value = resultList.value.concat(res.data.data.rows)
      }
      pageData.value.wordPage.current++

      isScrollLoading.value = false
    }
  }
}
onMounted(() => {
  fetchHistoryData()
})

onUnmounted(() => {
  clearTimeout(loadingTimer.value)
})
</script>
<style scoped lang="scss">
.statistics {
  padding: 1.67vh 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;

  .history {
    font-size: 2.67vh;
    color: #a6a6a4;
  }

  .delete-btn {
    cursor: pointer;
  }
}

.loading {
  margin: 20.83vh auto;
  width: 120px;
  height: 10vh;

  img {
    width: 120px;
    height: 10vh;
  }
}

.pop_loading {
  margin: auto;
  width: 80px;
  height: 6.67vh;

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

.pop_words_data {
  display: flex;
  align-items: center;
}

.words_data {
  .timeout {
    margin: auto;
    width: 400px;
  }

  .result_words {
    max-height: 63.33vh;
    scrollbar-color: transparent transparent;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;

    .uni-scroll-view {
      padding: 0;
    }

    &::-webkit-scrollbar {
      width: 0;
      height: 0;
      color: transparent;
      display: none;
    }

    .word {
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      margin-bottom: 1.33vh;
      color: $font-color;
      line-height: 4vh;
      box-sizing: border-box;

      &:last-child {
        margin-bottom: 0;
      }

      .english {
        font-size: 2.67vh;
      }

      .chinese {
        max-width: 746.01px;
        // white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-size: 2vh;
        font-weight: 300;

        &.chinese2 {
          display: flex;
          align-items: center;

          .chinese-box {
            display: flex;
            align-items: center;

            .span {
              white-space: nowrap;
            }
          }
        }
      }
    }

    .pop_word {
      margin-bottom: 0;
    }
  }

  .pop_result_words {
    max-height: 25.5vh;
  }

  .more {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 4vh;
    font-size: 2.67vh;
    color: #666;
    line-height: 2.67vh;
    cursor: pointer;
    span {
      margin-right: 10px;
    }
  }

  .pop_more {
    margin-top: 2vh;
    padding: 1.33vh 0 0 0;
    font-size: 1.67vh;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 1vh;
      background-image: v-bind(bg);
      background-size: 100% 100%;
      background-repeat: no-repeat;
    }

    img {
      width: 26px;
      height: 2.17vh;
      margin-left: 8px;
    }
  }
}

.abbr {
  width: 100%;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.empty {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
  text-align: center;
  margin-top: 8.33vh;
}

:deep(.pop_empty) {
  margin-top: 0;
  .empty {
    margin-top: 0;
  }
  .empty-content {
    font-size: 0.92vh;
    margin-top: 0;
  }
}
</style>
