import type { CustomRequestOptions } from '@/http/types'
import CacheManager from '@/utils/CacheManager'
import { ContentTypeEnum } from './enum'

const sm2Key = import.meta.env.VITE_SM2_KEY

/**
 * 获取请求头
 */
export function getHeader(options: CustomRequestOptions) {
  // 获取token
  const token = CacheManager.get('token')
  const { noToken, contentTypeUrlEncoded, header } = options

  // 自定义header
  if (header && Object.keys(header).length > 0) {
    return { ...header }
  }

  let _header = {}
  if (!noToken && token) {
    _header = {
      Authorization: token,
    }
  }
  _header = {
    ..._header,
    'Content-Type': contentTypeUrlEncoded ? ContentTypeEnum.FORM_URLENCODED : ContentTypeEnum.JSON,
  }
  return _header
}

/**
 * 加密query参数
 */
export function encryptQuery(options: CustomRequestOptions) {
  const { query } = options
  // 如果query存在且不是空对象，遍历对象的值进行SM2加密
  // if (query && Object.keys(query).length > 0) {
  //   for (const key in query) {
  //     if (Object.prototype.hasOwnProperty.call(query, key)) {
  //       query[key] = SM2.sm2Encrypt(query[key], sm2Key)
  //     }
  //   }
  // }
  return query
}

/**
 * 加密data参数
 */
export function encryptData(options: CustomRequestOptions) {
  const { data, contentTypeUrlEncoded } = options
  let _data: any = null

  if (data) {
    // _data = SM2.sm2Encrypt(JSON.stringify(data), sm2Key)
    _data = JSON.stringify(data)
  }

  if (contentTypeUrlEncoded && data) {
    const formData = new FormData()
    Object.keys(data).forEach((key) => {
      // const enKeyData = SM2.sm2Encrypt(data[key], sm2Key)
      const enKeyData = data[key]
      formData.append(key, enKeyData)
    })
    _data = formData
  }

  return _data
}
