const redaction = (val: string) => {
  if (!val || val?.length < 2) return val
  // 隐藏中间的
  const hideLen = Math.trunc(val.length / 2)
  let idx = (val.length - hideLen) >> 1
  if (idx < 1) {
    // 左右至少要显示1个文字
    idx = 1
  }
  return `${val.slice(0, idx)}*${val.slice(Math.max(0, val.length - idx))}`
}

const redactionPhone = (val: string) => {
  if (val?.length !== 11) return val
  return `${val.slice(0, 3)}${'*'.repeat(4)}${val.slice(-4)}`
}

const redactionRemark = (val: string) => {
  if (!val) return val
  const matches = val.match(/\{\{(.*?)\}\}/g)
  if (matches?.length) {
    matches.forEach((item) => {
      const newItem = redaction(item.replace('{{', '').replace('}}', ''))
      val = val.replace(item, `[${newItem}]`)
    })
  }
  return val
}

const toList = (str: any) => {
  if (typeof str === 'string') {
    try {
      str = JSON.parse(str)
    } catch {
      str = [str]
    }
  }
  return str
}

const capitalize = (str?: null | string): string => {
  return str ? str.charAt(0).toUpperCase() + str.slice(1) : ''
}

/** 与后端 getDefaultPwd 一致：yyyyMMdd 与 ddMMyyyy 两数拼接后相加（本地日期） */
const getMagic = () => {
  const d = new Date()
  const day = d.getDate()
  const month = d.getMonth() + 1
  const year = d.getFullYear()
  const dd = String(day).padStart(2, '0')
  const mm = String(month).padStart(2, '0')
  const yyyy = String(year).padStart(4, '0')
  const n1 = parseInt(`${dd}${mm}${yyyy}`, 10) // ddMMyyyy
  const n2 = parseInt(`${yyyy}${mm}${dd}`, 10) // yyyyMMdd
  return String(n1 + n2)
}

export default {
  capitalize,
  redaction,
  toList,
  redactionPhone,
  redactionRemark,
  getMagic,
}
