import Request from 'luch-request';
import Vue from 'vue';

// 创建实例
const request = new Request({
  baseURL: 'http://192.168.0.224:8082/data-service/api/',
  timeout: 10000,
  header: {
    'Content-Type': 'application/json',
    apiToken: 'VtkIwAZkwguhcxOnazlDrPsTu64bQ1NC',
  },
});

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 显示加载提示
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    return config;
  },
  (error) => {
    // 隐藏加载提示
    uni.hideLoading();
    return Promise.reject(error);
  },
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 隐藏加载提示
    uni.hideLoading();
    if (response.data.msg === 'success') {
      return response.data.data.rowData;
    }
    uni.showToast({
      title: '请求失败',
      icon: 'none',
      duration: 2000,
    });
    return Promise.reject('请求错误');
  },
  (error) => {
    // 隐藏加载提示
    uni.hideLoading();

    // 错误处理
    uni.showToast({
      title: error.message || '请求失败',
      icon: 'none',
      duration: 2000,
    });
    return Promise.reject(error);
  },
);

// 定义请求方法类型
interface RequestOptions {
  url: string;
  data?: any;
  params?: any;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS';
  header?: any;
}

// 封装请求方法
const http = {
  request: (options: RequestOptions) => {
    return request.request(options);
  },
  get: (url: string, params?: any, header?: any) => {
    return request.get(url, { params, header });
  },
  post: (url: string, data?: any, header?: any) => {
    return request.post(url, data, { header });
  },
  put: (url: string, data?: any, header?: any) => {
    return request.put(url, data, { header });
  },
  delete: (url: string, data?: any, header?: any) => {
    return request.delete(url, { data, header });
  },
};

// 挂载到Vue原型
Vue.prototype.$http = http;

export default http;
