/**
 * Created by supervisor on 2017/11/3.
 */
import axios from 'axios'
import router from '../router'
import {baseUrl} from './env'
import {
    Toast
} from 'vant';
// Vue.use($msg)

//axios 拦截器 请求时的拦截
axios.interceptors.request.use(config => {
    // 发送请求之前做一些处理
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
    });
    return config
}, error => {
    // 当请求异常时做一些处理
    return new Promise.reject(error)
})
// 响应时拦截
axios.interceptors.response.use(response => {
    // 返回响应时做一些处理
    return response
}, error => {
    // 当响应异常时做一些处理
    return Promise.resolve(error.response)
})

function errorState(status, data) {
    Toast.clear() // 关闭 loading
    if (!data) {
        Toast.fail("网络出小差咯~")
    }
    if (status === 401) {
        Toast({
            message: '您的用户权限已被禁用，请联系管理员!',
            onClose: () => {
                //这个时候点击确定后清除用户信息
                sessionStorage.removeItem('backToken')
                sessionStorage.removeItem('userId')
                router.push({
                    path: '/',
                    query: {
                        redirect: router.history.current.fullPath
                    }
                })
            }
        });
    }
    if (status === 500 && data.message) {
        if(data.message.indexOf("token invalid") !== -1){
            Toast({
                message: '您的登录过期，将重新登录!',
                onClose: () => {
                    //清除用户信息
                    sessionStorage.removeItem('backToken')
                    sessionStorage.removeItem('userId')
                    router.push({
                        path: '/',
                        query: {
                            redirect: router.history.current.fullPath
                        }
                    })
                }
            });
        }
        if(data.message.indexOf("not have permission") !== -1){
            Toast.fail("抱歉，你无权访问该页面!")
        }else{
            Toast.fail(data.message)
        }
    } else {
        Toast.fail(data)
    }
}

function successState() {
    Toast.clear() //隐藏loading
}

const httpServer = (opts, data, file, timeout) => {
    //如果是不需要登录就可以访问的接口 需要设置opts.open
    let Public = {} //公共参数
    let httpDefaultOpts = {
        method: opts.method,
        url: baseUrl + opts.url,
        timeout: timeout ? timeout : 20000,
        params: Object.assign(Public, data),
        data: data,
        headers: opts.headers || {},
    };
    httpDefaultOpts.headers["Access-control-Allow-Origin"] = "*";
    httpDefaultOpts.headers["Access-Control-Allow-Headers"] = "content-type,x-requested-with";
    let authToken = "";
    if (opts.authType && opts.authType != "") {
        if (opts.authType === "back") {
            authToken =sessionStorage.getItem('token') || "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsInVzZXJfaWQiOiIxIiwiaXNzIjoiSUFUQSIsImV4cCI6MTYxNjY2NTkzOCwiaWF0IjoxNjE2NjUxNTM4fQ._nqZq0LMwkurIBKJtfX-imXLCxQSNwJ-ueGZ8iwW-0oAW880gY7PjNEfroYYQZ91v0u5yQb73Alzvy6EIp6GGg"
        } else if (opts.authType === "front") {
            authToken = sessionStorage.getItem("token");
        }
        httpDefaultOpts.headers["Authorization"] = authToken
    }
    if (opts.method === 'get') {
        delete httpDefaultOpts.data
        httpDefaultOpts.params.timestamp_static = new Date().getTime();
    } else {
        delete httpDefaultOpts.params
        if (file) {
            httpDefaultOpts.data = data;
        }
    }

    let promise = new Promise(function (resolve, reject) {
        Toast.loading({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        });
        let markIndex = setTimeout(function () {
            Toast.clear()
        }, 10000)
        axios(httpDefaultOpts).then((res) => {
            Toast.clear()
            clearTimeout(markIndex)
            if (res.status === 200) {
                successState(res)
                resolve(res)
            }else{
                errorState(res.status, res.data)
            }
        }).catch((response) => {
            Toast.clear()
            clearTimeout(markIndex)
            if (response && response.response && response.response.status && response.response.data) {
                errorState(response.response.status, response.response.data)
            }
            reject(response)
            if (response.response.data) {
                if (response.response.data.message) {
                    Toast.fail(response.response.data.message)
                } else {
                    Toast.fail("操作失败!")
                }
            }
        })
    })
    return promise
}

export default httpServer