import axios from 'axios';

const api = axios.create({
  baseURL: 'https://mi.xyvan.cn/api',
  timeout: 10000
});

// Token续期状态管理
let isRefreshing = false;
let refreshSubscribers = [];

// 订阅token续期完成事件
const subscribeTokenRefresh = (cb) => {
  refreshSubscribers.push(cb);
};

// 通知所有订阅者token已更新
const onTokenRefreshed = (token) => {
  refreshSubscribers.forEach(cb => cb(token));
  refreshSubscribers = [];
};

// 检查token是否即将过期（剩余时间小于1天）
const shouldRefreshToken = (token) => {
  if (!token) return false;
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    const exp = payload.exp * 1000;
    const now = Date.now();
    const oneDay = 24 * 60 * 60 * 1000;
    return (exp - now) < oneDay && (exp - now) > 0;
  } catch {
    return false;
  }
};

// 续期token
const refreshToken = async () => {
  try {
    const { data } = await api.post('/admin/refresh-token', {}, {
      _skipRefresh: true // 标记跳过续期检查
    });
    localStorage.setItem('token', data.token);
    return data.token;
  } catch (error) {
    console.error('Token续期失败:', error);
    return null;
  }
};

api.interceptors.request.use(async config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
    
    // 跳过续期请求本身的续期检查
    if (!config._skipRefresh && shouldRefreshToken(token)) {
      if (!isRefreshing) {
        isRefreshing = true;
        const newToken = await refreshToken();
        isRefreshing = false;
        if (newToken) {
          config.headers.Authorization = `Bearer ${newToken}`;
          onTokenRefreshed(newToken);
        }
      } else {
        // 等待续期完成
        return new Promise(resolve => {
          subscribeTokenRefresh(newToken => {
            config.headers.Authorization = `Bearer ${newToken}`;
            resolve(config);
          });
        });
      }
    }
  }
  return config;
});

// 响应拦截器：确保所有错误都能被正确捕获
api.interceptors.response.use(
  response => response,
  error => {
    // 401错误：token过期或无效，跳转登录页
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
      localStorage.removeItem('admin');
      // 避免在登录页重复跳转
      if (!window.location.pathname.includes('/admin/login')) {
        window.location.href = '/admin/login';
      }
    }
    console.error('API请求错误:', error);
    return Promise.reject(error);
  }
);

// 获取完整的图片URL
export const getImageUrl = (path) => {
  if (!path) return '';
  if (path.startsWith('http://') || path.startsWith('https://')) {
    return path;
  }
  // 开发环境使用代理，生产环境使用完整域名
  if (import.meta.env.DEV) {
    return `http://localhost:3000${path}`;
  }
  return `https://mi.xyvan.cn${path}`;
};

export default {
  // 活动相关
  getActivities: (params) => api.get('/activities', { params }),
  getActivity: (id) => api.get(`/activities/${id}`),
  getVenueImages: (id) => api.get(`/activities/${id}/venue-images`),
  
  // 报名相关
  submitRegistration: (data) => api.post('/registrations', data),
  getRegistration: (id) => api.get(`/registrations/${id}`),
  getActivityRegistrations: (id) => api.get(`/activities/${id}/registrations`),
  
  // 用户上传照片
  uploadUserPhotos: (id, data) => api.post(`/activities/${id}/photos`, data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 300000 // 5分钟超时
  }),
  
  // 用户验证登录
  verifyUser: (activityId, data) => api.post(`/auth/verify/${activityId}`, data),
  
  // 管理员相关
  adminLogin: (data) => api.post('/admin/login', data),
  refreshToken: () => api.post('/admin/refresh-token'),
  createActivity: (data) => api.post('/admin/activities', data),
  updateActivity: (id, data) => api.put(`/admin/activities/${id}`, data),
  approveRegistration: (id, status) => api.put(`/admin/registrations/${id}`, { status }),
  updateRegistration: (id, data) => api.put(`/admin/registrations/${id}`, data),
  checkInRegistration: (id) => api.put(`/admin/registrations/${id}/checkin`),
  groupRegistration: (id) => api.put(`/admin/registrations/${id}/group`),
  deleteRegistration: (id) => api.delete(`/admin/registrations/${id}`),
  getAllRegistrations: (params) => api.get('/admin/registrations', { params }),
  addExpense: (data) => api.post('/admin/expenses', data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000
  }),
  getExpenses: (params) => api.get('/admin/expenses', { params }),
  updateExpense: (id, data) => api.put(`/admin/expenses/${id}`, data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000
  }),
  deleteExpense: (id) => api.delete(`/admin/expenses/${id}`),
  uploadPhotos: (data) => api.post('/admin/photos', data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 300000 // 5分钟超时，适配大文件上传
  }),
  getPendingPhotos: () => api.get('/admin/photos/pending'),
  approvePhoto: (id, status) => api.put(`/admin/photos/${id}`, { status }),
  deletePhoto: (id) => api.delete(`/admin/photos/${id}`),
  addSponsor: (data) => api.post('/admin/sponsors', data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000 // 1分钟超时
  }),
  updateSponsor: (id, data) => api.put(`/admin/sponsors/${id}`, data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000
  }),
  deleteSponsor: (id) => api.delete(`/admin/sponsors/${id}`),
  addPrize: (data) => api.post('/admin/prizes', data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000
  }),
  updatePrize: (id, data) => api.put(`/admin/prizes/${id}`, data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000
  }),
  deletePrize: (id) => api.delete(`/admin/prizes/${id}`),
  
  // 管理员账号管理（仅超级管理员）
  getAdmins: () => api.get('/admin/admins'),
  createAdmin: (data) => api.post('/admin/admins', data),
  updateAdmin: (id, data) => api.put(`/admin/admins/${id}`, data),
  updateAdminPassword: (id, data) => api.put(`/admin/admins/${id}/password`, data),
  deleteAdmin: (id) => api.delete(`/admin/admins/${id}`),
  
  // 场地图片管理
  getVenueImages: (activityId) => api.get('/admin/venue-images', { params: { activityId } }),
  uploadVenueImage: (data) => api.post('/admin/venue-images', data, {
    headers: { 'Content-Type': 'multipart/form-data' },
    timeout: 60000
  }),
  deleteVenueImage: (id) => api.delete(`/admin/venue-images/${id}`),
  updateVenueImageOrder: (id, sortOrder) => api.put(`/admin/venue-images/${id}`, { sortOrder })
};
