import axios, { AxiosInstance, AxiosResponse } from 'axios';

const API_BASE_URL = '/api';

// 创建自定义Axios实例类型，考虑响应拦截器的行为
type CustomAxiosInstance = AxiosInstance & {
  post<T = any>(url: string, data?: any, config?: any): Promise<T>;
  get<T = any>(url: string, config?: any): Promise<T>;
  put<T = any>(url: string, data?: any, config?: any): Promise<T>;
  delete<T = any>(url: string, config?: any): Promise<T>;
};

const api: CustomAxiosInstance = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000, // 增加超时时间到30秒
  headers: {
    'Content-Type': 'application/json',
  },
}) as unknown as CustomAxiosInstance;

// 请求拦截器
api.interceptors.request.use(
  (config: any) => {
    // 添加管理员token
    if (typeof window !== 'undefined') {
      const adminToken = localStorage.getItem('survey_admin');
      if (adminToken) {
        const { token } = JSON.parse(adminToken);
        config.headers.Authorization = `Bearer ${token}`;
      }
    }
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response: any) => {
    // 如果响应类型是 blob，直接返回原始响应
    if (response.config.responseType === 'blob') {
      return response.data;
    }
    
    const { data } = response;
    if (data.success) {
      return data;
    } else {
      throw new Error(data.message || '请求失败');
    }
  },
  (error: any) => {
    if (error.response?.status === 401) {
      // 未授权，清除管理员信息
      if (typeof window !== 'undefined') {
        localStorage.removeItem('survey_admin');
        window.location.href = '/admin/login';
      }
    }
    return Promise.reject(error);
  }
);

// 用户相关API
export const userAPI = {
  createUser: (data: { name: string; phone: string; password?: string }) => api.post('/users', data),
  getUser: (id: string) => api.get(`/users/${id}`),
  validateUserInfo: (data: { name: string; phone: string; password?: string }) => api.post('/users/validate', data),
  getUsersByName: (name: string) => api.get(`/users/name/${name}`),
};

// 题目相关API
export const questionAPI = {
  getQuestions: (params?: { type?: string; category?: string; keyword?: string; startDate?: string; endDate?: string; page?: number; limit?: number }) => 
    api.get('/questions', { params }),
  getQuestion: (id: string) => api.get(`/questions/${id}`),
  createQuestion: (data: any) => api.post('/questions', data),
  updateQuestion: (id: string, data: any) => api.put(`/questions/${id}`, data),
  deleteQuestion: (id: string) => api.delete(`/questions/${id}`),
  importQuestions: (file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    return api.post('/questions/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  },
  importQuestionsFromText: (data: { mode: 'overwrite' | 'incremental'; questions: any[] }) =>
    api.post('/questions/import-text', data),
  exportQuestions: (params?: { type?: string; category?: string }) => 
    api.get('/questions/export', {
      params,
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json',
      },
    }),
};

// 答题相关API
export const quizAPI = {
  generateQuiz: (userId: string, subjectId?: string, taskId?: string) => 
    api.post<{ questions: any[]; totalScore: number; timeLimit: number }>('/quiz/generate', { userId, subjectId, taskId }),
  submitQuiz: (data: { userId: string; subjectId?: string; taskId?: string; answers: any[] }) => 
    api.post<{ recordId: string; totalScore: number; correctCount: number; totalCount: number }>('/quiz/submit', data),
  getUserRecords: (userId: string, params?: { page?: number; limit?: number }) => 
    api.get<any[]>(`/quiz/records/${userId}`, { params }),
  getRecordDetail: (recordId: string) => 
    api.get<{ record: any; answers: any[] }>(`/quiz/records/detail/${recordId}`),
  getAllRecords: (params?: { page?: number; limit?: number }) => 
    api.get<any[]>(`/quiz/records`, { params }),
};

export const examSubjectAPI = {
  getSubjects: () => api.get('/exam-subjects'),
};

export const examTaskAPI = {
  getTasks: () => api.get('/exam-tasks'),
  getUserTasks: (userId: string) => api.get(`/exam-tasks/user/${userId}`),
};

// 管理员相关API
export const adminAPI = {
  login: (data: { username: string; password: string }) => api.post('/admin/login', data),
  getQuizConfig: () => api.get('/admin/config'),
  updateQuizConfig: (data: any) => api.put('/admin/config', data),
  getStatistics: () => api.get('/admin/statistics'),
  getActiveTasksStats: () => api.get('/admin/active-tasks'),
  getDashboardOverview: () => api.get('/admin/dashboard/overview'),
  getHistoryTaskStats: (params?: { page?: number; limit?: number }) =>
    api.get('/admin/tasks/history-stats', { params }),
  getUpcomingTaskStats: (params?: { page?: number; limit?: number }) =>
    api.get('/admin/tasks/upcoming-stats', { params }),
  getAllTaskStats: (params?: {
    page?: number;
    limit?: number;
    status?: 'completed' | 'ongoing' | 'notStarted';
    endAtStart?: string;
    endAtEnd?: string;
  }) => api.get('/admin/tasks/all-stats', { params }),
  getUserStats: () => api.get('/admin/statistics/users'),
  getSubjectStats: () => api.get('/admin/statistics/subjects'),
  getTaskStats: () => api.get('/admin/statistics/tasks'),
  updatePassword: (data: { username: string; oldPassword: string; newPassword: string }) => 
    api.put('/admin/password', data),
};

// 用户组相关API
export const userGroupAPI = {
  getAll: () => api.get('/admin/user-groups'),
  create: (data: { name: string; description?: string }) => api.post('/admin/user-groups', data),
  update: (id: string, data: { name?: string; description?: string }) => api.put(`/admin/user-groups/${id}`, data),
  delete: (id: string) => api.delete(`/admin/user-groups/${id}`),
  getMembers: (id: string) => api.get(`/admin/user-groups/${id}/members`),
};

export default api;
