/**
 * 工具类
 *
 */

import xss from 'xss'
import store from '@/store'

// 轻提示
export function toast(text, cb = false) {
  if (!text) return
  // #ifdef APP-PLUS
  plus.nativeUI.closeToast()
  plus.nativeUI.toast(`<div style="font-size:14px">${text}</div>`, {
    type: 'richtext',
    duration: 'short',
    align: 'center',
    verticalAlign: 'bottom',
    richTextStyle: {
      align: 'bottom',
    },
  })
  cb && cb()
  // #endif
  // #ifndef APP-PLUS
  uni.hideToast()
  uni.showToast({
    icon: 'none',
    title: text,
    duration: 2000,
    position: 'bottom',
    success() {
      cb && cb()
    },
  })
  // #endif
}

// 上级页面
export function parentPage(delta = 2) {
  const pages = getCurrentPages()
  const parentPage = pages[pages.length - delta]
  return parentPage ? parentPage.$vm : null
}

// 去除 HTML 标签
export function safeHTML(source) {
  return xss(source, {
    whiteList: {}, // 白名单为空，表示过滤所有标签
    stripIgnoreTag: true, // 过滤所有非白名单标签的HTML
    stripIgnoreTagBody: ['script'], // script标签较特殊，需要过滤标签中间的内容
  })
}

// 格式大数字
export function safeNum(num, max = 1e6 - 1, str = '100万+') {
  return Number(num) > max ? str : num
}

// 格式化时间
export function time(timeStamp, pattern = 'YYYY-MM-DD') {
  return this.$dayjs.unix(timeStamp).format(pattern)
}

// 补零
export function addZero(val) {
  val = Number(val)
  if (val < 10) return `0${val}`
  return val.toString()
}

// 修复时间戳长度
export function fixTime(timeStamp) {
  if (timeStamp.toString().length === 10) {
    timeStamp = timeStamp * 1000
  }
  return timeStamp
}

// 获取时间对象
export function timeObj(timeStamp) {
  const date = new Date(fixTime(timeStamp))
  return !isNaN(date)
    ? {
        year: date.getFullYear(),
        month: addZero(date.getMonth() + 1),
        day: addZero(date.getDate()),
        hour: addZero(date.getHours()),
        minute: addZero(date.getMinutes()),
      }
    : {}
}

// 个性化时间
export function beforeTime(timeStamp) {
  if (!timeStamp) return '刚刚'
  timeStamp = fixTime(timeStamp)
  // const nTime = timeObj(Date.now())
  // const yTime = timeObj(Date.now() - 3600 * 24 * 1000)
  // const time = timeObj(timeStamp)
  // const nTimeStr = [nTime.year, nTime.month, nTime.day].join('')
  // const yTimeStr = [yTime.year, yTime.month, yTime.day].join('')
  // const timeStr = [time.year, time.month, time.day].join('')
  // // 同一天
  // if (timeStr === nTimeStr) {
  //   return `${time.hour}:${time.minute}`
  // }
  // // 昨天
  // if (timeStr === yTimeStr) {
  //   return `昨天 ${time.hour}:${time.minute}`
  // }
  // // 其他时间
  // return `${time.year}-${time.month}-${time.day} ${time.hour}:${time.minute}`
  const oTime = (Date.now() - timeStamp) / 1000
  // 小于1分钟
  if (oTime < 60) {
    return '刚刚'
  }
  // 小于1小时
  if (oTime < 3600) {
    return `${Math.floor(oTime / 60)}分钟前`
  }
  // 小于24小时
  if (oTime < 24 * 3600) {
    return `${Math.floor(oTime / 3600)}小时前`
  }
  // 小于30天
  if (oTime <= 24 * 3600 * 30) {
    return `${Math.floor(oTime / (24 * 3600))}天前`
  }
  // 大于30天
  if (oTime > 24 * 3600 * 30) {
    const time = timeObj(timeStamp)
    return `${time.year}-${time.month}-${time.day}`
  }
}

