var sortObjASCII = function (obj) {
  var arr = Object.keys(obj).sort();
  if (arr.length === 0) {
    return {};
  }
  var sortObj = {};
  for (var ii in arr) {
    sortObj[arr[ii]] = obj[arr[ii]];
  }
  return sortObj;
}

function getToken () {
  return window.localStorage.getItem('token') ? window.localStorage.getItem('token') : ''
}

const request = axios.create({
  timeout: 120000,
});

// 请求拦截器
request.interceptors.request.use(
  function (config) {
    const token = getToken();
    // 请求头带上token
    if (token) {
      config.headers.Authorization = token
    } else {
      config.headers.Authorization = "075895df18c38c8950999cef1af1f0d6";
    }
    // 用户编码
    config.headers.UserNo = window.localStorage.getItem('user_no')
    // 应用设置
    const appId = 'dkFv6OwWyQhSeaZG'
    const appSecret = 'd34cea92316d1da113e95158bed9ca97'
    config.headers.AppId = appId
    config.headers.AppSecret = appSecret
    // 签名
    var signData = Qs.parse(config.data)
    var timeStr = Date.parse(new Date()) / 1000

    signData.appId = appId
    signData.appSecret = appSecret
    signData.timestamp = timeStr
    signData.url = decodeURI(config.url)
    signData.token = token || config.headers.Authorization;
    // 按照ASCII码进行排序
    var dataSign = sortObjASCII(signData)
    // 转换为字符串
    var signStr = ''
    for (var key in dataSign) {
      var str = ''
      if ((typeof signData[key] !== 'string') && signData[key].constructor !== String) {
        str = JSON.stringify(signData[key])
      } else {
        str = signData[key]
      }
      if (signStr === '') {
        signStr = key + '=' + str
      } else {
        signStr += '&' + key + '=' + str
      }
    }
    const salt = '&4F6g4Y6b5L4R9'
    const sign = signStr + salt;
    config.headers.Sign = md5(md5(sign)) // 加密盐
    config.headers.Timestamp = timeStr // 请求时间

    return config;
  },
  function (error) {
    return Promise.reject(error)
  }
);
// 响应拦截器
request.interceptors.response.use(
  function (response) {
    if (response.status === 200) {
      if (response.data && response.data.code === 200) {
        return response.data;
      } else {
        return false;
      }
    }
    return false;
  },
  function (error) {
    console.log(error)
    const str = `message: ${error.message} \n data: ${error.config.data} \n token: ${error.config.headers.Authorization}`
    alert(str);
    
    return Promise.reject(error);
  }
);
