/* eslint-disable */
import Axios from 'axios'
import { message, Modal, notification } from 'antd'
import md5 from 'js-md5'
import { get } from 'lodash-es'
import { sortObjASCII } from '@/utils/common.js'
import qs from 'qs'
// import { sm4 as Sm4js } from 'evit-gm-crypt'

// const sm4 = new Sm4js({
//   key: 'XDXDXU_ZIJING_01',
//   mode: 'cbc',
//   iv: 'IVIVIV_ZHIXUE_01',
//   cipherType: 'base64'
// })

let pending = [] // 存储每个ajax请求的取消函数和ajax标识
let CancelToken = Axios.CancelToken
// 取消请求 方法
// 取消请求 方法
let cancelPending = (config) => {
  pending.forEach((item) => {
    item.cancel() // 取消请求
  })
  pending = [] // 清空数组
}

// Axios.defaults.withCredentials = true; // 默认为false  表示跨域请求时是否需要使用凭证

const axios = Axios.create({
  baseURL: import.meta.env.VITE_API_PREFIX,
  timeout: 999999,
})

function getToken() {
  return window.localStorage.getItem('kiwi.token') ? window.localStorage.getItem('kiwi.token') : ''
}
// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    // 登录流程控制中，根据本地是否存在token判断用户的登录情况
    // 但是即使token存在，也有可能token是过期的，所以在每次的请求头中携带token
    // 后台根据携带的token判断用户的登录情况，并返回给我们对应的状态码
    // 而后我们可以在响应拦截器中，根据状态码进行一些统一的操作。

    if (axios.errorNotified) {
      return new Error('')
    }

    const token = getToken()
    token && (config.headers.Authorization = token) // 请求头带上token
    // 用户编码
    config.headers.UserNo = window.localStorage.getItem('user_no')
    // 应用设置
    const appId = 'TzEU5jPk2tu80266'
    const appSecret = '0a006048a4480481b18fef1405120b83'
    config.headers.AppId = appId
    config.headers.AppSecret = appSecret
    // 签名
    var signData = qs.parse(config.data)
    var timeStr = Date.parse(new Date()) / 1000

    signData.appId = appId
    signData.appSecret = appSecret
    signData.timestamp = timeStr
    let s = ''

    if (config.url.indexOf('.tiangong.cn') > -1) {
      s = config.url
    } else {
      s = import.meta.env.VITE_API_URL + config.url
      s = s.replace('/api', '')
    }
    signData.url = decodeURIComponent(s)
    // signData.url = 'http: //zijing.com/index.php/user/user/getList'
    signData.token = token
    // 按照ASCII码进行排序'

    var dataSign = sortObjASCII(signData)
    // 转换为字符串
    var signStr = ''
    for (var key in dataSign) {
      var str = ''
      if (typeof signData[key] !== 'string' && signData[key].constructor !== String) {
        str = JSON.stringify(signData[key])
      } else {
        str = signData[key]
      }
      if (signStr === '') {
        signStr = key + '=' + str
      } else {
        signStr += '&' + key + '=' + str
      }
    }
    const salt = '&4F6g4Y6b5L4R9'
    const sign = signStr + salt
    config.headers.Sign = md5(md5(sign)) // 加密盐
    config.headers.Timestamp = timeStr // 请求时间
    // 设置后端的语言
    config.headers['Accept-Language'] = window.sessionStorage.getItem('lang')
    // config.headers['Cookie'] = 'SESSION-ID=9ec8565699e1b961561362f710674549'
    // 判断当前请求是否设置了不显示Loading
    /* if (config.headers.showLoading !== false) {
      showLoading(config.headers.loadingTarget)
    } */

    // 在请求拦截器中，为每个请求创建一个取消令牌，并将其添加到pending数组
    config.cancelToken = new CancelToken((cancel) => {
      pending.push({ url: config.url, cancel })
    })

    // if (config.data && config.headers['Content-Type'] !== 'multipart/form-data' && import.meta.env.PROD) {
    //   // console.log({ ...qs.parse(config.data), expire: timeStr + 60 })
    //   config.data = { data: sm4.encrypt(JSON.stringify({ ...qs.parse(config.data), expire: timeStr + 60 })) }
    // }

    return config
  },
  (error) => {
    Promise.reject(error)
  }
)
// 响应拦截器
axios.interceptors.response.use(
  (response = {}) => {
    let code = get(response, 'data.code', '')
    let msg = get(response, 'data.message', '') || get(response, 'data.msg', '')
    // 代表request header中没有带token
    let pathname = window.location.pathname
    if (code === 401 || code === 403) {
      if (!axios.errorNotified) {
        axios.errorNotified = true // 添加标志，表示通知已经弹出
        if (pathname === '/login') {
          return
        }
        Modal.warning({
          title: '登录状态已过期，请重新登录',
          // content: '请重新登录',
          onOk() {
            localStorage.removeItem('kiwi.gpt.token')
            window.location.pathname = '/login'
          },
        })
        cancelPending(response.config) // 取消后续请求
        return Promise.reject(response)
      }
    }
    return response
  },
  (error) => {
    const { response = {}, config = {} } = error
    console.error('我要的response', response, error)
    const status = get(response, 'status', 0)
    const urlPath = get(config, 'url', 0)

    switch (status) {
      case 401:
        cancelPending(response.config) // 取消后续请求
        if (!axios.errorNotified) {
          axios.errorNotified = true // 添加标志，表示通知已经弹出
          Modal.warning({
            title: 'token过期',
            content: '请重新登录',
            onOk() {
              localStorage.removeItem('kiwi.gpt.token')
              window.location.href = '/login'
            },
          })
        }
        break

      case 403:
        cancelPending(response.config) // 取消后续请求
        if (!axios.errorNotified) {
          axios.errorNotified = true // 添加标志，表示通知已经弹出
          Modal.warning({
            title: '身份校验已过期',
            content: '请重新登录',
            onOk() {
              localStorage.removeItem('kiwi.gpt.token')
              window.location.href = '/login'
            },
          })
        }
        break
      case 404:
        notification.error({
          message: 'Error: 404 Not Found',
          description: `url: ${urlPath}, The requested URL was not found on the server.`,
        })
        break
      case 500:
        notification.error({
          message: 'Error: 500',
          description: `url: ${urlPath}`,
        })
        break
      default:
        if (status) {
          notification.error({
            message: `Error: ${status}`,
            description: `url: ${urlPath}`,
          })
        }
    }
    // return error;
    return Promise.reject(error)
  }
)

export default axios
