import { getConfig } from './configService';
import {
  RunTaskRequest,
  RunTaskApiResponse,
  Task,
  TaskStatus,
} from '../types/task';
import api from './api';
import axios from 'axios';

// 获取任务列表
export const getTasks = async (params: {
  pageNum: number;
  pageSize: number;
}): Promise<Task[]> => {
  try {
    const config = await getConfig();
    const endpoint = config?.apiEndpoints?.getTasks;
    if (!endpoint) throw new Error('获取任务列表的API端点未配置');

    const response = await api.get(endpoint, { params });
    return response as unknown as Task[];
  } catch (error) {
    console.error('获取任务列表失败 (service):', error);
    throw error;
  }
};

// 获取任务详情
export const getTaskDetail = async (taskId: string): Promise<Task> => {
  try {
    const config = await getConfig();
    let endpoint = config?.apiEndpoints?.getTaskDetail;
    if (!endpoint) throw new Error('获取任务详情的API端点未配置');

    endpoint = endpoint.replace('{taskId}', taskId);
    const response = await api.get(endpoint);
    return response as unknown as Task;
  } catch (error) {
    console.error(`获取任务详情失败 (ID: ${taskId}):`, error);
    throw error;
  }
};

// 运行任务
export const runTask = async (
  taskData: RunTaskRequest,
): Promise<RunTaskApiResponse> => {
  try {
    const config = await getConfig();
    const endpoint = config?.apiEndpoints?.runTask;
    if (!endpoint) throw new Error('运行任务的API端点未配置');

    const response = await api.post(endpoint, taskData);
    return response as unknown as RunTaskApiResponse;
  } catch (error) {
    console.error('运行任务失败:', error);
    throw error;
  }
};

// ============ 任务管理相关API ============

// 创建任务管理API实例
const createTaskApi = () => {
  return axios.create({
    timeout: 10000,
  });
};

// 请求拦截器 - 为任务管理API配置
const setupTaskApiInterceptors = async (apiInstance: any) => {
  const config = await getConfig();

  apiInstance.interceptors.request.use(
    async (requestConfig: any) => {
      const taskServerUrl = config?.taskServerUrl;
      if (!taskServerUrl) {
        throw new Error('任务管理服务器地址未配置');
      }

      requestConfig.baseURL = taskServerUrl.replace(/\/$/, '');
      requestConfig.headers = {
        'Content-Type': 'application/json',
        ...config?.headers,
        ...requestConfig.headers,
      };

      console.log(
        `[Task API Request] ${requestConfig.method?.toUpperCase()} ${
          requestConfig.baseURL
        }${requestConfig.url}`,
        { params: requestConfig.params, data: requestConfig.data },
      );
      return requestConfig;
    },
    (error: any) => {
      console.error('[Task API Request Error]', error);
      return Promise.reject(error);
    },
  );

  apiInstance.interceptors.response.use(
    (response: any) => {
      console.log(
        `[Task API Response] ${response.config.method?.toUpperCase()} ${
          response.config.url
        }`,
        response.data,
      );

      if (response.data && response.data.code && response.data.code !== 200) {
        throw new Error(`API 错误: ${response.data.message}`);
      }

      // 处理任务管理API的响应格式: { success: true, result: { records: [...] } }
      if (response.data && response.data.success && response.data.result) {
        // 如果result中有records数组，返回records
        if (
          response.data.result.records &&
          Array.isArray(response.data.result.records)
        ) {
          return response.data.result.records;
        }
        // 否则返回整个result对象
        return response.data.result;
      }

      return response.data;
    },
    (error: any) => {
      if (error.response) {
        console.error(
          `[Task API Response Error] Status: ${error.response.status}`,
          error.response.data,
        );
        const httpError = new Error(
          `HTTP ${error.response.status}: ${
            error.response.statusText || 'Unknown Error'
          }`,
        );
        return Promise.reject(httpError);
      } else if (error.request) {
        console.error('[Task API Network Error]', error.request);
        return Promise.reject(new Error('网络错误，请检查您的连接'));
      } else {
        console.error('[Task API Request Setup Error]', error.message);
        return Promise.reject(error);
      }
    },
  );

  return apiInstance;
};

/**
 * 获取任务运行列表
 * @param params 查询参数
 */
