/** 2018/2/23 17:42
 *  作者:周志豪
 *  功能:封装请求方法
 *  备注:
 */

import axios from 'axios'
import qs from 'qs'
import { Notice } from 'iview'
Notice.config({
    duration: 3
});
//mock地址
const mockUrl = 'http://localhost:8898';
let domain = '';
const path = '/';//根据项目修改'/rest/'

if(process.env.NODE_ENV === "development"){
    //本地开发可以随意修改
    // domain = 'http://ohaotian.tydicdev.com:8084';
    domain = 'http://10.16.44.23:8080/demo';
}else{
    domain = '';
}
const serverUrl = domain + path;
//axios默认参数配置
axios.defaults.timeout = 1000 * 50;
//添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    if(config.method === "post") {
        config.data = qs.stringify(config.data);
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
        config.headers['X-Requested-With'] = 'XMLHttpRequest';
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});
//添加一个响应拦截器
axios.interceptors.response.use(function (res) {
    let data = res.data;
    return new Promise((resolve) => {
        if(data.code){
            if (data.code === '0') {
                resolve(data.data);
            }else{
                debugger;
                Notice.error({
                    title:'系统提示',
                    desc:data.message ? data.message :'网络繁忙！'
                });
            }
        }else{
            if (data.respCode === '0000') {
                resolve(data);
            }else{
                Notice.error({
                    title:'系统提示',
                    desc:data.respDesc ? data.respDesc :'网络繁忙！'
                });
            }
        }
    }).catch(error => {
        console.log(error);
    });
}, function (error) {
    const res = error.response;
    console.log(res);
    if(res.status === 401){//token失效状态码
        window.parent.postMessage('refresh','*');
    }else{
        return Promise.reject(error);
    }
});

export default function request(url,option) {
    let httpUrl;
    if(!option.noPrefix){
        httpUrl= option.mock ? mockUrl + url : serverUrl + url;
    }else{
        httpUrl= option.mock ? mockUrl + url : url;
    }
    let reqUrl = '';
    if(option.body.method === 'GET' && option.body.data){
        reqUrl = httpUrl + '?' + qs.stringify(option.body.data);
    }else{
        reqUrl = httpUrl;
    }
    const defaultOptions = {
        method:'POST',
        url:reqUrl
    };
    const newOptions = { ...defaultOptions, ...option.body };
    return axios({
        ...newOptions
    }).then(res => {
        return res
    })
}
