import axios from 'axios'
import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import Qs from 'qs'
import { getToken, setToken } from '@/utils/auth'
import SM4 from './gmUtil'
import errorCode from '@/utils/errorCode'
import { refreshToken } from '@/api/login.js'

axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项,表示请求URL公共部分
  baseURL: process.env.VUE_APP_BASE_API,
  // 超时
  timeout: 100000
  // headers: { 'clientType': 'fy_authority' }
})
// let loadingInstance = ''
// request拦截器
service.interceptors.request.use(config => {
  // 请求开始 loading 开始
  /* const loadingCount = store.state.app.loadingCount
  console.log(loadingCount)
  if (loadingCount === 0) {
    loadingInstance = Loading.service({
      lock: true
    })
  }*/
  // store.dispatch('app/setLoadingCount', loadingCount + 1)
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false
  if (getToken() && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  // 参数发出前统一进行加密 白名单内的不进行加密
  /* console.log(config)
  if ((config.baseURL + config.url).indexOf('authority') < 0 && (config.baseURL + config.url).indexOf('internal') < 0) {
    console.log(config.params || config.data)
    if (config.params) {
      config.params = { sign: (new SM4(JSON.stringify(config.params)).encryptEcb()) }
    } else {
      if (config.data) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
        console.log(JSON.stringify(config.data))
        const temp = { sign: (new SM4(JSON.stringify(config.data)).encryptEcb()) }
        config.data = Qs.stringify(temp, { arrayFormat: 'indices', allowDots: true })
      }
    }
  }*/
  return config
}, error => {
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  /* // 判断 loading 状态
  const loadingCount = store.state.app.loadingCount
  const oneLessCount = loadingCount - 1
  if (oneLessCount === 0) {
    setTimeout(() => {
      loadingInstance.close()
    }, 300)
  }*/
  // store.dispatch('app/setLoadingCount', oneLessCount)
  // 未设置状态码则默认成功状态
  const code = res.data.code || 200
  // 获取错误信息
  const message = errorCode[code] || res.data.msg || res.data.message || errorCode['default']
  // status为401 code为e004则重新获取token
  if (code === 'E004') {
    const resConfig = res.config
    refreshToken({ token: getToken() }).then(res => {
      setToken(res.data)
      resConfig.baseURL = ''
      return service(resConfig)
    }).catch(error => {
      Message({
        message: '重新获取error失败',
        type: 'error',
        duration: 5 * 1000
      })
    })
  }
  if (code === 401) {
    Message({
      message: '用户不存在或密码错误',
      type: 'error'
    })
    // MessageBox.confirm(
    //   '登录状态已过期,您可以继续留在该页面,或者重新登录',
    //   '系统提示',
    //   {
    //     confirmButtonText: '重新登录',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }
    // ).then(() => {
    //   store.dispatch('LogOut').then(() => {
    //     location.reload() // 为了重新实例化vue-router对象 避免bug
    //   })
    // })
  } else if (code === 500 || code === 400) {
    const errMsg = res.data.data || res.data.message || res.data.msg
    Message({
      message: errMsg,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  } else if (code !== 200 && code !== 'E004') {
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject('error')
  } else if (code !== 'E004') {
    if (res.config.url.indexOf('downLoadSignaturesSample') > -1 || res.config.url.indexOf('downLoadSignatures') > -1) {
      return res
    } else {
      return res.data
    }
  }
},
error => {
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)
export default service