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),
  // updateKeyExpiration: (keyId: string, expirationTime: string) => api.put('/appVerify/updateKeyExpiration', { keyId, expirationTime }),
};