// 打印

import { isWebEvn } from '@/utils'
import hud from '@/utils/hud'

export function useWordPrint() {
  // 显示单词打印
  const showWordPrint = ref(false)
  // 被选中的单词
  const selectedWords = ref({} as any)
  // 传递给打印界面的数据
  const wordPrintData = ref([] as any)

  // 打印按钮文字
  const printBtnText = computed(() => {
    const len = Object.values(selectedWords.value).length
    return len > 0 ? `导出单词(${len})` : '导出单词'
  })

  // 打印
  function print() {
    const words = Object.values(selectedWords.value)
    if (words.length === 0) {
      hud.error('请先选择单词')
      return
    }
    wordPrintData.value = Object.values(selectedWords.value)
    showWordPrint.value = true
  }

  function wordClick(item: any) {
    if (!isWebEvn) return
    if (selectedWords.value[item.meaningId]) {
      delete selectedWords.value[item.meaningId]
    } else {
      selectedWords.value[item.meaningId] = item
    }
  }

  // 全选
  function selectAll(curPageData: any) {
    // 检测是否全页都选中了
    let pageSelected = true
    for (const item of curPageData) {
      if (!selectedWords.value[item.meaningId]) {
        pageSelected = false
        break
      }
    }

    if (pageSelected) {
      // 取消全选
      for (const item of curPageData) {
        delete selectedWords.value[item.meaningId]
      }
    } else {
      // 全选
      for (const item of curPageData) {
        selectedWords.value[item.meaningId] = item
      }
    }
  }

  // 清除所有选中
  function clearAll() {
    selectedWords.value = {}
  }

  return {
    printBtnText,
    showWordPrint,
    selectedWords,
    wordPrintData,
    selectAll,
    clearAll,
    wordClick,
    print,
  }
}
