<!--
 * @Version    : v1.00
 * @Author     : Wang Chao
 * @Date       : 2024-08-21 22:29
 * @LastAuthor : Wang Chao
 * @LastTime   : 2024-11-27 16:16
 * @desc       :
-->
<!--
 * @Version    : v1.00
 * @Author     : itchaox
 * @Date       : 2024-07-06 11:57
 * @LastAuthor : Wang Chao
 * @LastTime   : 2024-08-23 22:25
 * @desc       : 主页面
-->
<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { replace as elementReplace } from '@renderer/utils/replace.element.js'
import { replace as noteReplace } from '@renderer/utils/replace.note.js'
import translateFlat from '@renderer/utils/translate.flat.js'
import data from 'emoji-mart-vue-fast/data/all.json'
import {
  ANNOTREE_COMMON,
  ANNOTREE_SCAN,
  ANNOTREE_NOTES,
  ANNOTREE_EXPORT_CONFIG,
  ANNOTREE_EXPORT_PREVIEW
} from '@renderer/constants/storageConst.js'

import 'emoji-mart-vue-fast/css/emoji-mart.css'
import { Picker, EmojiIndex } from 'emoji-mart-vue-fast/src'
const emojiIndex = ref(new EmojiIndex(data))

import { set } from 'lodash'
import { extList, languageList } from '@renderer/constants/constants.js'

import packageJson from '@/package.json'

import width from 'string-width'

import { nextTick, onMounted, ref, watch, watchEffect } from 'vue'
import useClipboard from 'vue-clipboard3'

import { useI18n } from 'vue-i18n'

import { i18n } from '@renderer/locales/i18n.js'

import html2canvas from 'html2canvas'

import { Icon } from '@iconify/vue'
import { fileIconMap } from '@renderer/constants/fileIconMap.js'
import { folderIconMap } from '@renderer/constants/folderIconMap.js'

// 根据文件后缀返回对应的图标名
const getIconByFolder = (name) => {
  const _name = name && name.split('/')[0]
  return folderIconMap[_name] || 'flat-color-icons:opened-folder' // 默认图标
}

// 根据文件后缀返回对应的图标名
const getIconByExtension = (extension) => {
  return fileIconMap[extension.split('.')[1]] || 'flat-color-icons:file' // 默认图标
}

const { IPC_FOLDER_SELECT, EXPORT_TREE_TEXT, localStorage, getSystemLanguage } = window.api as any

const { t } = useI18n()

const { toClipboard } = useClipboard()

// 全局配置
const isCommon = ref(false)

// 导出后自动打开文件
const autoOpenFile = ref(true)

// 导出文件后自动打开所在目录
const autoOpenFolder = ref(false)

// 忽略文件夹
const ignoreFolderList = ref([])

// 忽略文件
const ignoreFileList = ref([])

// 扫描深度
const scanDeep = ref(0)

// 只扫描文件夹
const onlyScanFolder = ref(false)

// 忽略以 . 开头的文件
const ignoreDotFile = ref(false)

//  忽略以 . 开头的文件夹
const ignoreDotFolder = ref(false)

// 默认名称
const defaultFileName = ref('Annotree_{YYYY}-{MM}-{DD}_{HH}-{mm}-{ss}')

const emojisOutput = ref('')

const isShowEmoji = ref(false)

// 导出后展示彩蛋
const isEggshell = ref(true)

// 同步滚动
const syncScroll = ref(true)

// 缓存
const isCache = ref(false)

// 配置
const isConfig = ref(false)

// 文件夹显示 /
const folderSuffix = ref(true)

// 输出自带代码块符号
const showCodeBlock = ref(true)

// 确定重置配置
async function resetCache() {
  // 重置配置
  if (isConfig.value) {
    localStorage.removeItem(ANNOTREE_COMMON)
    localStorage.removeItem(ANNOTREE_SCAN)
    localStorage.removeItem(ANNOTREE_EXPORT_CONFIG)
    localStorage.removeItem(ANNOTREE_EXPORT_PREVIEW)
    // 获取系统语言
    const _languageId = await getSystemLanguage()

    const common = JSON.parse(localStorage.getItem(ANNOTREE_COMMON))

    // 如果当前语言支持，则展示选中语言，否则默认展示英文
    languageId.value =
      common?.languageId ??
      (languageList.find((item) => item.id === _languageId) ? _languageId : 'en')

    i18n.global.locale = languageId.value
  }

  // 重置注释
  if (isCache.value) {
    localStorage.removeItem(ANNOTREE_NOTES)
    treeData.value = []
    previewList.value = []
    folderPath.value = ''
  }

  loadLocalStorage()

  ElMessage({
    message: t('zhong-zhi-cheng-gong'),
    type: 'success',
    duration: 1500,
    showClose: true
  })
}

// 清除当前文件夹缓存的 note
function clearNotes() {
  const annotreeNotes = JSON.parse(localStorage.getItem(ANNOTREE_NOTES) || '{}')
  for (const item of treeData.value) {
    delete annotreeNotes[item.id]
  }

  localStorage.setItem(ANNOTREE_NOTES, JSON.stringify(annotreeNotes))
}

// 日语: ja
// 西班牙语: es
// 法语: fr
// 德语: de
// 韩语: ko
// 俄语: ru
// 葡萄牙语: pt
// 意大利语: it
// 中文: zh
// 英文: en

// 默认展示系统语言
const languageId = ref('en')

onMounted(async () => {
  const common = JSON.parse(localStorage.getItem(ANNOTREE_COMMON))

  // 获取系统语言
  const _languageId = await getSystemLanguage()

  const zhLanguages = ['zh-CN', 'zh-TW', 'zh-HK', 'zh-MO', 'zh-SG']

  // 如果当前语言支持，则展示选中语言，否则默认展示英文

  const defaultLanguage = 'en'

  // 确定最终使用的语言ID
  let languageToUse = common?.languageId

  if (!languageToUse) {
    if (zhLanguages.includes(_languageId)) {
      languageToUse = 'zh'
    } else if (languageList.some((item) => item.id === _languageId)) {
      languageToUse = _languageId
    } else {
      languageToUse = defaultLanguage
    }
  }

  loadLocalStorage()

  languageId.value = languageToUse
  i18n.global.locale = languageId.value
})

// 切换语言
watch([languageId], async () => {
  i18n.global.locale = languageId.value
})

