import axios from 'axios';
import Vue from 'vue'
import router from '@/router.js';
axios.defaults.timeout = 1000000; //设置超时时长
axios.defaults.baseURL = '';

//http request 拦截器
axios.interceptors.request.use(
    config => {
        // const token = getCookie('名称');
        config.data = JSON.stringify(config.data);
        if (config.url.indexOf('coreapiscn') != -1) {//台湾接口
            if (localStorage.getItem('TWtoken')) {
                config.headers = {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem('TWtoken'),
                }
            } else if (localStorage.getItem('mobiletoken')) {
                config.headers = {
                    'Content-Type': 'application/json',
                    'Authorization': localStorage.getItem('mobiletoken')
                }
            }
        } else if (config.url.indexOf('api2') != -1) {//api2
            //var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Il9DSkFPdHlzWVZtNXhjMVlvSzBvUTdxeUJDUSJ9.eyJhdWQiOiI3MjY0MzcwNC1iMmU3LTRiMjYtYjg4MS1iZDU4NjVlN2E3YTUiLCJpc3MiOiJodHRwczovL2xvZ2luLnBhcnRuZXIubWljcm9zb2Z0b25saW5lLmNuLzQ4MDdlOWNmLTg3YjgtNDE3NC1hYTViLWU3NjQ5N2Q3MzkyYi92Mi4wIiwiaWF0IjoxNjIwNjMwMDI4LCJuYmYiOjE2MjA2MzAwMjgsImV4cCI6MTYyMDYzMzkyOCwiYWlvIjoiNDJKZ1lNanJtWEE3KzgvUENuM1dGZS9tdlgxaER3QT0iLCJhenAiOiJjNzMxN2Y4OC03Y2VhLTRlNDgtYWM1Ny1hMTYwNzFmN2I4ODQiLCJhenBhY3IiOiIxIiwib2lkIjoiZDQ5YmI3ODItNmRjMi00OTM5LTg2NzgtZDMzYzI2NzE5YmY5IiwicmgiOiIwLkFBQUF6LWtIU0xpSGRFR3FXLWRrbDljNUs0aF9NY2ZxZkVoT3JGZWhZSEgzdUlRQkFBQS4iLCJyb2xlcyI6WyJJRVMiXSwic3ViIjoiZDQ5YmI3ODItNmRjMi00OTM5LTg2NzgtZDMzYzI2NzE5YmY5IiwidGlkIjoiNDgwN2U5Y2YtODdiOC00MTc0LWFhNWItZTc2NDk3ZDczOTJiIiwidXRpIjoiU3RteEN5NHFsa0tCTTJwclFpTU5BUSIsInZlciI6IjIuMCJ9.mkFRLPF1T2w5uCcphKX7ZDKilIJjBoE8gw4yjK5Jffwmo434AS21s9NnLWRiAqVpMXordVPGHoAKwEfJFQ4xQWxTCyxLc9JAlONWKU7-AsjQK9if8edZqIbroh_jB0P7Sxz7UeGLBaNRxgF10_0Sr7Ew7npS4YksTqgbKDnxzYFrvRtxF5eAP3Uwix611qA0v10YJl6zsJ11J9N0_raRWoycdpI53aGBAICziWJsAyogwUdLCb2x-9BG4fQOMRR7eFnjReZ8r9E2G1xpwBvdiDUs-dZ-gVhp8gkAu5u9bUSLOJC6SUhAw97OIZvFPQh68qDxkR_wA2zREGHpxnpEQw";
            //IM header
            if ((config.url.indexOf('create') != -1 || config.url.indexOf('join') != -1) && localStorage.getItem('accessToken')) {
                config.headers['access_token'] = localStorage.getItem('accessToken')
                config.headers['Content-Type'] = 'application/json'
            } else {
                config.headers['Content-Type'] = 'application/json'
            }
        } else if (config.url.indexOf('messages') != -1) {
            console.log('进入发送消息头部')
            var UserID = JSON.parse(localStorage.getItem('user'))
            config.headers = {
                "Content-Type": "application/json",
                "X-Auth-UserID": UserID.sub,
                "X-Auth-Channel": localStorage.getItem('classNum'),
                
            }
        } else {
            if (localStorage.getItem('TMDtoken')) {
                if (config.url.indexOf('UploadDocument') != -1) {//上传接口
                    config.headers = {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': 'Bearer ' + localStorage.getItem('TMDtoken'),
                        'lang': localStorage.getItem('local')
                    }
                } else {
                    config.headers = {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem('TMDtoken'),
                        'lang': localStorage.getItem('local')
                    }
                }
            } else {
                config.headers = {
                    'Content-Type': 'application/json',
                    'Authorization': ""
                }
            }
        }
        //新增blob数据头部
        //if (localStorage.getItem('idToken')) {
        //    if (config.url.indexOf('parse-doc') != -1) {
        //        //console.log(localStorage.getItem('idToken'))
        //        //console.log(JSON.parse(localStorage.getItem('idToken')))
        //        config.headers['X-Auth-IdToken'] = localStorage.getItem('token_type') + localStorage.getItem('idToken')
        //        config.headers['Content-Type'] = 'application/json'
        //    }
        //}
        return config;
    },
    error => {
        return Promise.reject(err);
    }
);


//http response 拦截器
// axios.interceptors.response.use(
//   response => {
//     if (response.data.errCode == 2) {
//       router.push({
//         path: "/login",
//         querry: { redirect: router.currentRoute.fullPath }//从哪个页面跳转
//       })
//     }
//     return response;
//   },
//   error => {
//     if (401 === error.response.status) {
//       // localStorage.clear();
//       window.location.href = window.location.origin;
//       //alert("登录状态已过期！请重新登录！");
//     } else if (500 === error.response.status) {
//       //alert("服务器错误！");
//     } else {
//       return Promise.reject(error);
//     }
//   }
// )


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

export function fetch(url, params) {
    let data = {};
    data.method = url;
    data.params = params;
    data.lang = localStorage.getItem('local');
    return new Promise((resolve, reject) => {
        axios.get(url, data)
            .then(response => {
                resolve(response.data);
                //  this.$Message.success('数据访问成功！');
            })
            .catch(err => {
                reject(err);
                this.$Message.error('数据访问错误！');
            })
    })
}

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

export function post(url, params) {
    let data = {};
    data.method = url;
    data.params = params;
    data.lang = localStorage.getItem('local');
    return new Promise((resolve, reject) => {
        axios.post(url, params)
            .then(response => {
                resolve(response.data);
                // this.$Message.success('数据访问成功！');
            }, err => {
                reject(err);
                //this.$Message.error('数据访问错误！');
            })
    })
}
