import api from './request';
import { getCookie,setCookie } from '@utils/index'
import {message} from 'antd'
const axios=require('axios');
axios.defaults.baseURL = 'http://192.168.2.237:8871';//'http://192.168.2.237:8871/';
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 (req) {
        const tokenStr = localStorage.getItem('token');
        const sysId = getCookie('systemId');
        const hisId = getCookie('hospitalId');
        const isOverTime = localStorage.getItem("overTime");
        if (tokenStr) {
            (req.headers.Authorization = `Bearer ${tokenStr}`);
            sysId&&(req.headers.softwareId=sysId);
            hisId&&(req.headers.hospitalId=hisId);
            return req;
        } else {
            return req;
        }
    }, 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");
		    setCookie();
            //标记登录失效被退出，后面的请求不发送/不显示相应消息
            localStorage.setItem("overTime",1);
            //localStorage.removeItem("hospitalId");
            message.error("登录信息失效，请重新登录");
            window.location = '/';
        }else{
            return res||{data:null};
        }
    }, function (error) {
        return Promise.reject(error);
    });
}

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