import Cookies from 'js-cookie'
import axios from 'axios'
import { MessageBox } from 'element-ui'
import { message } from '@/utils/resetMessage';
import store from '../store'


const TokenKey = 'Admin-Token'
const RequestIdKey = 'requestId'
const ExpireKey = 'expire'   //过期时间
const ExpireTime = 60 * 8    //分
Date.prototype.format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month
    "d+": this.getDate(),    //day
    "h+": this.getHours(),   //hour
    "m+": this.getMinutes(), //minute
    "s+": this.getSeconds(), //second
    "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
    "S": this.getMilliseconds() //millisecond
  }
  if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
    (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o) if (new RegExp("(" + k + ")").test(format))
    format = format.replace(RegExp.$1,
      RegExp.$1.length == 1 ? o[k] :
        ("00" + o[k]).substr(("" + o[k]).length));
  return format;
}



export function getToken() {
  let now = new Date().format('yyyy-MM-dd hh:mm')
  let expire = Cookies.get(ExpireKey)

  if (expire < now) {
    Cookies.set(ExpireKey, now)
    var service = axios.create({
      baseURL: process.env.VUE_APP_BASE_API,
      timeout: 10000 // request timeout
    })
    service.interceptors.request.use(
      config => {
        config.headers['Authorization'] = Cookies.get(TokenKey)
        config.headers['x-request-id'] = getRequestId()
        return config
      },
      error => {
        console.log(error)
        return Promise.reject(error)
      }
    )
    service.interceptors.response.use(
      response => {
        const res = response.data
        if (res.code === 1001) {
          MessageBox.confirm(res.msg, 'token刷新异常', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            //重置TOKEN
            store.dispatch('user/resetToken', res.data).then(() => {
              //重新载入
              location.reload()
            })
          })

          return Promise.reject(new Error(res.msg || 'Error'))
        } else {
          return res
        }
      },
      error => {
        console.log('err' + error) // for debug
        message({
          message: error.message,
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(error)
      }
    )
    service.get('/refToken')
      .then(function (response) {
        setToken(response.data)
      })
      .catch(function (error) {
        console.log(error);
      });


  }
  if (store != undefined) {
    return store.state.user.token
  }

  return Cookies.get(TokenKey)
}

export function setToken(token) {
  let curTime = new Date();
  let now = new Date(curTime.setMinutes(curTime.getMinutes() + ExpireTime)).format('yyyy-MM-dd hh:mm');
  Cookies.set(ExpireKey, now)
  store.state.user.token = token
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}



//uuid
export function getRequestId() {
  if (Cookies.get(RequestIdKey)) {
    return Cookies.get(RequestIdKey)
  } else {
    let key = uuid(16, 16)
    Cookies.set(RequestIdKey, key)
    return
  }

  function uuid(len, radix) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [], i;
    radix = radix || chars.length;

    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  }

}