/* eslint-disable */
// sd-skip-auto-import
import axiosDefault from 'axios'
import { sdLocalStorage, sdSessionStorage } from '@/common/services/storage-service'
const axios = axiosDefault.create()
axios.CancelToken = axiosDefault.CancelToken
axios.isCancel = axiosDefault.isCancel
function encrypt(word) {
  var key = window.CryptoJS.enc.Utf8.parse('abcdefgabcdefg12')
  var srcs = window.CryptoJS.enc.Utf8.parse(word)
  var encrypted = window.CryptoJS.AES.encrypt(srcs, key, {
    mode: window.CryptoJS.mode.ECB,
    padding: window.CryptoJS.pad.Pkcs7,
  })
  return encrypted.toString()
}
// 增加请求拦截，添加header
axios.interceptors.request.use((config) => {
  // 添加身份一致性校验 header参数
  config.headers['client-id'] = sdLocalStorage.getItem('WE.Client_ID')
  const loginName = sdSessionStorage.getItem('loginName')
  if (loginName) {
    config.headers.identity_code = encrypt(loginName)
    return config
  }

  return config
})
// 判断开关参数，如果未开，则不进行加密
if (
  sdLocalStorage.getItem('IS_OPEN_ENCRY') &&
  sdLocalStorage.getItem('IS_OPEN_ENCRY').toString() === 'true'
) {
  // 增加请求拦截，用于加密参数
  axios.interceptors.request.use((config) => {
    // 加密

    // 判断是否有params
    const params = []
    if (config.params) {
      for (const key in config.params) {
        if (config.params[key] !== undefined && config.params[key] !== null) {
          params.push(key + '=' + config.params[key])
        }
      }
    }
    const notdata = 'notdata'
    let url = config.url
    // 将params拼接到url上
    if (params.length > 0) {
      if (url.includes('?')) {
        url = url + '&' + params.join('&')
      } else {
        url = url + '?' + params.join('&')
      }
    }

    config.headers.encryptionParams = encrypt(
      `${config.method}$*$${url}$*$${config.data ? JSON.stringify(config.data) : notdata}`
    )

    return config
  })
}
export default axios
