import axios from 'axios';
import { aiSwapAPI } from './ai_swap';

const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000';

// 从生成文本中提取标题、文案和话题标签
const extractContent = (text) => {
  if (!text) return { title: '', content: '', topics: [] };
  
  // 提取标题
  const titleMatch = text.match(/[-\s]*标题：\s*([^\n-]+)/);
  const title = titleMatch ? titleMatch[1].trim() : '';
  
  // 提取文案
  const contentMatch = text.match(/[-\s]*文案：\s*([^\n-]+)/);
  const content = contentMatch ? contentMatch[1].trim() : '';
  
  // 提取话题标签
  const labelMatch = text.match(/[-\s]*话题标签：\s*([^\n-]+)/);
  const labelsStr = labelMatch ? labelMatch[1].trim() : '';
  const topics = labelsStr.split(/[#,，、\s]+/).filter(Boolean);
  
  return { title, content, topics };
};

// 后端托管任务状态版本

export const autoPublishApi = {
  /**
   * 获取任务列表
   * @returns {Promise} 
   */
  getTaskList: async (userId = null) => {
    try {
      const params = userId ? `?user_id=${userId}` : '';
      const res = await axios.get(`${BASE_URL}/auto_post/tasks${params}`);
      const tasks = (res.data?.tasks || []).map(t => ({
        id: t.task_id,
        name: t.name || '定时发布',
        platform: t.platform || 'xiaohongshu',
        frequency: t.frequency || 'daily',
        scheduled_times: t.scheduled_times || [],
        status: t.is_completed ? 'completed' : 'running',
        total_runs: t.total || 0,
        success_runs: t.success || 0,
        failed_runs: t.failure || 0,
        next_run: t.next_run,
        last_run: t.last_run,
        is_active: !t.is_completed,
      }));
      return tasks;
    } catch (error) {
      console.error('获取任务列表失败:', error);
      throw error;
    }
  },

  /**
   * 获取任务状态
   * @param {string} taskId - 任务ID
   * @returns {Promise} 
   */
  getTaskStatus: async (taskId) => {
    try {
      const res = await axios.get(`${BASE_URL}/auto_post/tasks/${taskId}/status`);
      const data = res.data;
      return {
        success: true,
        total_tasks: data.total || 0,
        success_count: data.success || 0,
        failure_count: data.failure || 0,
        next_run: data.next_run,
        last_run: data.last_run,
        is_completed: data.is_completed || false,
        items: data.items || [],
      };
    } catch (error) {
      console.error('获取任务状态失败:', error);
      throw error;
    }
  },
  /**
   * 创建自动发布任务
   * @param {Object} taskData - 任务数据
   * @returns {Promise} 
   */
  createAutoPublishTask: async (taskData, currentUserId = null) => {
    try {
      // 将时间格式转换为后端要求的格式 (YYYY-MM-DD HH:MM)
      const scheduleDate_start = new Date(taskData.start_date);
      const scheduleDate_end = new Date(taskData.end_date);

      // 获取从scheduleDate_start到scheduleDate_end之间的所有日期
      const scheduleDates = [];
      const currentDate = new Date(scheduleDate_start);
      while (currentDate <= scheduleDate_end) {
        scheduleDates.push(new Date(currentDate));
        currentDate.setDate(currentDate.getDate() + 1);
      }

      const scheduleTimes = taskData.scheduled_times;

      console.log('所有时刻:', scheduleTimes);
      console.log('所有日期:', scheduleDates);

      const publish_times = [];
      for (const scheduleDate of scheduleDates) {
        for (const scheduleTime of scheduleTimes) {
            const [hours, minutes] = scheduleTime.split(':');
            scheduleDate.setHours(parseInt(hours), parseInt(minutes));
            const publish_time = `${scheduleDate.getFullYear()}-${String(scheduleDate.getMonth() + 1).padStart(2, '0')}-${String(scheduleDate.getDate()).padStart(2, '0')} ${String(scheduleDate.getHours()).padStart(2, '0')}:${String(scheduleDate.getMinutes()).padStart(2, '0')}`;
            publish_times.push(publish_time);
        }
      }

      // 发布时刻表，相当于下面的 schedule_time
      console.log('发布时刻表:', publish_times);

      // TODO: 将历史记录与发布时刻表进行匹配：历史记录>发布时刻表，则多出来的历史记录不进行发布；历史记录<发布时刻表，则多出来的发布时刻表不进行发布；

      const [hours, minutes] = taskData.scheduled_times[0].split(':');
      scheduleDate_start.setHours(parseInt(hours), parseInt(minutes));
      const schedule_time = `${scheduleDate_start.getFullYear()}-${String(scheduleDate_start.getMonth() + 1).padStart(2, '0')}-${String(scheduleDate_start.getDate()).padStart(2, '0')} ${String(scheduleDate_start.getHours()).padStart(2, '0')}:${String(scheduleDate_start.getMinutes()).padStart(2, '0')}`;
      console.log('发布时间:', schedule_time);

      // 获取已审核的历史记录
      let userId = currentUserId;
      if (!userId) {
        try {
          const userInfoRaw = localStorage.getItem('userInfo');
          if (userInfoRaw) {
            const parsed = JSON.parse(userInfoRaw);
            if (parsed && parsed.id) userId = parsed.id;
          }
        } catch {}
      }
      if (!userId) {
        userId = localStorage.getItem('userId');
      }
      if (!userId) {
        throw new Error('用户未登录');
      }

      // 获取用户的所有处理历史记录
      const allApprovedRecords = [];
      let page = 1;
      const pageSize = 50;
      
      while (true) {
        const historyResponse = await aiSwapAPI.getUserProcessHistory(userId, page, pageSize);
        console.log(`获取用户${userId}第 ${page} 页历史记录:`, historyResponse);
        
        if (!historyResponse || !historyResponse.records || !historyResponse.records.length) {
          break;
        }

        // 找到所有已审核的记录
        const approvedRecords = historyResponse.records.filter(record => record.status === '已审核');
        allApprovedRecords.push(...approvedRecords);
        console.log('已审核的记录:', approvedRecords);
        // 如果返回的记录数小于页大小，说明已经到达最后一页
        if (historyResponse.records.length < pageSize) {
          break;
        }
        page++;
      }

      if (allApprovedRecords.length === 0) {
        throw new Error('没有找到已审核的历史记录');
      }

      console.log('所有已审核的记录:', allApprovedRecords);

      // 获取所有记录的详情
      const recordDetails = await Promise.all(
        allApprovedRecords.map(record => 
          aiSwapAPI.getProcessDetail(record.id, userId)
        )
      );
      
      console.log('获取到的所有记录详情:', recordDetails);
      
      // 以组合（face_image_id + cloth_image_id）为单位进行分组聚合
      const grouped = new Map();
      for (let i = 0; i < recordDetails.length; i++) {
        const rd = recordDetails[i];
        const pr = rd?.process_record;
        if (!rd || !pr) continue;
        const faceId = pr.face_image_id;
        const clothId = pr.cloth_image_id;
        if (faceId == null || clothId == null) continue;
        const key = `${faceId}-${clothId}`;
        if (!grouped.has(key)) grouped.set(key, []);
        grouped.get(key).push(rd);
      }

      // 构建按组合的发布任务，每组合并多图，标题/文案基于“偏好ID或最新一条”
      const getPreferredId = (key) => {
        try { return localStorage.getItem(`historyPreferred:${key}`); } catch { return null; }
      };

      const toAbsPath = (p) => `D:/桌面/研究生/组会/project/ai_swap_v6/` + p.replace(/\\/g, '/');

      const publishTasks = [];
      const groupsArray = Array.from(grouped.entries());

      for (let gi = 0; gi < groupsArray.length; gi++) {
        const [groupKey, details] = groupsArray[gi];
        // 按完成时间降序
        const sorted = details.slice().sort((a, b) => {
          const at = new Date(a?.process_record?.completed_at || 0).getTime();
          const bt = new Date(b?.process_record?.completed_at || 0).getTime();
          return bt - at;
        });

        // 选出文案来源的“基准记录”：优先 localStorage 偏好；否则用最新一条
        const preferredId = getPreferredId(groupKey);
        const canonical = (preferredId && sorted.find(d => String(d?.process_record?.id) === String(preferredId))) || sorted[0];

        // 聚合该组合的全部图片路径
        const imagePaths = [];
        for (const rd of sorted) {
          const pr = rd?.process_record;
          const candidates = [
            rd?.result_image?.stored_path,
            pr?.result_image_path,
            pr?.output_path,
            pr?.result_image?.stored_path,
          ];
          const valid = candidates.find(x => x && typeof x === 'string');
          if (valid) {
            const abs = toAbsPath(valid);
            if (!imagePaths.includes(abs)) imagePaths.push(abs);
          }
        }

        if (imagePaths.length === 0) {
          console.warn(`组合 ${groupKey} 无有效图片，跳过`);
          continue;
        }

        const { title, content, topics } = extractContent(canonical?.process_record?.generated_text || '');

        // 映射发布时间：按组合序号分配
        const scheduleTimeIndex = Math.min(gi, publish_times.length - 1);
        const schedule_time = publish_times[scheduleTimeIndex];

        publishTasks.push({
          image_paths: imagePaths,
          title: title || taskData.name,
          description: content || `自动发布任务 - ${taskData.name}`,
          topics: (topics && topics.length > 0) ? topics : ['自动发布'],
          schedule_time,
          // 传递该组合包含的所有处理记录ID，便于后端成功发布后批量更新为“已发布”
          record_ids: sorted
            .map(d => d?.process_record?.id)
            .filter(id => typeof id === 'number' && !Number.isNaN(id))
        });
      }

      console.log('准备发布的任务列表:', publishTasks);

      if (publishTasks.length === 0) {
        throw new Error('没有找到可以发布的有效内容');
      }

      // 改为调用后端批量任务接口，由后端托管执行与进度
      const payload = {
        name: taskData.name,
        platform: taskData.platform,
        frequency: taskData.frequency,
        scheduled_times: taskData.scheduled_times,
        tasks: publishTasks.map(t => ({
          ...t,
          if_clean: false,
        })),
      };
      const res = await axios.post(`${BASE_URL}/auto_post/tasks/batch`, { ...payload, user_id: currentUserId }, {
        headers: { 'Content-Type': 'application/json' },
      });
      return res.data;
    } catch (error) {
      console.error('创建自动发布任务失败:', error);
      // 处理特定的错误消息
      // 处理特定的错误类型
      const errorMessages = {
        '没有找到已审核的历史记录': '没有找到可以发布的已审核内容，请先审核内容后再创建自动发布任务',
        '记录中没有有效的结果图片路径': '所选记录没有有效的结果图片路径，请确保处理已完成并生成了结果图片',
        '获取记录详情失败': '无法获取记录详情，请稍后重试',
        '用户未登录': '用户未登录，请先登录后再试',
        '没有找到可以发布的有效内容': '没有找到可以发布的有效内容，请确保有已审核的内容且包含有效的图片',
      };

      // 检查是否是已知错误类型
      if (errorMessages[error.message]) {
        console.error('已知错误:', error.message);
        throw new Error(errorMessages[error.message]);
      }

      // 处理服务器响应错误
      if (error.response) {
        console.error('服务器错误详情:', {
          status: error.response.status,
          data: error.response.data,
          headers: error.response.headers
        });

        let errorMsg = '';
        const errorData = error.response.data;

        // 处理详细的错误信息
        if (errorData?.error) {
          const errorText = errorData.error;
          
          if (errorText.includes('validation error')) {
            if (errorText.includes('result_image')) {
              errorMsg = errorText.includes('Input should be a valid dictionary')
                ? '记录中缺少结果图片数据，请确保处理已完成并生成了结果图片'
                : '结果图片数据格式错误，请确保记录包含有效的图片数据';
            } else {
              errorMsg = '数据格式错误，请检查提交的内容';
            }
          } else if (errorText.includes('schedule_time')) {
            errorMsg = '发布时间设置无效，请检查时间格式是否正确';
          } else {
            errorMsg = errorText;
          }
        } else if (error.response.status === 429) {
          errorMsg = '发送请求过于频繁，请稍后再试';
        } else if (error.response.status === 413) {
          errorMsg = '上传的图片文件过大，请压缩后重试';
        } else {
          errorMsg = errorData?.detail || errorData?.message || '服务器响应错误';
        }
        
        console.error('处理后的错误消息:', errorMsg);
        throw new Error(`创建任务失败: ${errorMsg}`);
      }

      // 处理网络请求错误
      if (error.request) {
        console.error('网络请求失败:', {
          method: error.config?.method,
          url: error.config?.url,
          timeout: error.config?.timeout
        });
        throw new Error('无法连接到服务器，请检查网络连接');
      }

      // 处理其他未知错误
      console.error('未知错误:', {
        name: error.name,
        message: error.message,
        stack: error.stack
      });
      throw new Error(`创建任务失败: ${error.message}`);
    }
  }
};
