<template>
  <div class="code-fun-flex-col page">
    <!-- 全部便签文件夹项 -->

    <FolderItem id="all" name="全部便签" :noteCount="allCount" :isSelected="selectedFolder === 'all'" :onPress="handleAllClick" />

    <!-- 加星便签文件夹项 -->

    <FolderItem id="starred" name="加星便签" :noteCount="starredCount" :isSelected="selectedFolder === 'starred'" :onPress="handleStarredClick" />

    <!-- 回收站文件夹项 -->

    <FolderItem id="trash" name="回收站" :noteCount="trashCount" :isSelected="selectedFolder === 'trash'" :onPress="handleTrashClick" />

    <!-- 自定义文件夹项 -->

    <FolderItem
      v-for="folder in customFolders"
      :key="folder.id"
      :id="folder.id"
      :name="folder.name"
      :noteCount="getFolderNoteCount(folder.id)"
      :isSelected="selectedFolder === folder.id"
      :onPress="() => handleFolderClick(folder.id)"
      :onEdit="() => handleEditFolder(folder.id)"
      :onDelete="() => handleDeleteFolder(folder.id)"
      :isSelectionMode="isSelectionMode"
      :isChecked="selectedFolders.includes(folder.id)"
      :onCheckboxClick="() => toggleFolderSelection(folder.id)" />

    <div class="code-fun-flex-col code-fun-justify-start section_7">
      <div class="code-fun-flex-row code-fun-justify-between code-fun-items-center section_8">
        <div class="code-fun-flex-row code-fun-items-center">
          <!-- 切换文件夹选择模式按钮 -->

          <img class="code-fun-shrink-0 image_7" :src="isSelectionMode ? 'assets/icons/drawable-xxhdpi/btn_back_black.png' : 'assets/icons/drawable-xxhdpi/btn_edit_folder.png'" @click="toggleSelectionMode" />

          <!-- 同步信息区域 -->

          <span class="text_11 code-fun-ml-10">上次同步:{{ lastSyncTime }}</span>
        </div>

        <div class="code-fun-flex-row code-fun-items-center">
          <!-- 新建文件夹按钮 / 删除按钮 -->

          <img
            class="image_8 code-fun-ml-12"
            :src="isSelectionMode ? 'assets/icons/drawable-xxhdpi/icon_folder_trash.png' : 'assets/icons/drawable-xxhdpi/btn_add_folder.png'"
            @click="isSelectionMode ? handleDeleteSelectedFolders() : handleAddFolder()" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { useAppStore } from '../stores/useAppStore'
import FolderItem from './FolderItem.vue'
import { showConfirm, showPrompt } from '../utils/modalService'

const store = useAppStore()
const props = defineProps({
  allCount: {
    type: Number,
    default: 0,
  },
  starredCount: {
    type: Number,
    default: 0,
  },
  trashCount: {
    type: Number,
    default: 0,
  },
  archiveCount: {
    type: Number,
    default: 0,
  },
  selectedFolder: {
    type: String,
    default: '',
  },
  lastSyncTime: {
    type: String,
    default: '10/10上午9:28',
  },
  onAllClick: {
    type: Function,
    default: null,
  },
  onStarredClick: {
    type: Function,
    default: null,
  },
  onTrashClick: {
    type: Function,
    default: null,
  },
  onArchiveClick: {
    type: Function,
    default: null,
  },
  onAddFolder: {
    type: Function,
    default: null,
  },
  onFolderClick: {
    type: Function,
    default: null,
  },
})

// 重命名文件夹相关状态

const showRenameFolderModal = ref(false)

const renameFolderId = ref(null)

const renameFolderName = ref('')
// 选择模式相关状态

const isSelectionMode = ref(false)

const selectedFolders = ref([])
// 计算自定义文件夹（排除系统文件夹）
const customFolders = computed(() => {
  return store.folders.filter(folder => !['all', 'starred', 'trash', 'archive'].includes(folder.id))
})

// 获取文件夹中的便签数量
const getFolderNoteCount = folderId => {
  return store.notes.filter(note => note.folderId === folderId && !note.isDeleted).length
}

// 切换选择模式

const toggleSelectionMode = () => {
  isSelectionMode.value = !isSelectionMode.value
  // 退出选择模式时清空选中项
  if (!isSelectionMode.value) {
    selectedFolders.value = []
  }
}