export const getTaskRunList = async (params?: {
  status?: TaskStatus;
  name?: string;
  pageNum?: number;
  pageSize?: number;
}): Promise<any[]> => {
  try {
    const config = await getConfig();
    const endpoint = config?.taskApiEndpoints?.getTaskList;
    if (!endpoint) throw new Error('获取任务列表的API端点未配置');

    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.get(endpoint, { params });
    return response || [];
  } catch (error) {
    console.error('获取任务运行列表失败:', error);
    throw error;
  }
};

/**
 * 创建任务
 * @param params 任务参数
 */
export const createTaskRun = async (params: any): Promise<any> => {
  try {
    const config = await getConfig();
    const endpoint = config?.taskApiEndpoints?.createTask;
    if (!endpoint) throw new Error('创建任务的API端点未配置');

    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.post(endpoint, params);
    return response;
  } catch (error) {
    console.error('创建任务失败:', error);
    throw error;
  }
};

/**
 * 获取任务运行详情
 * @param id 任务ID
 */
export const getTaskRunDetail = async (id: string): Promise<any> => {
  try {
    const config = await getConfig();
    let endpoint = config?.taskApiEndpoints?.getTaskDetail;
    if (!endpoint) throw new Error('获取任务详情的API端点未配置');

    endpoint = endpoint.replace('{id}', id);
    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.get(endpoint);
    return response;
  } catch (error) {
    console.error(`获取任务运行详情失败 (ID: ${id}):`, error);
    throw error;
  }
};

/**
 * 获取任务进度和动作列表
 * @param ids 任务ID数组
 */
export const getTaskProgress = async (ids: string[]): Promise<any> => {
  try {
    const config = await getConfig();
    const endpoint = config?.taskApiEndpoints?.getTaskProgress;
    if (!endpoint) throw new Error('获取任务进度的API端点未配置');

    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.get(endpoint, {
      params: {
        ids: ids.join(','),
      },
    });
    return response;
  } catch (error) {
    console.error('获取任务进度失败:', error);
    throw error;
  }
};

/**
 * 调整任务优先级
 * @param id 任务ID
 * @param priority 新优先级
 */
export const adjustTaskPriority = async (
  id: string,
  priority: number,
): Promise<any> => {
  try {
    const config = await getConfig();
    let endpoint = config?.taskApiEndpoints?.adjustTaskPriority;
    if (!endpoint) throw new Error('调整任务优先级的API端点未配置');

    endpoint = endpoint.replace('{id}', id);
    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.put(endpoint, { priority });
    return response;
  } catch (error) {
    console.error(`调整任务优先级失败 (ID: ${id}):`, error);
    throw error;
  }
};

/**
 * 暂停任务
 * @param id 任务ID
 */
export const pauseTask = async (id: string): Promise<any> => {
  try {
    const config = await getConfig();
    let endpoint = config?.taskApiEndpoints?.pauseTask;
    if (!endpoint) throw new Error('暂停任务的API端点未配置');

    endpoint = endpoint.replace('{id}', id);
    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.put(endpoint);
    return response;
  } catch (error) {
    console.error(`暂停任务失败 (ID: ${id}):`, error);
    throw error;
  }
};

/**
 * 继续任务
 * @param id 任务ID
 */
export const continueTask = async (id: string): Promise<any> => {
  try {
    const config = await getConfig();
    let endpoint = config?.taskApiEndpoints?.continueTask;
    if (!endpoint) throw new Error('继续任务的API端点未配置');

    endpoint = endpoint.replace('{id}', id);
    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.put(endpoint);
    return response;
  } catch (error) {
    console.error(`继续任务失败 (ID: ${id}):`, error);
    throw error;
  }
};

/**
 * 终止任务
 * @param id 任务ID
 */
export const terminateTask = async (id: string): Promise<any> => {
  try {
    const config = await getConfig();
    let endpoint = config?.taskApiEndpoints?.terminateTask;
    if (!endpoint) throw new Error('终止任务的API端点未配置');

    endpoint = endpoint.replace('{id}', id);
    const taskApi = await setupTaskApiInterceptors(createTaskApi());
    const response = await taskApi.put(endpoint);
    return response;
  } catch (error) {
    console.error(`终止任务失败 (ID: ${id}):`, error);
    throw error;
  }
};
