/**
 * Created by supervisor on 2017/11/3.
 */
// import Vue from 'vue'
import axios from 'axios'
// import qs from  'qs'
import store from '../store'
import {Message, MessageBox, Loading} from 'element-ui';
import router from '../router'
import {baseUrl} from './env'
import MyLocalStorage from './myLocalStorage'
// Vue.use($msg)

//axios 拦截器 请求时的拦截
axios.interceptors.request.use(config=>{
  // 发送请求之前做一些处理
  store.commit('UPDATE_LOADING',true) //显示loading
  // config.headers = {
  //   'Content-Type': 'application/json'
  // };
  return config
},error => {
  // 当请求异常时做一些处理
  return new Promise.reject(error)
})
// 响应时拦截
axios.interceptors.response.use(response=>{
  // 返回响应时做一些处理
  return response
},error=>{
  // 当响应异常时做一些处理
  return Promise.resolve(error.response)
})
// let isOpen=false;
function errorState(status, data) {
  store.commit('UPDATE_LOADING',false)
  if(status === 500 && data.message.indexOf("token invalid")!==-1){
    // if(status == 500 && data == "sessionTimeOut"){
    if(store.state.isOpen){
      return ;
    }
    store.commit('setIsOpen',true)
    MessageBox.alert('您的登录过期，请重新登录!', '提示', {
      confirmButtonText: '确定',
      callback: () => {
        //清除用户信息
        localStorage.removeItem('backToken')
        localStorage.removeItem('userId')
        router.push({path: '/',query: {redirect: router.history.current.fullPath}})
      }
    });
  }else if(status===401){
    MessageBox.alert('您的用户权限已被禁用，请联系管理员!', '提示', {
      confirmButtonText: '确定',
      callback: () => {
        //这个时候点击确定后清除用户信息
        localStorage.removeItem('backToken')
        localStorage.removeItem('userId')
        router.push({path: '/',query: {redirect: router.history.current.fullPath}})
        store.commit('isAdminInfo',false);
      }
    });
  } else if (status === 500 && data.message.indexOf("not have permission") !== -1) {
    // router.push({path: 'page403'})
    Message.error("抱歉，你无权访问该页面!")
  }else if (!data) {
    Message.error("网络出小差咯~")
  }
}
function successState(res) {
  store.commit('UPDATE_LOADING',false) //隐藏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!=""){
    // Authorization
    if(opts.authType==="back"){
      authToken=localStorage.getItem('backToken');
    }else if(opts.authType==="front"){
      authToken = localStorage.getItem("token") || MyLocalStorage.Cache.get('token');
    }
    httpDefaultOpts.headers["Authorization"]=authToken
  }
  if(opts.method==='get'){
    delete httpDefaultOpts.data
    httpDefaultOpts.params.timestamp_static = new Date().getTime();
    // httpDefaultOpts.params.roleId = localStorage.getItem('roleId');
    // httpDefaultOpts.params.bankBranchId = localStorage.getItem('bankBranchId');
  }else{
    delete httpDefaultOpts.params
    if(file){
      httpDefaultOpts.data=data;
      // httpDefaultOpts.headers["X-Requested-With"]="multipart/form-data";
    }
  }

  let promise = new Promise(function (resolve,reject) {
    let loadingInstance = Loading.service({
      fullscreen: true,
      lock: true,
      background: 'rgba(0,0,0,.5)',
      text: 'Loading',
      spinner: 'el-icon-loading'
    })
    let markIndex= setTimeout(function () {
      loadingInstance.close();
    },10000)
    axios(httpDefaultOpts).then((res)=>{
      loadingInstance.close();
      clearTimeout(markIndex)
      successState(res)
      if(res){
        resolve(res)
        errorState(res.status, res.data)
      }
    }).catch((response)=>{
      loadingInstance.close();
      clearTimeout(markIndex)
      console.log("catch")
      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){
          Message.error(response.response.data.message)
        }else{
          Message.error("操作失败!")
        }
      }
    })
  })
  return promise
}

export  default httpServer
