import axios from 'axios'
import router from '../router'
import CryptoJS from 'crypto-js'

let instance = axios.create({
  headers: {
    'content-type': 'application/json'
  }
})
// instance.defaults.baseURL = config.baseURL
instance.defaults.baseURL = process.env.REQUEST_URL
instance.defaults.withCredentials = true
// 加密开关
const jmKG = false
const jmKGDatas = false
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  if (config.baseURL !== '/apis') {
    config.baseURL = window.location.origin
  }
  let UserToken = localStorage.getItem('UserToken')
  var currentDate = new Date()
  var gmtTime = currentDate.toUTCString()
  let headerObj = config.headers
  headerObj['laravel-session-admin'] = UserToken
  headerObj['x-date'] = gmtTime
  headerObj['digest'] = ''
  if (jmKG == true) {
    headerObj['sign-key'] = '123'
  }
  if (jmKGDatas == true) {
    headerObj['jm-key'] = '123'
  }

  // post 请求加密
  // 仅对POST请求进行处理
  // 加密签名
  var current = new Date()
  var gmtTimes = current.toUTCString()
  if (jmKG == true) {
    let base64Body = JSON.stringify(config.data)
    if (base64Body == '{}' || base64Body == undefined) {
      base64Body = ''
    } else {
      base64Body = CryptoJS.enc.Base64.stringify(CryptoJS.SHA256(base64Body))
    }
    let confitUrl = config.url
    let firstChar = confitUrl.charAt(0)
    if (firstChar != '/') {
      confitUrl = '/' + confitUrl
    }
    let str = 'x-date: ' + gmtTimes + '\n@request-target: ' + config.method + ' ' + confitUrl + '\ndigest: ' + base64Body
    var base64Encrypted = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA512(str, '123456'))
    headerObj['signature'] = base64Encrypted
    headerObj['digest'] = base64Body
  }
  if (jmKGDatas == true) {
  // 对数据进行加密
    headerObj['x-date'] = gmtTimes
    let message = JSON.stringify(config.data)
    let secretKey = CryptoJS.enc.Base64.parse('kujqUijm2Msym4nRm3RHoas/BVKWhUP3QxChma0qMZA=')
    var ivSc = CryptoJS.enc.Base64.stringify(CryptoJS.lib.WordArray.random(16)) // 加密时用生成的都用这个
    let ivs = CryptoJS.enc.Base64.parse(ivSc) // 示例IV 只有加密用这个
    let encrypted = CryptoJS.AES.encrypt(message, secretKey, {
      iv: ivs,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    })
    let encryptedString = encrypted.toString()
    let macstr = ivSc + encryptedString
    let macjm = CryptoJS.HmacSHA256(macstr, secretKey).toString()
    let jsonDatas = {
      iv: ivSc,
      value: encryptedString,
      mac: macjm,
      tag: ''
    }
    let jsonStr = JSON.stringify(jsonDatas)
    let base64Json = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(jsonStr))
    let obj = {}
    obj.encrypt_str = base64Json
    config.url = config.url
    config.data = obj
    return config
  } else {
    config.headers = {
      'laravel-session-admin': UserToken
    }
    if (UserToken == undefined || undefined == '') {
      router.push({name: 'Login'})
    }
    return config
  }
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  if (response.status == '200') {
    if (response.data.code == '1001') {
      console.log('response.data', response.data)
    } else if (response.data.code === 401) {
      router.push({name: 'Login'})
    } else if (response.data.code === 500) {
      // Vue.prototype.$message.error('服务器异常，请联系管理员')
      // return
    }
  }
  if (jmKGDatas == true) {
    // 解密
    let datas = response.data.encrypt_str
    if (datas != undefined) {
      let data = CryptoJS.enc.Base64.parse(datas).toString(CryptoJS.enc.Utf8)
      let dataJson = JSON.parse(data)
      let dataValue = dataJson.value
      let ivs = CryptoJS.enc.Base64.parse(dataJson.iv)
      // 待解密的字符串，这里是使用CryptoJS的enc.Base64.stringify方法将字节转换成Base64字符串
      // 解密密钥
      let secretKey = CryptoJS.enc.Base64.parse('kujqUijm2Msym4nRm3RHoas/BVKWhUP3QxChma0qMZA=') // 密钥长度应与加密时的密钥长度一致
      // 解密
      let decrypted = CryptoJS.AES.decrypt(dataValue, secretKey, {
        iv: ivs,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
      })
      // 将解密后的数据转换成UTF-8字符串
      let decryptedStr = decrypted.toString(CryptoJS.enc.Utf8)
      let oldDatas = response.data
      let jsonDats = JSON.parse(decryptedStr)
      let mergedObject = Object.assign({}, oldDatas, jsonDats)
      return mergedObject
    } else {
      return response.data
    }
  } else {
    return response.data
  }
}, function (error) {
  // 对响应错误做点什么
  console.log('--- 401 res error response ---')
  if (error && error.response && error.response.status == '401') {
    console.log('error.response', error.response)
  }
  return Promise.reject(error)
})

export default instance