import axios from 'axios';

// API配置
const API_BASE_URL = 'http://localhost:8889';
const API_VERSION = '/api/v1';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL + API_VERSION,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器 - 添加认证token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('auth_token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    console.error('API请求错误:', error);
    
    // 处理认证错误
    if (error.response?.status === 401) {
      localStorage.removeItem('auth_token');
      localStorage.removeItem('user_info');
      // 可以在这里跳转到登录页
      window.location.href = '/login';
    }
    
    return Promise.reject(error);
  }
);

// ======================================
// 认证相关API
// ======================================
export const authAPI = {
  // 用户登录
  login: (credentials) => apiClient.post('/auth/login', credentials),
  
  // 获取用户信息
  getProfile: () => apiClient.get('/auth/profile'),
  
  // 获取用户权限
  getPermissions: () => apiClient.get('/auth/permissions'),
  
  // 用户注册
  register: (userData) => apiClient.post('/auth/register', userData),
  
  // 刷新token
  refreshToken: () => apiClient.post('/auth/refresh'),
  
  // 用户登出
  logout: () => apiClient.post('/auth/logout'),
};

// ======================================
// 用户管理API
// ======================================
export const userAPI = {
  // 获取用户列表
  getUsers: (params) => apiClient.get('/users', { params }),
  
  // 创建用户
  createUser: (userData) => apiClient.post('/users', userData),
  
  // 更新用户
  updateUser: (id, userData) => apiClient.put(`/users/${id}`, userData),
  
  // 删除用户
  deleteUser: (id) => apiClient.delete(`/users/${id}`),
  
  // 获取角色列表
  getRoles: () => apiClient.get('/users/roles'),
  
  // 获取权限列表
  getPermissions: () => apiClient.get('/users/permissions'),
};

// ======================================
// 牛只档案API
// ======================================
export const cattleAPI = {
  // 获取牛只列表
  getCattle: (params) => apiClient.get('/cattle', { params }),
  
  // 获取牛只详情
  getCattleDetail: (id) => apiClient.get(`/cattle/${id}`),
  
  // 创建牛只档案
  createCattle: (cattleData) => apiClient.post('/cattle', cattleData),
  
  // 更新牛只信息
  updateCattle: (id, cattleData) => apiClient.put(`/cattle/${id}`, cattleData),
  
  // 删除牛只档案
  deleteCattle: (id) => apiClient.delete(`/cattle/${id}`),
  
  // 获取饲养记录
  getFeedingRecords: (cattleId, params) => apiClient.get(`/cattle/${cattleId}/feeding`, { params }),
  
  // 添加饲养记录
  addFeedingRecord: (cattleId, recordData) => apiClient.post(`/cattle/${cattleId}/feeding`, recordData),
  
  // 获取统计数据
  getStatistics: () => apiClient.get('/cattle/statistics'),
};

// ======================================
// 金融服务API
// ======================================
export const financeAPI = {
  // 贷款管理
  getLoans: (params) => apiClient.get('/finance/loans', { params }),
  getLoanDetail: (id) => apiClient.get(`/finance/loans/${id}`),
  createLoan: (loanData) => apiClient.post('/finance/loans', loanData),
  updateLoanStatus: (id, statusData) => apiClient.put(`/finance/loans/${id}/status`, statusData),
  
  // 保险管理
  getInsurance: (params) => apiClient.get('/finance/insurance', { params }),
  getInsuranceDetail: (id) => apiClient.get(`/finance/insurance/${id}`),
  createInsurance: (insuranceData) => apiClient.post('/finance/insurance', insuranceData),
  
  // 理赔管理
  getClaims: (params) => apiClient.get('/finance/claims', { params }),
  createClaim: (claimData) => apiClient.post('/finance/claims', claimData),
  
  // 统计数据
  getStatistics: () => apiClient.get('/finance/statistics'),
};

