import axios from 'axios';
// import Cookies from "js-cookie";
import {
    Message
} from 'element-ui';

axios.defaults.timeout = 5000;
axios.defaults.baseURL = 'http://whiteboardtest.ai160.com/';

/*** 
 * 
 * 复制于 https://www.cnblogs.com/ldlx-mars/p/7908950.html
 * 
*/

//http request 拦截器
axios.interceptors.request.use(
    config => {
        // const token = Cookies('token'); //注意使用的时候需要引入cookie方法，推荐js-cookie
        config.data = JSON.stringify(config.data);
        console.log(sessionStorage.getItem('uid'))
        const uid = sessionStorage.getItem('uid') ? sessionStorage.getItem('uid') : '';
        config.headers = {
            'Content-Type': 'application/json',
            'uid': uid,
        }
        // if(token){
        //   config.params = {'X-Token':token}
        // }
        return config;
    },
    error => {
        return Promise.reject(err);
    }
);

//http response 拦截器 暂时不用
axios.interceptors.response.use(
    response => {
        console.log('response',response)
        if (response.data.code == 402) {
            // router.push({
            //     path: "/login",
            //     // querry: {
            //     //     redirect: Router.currentRoute.fullPath
            //     // } //从哪个页面跳转
            // })
            Message.warning({
                message: '请登录',
                type: 'warning'
              });
            window.location.href = '/manageWeb/'
        }
        return response;
    },
    error => {
        return Promise.reject(error)
    }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url, params = {}) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
                params: params
            })
            .then(response => {
                resolve(response.data);
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url, data = {}) {
    console.log(data)
    return new Promise((resolve, reject) => {
        axios.post(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.patch(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
    return new Promise((resolve, reject) => {
        axios.put(url, data)
            .then(response => {
                resolve(response.data);
            }, err => {
                reject(err)
            })
    })
}