// 加载本地存储的数据
const loadLocalStorage = () => {
  // 通用
  const common = JSON.parse(localStorage.getItem(ANNOTREE_COMMON))
  languageId.value = common?.languageId ?? 'en'
  autoOpenFile.value = common?.autoOpenFile ?? true
  isEggshell.value = common?.isEggshell ?? true
  syncScroll.value = common?.syncScroll ?? true
  showIcon.value = common?.showIcon ?? true
  folderSuffix.value = common?.folderSuffix ?? true
  showCodeBlock.value = common?.showCodeBlock ?? true

  // 扫描
  const scan = JSON.parse(localStorage.getItem(ANNOTREE_SCAN))
  ignoreDotFile.value = scan?.ignoreDotFile ?? false
  ignoreDotFolder.value = scan?.ignoreDotFolder ?? false
  onlyScanFolder.value = scan?.onlyScanFolder ?? false
  scanDeep.value = scan?.scanDeep ?? 0
  ignoreFolderList.value = scan?.ignoreFolderList ?? []
  ignoreFileList.value = scan?.ignoreFileList ?? []

  // 导出
  const exportConfig = JSON.parse(localStorage.getItem(ANNOTREE_EXPORT_CONFIG))
  defaultFileName.value =
    exportConfig?.defaultFileName ?? 'Annotree_{YYYY}-{MM}-{DD}_{HH}-{mm}-{ss}'

  // 预览区
  const preview = JSON.parse(localStorage.getItem(ANNOTREE_EXPORT_PREVIEW))
  bridgeChar.value = preview?.bridgeChar ?? '-'
  minBridge.value = preview?.minBridge ?? 4
  noteFormat.value = preview?.noteFormat ?? ' # {note}'
  showBridge.value = preview?.showBridge ?? false
}

async function copy() {
  try {
    // 复制
    await toClipboard(emojisOutput.value)
    ElMessage({
      message: `${emojisOutput.value} ${t('copySuccess')}`,
      type: 'success',
      duration: 1500,
      showClose: true
    })
    // 复制成功
  } catch (e) {
    // 复制失败
  }
}

const treeData = ref([])

// 忽略文件夹列表
const folderList: any = ref([])

// 扫描目录
const folderPath = ref('')

// 未拍平数组
const noFlatData = ref([])

// 扫描
async function scan() {
  const params = {
    ignoreFolderList: ignoreFolderList.value,
    ignoreFileList: ignoreFileList.value,
    scanDeep: scanDeep.value,
    onlyScanFolder: onlyScanFolder.value,
    ignoreDotFile: ignoreDotFile.value,
    ignoreDotFolder: ignoreDotFolder.value
  }

  try {
    // 更新数据
    const allData = await IPC_FOLDER_SELECT(JSON.stringify(params))
    const result = allData.flatData
    noFlatData.value = allData?.noFlatData
    folderPath.value = allData.folderPath

    treeData.value = result

    // 初始化缓存
    cacheNoteList.value = result.map((item) => ({ id: item?.id, note: null }))

    folderNumber.value = treeData?.value.filter((item) => item?.isDirectory).length
    fileNumber.value = treeData?.value.filter((item) => item?.isFile).length

    // 读取缓存
    const annotreeNotes = JSON.parse(localStorage.getItem(ANNOTREE_NOTES) || '{}')

    // 读取缓存的 note
    treeData.value = treeData.value.map((item) => {
      for (const key in annotreeNotes) {
        const value = annotreeNotes[key]
        if (item.id === key) {
          item.note = value
        }
      }

      return item
    })
    getPreviewData()
    getIgnoreFolderList()

    // 聚焦第一个输入框
    setTimeout(() => {
      const inputs = document.getElementsByTagName('input')
      if (inputs.length > 0) {
        inputs[0].focus()
        currentIndex.value = -1
      } else {
        console.error('No input elements found on the page.')
      }
    }, 0)

    handleFolderSuffix()
  } catch (error) {
    console.error('Scan failed:', error)
  }
}

// 获取忽略的目录
function getIgnoreFolderList() {
  let result = []
  function isFolderAndPush(elements, level = 1) {
    if (level > 2) return
    for (const item of elements) {
      if (item.isDirectory) {
        result.push(item.filePath)
        isFolderAndPush(item.elements, level + 1)
      }
    }
  }
  isFolderAndPush(treeData.value)

  let uniquePaths = [...new Set(result)]
  folderList.value = uniquePaths
}

// 设置
function setCommon() {
  isCommon.value = true
}

// 导出
function exportFile() {
  const params = {
    bridgeChar: bridgeChar.value,
    minBridge: minBridge.value,
    noteFormat: noteFormat.value,
    showBridge: showBridge.value,
    isRight: isRight.value,
    autoOpenFile: autoOpenFile.value,
    autoOpenFolder: autoOpenFolder.value,
    defaultFileName: defaultFileName.value,
    isEggshell: isEggshell.value,
    showCodeBlock: showCodeBlock.value
  }

  // 临时的数组，增加文件夹和文件的图标显示
  let _list = treeData.value
  _list = treeData.value.map((item) => {
    return {
      ...item,
      tree: item.tree + (showIcon.value ? (item?.isDirectory ? '📁 ' : '📄 ') : '')
    }
  })
  // ipc 通信需要序列化
  EXPORT_TREE_TEXT(JSON.stringify(_list), JSON.stringify(params))
}

// 生成合适的桥梁
function bridgeAuto({ element, note }, max) {
  if (note !== '' || showBridge.value) {
    let length = minBridge.value
    if (isRight.value) {
      length += max - width(`${element}${note}`)
    } else {
      length += max - width(element)
    }

    return bridgeChar.value.repeat(length)
  }

  return ''
}

// 获取最大宽度
function getMaxWidth(result) {
  // 第一步 转换 element 和 note
  // const result = data.map((item) => {
  //   const element = elementReplace('{tree}{name}{ext}', {
  //     data: item
  //   })
  //   const bridge = ''

  //   const note = item.note
  //     ? noteReplace(noteFormat.value, {
  //         data: item
  //       })
  //     : ''
  //   return { element, bridge, note }
  // })

  // 右边对齐
  if (isRight.value) {
    // 计算result中每个对象的element属性的最大宽度
    const elementLengthMax = result.reduce(
      (max, { element }) => (width(element) > max ? width(element) : max),
      0
    )

    // 计算result中每个对象的note属性的最大宽度
    const noteLengthMax = result.reduce(
      (max, { note }) => (width(note) > max ? width(note) : max),
      0
    )

    // 返回element和note最大宽度之和
    return elementLengthMax + noteLengthMax
  } else {
    // 左对齐
    // 计算result中每个对象的element属性的最大宽度
    return result.reduce((max, { element }) => {
      const length = width(element)
      return length > max ? length : max
    }, 0)
  }
}