// ======================================
// 交易管理API
// ======================================
export const tradingAPI = {
  // 交易记录
  getTransactions: (params) => apiClient.get('/trading/transactions', { params }),
  getTransactionDetail: (id) => apiClient.get(`/trading/transactions/${id}`),
  createTransaction: (transactionData) => apiClient.post('/trading/transactions', transactionData),
  updateTransactionStatus: (id, statusData) => apiClient.put(`/trading/transactions/${id}/status`, statusData),
  
  // 合同管理
  getContracts: (params) => apiClient.get('/trading/contracts', { params }),
  getContractDetail: (id) => apiClient.get(`/trading/contracts/${id}`),
  createContract: (contractData) => apiClient.post('/trading/contracts', contractData),
  
  // 统计数据
  getStatistics: () => apiClient.get('/trading/statistics'),
};

// ======================================
// 政府监管API
// ======================================
export const governmentAPI = {
  // 牧场监管
  getFarmSupervision: (params) => apiClient.get('/government/farms/supervision', { params }),
  
  // 检查记录
  getInspections: (params) => apiClient.get('/government/inspections', { params }),
  createInspection: (inspectionData) => apiClient.post('/government/inspections', inspectionData),
  
  // 质量追溯
  getTraceability: (productId) => apiClient.get(`/government/traceability/${productId}`),
  
  // 政策法规
  getPolicies: (params) => apiClient.get('/government/policies', { params }),
  
  // 统计数据
  getStatistics: () => apiClient.get('/government/statistics'),
  
  // 生成报告
  generateReport: (reportData) => apiClient.post('/government/reports', reportData),
};

// ======================================
// 商城管理API
// ======================================
export const mallAPI = {
  // 商品管理
  getProducts: (params) => apiClient.get('/mall/products', { params }),
  getProductDetail: (id) => apiClient.get(`/mall/products/${id}`),
  createProduct: (productData) => apiClient.post('/mall/products', productData),
  updateProduct: (id, productData) => apiClient.put(`/mall/products/${id}`, productData),
  deleteProduct: (id) => apiClient.delete(`/mall/products/${id}`),
  
  // 订单管理
  getOrders: (params) => apiClient.get('/mall/orders', { params }),
  getOrderDetail: (id) => apiClient.get(`/mall/orders/${id}`),
  createOrder: (orderData) => apiClient.post('/mall/orders', orderData),
  updateOrderStatus: (id, statusData) => apiClient.put(`/mall/orders/${id}/status`, statusData),
  
  // 商品评价
  getProductReviews: (productId, params) => apiClient.get(`/mall/products/${productId}/reviews`, { params }),
  
  // 统计数据
  getStatistics: () => apiClient.get('/mall/statistics'),
};

// ======================================
// 大屏数据API
// ======================================
export const dashboardAPI = {
  // 概览数据
  getOverview: () => apiClient.get('/dashboard/overview'),
  
  // 实时数据
  getRealtime: () => apiClient.get('/dashboard/realtime'),
  
  // 地图数据
  getMapRegions: () => apiClient.get('/dashboard/map/regions'),
  getRegionDetail: (regionId) => apiClient.get(`/dashboard/map/region/${regionId}`),
  
  // 各模块数据
  getFarmData: () => cattleAPI.getStatistics(),
  getFinanceData: () => financeAPI.getStatistics(),
  getTradingData: () => tradingAPI.getStatistics(),
  getGovernmentData: () => governmentAPI.getStatistics(),
  getMallData: () => mallAPI.getStatistics(),
};

// ======================================
// 系统管理API
// ======================================
export const systemAPI = {
  // 健康检查
  getHealth: () => axios.get(`${API_BASE_URL}/health`),
  
  // 数据库状态
  getDatabaseStatus: () => apiClient.get('/database/status'),
  
  // 数据库表信息
  getDatabaseTables: () => apiClient.get('/database/tables'),
  
  // 操作日志
  getOperationLogs: (params) => apiClient.get('/logs/operations', { params }),
};

// 导出所有API
export default {
  auth: authAPI,
  user: userAPI,
  cattle: cattleAPI,
  finance: financeAPI,
  trading: tradingAPI,
  government: governmentAPI,
  mall: mallAPI,
  dashboard: dashboardAPI,
  system: systemAPI,
};

// 导出axios实例供其他地方使用
export { apiClient };