import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

/**
 * 每日任务状态管理Store
 * 用于持久化每个token的每日任务完成状态，避免重复执行消耗资源的任务
 */
export const useDailyTaskStateStore = defineStore('dailyTaskState', () => {
  
  // ==================== 任务定义 ====================
  
  /**
   * 所有批量任务定义
   * 每个子任务包含: id, name, consumesResources(是否消耗资源), category(任务类别)
   */
  
  // 一键补差子任务
  const DAILY_FIX_TASKS = [
    { id: 'share_game', name: '分享游戏', consumesResources: false },
    { id: 'send_friend_gold', name: '赠送好友金币', consumesResources: false },
    { id: 'free_recruit', name: '免费招募', consumesResources: false },
    { id: 'paid_recruit', name: '付费招募', consumesResources: true }, // 消耗资源
    { id: 'buy_gold_1', name: '免费点金 1/3', consumesResources: true }, // 消耗资源
    { id: 'buy_gold_2', name: '免费点金 2/3', consumesResources: true }, // 消耗资源
    { id: 'buy_gold_3', name: '免费点金 3/3', consumesResources: true }, // 消耗资源
    { id: 'open_box', name: '开启宝箱×10（优先木质，不足则青铜）', consumesResources: true }, // 消耗资源
    { id: 'sign_in', name: '福利签到', consumesResources: false },
    { id: 'daily_gift', name: '领取每日礼包', consumesResources: false },
    { id: 'free_card', name: '领取免费礼包', consumesResources: false },
    { id: 'permanent_card', name: '领取永久卡礼包', consumesResources: false },
    { id: 'claim_mail', name: '领取邮件奖励', consumesResources: false },
    { id: 'fish_1', name: '免费钓鱼 1/3', consumesResources: true }, // 消耗资源
    { id: 'fish_2', name: '免费钓鱼 2/3', consumesResources: true }, // 消耗资源
    { id: 'fish_3', name: '免费钓鱼 3/3', consumesResources: true }, // 消耗资源
    { id: 'genie_wei', name: '魏国灯神免费扫荡', consumesResources: false },
    { id: 'genie_shu', name: '蜀国灯神免费扫荡', consumesResources: false },
    { id: 'genie_wu', name: '吴国灯神免费扫荡', consumesResources: false },
    { id: 'genie_qun', name: '群雄灯神免费扫荡', consumesResources: false },
    { id: 'sweep_card_1', name: '领取免费扫荡卷 1/3', consumesResources: false },
    { id: 'sweep_card_2', name: '领取免费扫荡卷 2/3', consumesResources: false },
    { id: 'sweep_card_3', name: '领取免费扫荡卷 3/3', consumesResources: false },
    { id: 'black_market', name: '黑市一键采购', consumesResources: true }, // 消耗资源
    { id: 'arena_1', name: '竞技场战斗 1/3', consumesResources: true }, // 消耗资源
    { id: 'arena_2', name: '竞技场战斗 2/3', consumesResources: true }, // 消耗资源
    { id: 'arena_3', name: '竞技场战斗 3/3', consumesResources: true }, // 消耗资源
    { id: 'legion_boss', name: '军团BOSS', consumesResources: false },
    { id: 'daily_boss_1', name: '每日BOSS 1/3', consumesResources: false },
    { id: 'daily_boss_2', name: '每日BOSS 2/3', consumesResources: false },
    { id: 'daily_boss_3', name: '每日BOSS 3/3', consumesResources: false },
    { id: 'bottle_claim', name: '领取盐罐奖励', consumesResources: false },
    { id: 'task_reward_1', name: '领取任务奖励1', consumesResources: false },
    { id: 'task_reward_2', name: '领取任务奖励2', consumesResources: false },
    { id: 'task_reward_3', name: '领取任务奖励3', consumesResources: false },
    { id: 'task_reward_4', name: '领取任务奖励4', consumesResources: false },
    { id: 'task_reward_5', name: '领取任务奖励5', consumesResources: false },
    { id: 'task_reward_6', name: '领取任务奖励6', consumesResources: false },
    { id: 'task_reward_7', name: '领取任务奖励7', consumesResources: false },
    { id: 'task_reward_8', name: '领取任务奖励8', consumesResources: false },
    { id: 'task_reward_9', name: '领取任务奖励9', consumesResources: false },
    { id: 'task_reward_10', name: '领取任务奖励10', consumesResources: false },
    { id: 'daily_reward', name: '领取日常任务奖励', consumesResources: false },
    { id: 'week_reward', name: '领取周常任务奖励', consumesResources: false }
  ]
  
  // 其他批量任务
  const OTHER_TASKS = [
    { id: 'legion_signin', name: '俱乐部签到', consumesResources: false },
    { id: 'auto_study', name: '一键答题', consumesResources: false },
    { id: 'claim_hangup_reward', name: '领取挂机奖励', consumesResources: false },
    { id: 'add_clock', name: '加钟', consumesResources: false },
    { id: 'climb_tower', name: '爬塔', consumesResources: false } // 爬塔次数动态
  ]
  
  // 所有任务合集
  const ALL_TASKS = [...DAILY_FIX_TASKS, ...OTHER_TASKS]
  
  // ==================== 状态数据 ====================
  
  /**
   * 任务状态数据结构:
   * {
   *   [tokenId]: {
   *     date: '2025-10-07', // 最后更新日期
   *     tasks: {
   *       [taskId]: {
   *         completed: true/false,
   *         completedAt: timestamp,
   *         success: true/false,
   *         error: 'error message'
   *       }
   *     }
   *   }
   * }
   */
  const taskStates = ref(
    JSON.parse(localStorage.getItem('dailyTaskStates') || '{}')
  )
  
  // ==================== 工具函数 ====================
  
  /**
   * 获取今天的日期字符串 (YYYY-MM-DD)
   */
  const getTodayDateString = () => {
    const now = new Date()
    return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')}`
  }
  
  /**
   * 检查日期是否是今天
   */
  const isToday = (dateString) => {
    return dateString === getTodayDateString()
  }
  
  /**
   * 保存到localStorage
   */
  const saveToStorage = () => {
    localStorage.setItem('dailyTaskStates', JSON.stringify(taskStates.value))
  }
  
  // ==================== 核心方法 ====================
  
  /**
   * 初始化token的任务状态（如果不存在或过期）
   */
  const initTokenTaskState = (tokenId) => {
    const today = getTodayDateString()
    
    if (!taskStates.value[tokenId] || !isToday(taskStates.value[tokenId].date)) {
      // 创建新的任务状态
      taskStates.value[tokenId] = {
        date: today,
        tasks: {}
      }
      
      // 初始化所有任务为未完成
      ALL_TASKS.forEach(task => {
        taskStates.value[tokenId].tasks[task.id] = {
          completed: false,
          completedAt: null,
          success: null,
          error: null
        }
      })
      
      saveToStorage()
    }
  }
  
  /**
   * 获取token的任务状态
   */
  const getTokenTaskState = (tokenId) => {
    initTokenTaskState(tokenId)
    return taskStates.value[tokenId]
  }
  
  /**
   * 获取单个任务的状态
   */
  const getTaskState = (tokenId, taskId) => {
    const state = getTokenTaskState(tokenId)
    return state.tasks[taskId] || { completed: false, completedAt: null, success: null, error: null }
  }
  
  /**
   * 检查任务是否已完成
   */
  const isTaskCompleted = (tokenId, taskId) => {
    const state = getTaskState(tokenId, taskId)
    return state.completed === true && state.success === true
  }
  
  /**
   * 标记任务为已完成
   */
  const markTaskCompleted = (tokenId, taskId, success = true, error = null) => {
    initTokenTaskState(tokenId)
    
    taskStates.value[tokenId].tasks[taskId] = {
      completed: true,
      completedAt: Date.now(),
      success,
      error
    }
    
    saveToStorage()
  }
  
  /**
   * 标记任务为失败
   */
  const markTaskFailed = (tokenId, taskId, error) => {
    markTaskCompleted(tokenId, taskId, false, error)
  }
  
  /**
   * 重置token的所有任务状态
   */
  const resetTokenTasks = (tokenId) => {
    delete taskStates.value[tokenId]
    initTokenTaskState(tokenId)
  }
  
  /**
   * 重置所有token的任务状态
   */
  const resetAllTasks = () => {
    taskStates.value = {}
    saveToStorage()
  }
  
  /**
   * 获取token的任务完成统计
   */
  const getTaskStatistics = (tokenId) => {
    const state = getTokenTaskState(tokenId)
    const tasks = Object.values(state.tasks)
    
    return {
      total: tasks.length,
      completed: tasks.filter(t => t.completed).length,
      success: tasks.filter(t => t.success).length,
      failed: tasks.filter(t => t.completed && !t.success).length,
      pending: tasks.filter(t => !t.completed).length
    }
  }
  
  /**
   * 获取需要跳过的任务列表（已成功完成且消耗资源的任务）
   */
  const getTasksToSkip = (tokenId) => {
    const tasksToSkip = []
    
    ALL_TASKS.forEach(task => {
      if (task.consumesResources && isTaskCompleted(tokenId, task.id)) {
        tasksToSkip.push(task.id)
      }
    })
    
    return tasksToSkip
  }
  
  /**
   * 获取某个token的详细任务列表（用于UI展示）
   * @param {string} tokenId - Token ID
   * @param {string} category - 任务类别: 'dailyFix' | 'all' (默认显示所有)
   */
  const getDetailedTaskList = (tokenId, category = 'all') => {
    const state = getTokenTaskState(tokenId)
    
    let tasks = ALL_TASKS
    if (category === 'dailyFix') {
      tasks = DAILY_FIX_TASKS
    } else if (category === 'other') {
      tasks = OTHER_TASKS
    }
    
    return tasks.map(task => ({
      ...task,
      state: state.tasks[task.id]
    }))
  }
  
  /**
   * 获取一键补差任务列表
   */
  const getDailyFixTaskList = (tokenId) => {
    return getDetailedTaskList(tokenId, 'dailyFix')
  }
  
  /**
   * 获取其他任务列表
   */
  const getOtherTaskList = (tokenId) => {
    return getDetailedTaskList(tokenId, 'other')
  }
  
  // ==================== 自动重置机制 ====================
  
  /**
   * 检查并自动重置过期的任务状态
   */
  const checkAndResetExpiredTasks = () => {
    const today = getTodayDateString()
    let hasChanges = false
    
    Object.keys(taskStates.value).forEach(tokenId => {
      if (!isToday(taskStates.value[tokenId].date)) {
        delete taskStates.value[tokenId]
        hasChanges = true
      }
    })
    
    if (hasChanges) {
      saveToStorage()
    }
  }
  
  /**
   * 🆕 v3.14.1: 清理长时间未使用的token数据（超过7天）
   * 用于防止localStorage无限增长，减少内存占用
   */
  const cleanUnusedTokenData = () => {
    const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
    let cleaned = 0
    
    Object.keys(taskStates.value).forEach(tokenId => {
      const stateDate = new Date(taskStates.value[tokenId].date)
      if (stateDate < sevenDaysAgo) {
        delete taskStates.value[tokenId]
        cleaned++
      }
    })
    
    if (cleaned > 0) {
      saveToStorage()
      console.log(`🧹 [DailyTask] 清理了 ${cleaned} 个长期未使用token的数据（7天前）`)
    }
    
    return cleaned
  }
  
  /**
   * 🆕 v3.14.1: 获取存储统计信息（用于内存监控）
   */
  const getStorageStats = () => {
    const tokenCount = Object.keys(taskStates.value).length
    let totalTasks = 0
    let completedTasks = 0
    
    Object.values(taskStates.value).forEach(state => {
      const tasks = Object.values(state.tasks)
      totalTasks += tasks.length
      completedTasks += tasks.filter(t => t.completed).length
    })
    
    return {
      tokenCount,
      totalTasks,
      completedTasks,
      estimatedSize: `${Math.round(JSON.stringify(taskStates.value).length / 1024)}KB`
    }
  }
  
  // 启动时检查并重置过期任务
  checkAndResetExpiredTasks()
  
  // 🆕 v3.14.1: 启动时清理长期未使用的数据
  cleanUnusedTokenData()
  
  // 每小时检查一次
  setInterval(checkAndResetExpiredTasks, 60 * 60 * 1000)
  
  // 🆕 v3.14.1: 每6小时清理一次长期未使用的数据
  setInterval(cleanUnusedTokenData, 6 * 60 * 60 * 1000)
  
  // ==================== 计算属性 ====================
  
  /**
   * 获取所有任务定义
   */
  const allTaskDefinitions = computed(() => ALL_TASKS)
  
  /**
   * 获取一键补差任务定义
   */
  const dailyFixTaskDefinitions = computed(() => DAILY_FIX_TASKS)
  
  /**
   * 获取其他任务定义
   */
  const otherTaskDefinitions = computed(() => OTHER_TASKS)
  
  /**
   * 获取消耗资源的任务列表
   */
  const resourceConsumingTasks = computed(() => 
    ALL_TASKS.filter(t => t.consumesResources)
  )
  
  // ==================== 导出 ====================
  
  return {
    // 状态
    taskStates,
    
    // 任务定义
    allTaskDefinitions,
    dailyFixTaskDefinitions,
    otherTaskDefinitions,
    resourceConsumingTasks,
    
    // 方法
    initTokenTaskState,
    getTokenTaskState,
    getTaskState,
    isTaskCompleted,
    markTaskCompleted,
    markTaskFailed,
    resetTokenTasks,
    resetAllTasks,
    getTaskStatistics,
    getTasksToSkip,
    getDetailedTaskList,
    getDailyFixTaskList,
    getOtherTaskList,
    checkAndResetExpiredTasks,
    cleanUnusedTokenData, // 🆕 v3.14.1
    getStorageStats // 🆕 v3.14.1
  }
})

