/**
 * 封装请求
 * @author Rockery(1113269755@qq.com)
 */

import indexConfig from '@/agrcloud-config/index.config';

module.exports = (params) => {
  let url = indexConfig.baseUrl + params.url;
  let method = params.method;
  let header = params.header || {};
  let data = params.data || {};
  if (method) {
    method = method.toUpperCase();
    if (method == "POST") {
      header = {
        // 'Content-Type': 'application/x-www-form-urlencoded',
        'Access-Control-Allow-Origin': '*',
        accessToken: uni.getStorageSync("token")
      };
    }
  }
  //	发起请求 加载动画
  if (!params.hideLoading) {
    uni.showLoading({
      title: "加载中..."
    });
  }
  //	发起网络请求
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: method || "GET",
      header: header,
      data: data,
      dataType: "json",
      sslVerify: false, //是否验证ssl证书
      success: res => {
        if (res.statusCode && res.statusCode != 200) {
          uni.hideLoading();
          uni.showToast({
            title: res.errMsg,
            icon: 'none'
          });
          reject({ code: res.statusCode, msg: res.errMsg });
        } else {
          const respData = res.data || {};
          if (respData.code != 200) {
            uni.hideLoading();
            uni.showToast({
              title: respData.msg,
              icon: 'none'
            });
            reject({ code: respData.code, msg: respData.msg });
          } else {
            uni.hideLoading();
            resolve(res.data);
          }
        }
      },
      fail: err => {
        uni.hideLoading();
        uni.showToast({
          title: err.errMsg,
          icon: 'none'
        });
        reject(err.data);
      }
    });
  });
}
