import Cookies from 'js-cookie'
import CryptoJS from 'crypto-js'
import $ from 'jquery'

const TokenKey = 'token'
const keyWords = 'toflysxgk'
// 获取token
export function getToken() {
  return Cookies.get(TokenKey)
}

// 设置token
export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

// 删除token
export function removeToken() {
  return Cookies.remove(TokenKey)
}

// 获取username
export function geteSessionStorage(key) {
  return sessionStorage.getItem(key)
}

// 设置username
export function setSessionStorage(key, name) {
  return sessionStorage.setItem(key, name)
}

// 删除username
export function removeSessionStorage(key) {
  return sessionStorage.removeItem(key)
}
/**
  * DES加密、解密
  * @param data 信息
  * @param isdes 加密(true)、解密(false)
  * @param nullCheck 是否替换空值
*/
export function desCodeConvert(data: string, isdes: boolean, nullCheck: boolean = false) {
  // debugger;
  const key = keyWords;
  try {
    if (isdes) {
      if ($.trim(data) === "") return "";
      const keyHex = CryptoJS.enc.Utf8.parse(key);
      const encrypted = CryptoJS.DES.encrypt(data, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      });
      //16进制字符串
      const result = encrypted.ciphertext.toString();
      return result;

    } else if (!isdes) {
      if ($.trim(data) === "") {
        if (nullCheck) {
          return setNullAndUndefined(data);
        }
        return "";
      }
      var keyHex = CryptoJS.enc.Utf8.parse(key);
      var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Hex.parse(data)//hex 16进制字符串转化为字节数组
      }
        , keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      });
      const result = decrypted.toString(CryptoJS.enc.Utf8);
      return result
    }
  } catch (error) {
    console.log(error);
    return "";
  }

}
/**
     * 本方法用于对列表输出的空值的统一设置（传入值为null、undefined、""的统一设置），目前统一设置为--
     * @param input 判断的输入
     * */
function setNullAndUndefined(input, type?) {
  if (input === null && type === 'user') return "本系统创建";
  if (input === null || input === undefined || input === "" || (input + "").toLowerCase() === "null" || (input + "").toLowerCase() === "undefined") {
    return "/"
  } else {
    return input
  }
}