// 函数节流防抖
export function throttle(event, time) {
  let pre = 0
  let timer = null
  return function (...args) {
    if (Date.now() - pre > time) {
      clearTimeout(timer)
      timer = null
      pre = Date.now()
      event.apply(this, args)
    } else if (!timer) {
      timer = setTimeout(() => {
        event.apply(this, args)
      }, time)
    }
  }
}

// 转换秒为分钟
export function sec2minute(sec) {
  return [parseInt((sec / 60) % 60), parseInt(sec % 60)]
    .join(':')
    .replace(/\b(\d)\b/g, '0$1')
}

// 预览图片
export function previewImage(index, images, preview = true) {
  if (!preview) return
  uni.previewImage({
    current: index ? index : 0,
    urls: images,
  })
}

// 调起支付选项
export function showPayment(cb = () => {}) {
  const payType = [
    {
      id: 1,
      name: '微信',
    },
    {
      id: 2,
      name: '支付宝',
    },
  ]
  if (uni.getSystemInfoSync().platform === 'ios') {
    payType.unshift({
      id: 99,
      name: '应用内购',
    })
  }
  uni.showActionSheet({
    title: '请选择支付方式',
    itemList: this._.values(this._.mapValues(payType, 'name')),
    success: s => cb(payType[s.tapIndex].id),
  })
}

// 发起支付
export function payment(params, cb = () => {}) {
  const type = this._.isNumber(params.type)
    ? {
        97: 'vcoinspay',
        98: 'balancepay',
        99: 'appleiap',
        1: 'wxpay',
        2: 'alipay',
      }[params.type]
    : params.type
  const requestPayment = (provider, orderInfo) => {
    uni.getProvider({
      service: 'payment',
      success: r => {
        if (!r.provider.includes(provider)) {
          toast('无效的支付方式')
          return cb()
        }
        toast('正在发起支付...')
        uni.requestPayment({
          provider,
          orderInfo,
          success: res => {
            console.log('支付成功', res)
            res && cb(res)
          },
          fail: err => {
            console.log('支付失败', err)
            toast('支付失败')
            cb()
          },
        })
      },
      fail: err => {
        console.log('支付发起失败', err)
        toast('支付发起失败')
        cb()
      },
    })
  }
  if (!type) {
    toast('无效的支付方式')
    return cb()
  }
  // 苹果应用内支付
  if (type === 'appleiap') {
    return requestPayment(type, {
      quantity: 1,
      productid: 'test123', // todo，内购产品id，在苹果开发者中心配置
      username: `${this.userinfo?.member_id}|${this.userinfo?.nickname}`,
      manualFinishTransaction: false,
    })
  }
  // 微信、支付宝
  this.$api
    .post(`/${type}`, { attach: params.attach, order_sn: params.order_sn })
    .then(r => {
      if (r) {
        if (['balancepay', 'vcoinspay'].includes(type)) {
          return cb(r)
        }
        if (r.state === 1) {
          requestPayment(type, r.datas)
        }
      } else {
        cb()
      }
    })
}
// TIM 方法操作
export function timEmit(method, payload) {
  // #ifdef APP-PLUS
  if (!store.state.timReady) {
    toast('操作失败，请重新登录')
    store.commit('removeUserInfo')
    return uni.reLaunch({ url: '/pages/login/login' })
  }
  // #endif
  // #ifndef APP-PLUS
  toast('注意！请勿在非APP平台使用TIM')
  // #endif
  return this.$tim[method](payload)
}

// 检测权限
export async function checkPermission(android, ios) {
  const { platform } = uni.getSystemInfoSync()
  let allowed
  if (platform === 'android') {
    allowed =
      (await this.$permission.requestAndroidPermission(
        `android.permission.${android}`
      )) === 1
  }
  if (platform === 'ios') {
    allowed = this.$permission.judgeIosPermission(ios)
  }
  return allowed
}