// 当前输入框索引
const currentIndex = ref(-1)

const isShiftTab = ref(false)
// tab 聚焦下一个输入框；shift + tab 聚焦上一个输入框；
document.addEventListener('keydown', function (event) {
  nextTick(() => {
    if (event.key === 'Tab') {
      const activeElement = document.activeElement
      const inputs = document.querySelectorAll('input')
      currentIndex.value = Array.from(inputs).indexOf(activeElement)

      const firstInput = inputs[0]
      const lastInput = inputs[inputs.length - 1]

      if (!inputs.length) return // 如果没有输入框，直接返回

      // 检查当前焦点是否在输入框上
      if (![...inputs].includes(activeElement)) {
        event.preventDefault()
        if (event.shiftKey) {
          lastInput.focus()

          if (scrollLeft.value) {
            // 确保滚动条到底部
            setTimeout(() => {
              scrollLeft.value.scrollTop = scrollLeft.value.scrollHeight
            }, 10)
          }
        } else {
          firstInput.focus()
        }
        return
      }

      if (event.shiftKey) {
        isShiftTab.value = true
        // Shift + Tab
        event.preventDefault()
        if (activeElement === firstInput) {
          lastInput.focus() // 从第一个跳到最后一个
          currentIndex.value = inputs.length

          if (scrollLeft.value) {
            // 确保滚动条到底部
            setTimeout(() => {
              scrollLeft.value.scrollTop = scrollLeft.value.scrollHeight
            }, 10)
          }
        } else {
          inputs[currentIndex.value - 1].focus() // 焦点移到上一个输入框
        }
      } else {
        isShiftTab.value = false
        // Tab
        event.preventDefault()
        if (activeElement === lastInput) {
          firstInput.focus() // 从最后一个跳到第一个
          currentIndex.value = -1
        } else {
          inputs[currentIndex.value + 1].focus() // 焦点移到下一个输入框
        }
      }
    }
  })
})

// 预览数据
const previewList = ref([])

// 处理预览区域展示
function getPreviewData() {
  let result = treeData.value

  // 第一步 转换 element 和 note
  result = result?.map((item) => {
    const element = elementReplace(
      `{tree}${showIcon.value ? (item?.isDirectory ? '📁 ' : '📄 ') : ''}{name}{ext}`,
      {
        data: item
      }
    )
    const bridge = ''

    const note = item.note
      ? noteReplace(noteFormat.value, {
          data: item
        })
      : ''
    return {
      ...item,
      element,
      tree: item.tree,
      name: item.name,
      ext: item.ext,
      bridge,
      note,
      type: item?.isFile ? 'file' : 'folder'
    }
  })

  const max = getMaxWidth(result)

  // 补齐桥梁
  result = result.map((item) => ({ ...item, bridge: bridgeAuto(item, max) }))

  // 转换为字符串
  // result = result.map((e) => `${e.element}${e.bridge}${e.note}`)
  result = result.map((e) => ({
    ...e,
    value: `${e.element}${e.bridge}${e.note}`,
    tree: e.tree,
    name: e.name,
    ext: e.ext,
    bridge: e.bridge,
    note: e.note,
    id: Math.random()
  }))

  previewList.value = result
}

// 显示预览配置
const isPreview = ref(false)

// 注释格式化
const noteFormat = ref(' # {note}')

// 桥梁最短字符数
const minBridge = ref(4)

// 桥梁字符
const bridgeChar = ref('-')

// 始终显示桥梁
const showBridge = ref(false)

// 右侧对齐
const isRight = ref(false)

function inputChange(item) {
  //  缓存 note
  cacheNoteList.value = cacheNoteList.value.map((i) => {
    if (i?.id === item.id) {
      return {
        id: i?.id,
        note: item.note
      }
    } else {
      return i
    }
  })

  getPreviewData()
}

let typingTimer: any = null
let typingDelay = 100

// 实现实时预览效果
const handleInputChange = (item) => {
  // 如果之前有定时器，清除它
  if (typingTimer) {
    clearTimeout(typingTimer)
  }

  // 设置新的定时器
  typingTimer = setTimeout(() => {
    // 此处缓存 note
    const obj = JSON.parse(localStorage.getItem(ANNOTREE_NOTES) || '{}')
    const id = item.id
    const note = item.note

    localStorage.setItem(
      ANNOTREE_NOTES,
      JSON.stringify({
        ...obj,
        [id]: note
      })
    )

    getPreviewData()
  }, typingDelay)
}

// 是否显示文件和文件夹的图标
const showIcon = ref(true)

// 全局配置-通用
watch(
  [autoOpenFile, isEggshell, syncScroll, showIcon, languageId, folderSuffix, showCodeBlock],
  () => {
    //  存储数据
    localStorage.setItem(
      ANNOTREE_COMMON,
      JSON.stringify({
        autoOpenFile: autoOpenFile.value,
        isEggshell: isEggshell.value,
        syncScroll: syncScroll.value,
        showIcon: showIcon.value,
        languageId: languageId.value,
        folderSuffix: folderSuffix.value,
        showCodeBlock: showCodeBlock.value
      })
    )
  }
)

// 控制文件夹结尾显示 /
watch([folderSuffix], () => {
  handleFolderSuffix()
})

// 处理文件夹尾部
function handleFolderSuffix() {
  if (folderSuffix.value) {
    treeData.value = treeData.value.map((item) => {
      if (item.isDirectory) {
        // 检查名称是否已经以斜杠结尾
        if (!item.name.endsWith('/')) {
          item.name = item.name + '/'
        }
      }
      return item
    })
  } else {
    treeData.value = treeData.value.map((item) => {
      if (item.isDirectory) {
        // 去掉文件夹名称末尾的斜杠
        if (item.name.endsWith('/')) {
          item.name = item.name.slice(0, -1)
        }
      }
      return item
    })
  }

  getPreviewData()
}

// 全局配置-扫描
watch(
  [ignoreDotFolder, ignoreDotFile, onlyScanFolder, scanDeep, ignoreFolderList, ignoreFileList],
  () => {
    //  存储数据
    localStorage.setItem(
      ANNOTREE_SCAN,
      JSON.stringify({
        ignoreDotFile: ignoreDotFile.value,
        ignoreDotFolder: ignoreDotFolder.value,
        onlyScanFolder: onlyScanFolder.value,
        scanDeep: scanDeep.value,
        ignoreFolderList: ignoreFolderList.value,
        ignoreFileList: ignoreFileList.value
      })
    )
  }
)

