// src/utils/request.ts
import axios from 'axios';
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

// 配置常量
export const wsuri = 'ws://127.0.0.1:61101//WebMoudule//websocket';
export const opname = 'SCADAMain';
export const opnameBs = 'TOCS?CS?MesWork?MES|';
export const mqttIp = (window as any).dt_Config?.mqttIp || 'localhost';
export const mqttPort = parseInt((window as any).dt_Config?.mqttPort || '8083', 10);
export const ExcelDownLoad = (window as any).dt_Config?.serverAddress;
export const action = (window as any).dt_Config?.serverAddress;

class Request {
  private instance: AxiosInstance;

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.setupInterceptors();
  }

  // 设置拦截器
  private setupInterceptors() {
    // 请求拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 设置默认请求头
        config.headers = config.headers || {};
        config.headers['Content-Type'] = 'application/json';

        // 调试信息
        /* console.log('=== 请求拦截器 ===')
        console.log('请求URL:', config.url)
        console.log('请求方法:', config.method)
        console.log('请求数据:', config.data)
        console.log('请求头:', config.headers) */

        return config;
      },
      (error) => {
        console.error('请求拦截器错误:', error);
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (response: AxiosResponse) => {
        // 调试信息
        /* console.log('=== 响应拦截器 ===')
        console.log('响应状态:', response.status)
        console.log('响应数据:', response.data) */

        return response.data;
      },
      (error) => {
        console.error('响应拦截器错误:', error);
        return Promise.reject(error);
      }
    );
  }

  // 通用请求方法
  public request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config);
  }

  public get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config);
  }

  public post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.post(url, data, config);
  }

  public put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.put(url, data, config);
  }

  public delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config);
  }
}

// 创建请求实例
const service = new Request({
  baseURL: (window as any).dt_Config?.serverAddress || '',
  timeout: 1500000
});

// 同时导出原始的 axios 实例以保持兼容性
export const axiosInstance: AxiosInstance = axios.create({
  baseURL: (window as any).dt_Config?.serverAddress || '',
  timeout: 1500000
});

// 设置默认请求头
axios.defaults.headers.post['Content-Type'] = 'application/json';

export default service;
