import axios from 'axios';
import { auth } from '../utils/auth';

// 全局方法
let showToast: (message: string) => void;
let globalLogout: (() => Promise<void>) | null = null;

export const setToastFunction = (toastFn: (message: string) => void) => {
  showToast = toastFn;
};

export const setLogoutFunction = (logoutFn: () => Promise<void>) => {
  globalLogout = logoutFn;
};

// 创建 axios 实例
const api = axios.create({
  baseURL: 'https://testlu.chuangtewl.com/prod-api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
api.interceptors.request.use(
  async (config) => {
    if (__DEV__) {
      // console.log('[Request]:', config.url, config.data);
    }

    const token = await auth.getToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    if (__DEV__) {
      // console.log('[Response]:', response.config.url, response.data);
    }

    const { code, msg, data } = response.data;
    
    if (code === 401) {
      auth.removeToken();
      globalLogout?.();
      showToast?.('登录已过期，请重新登录');
      return Promise.reject(response.data);
    }

    if (code !== 200) {
      showToast?.(msg || '服务器错误');
      return Promise.reject(response.data);
    }

    return response.data;
  },
  error => {
    if (__DEV__) {
      console.log('[Response Error]:', error.config?.url, error.message);
    }

    const errorMsg = error.message === 'Network Error' 
      ? '网络连接失败，请检查网络设置' 
      : (error.response?.data?.msg || '请求失败，请稍后重试');
    
    showToast?.(errorMsg);
    return Promise.reject(error);
  }
);

// API 方法
export const apiService = {
  getPhoneCode: (phone: string, type: string) => 
    api.get('/appCaptcha', { params: { phone, type } }),

  phoneCodeLogin: (phone: string, phoneCode: string, uuid: string) =>
    api.post('/appCodeLogin', { phone, phoneCode, uuid }),
  // 密码登录
  passwordLogin: (username: string, password: string) =>
    api.post('/appLogin', { username, password }),

  register: (username: string, password: string, code: string, uuid: string) =>
    api.post('/register', { username, password, code, uuid }),
  // 重置密码
  resetPassword: (phone: string, newPassword: string, phoneCode: string, uuid: string) =>
    api.post('/forgotPassword', { phone, newPassword, phoneCode, uuid }),

  // 获取用户信息
  getUserInfo: () => api.get('/getInfo'),
  // 获取设备信息
  getDeviceInfo: (sn: string) => 
    api.get('/appVerify/getDeviceBySn', { params: { sn } }),

  // 绑定设备
  bindSn: (sn: string) => 
    api.post('/appVerify/userBandDevice?sn=' + sn),

  // 获取设备列表
  getDeviceList: () => api.get('/appVerify/getDeviceListByMerchantToken'),

  toggleDefault: (sn: string) => api.put(`/appVerify/toggleDefault?sn=${sn}`),
  // 响铃
  ring: (sn: string) => api.post(`/app/device/ring?sn=${sn}`),
  // 解锁
  unlocking: (sn: string) => api.post(`/appVerify/admin/unlocking?sn=${sn}`),
  // 锁车
  lock: (sn: string) => api.post(`/appVerify/admin/lock?sn=${sn}`),
  // 获取钥匙列表
  getKeyListByOwnerId: () => api.get('/appVerify/getKeyListByOwnerId'),
  // 添加钥匙
  addKey: (data: any) => api.post('/appVerify/addKey', data),
  // 更新钥匙
  updateKey: (data: any) => api.put('/appVerify/editKey', data),
  // 删除钥匙
  deleteKey: (key: any) => api.delete('/appVerify/del/' + key),
  // 获取过期钥匙
  getExpiredKeys: () => api.get('/appVerify/getExpiredKeyListByOwnerId'),
  // 获取钥匙信息
  getKeyInfo: (keyId: string) => api.get('/appVerify/key/'+keyId),
  // 绑定钥匙
  bindKey: (keyId: string) => api.post('/appVerify/claimKey?keyId='+keyId),
  // 更新设备
  updateDevice: ( data: any) => api.put('/appVerify/device/edit', data),
  // 解绑设备
  untieDevice: (deviceId: string) => api.post('/appVerify/untie/'+deviceId),
  // 获取七牛云token
  getQiniuToken: () => api.get('/common/qiniu/uploadInfo'),
  // 获取车型
  getModelList: () => api.get('/appVerify/modelList'),
  // 获取帮助中心分类
  getClassifyList: () => api.get('/app/classify/list'),
  // 获取帮助中心文章列表
  getArticleList: (classifyId: string) => api.get('/app/article/list?classifyId=' + classifyId),
  // 获取客服电话
  getServerPhone: () => api.get('/app/getServerPhone'),
  

  getArticleById: (id: string) => api.get('/app/article/' + id),
  // updateKeyExpiration: (keyId: string, expirationTime: string) => api.put('/appVerify/updateKeyExpiration', { keyId, expirationTime }),
};