// 全局配置-导出文本

watch([defaultFileName], () => {
  //  存储数据
  localStorage.setItem(
    ANNOTREE_EXPORT_CONFIG,
    JSON.stringify({
      defaultFileName: defaultFileName.value
    })
  )
})

// 预览区配置
watch([bridgeChar, minBridge, noteFormat, showBridge, isRight, showIcon], () => {
  //  存储数据
  localStorage.setItem(
    ANNOTREE_EXPORT_PREVIEW,
    JSON.stringify({
      bridgeChar: bridgeChar.value,
      minBridge: minBridge.value,
      noteFormat: noteFormat.value,
      showBridge: showBridge.value
    })
  )

  getPreviewData()
})

// 更新 emoji
function selectEmoji(emoji) {
  emojisOutput.value = emoji.native

  copy()
}

// 重置数据
function refreshData() {
  clearNotes()

  treeData.value = []
  previewList.value = []
  folderPath.value = ''

  ElMessage({
    message: t('zhong-zhi-shu-ju-cheng-gong'),
    type: 'success',
    duration: 1500,
    showClose: true
  })
}

// 重置注释
function refreshNote() {
  treeData.value = treeData.value.map((item) => ({
    ...item,
    note: ''
  }))

  clearNotes()

  getPreviewData()

  ElMessage({
    message: t('zhong-zhi-zhu-shi-cheng-gong'),
    type: 'success',
    duration: 1500,
    showClose: true
  })
}

// 文件夹数量
const folderNumber = ref(0)

// 文件数量
const fileNumber = ref(0)

/**
 * 根据 isShow 和 isShowElements 过滤数据
 * @param {Array} elements 需要过滤的原数组
 */
function showFilter(els) {
  return els
    .filter((el) => el.isShow)
    .map((el) => ({
      ...el,
      elements: el.isShowElements ? showFilter(el.elements) : []
    }))
}

// 删除节点
function removeNode(item) {
  const data = set(noFlatData.value, `${item.dataPath}.isShow`, false)

  const newData = translateFlat({
    data: showFilter(data),
    notes: []
  })

  // 找到之前的对象，因为以前有 note 数据
  // 这里有问题，需要替换 tree

  treeData.value = newData.map((i) => {
    let obj = treeData.value.find((j) => j.id === i.id)
    return {
      ...obj,
      tree: i.tree
    }
  })

  getPreviewData()
}

// 缓存 note 列表
const cacheNoteList = ref([])

// 折叠节点
function foldNode(item) {
  const data = set(noFlatData.value, `${item.dataPath}.isShowElements`, !item.isShowElements)

  const newData = translateFlat({
    data: showFilter(data),
    notes: []
  })

  // 找到之前的对象，因为以前有 note 数据
  // 这里有问题，需要替换 tree

  treeData.value = newData.map((i) => {
    let obj = cacheNoteList.value?.find((j) => j?.id === i.id)
    return {
      ...i,
      note: obj?.note
    }
  })

  getPreviewData()
}

// 复制树
async function copyTree() {
  // 直接拿到处理后的tree

  // 显示图标
  const result = previewList.value.map((item) => item?.value)

  // 换行分割数组至字符串
  let data = result.join('\n')

  if (showCodeBlock.value) {
    data = '```\n' + data + '\n```'
  }

  try {
    // 复制
    await toClipboard(data)
    ElMessage({
      message: t('copySuccess'),
      type: 'success',
      duration: 1500,
      showClose: true
    })
    // 复制成功
  } catch (e) {
    // 复制失败
  }
}

const scrollLeft = ref(null)
const scrollRight = ref(null)

// 使用 isScrolling 标志来防止无限循环
let isScrolling = false

// 开启同步滚动后，先保证位置一致
watchEffect(() => {
  if (syncScroll.value && scrollLeft.value && scrollRight.value) {
    scrollLeft.value.scrollTop = scrollRight.value.scrollTop
    scrollLeft.value.scrollLeft = scrollRight.value.scrollLeft
  }
})

// 处理同步滚动
const handleScroll = (scrolledContainer, otherContainer) => {
  if (!isScrolling && syncScroll.value) {
    isScrolling = true
    otherContainer.scrollTop = scrolledContainer.scrollTop
    otherContainer.scrollLeft = scrolledContainer.scrollLeft
    isScrolling = false
  }
}

// 复制图片
function copyImg() {
  html2canvas(document.querySelector('#capture'), {
    backgroundColor: '#f8f9fa',
    useCORS: true, //支持图片跨域
    scale: 1 //设置放大的倍数
  }).then((canvas) => {
    canvas.toBlob(async (blob) => {
      try {
        await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })])
        ElMessage({
          message: t('tu-pian-yi-fu-zhi-dao-jian-tie-ban'),
          type: 'success',
          duration: 1500,
          showClose: true
        })
      } catch (err) {
        console.error('无法复制图片到剪贴板', err)
      }
    }, 'image/png')
  })
}

// 导出图片
function exportImg() {
  html2canvas(document.querySelector('#capture'), {
    backgroundColor: '#f8f9fa',
    useCORS: true, //支持图片跨域
    scale: 1 //设置放大的倍数
  }).then((canvas) => {
    // 获取当前时间
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，所以加1，并确保格式为两位数
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')

    // 格式化时间字符串
    const formattedDate = `${year}-${month}-${day} ${hours}-${minutes}-${seconds}`

    // 设置下载文件名
    const filename = `Annotree ${formattedDate}.png`

    const img = canvas.toDataURL('image/png')
    const link = document.createElement('a')
    link.href = img
    link.download = filename
    link.click()
  })
}

// 点击树节点
function nodeClick(index) {
  if (isShiftTab.value) {
    currentIndex.value = index + 1
  } else {
    currentIndex.value = index - 1
  }

  // 点击后聚焦至当前输入框
  const inputs = document.querySelectorAll('input')
  inputs[index].focus()
}

// 仅编辑区
const onlyEdit = ref(false)
function handleOnlyEdit() {
  onlyEdit.value = !onlyEdit.value
  onlyPreview.value = false
}

// 仅预览区
const onlyPreview = ref(false)
function handleOnlyPreview() {
  onlyPreview.value = !onlyPreview.value
  onlyEdit.value = false
}

const isSpecialIcon = ref(false)
function handleSpecialIcon() {
  isSpecialIcon.value = !isSpecialIcon.value
}
</script>

