function randomWord(randomFlag: boolean, min: number, max: number = 15) {
  let str = ''
  let range = min
  const arr = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
  ]
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    const pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}

const encodeStr = (str: string, strv = '') => {
  const NUM = 2
  const front = randomWord(false, 8)
  const middle = randomWord(false, 8)
  const end = randomWord(false, 8)

  const str1 = str.substring(0, NUM)
  const str2 = str.substring(NUM)

  if (strv) {
    const strv1 = strv.substring(0, NUM)
    const strv2 = strv.substring(NUM)
    return [front + str2 + middle + str1 + end, front + strv2 + middle + strv1 + end]
  }

  return front + str2 + middle + str1 + end
}

const decodeOne = (str: string) => {
  const str1 = str.substring(str.length - 10, str.length - 8)
  const str2 = str.substring(8, str.length - 18)
  return str1 + str2
}

const decodeStr = (encoded: string | [string, string]) => {
  if (Array.isArray(encoded)) {
    return [decodeOne(encoded[0]), decodeOne(encoded[1])]
  }
  return decodeOne(encoded)
}

/** 判断是否为 encodeStr 加密后的字符串（长度>=26） */
const isEncoded = (str: string) => str && str.length >= 26

/** 解密或返回原值（兼容未加密的旧数据） */
export const decodeIfEncoded = (str: string): string => (isEncoded(str) ? decodeOne(str) : str)

/** 脱敏：papers 保留前2位、后2位 */
export const maskPapers = (str: string) => {
  if (!str) return str
  if (str.length <= 4) return str
  return str.substring(0, 2) + '*'.repeat(str.length - 4) + str.substring(str.length - 2)
}

/** 脱敏：phone 保留前3位、后4位 */
export const maskPhone = (str: string) => {
  if (!str) return str
  if (str.length <= 7) return str
  return str.substring(0, 3) + '*'.repeat(str.length - 7) + str.substring(str.length - 4)
}

/** 列表显示：papers 解密后脱敏 */
export const getStaffDisplayPapers = (val: string) => maskPapers(decodeIfEncoded(val || ''))

/** 列表显示：phone 解密后脱敏 */
export const getStaffDisplayPhone = (val: string) => maskPhone(decodeIfEncoded(val || ''))

export default encodeStr
export { decodeStr }
