//服务器接口地址
// const baseURL : string = 'https://newblockwlx.sxczgkj.cn/index.php/api/'
let baseURL: string = "http://192.168.1.42:8787/api/";
// #ifdef H5
baseURL = "/phpapi/api/";
// #endif


// 封装公共请求方法
function request(
  url: string,
  method: "GET" | "POST" | undefined,
  data: object | any,
  toast: boolean
) {
  let networkType = "";
  uni.getNetworkType({
    success: (res) => {
      networkType = res.networkType;
    },
  });
  if (networkType == "none") {
    uni.showToast({
      title: "网络异常，请检查网络",
      icon: "none",
    });
    return false;
  }
  if (toast) {
    uni.showLoading({
      title: "加载中",
      mask: true,
    });
  }
  return new Promise(async (resolve, reject) => {
    let header: any;
    header = {
      "content-type": "application/json",
      token: uni.cache.get('token'),
    };
    uni.request({
      url: baseURL + url,
      method: method,
      data: data,
      header: header,
      success(res: any) {
        if (res.data.code != 1) {
          if (res.data.code === 3000) {
            uni.showToast({
              title: '请登录后操作',
              icon: "none",
            });
			      uni.hideLoading();
            reject();
            return;
          }
          //是否提示错误
          if (toast) {
            uni.showToast({
              title: res.data.msg || res.data.message,
              icon: "none",
            });
            setTimeout(() => {
              uni.hideLoading();
            }, 1000);
          }
          if (res.data.code == 401) {
            uni.showToast({
              title: res.message || res.msg,
              icon: "none",
              success: () => {
                // uni.removeStorageSync('logintoken');
                // uni.removeStorageSync('token');
                uni.reLaunch({
                  url: "/pages/index/index",
                });
              },
            });
          }
          uni.hideLoading();
          reject(res.message | res.msg);
        } else {
          uni.hideLoading();
          console.log(res);
          resolve(res.data.data);
        }
      },
      fail(err) {
        uni.hideLoading();
        //请求失败
        uni.showToast({
          title: "无法连接到服务器",
          icon: "none",
        });
        reject(err);
      },
    });
  });
}
export { request, baseURL };
