import { apiUrl } from '@/config'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { pageUrl } from './constants'
import { nextTick } from 'vue'
import { useSettingStore } from '@/stores'

/** 延迟执行 */
export const executeWithLoading = (fn: () => void, delay: number, title = '加载中') => {
  uni.showLoading({
    title: title,
    mask: true,
    success: () => {
      setTimeout(() => {
        fn()
        uni.hideLoading()
      }, delay)
    },
  })
}

/**
 * 获取支付页面URL
 * @param orderId 订单ID
 * @param orderPrice 支付价格
 * @returns
 */
export const getPayPageUrl = (orderId: string | number, orderPrice: string) => {
  return `${pageUrl['order-pay']}?orderId=${orderId}&payPrice=${orderPrice}`
}

/**
 * 过滤文本内容
 * @param content 内容
 * @returns
 */
export const cleanContent = (content: string): string => {
  // 去除HTML标签
  let result = content.replace(/<[^>]*>/g, '')
  // 去除URL链接
  result = result.replace(/https?:\/\/[^\s]+/g, '')
  // 去除邮箱地址
  result = result.replace(/[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}/g, '')
  result = result.replace(/\r\n|\n|\r/g, ' ')
  // 可选：去除连续的空格为一个空格
  result = result.replace(/\s\s+/g, '')
  return result.trim()
}

/**
 * 预览图片
 * @param url 预览的图片地址
 * @param urlArr 预览的图片地址数组
 */
export const previewImg = (url: string, urlArr: string[]) => {
  uni.previewImage({
    current: fullUrl(url),
    urls: arrayFullUrl(urlArr),
  })
}

/**
 * 批量获取完整url
 * @param arr
 * @returns
 */
export const arrayFullUrl = (arr: string[]) => {
  return arr.map((url) => fullUrl(url))
}

// 获取完整url地址
export const fullUrl = (relativeUrl: string, domain = '') => {
  relativeUrl = relativeUrl.replace(/\\/g, '/')

  if (!domain) {
    const cdnUrl = useSettingStore().data.cdn_url
    domain = cdnUrl ? cdnUrl : apiUrl
    // #ifdef WEB
    if (cdnUrl.startsWith('//')) {
      domain = apiUrl
    }
    // #endif
  }
  if (!relativeUrl) return domain

  const regUrl = new RegExp(/^http(s)?:\/\//)
  const regexImg = new RegExp(/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i)
  if (!domain || regUrl.test(relativeUrl) || regexImg.test(relativeUrl)) {
    return relativeUrl
  }

  return domain + relativeUrl
}

// 格式化价格
export const formatPrice = (price: string | number) => {
  return price ? price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '') : '0.00'
}

/**
 * 用于页面返回重新加载数据用
 * @param callback 加载数据回调函数
 * @param onShowTrigger true：onshow方式触发,false:onload方式触发
 */
export const onShowRefreshData = (callback: any, onShowTrigger: boolean = false) => {
  if (onShowTrigger) {
    onShow(() => {
      callback()
    })
  } else {
    onLoad(() => {
      callback()
    })
    uni.$on('refreshData', () => {
      console.log('refreshData trigger')
      nextTick(() => {
        callback()
      })
    })
  }
}

/**
 * 唯一标识uuid
 * @returns 唯一标识uuid
 */
export function uuid(): string {
  let uuid = ''
  for (let i = 1; i <= 36; i++) {
    if (i === 9 || i === 14 || i === 19 || i === 24) {
      uuid += '-'
    } else if (i === 15) {
      uuid += 4
    } else if (i === 20) {
      uuid += hexList[(Math.random() * 4) | 8]
    } else {
      uuid += hexList[(Math.random() * 16) | 0]
    }
  }
  return uuid
}

const hexList: string[] = []
for (let i = 0; i <= 15; i++) {
  hexList[i] = i.toString(16)
}

/**
 * 生成唯一标识
 * @param prefix 前缀
 * @returns 唯一标识
 */
export function shortUuid(prefix = ''): string {
  const time = Date.now()
  const random = Math.floor(Math.random() * 1000000000)

  const wd: any = window
  if (!wd.unique) wd.unique = 0
  wd.unique++
  return prefix + '_' + random + wd.unique + String(time)
}

/**
// 获取短信验证码ID
 * @param phone 手机号码
 * @param sms_template_code 短信验证码类型
 * @returns 
 */
export const getSmsTemplateId = (phone: string, sms_template_code: string) => {
  return phone + sms_template_code
}

/**
 * 刷新页面
 */
export const refreshPage = () => {
  const pages = getCurrentPages()
  const page = pages[pages.length - 1]

  uni.redirectTo({ url: (page as any).$page.fullPath })
}

/**
 * 检测图片是否存在
 * @param url
 */
export const checkImage = (url: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: 'HEAD',
      header: {
        'content-type': 'application/json',
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(url)
        } else {
          console.log('图片访问失败：' + url)
          reject()
        }
      },
      fail: (err) => {
        console.log('图片访问失败：' + url, 'err：', err)
        reject(err)
      },
    })
  })
}

export const computeConversion = (sale: number, omitDigits: number = 4): string => {
  const units = [
    { value: 100000000, label: '亿+' },
    { value: 10000000, label: '000万+' },
    { value: 1000000, label: '00万+' },
    { value: 100000, label: '0万+' },
    { value: 10000, label: '万+' },
    { value: 1000, label: '000+' },
    { value: 100, label: '00+' },
  ].filter((unit) => Math.floor(Math.log10(unit.value)) >= omitDigits)

  for (const unit of units) {
    if (sale >= unit.value) {
      return `${Math.floor(sale / unit.value)}${unit.label}`
    }
  }

  return sale > 0 ? `${sale}` : sale.toString()
}

/**
 * 获取用户默认头像
 * @returns
 */
export const getUserDefaultAvatar = () => {
  return '/static/images/default_avatar.png'
}
