import {host,prefix} from './config'
import { getUrlArgObject } from "@utils/tools";
const $ = require('jquery');
$.support.cors = true;
const axios=require('axios');
const qs=require('querystring');
const isLocal = window.location.hostname.indexOf('localhost')!=-1;
// const qhost = isLocal?host+prefix:prefix;
const qhost = isLocal?host+prefix:prefix;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//axios.defaults.baseURL = host;       //默认地址
// axios.defaults.timeout = 60000;       //请求超时


    const securityCode = getUrlArgObject("code");
    const appKeyId = getUrlArgObject("appI");
    const appKeySecret = getUrlArgObject("appS");
    axios.interceptors.request.use(
        req => {
          req.headers.appKeyId = appKeyId;
          req.headers.appKeySecret = appKeySecret;
          req.headers.securityCode = securityCode;
            return req;
        },
        error => {
            return Promise.reject(error);
        }
    );
    //请求响应拦截，401则调到登录页
    axios.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            if((error+'').indexOf('timeout') != -1) {
                //alert('网络请求超时')
            }
            if (error.response) {
                switch (error.response.status) {
                    case 401:
                        //alert("服务正在升级，请稍后再试");
                        break;
                    case 500:
                        //alert('后台接口报错');
                        break;
                    default:
                        //alert('其他')
                        break;
                }
            }
            return Promise.reject(error); // 返回接口返回的错误信息
        }
    );
const post=(url,data)=>{
  if(typeof data!=='string'){
    data=qs.stringify(data);
  }

  return axios({
    method:'post',
    url:qhost+url,
    data
  });
};

//json传参
const json=(url,data)=>{
  //兼容ie8,axios在ie8下content-type设置不成功且会把headers置为null
  return axios({
    method:'post',
    url:url.indexOf('http:')!=-1?url:qhost+url,
    data
  });/*new Promise((resolve,reject)=>{
    $.ajax({
      method:'post',
      url:qhost+url,
      data:JSON.stringify(data),
      contentType:"application/json; charset=UTF-8",
      success:function(res){
        resolve({data:res});
      },
      error:function(error){
        reject(error);
      },
    });
  });*/
};

const get=(url)=>{
  return axios.get(qhost+url).then(data=>data.data);
};

module.exports={
  post,
  get,
  json
};