// 切换文件夹选中状态
const toggleFolderSelection = folderId => {
  if (!isSelectionMode.value) return
  const index = selectedFolders.value.indexOf(folderId)
  if (index > -1) {
    // 已选中，取消选中
    selectedFolders.value.splice(index, 1)
  } else {
    // 未选中，添加选中
    selectedFolders.value.push(folderId)
  }
}

// 处理文件夹点击

const handleFolderClick = folderId => {
  if (isSelectionMode.value) {
    toggleFolderSelection(folderId)
  } else {
    if (props.onFolderClick) {
      props.onFolderClick(folderId)
    }
  }
}

// 处理删除选中的文件夹

const handleDeleteSelectedFolders = async () => {
  if (selectedFolders.value.length === 0) return

  try {
    const confirmed = await showConfirm(`确定要删除选中的 ${selectedFolders.value.length} 个文件夹吗？文件夹中的便签将移至"全部便签"。`, '删除文件夹')

    if (confirmed) {
      // 删除选中的文件夹

      for (const folderId of selectedFolders.value) {
        // 跳过系统文件夹

        if (['all', 'starred', 'trash', 'archive'].includes(folderId)) continue

        await store.deleteFolder(folderId)
      }

      // 清空选中项并退出选择模式

      selectedFolders.value = []

      isSelectionMode.value = false
    }
  } catch (error) {
    console.error('删除文件夹失败:', error)
  }
}

// 处理删除文件夹

const handleDeleteFolder = async folderId => {
  // 阻止事件冒泡到父元素
  event.stopPropagation()

  // 确认删除
  try {
    const confirmed = await showConfirm(`确定要删除文件夹 "${getFolderName(folderId)}" 吗？文件夹中的便签将移至"全部便签"。`, '删除文件夹')
    if (confirmed) {
      await store.deleteFolder(folderId)
    }
  } catch (error) {
    console.error('删除文件夹失败:', error)
  }
}

// 处理编辑文件夹

const handleEditFolder = async folderId => {
  // 阻止事件冒泡到父元素

  event.stopPropagation()

  const folder = store.folders.find(f => f.id === folderId)

  if (folder) {
    try {
      const newName = await showPrompt('请输入文件夹名称', '重命名文件夹', '请输入文件夹名称', folder.name)

      if (newName && newName.trim()) {
        await store.updateFolder(folderId, { name: newName.trim() })
      }
    } catch (error) {
      // 用户取消操作或出现错误

      console.log('重命名文件夹操作已取消或出现错误:', error)
    }
  }
}

// 获取文件夹名称

const getFolderName = folderId => {
  const folder = store.folders.find(f => f.id === folderId)
  return folder ? folder.name : ''
}

const handleAllClick = () => {
  if (isSelectionMode.value) {
    toggleFolderSelection('all')
  } else {
    if (props.onAllClick) {
      props.onAllClick()
    }
  }
}

const handleStarredClick = () => {
  if (isSelectionMode.value) {
    toggleFolderSelection('starred')
  } else {
    if (props.onStarredClick) {
      props.onStarredClick()
    }
  }
}

const handleTrashClick = () => {
  if (isSelectionMode.value) {
    toggleFolderSelection('trash')
  } else {
    if (props.onTrashClick) {
      props.onTrashClick()
    }
  }
}

const handleAddFolder = async () => {
  try {
    const folderName = await showPrompt('请输入文件夹名称', '添加文件夹', '请输入文件夹名称')
    if (folderName && folderName.trim()) {
      const newFolder = {
        name: folderName.trim(),
        id: `folder_${Date.now()}`, // 生成唯一ID
        createdAt: new Date().toISOString(),
      }

      await store.addFolder(newFolder)
    }
  } catch (error) {
    // 用户取消操作或出现错误
    console.log('添加文件夹操作已取消或出现错误:', error)
  }
}
</script>

<style lang="less" scoped>
.page {
  .section_7 {
    margin-top: 2rem;

    background-color: #00000000;

    .section_8 {
      padding: 0.29rem 0.92rem;

      background-color: #f4f4f4;

      border: solid 0.063rem #f0ece7;

      .image_7,
      .image_8 {
        border-radius: 0.63rem;

        width: 2.2rem;

        height: 1.75rem;

        object-fit: contain;

        background: url(/assets/icons/drawable-xxhdpi/folder_bottom_button_normal.9.png), #fdfbfb;
      }

      .text_11 {
        color: #cacaca;

        font-size: 0.7rem;

        line-height: 1.16rem;
      }
    }
  }
}
</style>
