import dayjs from 'dayjs'
import {AgreementType} from "@/core/libs/enums";
export const handleCall = (phone: string) => {
  uni.makePhoneCall({ phoneNumber: phone }).then()
}
/**
 * 预览图片
 */
export const previewImage = (current: number, urls: string[]) => {
  uni
    .previewImage({
      current,
      urls,
    })
    .then()
}
/**
 * 打开位置
 */
export const openLocation = (options: Omit<UniNamespace.OpenLocationOptions, 'success'>) => {
  uni.openLocation({
    ...options,
    success: function () {
      console.log('success')
    },
    fail: (fail) => {
      console.log(fail)
    },
  })
}
export const isImageOrVideo = (url) => {
  const ext = url.split('.').pop().toLowerCase()
  if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext)) {
    return 'image'
  } else if (['mp4', 'avi', 'mov', 'mkv', 'webm', 'flv'].includes(ext)) {
    return 'video'
  } else {
    return 'unknown'
  }
}
export const toast = (
  msg: string,
  icon: 'none' | 'success' | 'loading' | 'error' | 'fail' | 'exception' = 'none',
) => {
  uni.showToast({ title: msg, icon }).then()
}
export const requestToast = async <T>(
  func: () => Promise<IResData<T>>,
  options: {
    error?: boolean
    errorTitle?: string
    success?: boolean
    successTitle?: string
    duration?: number
  } = {
    error: true,
  },
) => {
  const { code, data, msg } = await func()
  const duration = options.duration || 3000
  if (code === 0 && options.success) {
    await uni.showToast({
      title: options.successTitle,
      icon: 'none',
      duration,
    })
  }
  if (code !== 0 && options.error) {
    await uni.showToast({
      title: options.errorTitle || msg,
      icon: 'none',
      duration: 5000,
    })
  }
  return { code, data, msg, duration }
}

export const getActivityStatus = (startAt: string | number, endAt: string | number) => {
  const now = new Date()
  if (dayjs(now).isBefore(dayjs(startAt))) {
    return 'waiting'
  } else if (dayjs(now).isAfter(dayjs(startAt)) && dayjs(now).isBefore(dayjs(endAt))) {
    return 'running'
  } else {
    return 'overdue'
  }
}
export const getActivityStatusText = (startAt: string | number, endAt: string | number) =>
  ({ running: '报名中', waiting: '未开始', overdue: '已结束' })[getActivityStatus(startAt, endAt)]
export const getActivityStatusButtonText = (startAt: string | number, endAt: string | number) =>
  ({ running: '立即报名', waiting: '查看详情', overdue: '查看详情' })[
    getActivityStatus(startAt, endAt)
  ]
export const getCountsArr = (data, imgWidth, imgHeight) => {
  let r = 1
  let g = 1
  let b = 1
  // 获取所有像素的累加值
  for (let row = 0; row < imgHeight; row++) {
    for (let col = 0; col < imgWidth; col++) {
      if (row === 0) {
        r += data[imgWidth * row + col]
        g += data[imgWidth * row + col + 1]
        b += data[imgWidth * row + col + 2]
      } else {
        r += data[(imgWidth * row + col) * 4]
        g += data[(imgWidth * row + col) * 4 + 1]
        b += data[(imgWidth * row + col) * 4 + 2]
      }
    }
  }
  // 求rgb平均值
  r /= imgWidth * imgHeight
  g /= imgWidth * imgHeight
  b /= imgWidth * imgHeight
  // 四舍五入
  r = Math.round(r)
  g = Math.round(g)
  b = Math.round(b)
  return [r, g, b].join(',')
}
/**
 * 对象转二维码参数
 */
export const toQrCodeString = (type: string, options: Record<string, any>) => {
  if (!options || typeof options !== 'object') {
    return ''
  }
  let str = `${type}:`
  for (const key in options) {
    str += `${key}:${options[key]};`
  }
  return `${str};`
}
/**
 * 二维码参数转对象
 */
export const qrCodeString2Object = (str: string): Record<string, any> => {
  if (!str || typeof str !== 'string') {
    return {}
  }
  const [type, ...options] = str.split(':')
  const obj = {} as Record<string, any>
  for (const item of options.join(':').split(';' as const)) {
    const [key, value] = item.split(':')
    if (key && value) {
      obj[key] = value
    }
  }
  return { type, options: obj }
}
export const validate = (
  form,
  rules: { [key: string]: { required?: boolean; message?: string; pattern?: RegExp }[] },
) => {
  for (const field in rules) {
    for (const rule of rules[field]) {
      if (rule.required && !form[field]) {
        uni
          .showToast({
            title: rule.message,
            icon: 'none',
            duration: 2000,
          })
          .then()
        return false
      }
      if (rule.pattern && !rule.pattern.test(form[field])) {
        uni
          .showToast({
            title: rule.message,
            icon: 'none',
            duration: 2000,
          })
          .then()
        return false
      }
    }
  }
  return true
}

// 浏览时长 小于60秒，显示秒 大于60秒小于1小时，显示分钟 大于1小时小于1天，显示x小时x分钟 大于1天，显示x天x小时x分钟
export const formatDuration = (duration: number) => {
  if (duration < 60) {
    return `${duration}秒`
  } else if (duration < 3600) {
    return `${Math.floor(duration / 60)}分钟`
  } else if (duration < 86400) {
    return `${Math.floor(duration / 3600)}小时${Math.floor((duration % 3600) / 60)}分钟`
  } else {
    return `${Math.floor(duration / 86400)}天${Math.floor((duration % 86400) / 3600)}小时${Math.floor(
      (duration % 3600) / 60,
    )}分钟`
  }
}
export const toContentHtml = async (option: { title: string; type: AgreementType }) => {
  await uni.navigateTo({
    url: `/pages/common/content-html/index?title=${option.title}&type=${option.type}`,
  })
}
