import api from './request';
import { Modal } from 'antd';
const axios=require('axios');
axios.defaults.baseURL = 'http://192.168.2.237:8871';//'http://192.168.2.237:8871/';
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
const post=(url,data)=>{
    return axios({
        method:'post',
        url:url,
        data
    });
};
const xPost=(url,data)=>{
    let param = new URLSearchParams();
    for(let i in data){
        param.append(i,data[i]);
    }
    return axios({
        method:'post',
        contentType:'application/x-www-form-urlencoded',
        url:url,
        data:param
    });
};
// 导出
const expJson = (url,data) =>{
    return axios({
        method:'post',
        url,
        data,
        contentType: "application/vnd.ms-excel;charset=UTF-8" ,
        responseType: 'blob' //必须添加，否则会乱码
    });
}

const get=(url,data)=>{
    return axios({
        method:'get',
        url:url,
        data
    });
};

function interceptors(){
//拦截所有请求添加token
    axios.interceptors.request.use(function (config) {
        const tokenStr = localStorage.getItem('token');
        const sysId = localStorage.getItem('systemId');
        const hisId = localStorage.getItem('hospitalId');
	    const isOverTime = localStorage.getItem("overTime");
        if(isOverTime){
		  config.cancelToken = source.token;
		  return config;
        }
        if (tokenStr) {
            (config.headers.Authorization = `Bearer ${tokenStr}`);
            sysId&&(config.headers.softwareId=sysId);
            hisId&&(config.headers.hospitalId=hisId);
            return config;
        } else {
            return config;
        }
    }, function (error) {
        return Promise.reject(error);
    });
    //拦截响应
    axios.interceptors.response.use(function (res) {
        const code = (res.data||{}).code;
        if (code===401||code===403) {   //401/403返回登录
            localStorage.removeItem("token");
            localStorage.removeItem("systemId");
            localStorage.removeItem("hospitalId");
            localStorage.removeItem("software");
		    const isOverTime = localStorage.getItem("overTime");
		    if(!isOverTime){
			  /*   console.log(444,res)
			   const msg = res.data.message;
			   /*Modalonfirm({
				 title:'提示',
				 content:msg||`登录信息失效，请重新登录`,
				 footer:`<Button key="submit" type="primary" onClick={()=>{ window.location = '/';}}>知道了</Button>`,
				 /!*onOk:function(){
				   window.location = '/';
				 }*!/
			   })*/
			  //message.error("登录信息失效，请重新登录");
            }
            //标记登录失效被退出，后面的请求不发送/不显示相应消息
            localStorage.setItem("overTime",1);
            //localStorage.removeItem("hospitalId");
            window.location = '/';
        }else{
		  localStorage.removeItem("overTime");
           return res;
        }
    }, function (error) {
        return Promise.reject(error);
    });
}

const obj = {
    post,
    xPost,
    get,
    api,
    interceptors
};
export default obj;