<script setup lang="ts">
import type { WordCardType } from './interface'
import wordBookApi from '@/api/subject/wordBook'
import { debounce } from '@/hooks'
import WordCard from './components/WordCard.vue'
import TopSearch from '../dictionaries/components/TopSearch.vue'
import { dialog } from '@/components/mj/mj-dialog'
const OSS_URL = import.meta.env.VITE_OSS_URL

const topSearch = ref()
const deleteBtn = ref(false)
const activeMode = ref('浏览模式')
const showDelSelect = ref(false)
const reviewMode = ref(false) // 复习模式
const isEmpty = ref(false)
const keyWord = ref<string>('')
const isLoading = ref(true)
const dataLoading = ref(false) // 数据加载
const loadingTimer = ref<any>()
const page = ref({
  size: 24,
  current: 1,
})
const total = ref(0)
const removeWordList = ref<string[]>([])
const tipText = ref<string>()
const mode = [
  {
    name: '复习模式',
    type: 2,
  },
  {
    name: '浏览模式',
    type: 1,
  },
]
const strangeWordList = ref<WordCardType[]>([])
const wordItem = ref<WordCardType>()
const isAutoOpen = ref(false)
// 搜索
function tapSearch(val: any) {
  keyWord.value = val.value
  page.value.current = 1
  strangeWordList.value = []
  fetchStrangeWord()
}
// 删除icon
function tapDeleteIcon() {
  if (total.value > 0) {
    deleteBtn.value = true
    showDelSelect.value = true
  }
}
// 删除按钮
function tapDeleteBtn() {
  if (removeWordList.value.length > 0) {
    let num = 0
    num = removeWordList.value.length
    tipText.value = `确定要把${num}个单词从生词本中删除吗？`
    dialog.show({
      content: tipText.value,
      ok: confirmDelete,
    })
  }
}
// 取消按钮
function tapCancelBtn() {
  deleteBtn.value = false
  showDelSelect.value = false
  removeWordList.value = []
}
// 切换模式
function tapChangeMode(i: any, handle = false) {
  if (activeMode.value === i.name && !handle) return
  activeMode.value = i.name
  strangeWordList.value = []
  page.value.current = 1
  removeWordList.value = []
  deleteBtn.value = false
  showDelSelect.value = false
  fetchStrangeWord()
  if (activeMode.value === '复习模式') {
    reviewMode.value = true
  } else {
    reviewMode.value = false
  }
}
// 二次确认
const confirmDelete = debounce(
  () => {
    if (removeWordList.value?.length <= 0) return
    let wordIds = removeWordList.value.join(',')
    page.value.current = 1
    strangeWordList.value = []
    wordBookApi.deleteStrangeWord(wordIds).then((res: any) => {
      if (res.data.code === 200) {
        deleteBtn.value = false
        showDelSelect.value = false
        fetchStrangeWord()
        removeWordList.value = []
      }
    })
  },
  1500,
  false,
)
// 数据获取
async function fetchStrangeWord(showLoading = false) {
  if (dataLoading.value) return
  dataLoading.value = true
  isEmpty.value = false
  if (page.value.current > 1 || showLoading) {
    isLoading.value = false
  } else {
    isLoading.value = true
  }
  if (showLoading) page.value.current = 1
  try {
    const res: any = await wordBookApi.getStrangeWord({ wordSpell: keyWord.value, ...page.value })
    if (showLoading) {
      strangeWordList.value = []
    }
    let data = res.data.data
    total.value = data.totalRows
    strangeWordList.value?.push(...data.rows)
    isEmpty.value = strangeWordList.value.length === 0 ? true : false
    if (res.data.code === 200) {
      if (reviewMode.value) {
        // 复习模式
        for (let i in strangeWordList.value) {
          strangeWordList.value[i].isReviewMode = true
        }
      }
    }
    page.value.current++
    loadingTimer.value = setTimeout(() => {
      isLoading.value = false
    }, 0)
  } catch (err) {
    console.log(err)
  } finally {
    dataLoading.value = false
  }
}

// 移除删除单词
function removeDelWord(i: any) {
  removeWordList.value = removeWordList.value.filter(item => item !== i)
}
// 添加删除单词
function addDelWord(i: any) {
  removeWordList.value.push(i)
}

// 触底滚动加载
function scrollLoadData() {
  if (dataLoading.value) return
  if (total.value > strangeWordList.value?.length) {
    fetchStrangeWord()
  }
}
async function onScrollToLower(e: any) {
  if (dataLoading.value) return
  // 滚动条滚动时，距离顶部的距离
  const scrollTop = e.target.scrollTop
  // 可视区的高度
  const windowHeight = e.target.clientHeight
  // 滚动条的总高度
  const scrollHeight = e.target.scrollHeight
  // 当滚动条滚动到距离底部50px时进行翻页
  if (scrollTop + windowHeight >= scrollHeight - 50) {
    scrollLoadData()
  }
}

