// 检测手机号是否合规
export function isValidPhoneNumber(phoneNumber: string): boolean {
  const regex = /^1[3456789]\d{9}$/
  return regex.test(phoneNumber)
}

// 检测银行卡是否合规
export function isValidBankCard(phoneNumber: string): boolean {
  const regex = /^([1-9]{1})(\d{15}|\d{18})$/
  return regex.test(phoneNumber)
}

// 检测邮箱是否合规
export function validateEmail(email: string): boolean {
  const regex: RegExp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
  return regex.test(email)
}

export function isValidChineseIDNumber(idNumber: string): boolean {
  // 正则表达式匹配身份证号码格式
  const idRegex =
    /^[1-9]\d{5}(19\d{2}|20\d{2})((0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])|[1-9]\d{3})(\d{3}[0-9Xx])$/

  if (!idRegex.test(idNumber)) {
    return false // 格式不正确
  }
  // 加权因子
  const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  // 校验位对应值
  const checkCodeMap = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  // 提取前17位数字
  const digits = idNumber.slice(0, 17)
  // 计算校验位
  let sum = 0
  for (let i = 0; i < 17; i++) {
    sum += parseInt(digits[i], 10) * weightFactors[i]
  }
  // 取余数
  const mod = sum % 11
  // 获取校验位
  const checkCode = checkCodeMap[mod]
  // 检查校验位是否匹配
  return idNumber[17].toUpperCase() === checkCode
}

// 防抖
export function debounce<T extends (...args: any[]) => void>(func: T, delay: number = 500): T {
  let timer: ReturnType<typeof setTimeout> | null = null
  return function (this: ThisParameterType<T>, ...args: Parameters<T>) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  } as T
}

/**
 * 把富文本格式化为纯内容
 * @param {*} str
 */
export const formatRichTxt = (str: string) => {
  let htmlStr = str.replace(/<.*?>/g, '')
  htmlStr = htmlStr.replace(/(\n)/g, '')
  htmlStr = htmlStr.replace(/(\t)/g, '')
  htmlStr = htmlStr.replace(/(\r)/g, '')
  htmlStr = htmlStr.replace(/<\/?[^>]*>/g, '')
  htmlStr = htmlStr.replace(/\s*/g, '')
  return htmlStr.replace(/&(lt|gt|nbsp|amp|quot);/gi, '')
}

/*
计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
默认单位km
*/
const EARTH_RADIUS = 6378.137 //地球半径
function rad(d: any) {
  return (d * Math.PI) / 180.0
}

export const getDistance = (lng1: any, lat1: any, lng2: any, lat2: any) => {
  const radLat1 = rad(lat1)
  const radLat2 = rad(lat2)
  const a = radLat1 - radLat2
  const b = rad(lng1) - rad(lng2)
  let s =
    2 *
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
          Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
      )
    )
  s = s * EARTH_RADIUS
  s = Math.round(s * 10000) / 10000
  return s //返回数值单位：公里
}

/**
 * canvas绘图相关，把文字转化成只能行数，多余显示省略号
 * @param {*} ctx   当前的canvas
 * @param {*} text  文本
 * @param {*} contentWidth  文本最大宽度
 * @param {*} lineNumber  显示几行
 */
export const transformContentToMultiLineText = (
  ctx: any,
  text: string,
  contentWidth: any,
  lineNumber: any
) => {
  const textArray = text.split('') // 分割成字符串数组
  let temp = ''
  let row = []
  for (let i = 0; i < textArray.length; i++) {
    if (ctx.measureText(temp).width < contentWidth) {
      temp += textArray[i]
    } else {
      i-- // 这里添加i--是为了防止字符丢失
      row.push(temp)
      temp = ''
    }
  }
  row.push(temp)
  // 如果数组长度大于2，则截取前两个
  if (row.length > lineNumber) {
    if (!lineNumber || lineNumber == 1) {
      row[0] += '...'
    } else {
      const rowCut = row.slice(0, lineNumber)
      const rowPart = rowCut[1]
      let test = ''
      const empty = []
      for (let a = 0; a < rowPart.length; a++) {
        if (ctx.measureText(test).width < contentWidth) {
          test += rowPart[a]
        } else {
          break
        }
      }
      empty.push(test) // 处理后面加省略号
      const group = empty[0] + '...'
      rowCut.splice(lineNumber - 1, 1, group)
      row = rowCut
    }
  }
  console.log('row', row)

  return row
}
