import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import type { Task, TaskType, CreateTaskRequest, TaskProgressUpdate } from '@media-manager/shared';
import { TASK_TYPE_CONFIG, TASK_WS_EVENTS, WS_EVENTS } from '@media-manager/shared';
import { useAuthStore } from './auth';
import { useServerStore } from './server';
import request from '@/api/request';

export const useTaskQueueStore = defineStore('taskQueue', () => {
  // 状态
  const tasks = ref<Task[]>([]);
  const isDialogVisible = ref(false);
  const ws = ref<WebSocket | null>(null);
  const wsConnected = ref(false);
  
  // 作品刷新信号（当 sync_works 任务完成时递增）
  const worksRefreshTrigger = ref(0);
  
  // 账号刷新信号（当 sync_account 任务完成时递增）
  const accountRefreshTrigger = ref(0);
  
  // 验证码相关状态
  const showCaptchaDialog = ref(false);
  const captchaTaskId = ref('');
  const captchaType = ref<'sms' | 'image'>('sms');
  const captchaPhone = ref('');
  const captchaImageBase64 = ref('');

  // 计算属性
  const activeTasks = computed(() => 
    tasks.value.filter(t => t.status === 'pending' || t.status === 'running')
  );

  const runningTasks = computed(() => 
    tasks.value.filter(t => t.status === 'running')
  );

  const hasActiveTasks = computed(() => activeTasks.value.length > 0);

  const activeTaskCount = computed(() => activeTasks.value.length);

  // 获取任务类型配置
  const getTaskConfig = (type: TaskType) => TASK_TYPE_CONFIG[type];

  // WebSocket 重连计时器
  let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
  let reconnectAttempts = 0;
  const maxReconnectAttempts = 10;
  
  // 轮询任务状态（当 WebSocket 不可用时）
  const pollingTimers = new Map<string, ReturnType<typeof setTimeout>>();
  
  function stopTaskPolling(taskId: string) {
    const timer = pollingTimers.get(taskId);
    if (timer) {
      clearTimeout(timer);
      pollingTimers.delete(taskId);
    }
  }
  
  function stopAllPolling() {
    pollingTimers.forEach((timer) => clearTimeout(timer));
    pollingTimers.clear();
  }
  
  // WebSocket 连接
  function connectWebSocket() {
    const authStore = useAuthStore();
    const serverStore = useServerStore();
    
    // 清除之前的重连计时器
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
    
    if (!authStore.accessToken) {
      console.warn('[TaskWS] No token available, will retry in 2s');
      // 没有 token 时延迟重试
      reconnectTimer = setTimeout(connectWebSocket, 2000);
      return;
    }

    // 如果已经连接，不重复连接
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      console.log('[TaskWS] Already connected');
      return;
    }
    
    // 如果正在连接中，等待
    if (ws.value && ws.value.readyState === WebSocket.CONNECTING) {
      console.log('[TaskWS] Connection in progress...');
      return;
    }

    const serverUrl = serverStore.currentServer?.url || 'http://localhost:3000';
    const wsUrl = serverUrl.replace(/^http/, 'ws') + '/ws';
    
    console.log('[TaskWS] Connecting to:', wsUrl);

    try {
      // 关闭旧连接
      if (ws.value) {
        ws.value.onclose = null; // 防止触发重连
        ws.value.close();
        ws.value = null;
      }
      
      ws.value = new WebSocket(wsUrl);

      ws.value.onopen = () => {
        console.log('[TaskWS] Connected, authenticating...');
        reconnectAttempts = 0; // 重置重连计数
        ws.value?.send(JSON.stringify({ 
          type: 'auth', 
          payload: { token: authStore.accessToken } 
        }));
      };

      ws.value.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data);
          console.log('[TaskWS] Received:', data.type || data.payload?.event);
          handleWebSocketMessage(data);
        } catch (e) {
          console.error('[TaskWS] Parse error:', e);
        }
      };

      ws.value.onclose = (event) => {
        console.log('[TaskWS] Disconnected, code:', event.code, 'reason:', event.reason);
        wsConnected.value = false;
        ws.value = null;
        
        // 只有在正常情况下才重连（不是主动关闭）
        if (reconnectAttempts < maxReconnectAttempts) {
          reconnectAttempts++;
          const delay = Math.min(1000 * Math.pow(2, reconnectAttempts - 1), 30000); // 指数退避，最大 30 秒
          console.log(`[TaskWS] Reconnecting in ${delay}ms (attempt ${reconnectAttempts}/${maxReconnectAttempts})`);
          reconnectTimer = setTimeout(connectWebSocket, delay);
        } else {
          console.error('[TaskWS] Max reconnect attempts reached');
        }
      };

      ws.value.onerror = (error) => {
        console.error('[TaskWS] Error:', error);
      };
    } catch (e) {
      console.error('[TaskWS] Setup error:', e);
      // 出错后也尝试重连
      reconnectTimer = setTimeout(connectWebSocket, 5000);
    }
  }

  function disconnectWebSocket() {
    // 清除重连计时器
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
    reconnectAttempts = maxReconnectAttempts; // 防止自动重连
    
    // 停止所有轮询
    stopAllPolling();
    
    if (ws.value) {
      ws.value.onclose = null; // 防止触发重连逻辑
      ws.value.close();
      ws.value = null;
    }
    wsConnected.value = false;
  }
  
  // 强制重连
  function reconnectWebSocket() {
    reconnectAttempts = 0;
    disconnectWebSocket();
    setTimeout(connectWebSocket, 100);
  }

  // 处理 WebSocket 消息
  function handleWebSocketMessage(data: { type?: string; payload?: Record<string, unknown> }) {
    // 系统通知：直接按 type 处理（不走 task 事件映射）
    if (data.type === WS_EVENTS.SYSTEM_MESSAGE || data.type === 'system:message') {
      const payload = (data.payload || {}) as any;
      const msg = payload.message || '系统通知';
      const level = payload.level || 'warning';
      if (level === 'success') ElMessage.success(msg);
      else if (level === 'info') ElMessage.info(msg);
      else if (level === 'error') ElMessage.error(msg);
      else ElMessage.warning(msg);
      return;
    }

    const event = (data.payload?.event as string) || data.type?.split(':')[1] || '';

    switch (event) {
      case 'success':
        wsConnected.value = true;
        // 连接成功后获取任务列表
        fetchTasks();
        break;

      case 'created': {
        const task = data.payload?.task as Task;
        // 静默任务不添加到任务列表中
        if (task && !task.silent && !tasks.value.find(t => t.id === task.id)) {
          tasks.value.unshift(task);
        }
        break;
      }

      case 'started': {
        const task = data.payload?.task as Task;
        if (task) {
          updateTask(task);
        }
        break;
      }

      case 'progress': {
        const update = data.payload as TaskProgressUpdate & { taskId: string };
        if (update?.taskId) {
          const task = tasks.value.find(t => t.id === update.taskId);
          if (task) {
            task.progress = update.progress || task.progress;
            task.currentStep = update.currentStep || task.currentStep;
            task.currentStepIndex = update.currentStepIndex ?? task.currentStepIndex;
          }
        }
        break;
      }

      case 'completed':
      case 'failed':
      case 'cancelled': {
        const task = data.payload?.task as Task;
        if (task) {
          updateTask(task);
          if (event === 'completed') {
            // 如果是 sync_works 任务完成，触发作品列表刷新
            if (task.type === 'sync_works') {
              worksRefreshTrigger.value++;
              console.log('[TaskQueue] sync_works completed, triggering refresh');
            }
            // 如果是 sync_account 任务完成，触发账号列表刷新
            if (task.type === 'sync_account') {
              accountRefreshTrigger.value++;
              console.log('[TaskQueue] sync_account completed, triggering refresh');
            }
          }
        }
        break;
      }

      case 'list': {
        const taskList = data.payload?.tasks as Task[];
        if (taskList) {
          // 过滤掉静默任务
          tasks.value = taskList.filter(t => !t.silent);
        }
        break;
      }

      // 兼容旧的评论同步事件
      case 'sync_started':
      case 'sync_progress':
      case 'synced':
      case 'sync_failed':
        // 这些事件由 Works 页面处理
        break;
    }
    
    // 处理账号相关事件（直接通过 type 判断）
    if (data.type === 'account:added' || data.type === 'account:updated' || data.type === 'account:deleted') {
      console.log('[TaskQueue] Account event received:', data.type);
      accountRefreshTrigger.value++;
    }
    
    // 处理验证码事件
    // 1. 通过 type 判断
    // 2. 或者 payload 中包含 captchaTaskId 字段（兼容 type 为 undefined 的情况）
    const payload = data.payload as Record<string, unknown> | undefined;
    if (data.type === 'captcha:required' || 
        (payload && 'captchaTaskId' in payload && payload.captchaTaskId)) {
      console.log('[TaskQueue] Captcha event detected, type:', data.type, 'payload:', payload);
      handleCaptchaRequired(payload as { 
        captchaTaskId: string; 
        type?: 'sms' | 'image';
        phone?: string;
        imageBase64?: string;
      });
    }
  }
  
  // 处理验证码请求
  function handleCaptchaRequired(payload: { 
    captchaTaskId: string; 
    type?: 'sms' | 'image';
    phone?: string;
    imageBase64?: string;
  }) {
    console.log('[TaskQueue] Captcha required:', payload);
    captchaTaskId.value = payload.captchaTaskId || '';
    captchaType.value = payload.type || 'sms';
    captchaPhone.value = payload.phone || '';
    captchaImageBase64.value = payload.imageBase64 || '';
    showCaptchaDialog.value = true;
  }
  
  // 提交验证码
  function submitCaptcha(taskId: string, code: string) {
    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify({
        type: 'captcha:submit',
        payload: {
          captchaTaskId: taskId,
          code,
        },
      }));
      console.log('[TaskQueue] Captcha submitted:', taskId, code);
    }
    showCaptchaDialog.value = false;
  }
  
  // 取消验证码输入
  function cancelCaptcha() {
    showCaptchaDialog.value = false;
    // 发送空验证码表示取消
    if (captchaTaskId.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
      ws.value.send(JSON.stringify({
        type: 'captcha:submit',
        payload: {
          captchaTaskId: captchaTaskId.value,
          code: '',
        },
      }));
    }
  }

  function updateTask(task: Task) {
    const index = tasks.value.findIndex(t => t.id === task.id);
    if (index >= 0) {
      tasks.value[index] = task;
    } else {
      tasks.value.unshift(task);
    }
  }

  // API 操作
  async function fetchTasks() {
    try {
      const result = await request.get('/api/tasks') as { 
        success?: boolean; 
        data?: { tasks: Task[] }; 
        tasks?: Task[] 
      };
      // 兼容两种返回格式，过滤掉静默任务
      const allTasks = result?.data?.tasks || result?.tasks || [];
      tasks.value = allTasks.filter(t => !t.silent);
      console.log('[TaskQueue] Fetched tasks:', tasks.value.length);
    } catch (e) {
      console.error('Failed to fetch tasks:', e);
    }
  }

  async function createTask(taskRequest: CreateTaskRequest): Promise<Task | null> {
    try {
      const result = await request.post('/api/tasks', taskRequest) as { 
        success?: boolean; 
        data?: { task: Task }; 
        task?: Task 
      };
      // 兼容两种返回格式
      const task = result?.data?.task || result?.task || null;
      
      // 如果任务创建成功，添加到本地列表
      if (task && !tasks.value.find(t => t.id === task.id)) {
        tasks.value.unshift(task);
      }
      
      // 如果 WebSocket 未连接，启动轮询
      if (!wsConnected.value && task) {
        console.log('[TaskQueue] WebSocket not connected, starting polling for task:', task.id);
        startTaskPolling(task.id);
      }
      
      return task;
    } catch (e) {
      console.error('Failed to create task:', e);
      return null;
    }
  }
  
  function startTaskPolling(taskId: string) {
    // 防止重复轮询
    if (pollingTimers.has(taskId)) return;
    
    const poll = async () => {
      // 如果 WebSocket 已连接，停止轮询
      if (wsConnected.value) {
        stopTaskPolling(taskId);
        return;
      }
      
      try {
        await fetchTasks();
        const task = tasks.value.find(t => t.id === taskId);
        
        // 如果任务已完成，停止轮询
        if (task && (task.status === 'completed' || task.status === 'failed' || task.status === 'cancelled')) {
          console.log('[TaskQueue] Task completed via polling:', taskId, 'status:', task.status);
          if (task.status === 'completed') {
            // 触发作品刷新
            if (task.type === 'sync_works') {
              worksRefreshTrigger.value++;
            }
            // 触发账号刷新
            if (task.type === 'sync_account') {
              accountRefreshTrigger.value++;
            }
          }
          stopTaskPolling(taskId);
          return;
        }
        
        // 继续轮询
        pollingTimers.set(taskId, setTimeout(poll, 2000));
      } catch (e) {
        console.error('[TaskQueue] Polling error:', e);
        // 出错后继续轮询
        pollingTimers.set(taskId, setTimeout(poll, 5000));
      }
    };
    
    // 立即开始轮询
    poll();
  }

  async function cancelTask(taskId: string): Promise<boolean> {
    try {
      await request.post(`/api/tasks/${taskId}/cancel`);
      const task = tasks.value.find(t => t.id === taskId);
      if (task) {
        task.status = 'cancelled';
      }
      return true;
    } catch (e) {
      console.error('Failed to cancel task:', e);
      return false;
    }
  }

  // 快捷方法：创建同步评论任务
  async function syncComments(accountId?: number, accountName?: string) {
    return createTask({
      type: 'sync_comments',
      title: accountName ? `同步评论 - ${accountName}` : '同步所有评论',
      accountId,
    });
  }

  // 快捷方法：创建同步作品任务
  async function syncWorks(accountId?: number, accountName?: string) {
    return createTask({
      type: 'sync_works',
      title: accountName ? `同步作品 - ${accountName}` : '同步所有作品',
      accountId,
    });
  }

  // 快捷方法：创建同步账号任务
  async function syncAccount(accountId: number, accountName?: string) {
    return createTask({
      type: 'sync_account',
      title: `同步账号 - ${accountName || accountId}`,
      accountId,
    });
  }

  // 弹框控制
  function openDialog() {
    isDialogVisible.value = true;
    // 打开时刷新任务列表
    fetchTasks();
  }

  function closeDialog() {
    isDialogVisible.value = false;
  }

  function toggleDialog() {
    isDialogVisible.value = !isDialogVisible.value;
  }

  // 清理已完成任务
  function clearCompletedTasks() {
    tasks.value = tasks.value.filter(t => 
      t.status === 'pending' || t.status === 'running'
    );
  }

  return {
    // 状态
    tasks,
    isDialogVisible,
    wsConnected,
    worksRefreshTrigger,
    accountRefreshTrigger,
    // 验证码状态
    showCaptchaDialog,
    captchaTaskId,
    captchaType,
    captchaPhone,
    captchaImageBase64,
    // 计算属性
    activeTasks,
    runningTasks,
    hasActiveTasks,
    activeTaskCount,
    // 方法
    getTaskConfig,
    connectWebSocket,
    disconnectWebSocket,
    reconnectWebSocket,
    fetchTasks,
    createTask,
    cancelTask,
    syncComments,
    syncWorks,
    syncAccount,
    openDialog,
    closeDialog,
    toggleDialog,
    clearCompletedTasks,
    stopAllPolling,
    // 验证码方法
    submitCaptcha,
    cancelCaptcha,
  };
});