onActivated(() => {
  strangeWordList.value = []
  topSearch.value?.clearkeyWord()
  keyWord.value = ''
  tapChangeMode(mode[0], true)
})
onUnmounted(() => {
  clearTimeout(loadingTimer.value)
})
</script>
<template>
  <div class="strange_book">
    <div class="book">
      <TopSearch ref="topSearch" title="生词本" @tapSearch="tapSearch" @onSearchInput="tapSearch">
      </TopSearch>
      <div
        class="strange_words"
        :style="{
          'background-image': `url(${OSS_URL}/urm/dictionaries_box.svg)`,
        }"
      >
        <div class="statistics">
          <div class="all">
            全部<text class="num">（共{{ total }}个）</text>
          </div>
          <div class="right">
            <div v-if="!deleteBtn" class="right_delete" @click="tapDeleteIcon">
              <Icon name="delete" size="40"></Icon>
            </div>
            <div v-else class="operation_btn">
              <div class="button cancel_btn" @click="tapCancelBtn">取消</div>
              <div class="button del_btn" @click="tapDeleteBtn">删除</div>
            </div>
          </div>
        </div>
        <div class="nav_box">
          <div class="nav_tabs">
            <div
              v-for="(i, index) in mode"
              :key="index"
              :class="{
                tab: true,
                active: activeMode === i.name,
              }"
              @click="tapChangeMode(i)"
            >
              {{ i.name }}
            </div>
          </div>
          <div v-show="activeMode === '复习模式'" class="nav_tips">*点击卡片出现中文释义</div>
        </div>
        <div class="word_card" @scroll="onScrollToLower">
          <template v-if="isLoading">
            <div class="loading">
              <Icon name="global_loading" loading size="56"></Icon>
            </div>
          </template>
          <template v-else>
            <Empty v-if="isEmpty" :type="keyWord ? 'search' : 'learn'"> </Empty>
            <WordCard
              v-else
              :wordList="strangeWordList"
              :showDelSelect="showDelSelect"
              :reviewMode="reviewMode"
              :wordItem="wordItem as any"
              :isAutoOpenPop="isAutoOpen"
              @removeDelWord="removeDelWord"
              @addDelWord="addDelWord"
              @changeWord="
                () => {
                  page.current = 1
                  fetchStrangeWord(true)
                }
              "
            >
            </WordCard>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.strange_book {
  @include main_bg;
  padding: 2.67vh $space-6 0;
  height: 100%;
  overflow: hidden;
  box-sizing: border-box;
  .book {
    .strange_words {
      padding: 9.17vh 10.67vh;
      box-sizing: border-box;
      width: 144vh;
      height: 90vh;
      margin: 0 auto;
      // background-image: url('~@/static/unity/dictionaries_box.png');
      background-repeat: no-repeat;
      background-size: contain;

      .search_input {
        height: 8.33vh;
      }

      .statistics {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .all {
          font-size: 2.33vh;
          line-height: 3.5vh;
          font-weight: 600;
          color: $font-color;
          .num {
            margin-left: 0.67vh;
            font-size: 1.67vh;
            color: $font-color;
          }
        }

        .right {
          height: 4.33vh;
          .right_delete {
            display: flex;
            align-items: center;
            height: 100%;
            .del_icon {
              display: block;
              width: 3.33vh;
              height: 3.33vh;
              cursor: pointer;
              // background-image: url('~@/static/unity/delete_btn.png');
              background-repeat: no-repeat;
              background-size: cover;
            }
          }
          .operation_btn {
            display: flex;
            .button {
              width: 9.17vh;
              height: 4.33vh;
              line-height: 4.33vh;
              border-radius: 0.83vh;
              white-space: nowrap;
              font-size: 2vh;
              font-weight: 500;
              text-align: center;
            }
            .cancel_btn {
              margin-right: 2vh;
              border: 0.17vh solid #999999;
              color: #999999;
              background-color: #fafcfe;
            }

            .del_btn {
              background-color: #d9574e;
              border: 0.17vh solid #bf4d45;
              color: #fff2f2;
            }
          }
        }
      }

      .nav_box {
        margin: 2.5vh 0 2vh 0;
        font-size: 0;
        display: flex;
        align-items: center;

        .nav_tabs {
          box-sizing: border-box;
          display: inline-flex;
          width: auto;
          border-radius: 1.67vh;
          font-size: 2.67vh;
          font-family: $font-special;
          background: rgba(0, 0, 0, 0.6);

          .tab {
            padding: 0 74px;
            margin: 0.33vh;
            height: 100%;
            line-height: 4.17vh;
            color: rgba(255, 255, 255, 0.65);
            box-sizing: border-box;
            border-radius: 1.33vh;
            cursor: pointer;
          }

          .active {
            background: linear-gradient(249deg, #4de798 26.9%, #a2fb6e 79.86%);
            backdrop-filter: blur(3px);
            color: #0d1b0d;
          }
        }

        .nav_tips {
          margin-left: 20px;
          font-family: 'PingFang SC';
          font-size: 2vh;
          color: #8409d6;
        }
      }

      .word_card {
        height: 61.67vh;
        overflow: scroll;
        &::-webkit-scrollbar {
          display: none;
          width: 0 !important;
          height: 0 !important;
          -webkit-appearance: none;
          background: transparent;
          color: transparent;
        }
        .loading {
          margin: auto;
          margin-top: 18.17vh;
          width: 10vh;
          height: 10vh;

          img {
            width: 100%;
          }
        }

        .empty {
          margin: auto;
          margin-top: 7.33vh;
          // width: 320px;
          height: 30.17vh;

          img {
            width: 100%;
          }
          .wink {
            width: 320px;
            height: 30.17vh;
            margin: 0 auto;
            display: flex;
            align-items: center;
            flex-direction: column;
            justify-content: center;
            text-align: center;
            img {
              width: 22.75vh;
              height: 22.75vh;
            }
            .title {
              margin-top: 1.67vh;
              text-align: center;
              font-family: $font-special;
              font-size: 2.33vh;
              font-weight: 400;
              line-height: 3.5vh;
              color: #afbfcf;
            }
          }
        }
      }
    }
  }
}
</style>