<template>
  <div class="main-page" @click="isShowEmoji = false">
    <!-- TODO 顶部按钮 -->
    <div class="operation">
      <div>
        <el-button type="primary" @click="scan">
          <el-icon><Search /></el-icon>
          <span> {{ $t('sao-miao') }} </span>
        </el-button>
        <el-button type="success" plain @click="setCommon">
          <el-icon size="16"><Setting /></el-icon>
          <span> {{ $t('quan-ju-pei-zhi') }} </span>
        </el-button>
      </div>
    </div>

    <!-- TODO 内容区 -->
    <div class="content" v-if="treeData.length > 0">
      <div class="top-tools">
        <div class="edit-tools">
          <div>
            <el-icon
              size="24"
              class="tools-icon"
              @click="refreshNote"
              :title="$t('zhong-zhi-zhu-shi')"
              ><Refresh
            /></el-icon>
          </div>

          <div style="position: relative">
            <el-icon
              size="24"
              :title="$t('xuan-ze-biao-qing')"
              @click.stop="isShowEmoji = !isShowEmoji"
              class="tools-icon"
              ><Star
            /></el-icon>
            <Picker
              @click.stop="isShowEmoji = true"
              v-if="isShowEmoji"
              style="position: absolute; top: 45px; left: 20px; z-index: 2"
              :data="emojiIndex"
              set="google"
              @select="selectEmoji"
              :emojiSize="26"
              :emojiTooltip="true"
              :showPreview="false"
              :i18n="{
                search: t('p1'),
                notfound: t('p2'),
                categories: {
                  search: t('p3'),
                  recent: t('p4'),
                  smileys: t('p5'),
                  people: t('p6'),
                  nature: t('p7'),
                  foods: t('p8'),
                  activity: t('p9'),
                  places: t('p10'),
                  objects: t('p11'),
                  symbols: t('p12'),
                  flags: t('p13'),
                  custom: t('p14')
                }
              }"
            />
          </div>
        </div>

        <div class="preview-tools" v-if="previewList.length > 0">
          <el-icon
            class="tools-icon"
            size="24"
            @click="isPreview = true"
            :title="$t('yu-lan-qu-pei-zhi')"
            ><Setting
          /></el-icon>

          <span
            v-if="showIcon"
            :title="isSpecialIcon ? t('tong-yong-tu-biao') : t('bian-cheng-tu-biao')"
            @click="handleSpecialIcon"
          >
            <svg
              class="tools-icon"
              width="24"
              height="24"
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M36 4H12C7.58172 4 4 7.58172 4 12C4 16.4183 7.58172 20 12 20H36C40.4183 20 44 16.4183 44 12C44 7.58172 40.4183 4 36 4Z"
                fill="none"
                :stroke="isSpecialIcon ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linejoin="round"
              />
              <path
                d="M36 28H12C7.58172 28 4 31.5817 4 36C4 40.4183 7.58172 44 12 44H36C40.4183 44 44 40.4183 44 36C44 31.5817 40.4183 28 36 28Z"
                fill="none"
                :stroke="isSpecialIcon ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linejoin="round"
              />
              <path
                d="M36 14C37.1046 14 38 13.1046 38 12C38 10.8954 37.1046 10 36 10C34.8954 10 34 10.8954 34 12C34 13.1046 34.8954 14 36 14Z"
                fill="none"
                :stroke="isSpecialIcon ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linejoin="round"
              />
              <path
                d="M12 38C13.1046 38 14 37.1046 14 36C14 34.8954 13.1046 34 12 34C10.8954 34 10 34.8954 10 36C10 37.1046 10.8954 38 12 38Z"
                fill="none"
                :stroke="isSpecialIcon ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linejoin="round"
              />
            </svg>
          </span>

          <span
            :title="onlyEdit ? t('hui-fu-mo-ren') : t('jin-bian-ji-qu')"
            @click="handleOnlyEdit"
          >
            <svg
              class="tools-icon"
              width="24"
              height="24"
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <rect
                x="6"
                y="6"
                width="28"
                height="36"
                rx="2"
                fill="none"
                :stroke="onlyEdit ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M42 6V42"
                :stroke="onlyEdit ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </span>

          <span
            :title="onlyPreview ? t('hui-fu-mo-ren') : t('jin-yu-lan-qu')"
            @click="handleOnlyPreview"
          >
            <svg
              class="tools-icon"
              width="24"
              height="24"
              viewBox="0 0 48 48"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <rect
                x="14"
                y="6"
                width="28"
                height="36"
                rx="2"
                fill="none"
                :stroke="onlyPreview ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
              <path
                d="M6 6V42"
                :stroke="onlyPreview ? '#5a9cf8' : 'currentColor'"
                stroke-width="4"
                stroke-linecap="round"
                stroke-linejoin="round"
              />
            </svg>
          </span>

          <el-icon
            v-if="!isSpecialIcon"
            class="tools-icon"
            size="24"
            @click="copyTree"
            :title="$t('fu-zhi-wen-ben')"
            ><CopyDocument
          /></el-icon>

          <el-icon
            v-if="!isSpecialIcon"
            class="tools-icon"
            size="24"
            @click="exportFile"
            :title="$t('dao-chu-wen-ben')"
            ><Download
          /></el-icon>

          <el-icon class="tools-icon" size="24" @click="copyImg" :title="$t('fu-zhi-tu-pian')"
            ><Picture
          /></el-icon>

          <el-icon class="tools-icon" size="24" @click="exportImg" :title="$t('dao-chu-tu-pian')"
            ><Camera
          /></el-icon>
        </div>
      </div>

      <div class="tree-container">
        <!-- TODO 编辑器树 -->
        <div class="left" :class="{ 'left-none': onlyPreview }">
          <div
            @scroll="handleScroll(scrollLeft, scrollRight)"
            ref="scrollLeft"
            class="tree-scroller"
          >
            <div
              v-for="(item, index) in treeData"
              :class="{
                'tree-node-active': isShiftTab
                  ? currentIndex - 1 === index
                  : currentIndex + 1 === index
              }"
              :key="item.id"
              class="tree-node"
              @click="nodeClick(index)"
            >
              <div style="display: flex">
                <div style="display: flex; flex: 1">
                  <div
                    class="folder-icon"
                    style="width: 15px"
                    v-if="item?.isDirectory"
                    @click="foldNode(item)"
                  >
                    <el-icon color="#00000088" v-if="item.isShowElements"><CaretBottom /></el-icon>
                    <el-icon color="#00000088" v-else><CaretRight /></el-icon>
                  </div>
                  <div v-else style="width: 15px"></div>
                  <!-- 树枝 -->
                  <span class="row-tree">
                    <pre>{{ item.tree }}</pre>
                  </span>
                  <!-- 文件信息 -->
                  <span class="row-info">
                    <!-- 文件名 -->
                    <div style="display: flex">
                      <span v-if="showIcon">
                        <pre v-if="!isSpecialIcon">{{ item?.isDirectory ? '📁' : '📄' }}</pre>

                        <span v-if="isSpecialIcon">
                          <icon
                            v-if="item?.isDirectory"
                            :icon="getIconByFolder(item.name)"
                            :style="{ fontSize: '18px' }"
                          />
                          <!-- 根据文件后缀动态显示图标 -->
                          <icon
                            v-if="!item?.isDirectory"
                            :icon="getIconByExtension(item.ext)"
                            :style="{ fontSize: '18px' }"
                          />
                        </span>
                      </span>

                      <span style="margin-right: 5px"></span>
                      <pre>{{ item.name }}</pre>
                      <!-- 扩展名 -->
                      <pre v-if="item.ext">{{ item.ext }}</pre>
                    </div>
                  </span>
                </div>

                <div>
                  <!-- 注释 -->
                  <el-input
                    style="height: 20px; width: 120px; margin-right: 2px"
                    v-model="item.note"
                    size="small"
                    :placeholder="$t('qing-shu-ru-zhu-shi')"
                    clearable
                    :tabindex="index + 1"
                    @change="inputChange(item)"
                    @input="handleInputChange(item)"
                  ></el-input>

                  <el-button link type="danger" @click="removeNode(item)"
                    ><el-icon><Delete /></el-icon
                  ></el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- TODO 预览树 -->
        <div class="right" :class="{ 'right-none': onlyEdit }">
          <div
            class="tree-scroller preview-tree"
            ref="scrollRight"
            @scroll="handleScroll(scrollRight, scrollLeft)"
          >
            <div id="capture">
              <div
                class="tree-node"
                style="display: flex"
                v-for="item in previewList"
                :key="item.id"
              >
                <span style="display: inline-block">
                  <pre>{{ item.tree }}</pre>
                </span>

                <span v-if="showIcon">
                  <pre v-if="!isSpecialIcon">{{ item?.isDirectory ? '📁' : '📄' }}</pre>

                  <span v-if="isSpecialIcon">
                    <icon
                      v-if="item?.isDirectory"
                      :icon="getIconByFolder(item.name)"
                      :style="{ fontSize: '18px' }"
                    />
                    <!-- 根据文件后缀动态显示图标 -->
                    <icon
                      v-if="!item?.isDirectory"
                      :icon="getIconByExtension(item.ext)"
                      :style="{ fontSize: '18px' }"
                    />
                  </span>
                </span>

                <span style="margin-right: 5px"></span>
                <span style="display: inline-block">
                  <pre>{{ item.name }}</pre>
                </span>
                <span style="display: inline-block">
                  <pre>{{ item.ext }}</pre>
                </span>
                <span style="display: inline-block">
                  <pre>{{ item.bridge }}</pre>
                </span>
                <span style="display: inline-block">
                  <pre>{{ item.note }}</pre>
                </span>
                <!-- {{ '' }} -->
                <!-- {{ item.value }} -->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- TODO 无数据 -->
    <div class="no-data" v-else>
      <img src="@renderer/assets/images/noData.png" alt="" />
      <div>
        {{ $t('qing') }} <span class="no-data-btn" @click="scan">{{ $t('sao-miao') }}</span>
        {{ $t('wen-jian-jia-lu-ru-shu-ju') }}
      </div>
    </div>

    <!-- TODO 预览配置 -->
    <el-drawer v-model="isPreview" direction="ltr" :modal="true" @close="isPreview = false">
      <template #header>
        <h4>{{ $t('yu-lan-pei-zhi') }}</h4>
      </template>
      <template #default>
        <div class="preview-config">
          <div class="preview-item">
            <div class="preview-label">{{ $t('zhu-shi-ge-shi-hua') }}</div>
            <div class="preview-value">
              <el-input
                v-model="noteFormat"
                :placeholder="$t('qing-shu-ru-ge-shi-hua-zi-fu-chuan')"
              ></el-input>
            </div>
          </div>

          <div class="preview-item">
            <div class="preview-label">{{ $t('qiao-liang-zui-duan-zi-fu-shu') }}</div>
            <div class="preview-value">
              <el-input-number
                v-model="minBridge"
                :placeholder="$t('qing-shu-ru-qiao-liang-zui-duan-zi-fu-shu')"
                :min="0"
              ></el-input-number>
            </div>
          </div>

          <div class="preview-item">
            <div class="preview-label">{{ $t('qiao-liang-tian-chong-zi-fu') }}</div>
            <div class="preview-value">
              <el-input
                v-model="bridgeChar"
                :placeholder="$t('qing-shu-ru-dan-zi-jie-tian-chong-zi-fu')"
                maxlength="1"
              ></el-input>
            </div>
          </div>

          <div class="preview-item">
            <div class="preview-label">{{ $t('shi-zhong-xian-shi-qiao-liang') }}</div>
            <div class="preview-value">
              <el-switch size="large" v-model="showBridge"></el-switch>
            </div>
          </div>
        </div>
      </template>
    </el-drawer>

    <!-- TODO 全局配置 -->
    <el-dialog
      v-model="isCommon"
      :title="$t('quan-ju-pei-zhi')"
      width="40vw"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      @close="isCommon = false"
    >
      <div class="dialog-body">
        <el-tabs type="border-card" class="demo-tabs">
          <!-- 通用 -->
          <el-tab-pane>
            <template #label>
              <span class="custom-tabs-label">
                <el-icon><house /></el-icon>
                <span>{{ $t('tong-yong') }}</span>
              </span>
            </template>
            <div>
              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('yu-yan') }}
                  <el-tooltip
                    effect="dark"
                    :content="$t('pei-zhi-ruan-jian-xian-shi-yu-yan')"
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value">
                  <el-select
                    v-model="languageId"
                    :placeholder="$t('qing-xuan-ze-yu-yan')"
                    style="width: 110px"
                  >
                    <el-option
                      v-for="item in languageList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('zi-dong-da-kai-wen-jian') }}
                  <el-tooltip
                    effect="dark"
                    :content="$t('dao-chu-wen-jian-hou-zi-dong-da-kai')"
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value"><el-switch v-model="autoOpenFile"></el-switch></div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('dao-chu-hou-zhan-shi-cai-dai') }}
                  <el-tooltip
                    effect="dark"
                    :content="$t('dao-chu-cheng-gong-hou-zi-dong-zhan-shi-cai-dan')"
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value"><el-switch v-model="isEggshell"></el-switch></div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('tong-bu-gun-dong') }}
                  <el-tooltip
                    effect="dark"
                    :content="$t('bian-ji-qu-he-yu-lan-qu-shi-fou-tong-bu-gun-dong')"
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value"><el-switch v-model="syncScroll"></el-switch></div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('xian-shi-tu-biao') }}
                  <el-tooltip
                    effect="dark"
                    :content="$t('shi-fou-xian-shi-wen-jian-jia-he-wen-jian-de-tu-biao')"
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value"><el-switch v-model="showIcon"></el-switch></div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">{{ $t('wen-jian-jia-jie-wei-xian-shi') }}</div>
                <div class="tab-item-value"><el-switch v-model="folderSuffix"></el-switch></div>
              </div>

              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('xian-shi-dai-ma-kuai') }}

                  <el-tooltip
                    effect="dark"
                    :content="$t('fu-zhi-he-dao-chu-wen-ben-shi-fou-xian-shi-dai-ma-kuai')"
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value"><el-switch v-model="showCodeBlock"></el-switch></div>
              </div>

              <div class="tab-item">
                <div class="tab-item-label">{{ $t('zhong-zhi-fan-wei') }}</div>
                <div class="tab-item-value" style="display: flex; align-items: center">
                  <div style="margin-right: 30px">
                    <el-checkbox v-model="isCache" :label="$t('huan-cun')" />
                    <el-checkbox v-model="isConfig" :label="$t('she-zhi')" />
                  </div>
                  <div>
                    <el-popconfirm
                      :title="$t('que-ren-zhong-zhi-suo-you-shu-ju-ma')"
                      @confirm="resetCache"
                      confirm-button-type="danger"
                      width="210"
                      :confirm-button-text="$t('que-ding')"
                      :cancel-button-text="$t('qu-xiao')"
                    >
                      <template #reference>
                        <el-button type="danger" :disabled="!isCache && !isConfig">
                          <el-icon><Refresh /></el-icon>
                          <span> {{ $t('zhong-zhi') }} </span>
                        </el-button>
                      </template>
                    </el-popconfirm>
                  </div>
                </div>
              </div>
              <!-- TODO 不生效，暂时注释 -->
              <!-- <div class="tab-item">
                  <div class="tab-item-label">自动打开文件夹</div>
                  <div class="tab-item-value"><el-switch v-model="autoOpenFolder"></el-switch></div>
                </div> -->
            </div>
          </el-tab-pane>
          <!-- TODO 扫描 -->
          <el-tab-pane>
            <template #label>
              <span class="custom-tabs-label">
                <el-icon><Search /></el-icon>
                <span>{{ $t('sao-miao') }}</span>
              </span>
            </template>
            <div>
              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('hu-lve-wen-jian-jia') }}
                  <el-tooltip
                    effect="dark"
                    :content="
                      $t(
                        'hu-lve-bu-xu-yao-sao-miao-de-wen-jian-jia-ti-gao-sao-miao-xiao-shuai-ke-xin-zeng-xu-yao-guo-lv-de-wen-jian-jia-li-ru-macos-xia-wei-builddistwindows-xia-wei-builddist'
                      )
                    "
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value">
                  <el-select
                    v-model="ignoreFolderList"
                    :placeholder="$t('qing-xuan-ze-xu-yao-hu-lve-de-wen-jian-jia')"
                    style="width: 325px"
                    multiple
                    collapse-tags
                    :max-collapse-tags="3"
                    filterable
                    default-first-option
                    allow-create
                  >
                    <el-option
                      v-for="item in folderList.filter((i) => i)"
                      :key="item"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('hu-lve-yi-kai-tou-de-wen-jian-jia') }}
                  <el-tooltip
                    effect="dark"
                    :content="
                      $t(
                        'zhe-lei-wen-jian-jia-zai-macos-he-linux-shang-shi-mo-ren-yin-cang-de-wen-jian-jia'
                      )
                    "
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value">
                  <el-switch v-model="ignoreDotFolder"></el-switch>
                </div>
              </div>

              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('zhi-sao-miao-wen-jian-jia') }}
                  <el-tooltip
                    effect="dark"
                    :content="$t('hu-lve-suo-you-wen-jian-zhi-sao-miao-wen-jian-jia')"
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value"><el-switch v-model="onlyScanFolder"></el-switch></div>
              </div>

              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('hu-lve-yi-kai-tou-de-wen-jian') }}
                  <el-tooltip
                    effect="dark"
                    :content="
                      $t(
                        'zhe-lei-wen-jian-zai-macos-he-linux-shang-shi-mo-ren-yin-cang-de-wen-jian'
                      )
                    "
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value"><el-switch v-model="ignoreDotFile"></el-switch></div>
              </div>

              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('hu-lve-wen-jian-lei-xing') }}
                  <el-tooltip
                    effect="dark"
                    :content="
                      $t(
                        'xuan-ze-hu-lve-bu-xu-yao-de-wen-jian-lei-xing-yi-ti-gao-sao-miao-xiao-shuai-ke-xin-zeng-xu-yao-guo-lv-de-wen-jian-lei-xing'
                      )
                    "
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value">
                  <el-select
                    v-model="ignoreFileList"
                    :placeholder="$t('qing-xuan-ze-xu-yao-hu-lve-de-wen-jian-lei-xing')"
                    filterable
                    style="width: 325px"
                    multiple
                    collapse-tags
                    default-first-option
                    allow-create
                    :max-collapse-tags="3"
                  >
                    <el-option-group
                      v-for="group in extList"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.options"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-option-group>
                  </el-select>
                </div>
              </div>

              <div class="tab-item">
                <div class="tab-item-label">
                  {{ $t('sao-miao-shen-du') }}
                  <el-tooltip
                    effect="dark"
                    :content="
                      $t(
                        'she-zhi-sao-miao-mu-lu-de-shen-du-0-wei-suo-you-shen-du-mei-di-zeng-yi-ge-shu-zi-ze-dai-biao-sao-miao-shen-du-1'
                      )
                    "
                    placement="top"
                  >
                    <el-icon size="16" style="margin-left: 3px"><Warning /></el-icon>
                  </el-tooltip>
                </div>
                <div class="tab-item-value">
                  <el-input-number v-model="scanDeep" :min="0"></el-input-number>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <!-- 导出文本 -->
          <el-tab-pane>
            <template #label>
              <span class="custom-tabs-label">
                <el-icon><Download /></el-icon>
                <span>{{ $t('dao-chu-wen-ben') }}</span>
              </span>
            </template>
            <div>
              <div class="tab-item">
                <div style="width: 100px">{{ $t('mo-ren-ming-cheng') }}</div>
                <div>
                  <el-input
                    style="width: 380px; font-size: 12px"
                    v-model="defaultFileName"
                    :placeholder="$t('qing-shu-ru-mo-ren-ming-cheng')"
                  >
                    <template #append>.txt</template>
                  </el-input>
                </div>
              </div>
            </div>
          </el-tab-pane>
          <!-- 关于 -->
          <el-tab-pane>
            <template #label>
              <span class="custom-tabs-label">
                <el-icon><WarningFilled /></el-icon>
                <span>{{ $t('guan-yu') }}</span>
              </span>
            </template>
            <div>
              <div class="tab-item">
                <div class="tab-item-label">{{ $t('kai-fa-zhe') }}</div>
                <div class="tab-item-value">
                  <el-link type="primary" href="https://github.com/itchaox" target="_blank"
                    >itchaox</el-link
                  >
                </div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">{{ $t('qi-ta-xin-xi') }}</div>
                <div class="tab-item-value">
                  {{ $t('kai-yuan') }}

                  <el-link
                    type="primary"
                    href="https://github.com/itchaox/annotree"
                    target="_blank"
                    >{{ $t('github-di-zhi') }}</el-link
                  >{{ $t('gan-xie-star') }}
                </div>
              </div>
              <div class="tab-item">
                <div class="tab-item-label">{{ $t('guan-fang-wen-dang') }}</div>
                <div class="tab-item-value">
                  <el-link type="primary" href="https://www.annotree.com" target="_blank">{{
                    $t('dian-wo-cha-kan')
                  }}</el-link>
                </div>
              </div>

              <div class="tab-item-center">
                <img src="@renderer/assets/images/icon-128.png" alt="" />
                <div class="tab-item-center-title">Annotree</div>
                <div class="tab-item-center-version">v{{ packageJson.version }}</div>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- TODO 底部信息 -->
    <div class="info" v-if="treeData?.length > 0">
      <div class="dir" v-if="folderPath">
        <div>{{ $t('sco-miao-mu-lu') }}：{{ folderPath }}</div>
      </div>
      <div>
        <div>{{ $t('zong-ji-treedatalength', [treeData?.length]) }}</div>
        <div v-if="folderNumber > 0">
          <el-icon><FolderChecked /></el-icon>
          <span>{{ $t('wen-jian-jia-foldernumber', [folderNumber]) }}</span>
        </div>
        <div v-if="fileNumber > 0">
          <el-icon><DocumentChecked /></el-icon>
          <span>{{ $t('wen-jian-filenumber', [fileNumber]) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.main-page {
  padding: 14px;
  .operation {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .dir {
    &::after {
      content: '|';
    }
  }

  .no-data {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border: 1px solid #dee2e6;
    height: 88vh;
    border-radius: 4px;
    font-size: 20px;
    img {
      width: 35%;
    }

    .no-data-btn {
      color: #5a9cf8;
      font-size: 24px;

      &:hover {
        cursor: pointer;
      }
    }
  }

  .content {
    display: flex;
    flex-direction: column;
    width: 100%;

    .tree-container {
      display: flex;
    }

    pre {
      color: #333;
    }

    .left {
      flex: 1;

      background-color: #f7f8f9;
      height: 83vh;
      border-radius: 4px;
      border: 1px solid #dee2e6;
      border-right: none;
      border-top: none;
    }

    .left-none {
      display: none;
    }

    .top-tools {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border: 1px solid #dee2e6;
      .edit-tools {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 5px 10px;

        .edit-tool {
          margin-right: 15px;
        }
      }

      .preview-tools {
        display: flex;
        align-items: center;
        justify-content: flex-end;

        width: 100%;
        padding: 5px 10px;
      }
    }

    .right {
      flex: 1;
      height: 83vh;
      border-radius: 4px;
      padding-left: 10px;

      background-color: #fff;
      border: 1px solid #dee2e6;
      border-top: none;
    }

    .right-none {
      display: none;
    }

    .tree-scroller {
      padding: 20px;
      height: 100%;
      overflow: auto;

      // 溢出滚动样式
      &::-webkit-scrollbar {
        width: 4px;
        height: 4px;
      }

      &::-webkit-scrollbar-thumb {
        border-radius: 3px;
        background-color: #b7bdc6;
        cursor: pointer;
      }

      &::-webkit-scrollbar-track {
        border-radius: 3px;
        background-color: #f7f8f9;
      }
    }

    .tree-node {
      height: 20px;
      padding-right: 30px;

      &:hover {
        background-color: #99999950;
        cursor: pointer;
      }
    }

    .tree-node-active {
      background-color: #99999950;
      cursor: pointer;
    }

    .folder-icon {
      &:hover {
        cursor: pointer;

        .el-icon {
          color: #5a9cf8;
        }
      }
    }

    .row-info {
      display: inline-flex;
      justify-content: space-between;
      margin-left: 2px;
    }
  }

  .preview-config {
    .preview-item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      .preview-label {
        width: 125px;
      }

      .preview-value {
        margin-left: 15px;
      }
    }
  }

  .info {
    display: flex;
    align-items: center;
    margin-top: 14px;
    font-size: 14px;
    div {
      margin-right: 14px;
      display: flex;
      align-items: center;
      span {
        margin-left: 3px;
      }
    }
  }
}

.tools-icon {
  margin-right: 24px;
  color: #333; /* 默认颜色 */

  &:hover {
    color: #5a9cf8;
    cursor: pointer;
  }
}

.dialog-body {
  .custom-tabs-label {
    display: flex;
    align-items: center;
    span {
      margin-left: 5px;
    }
  }
  .tab-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    .tab-item-label {
      display: flex;
      align-items: center;
      margin-right: 10px;
      width: 188px;
    }

    .tab-item-value {
      width: 400px;
    }
  }

  .tab-item-center {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;

    .tab-item-center-title {
      padding: 10px;
      font-size: 24px;
      font-weight: 700;
    }

    .tab-item-center-version {
      font-size: 20px;
      color: #00000090;
    }
  }
}
</style>
