// uni-app 对部分 API 进行了 Promise 封装，返回数据的第一个参数是错误对象，第二个参数是返回数据。let [err, res] = await uni.xxxx
// toast
export const toast = async (title, options = {}) => uni.showToast({
  title,
  icon: 'none',
  duration: 3000,
  ...options
})

// errToast
export const errToast = async (title, options = {}) => {
  let msg = title
  if (Object.prototype.toString.call(title).indexOf('Error') > -1) msg = title.message
  return uni.showToast({
    title: msg,
    icon: 'none',
    duration: 3000,
    ...options
  })
}

// modal
export const modal = async (title, content, options = {}) => {
  let res = await uni.showModal({
    title,
    content,
    showCancel: true,
    cancelColor: '#999999',
    confirmColor: '#4EB331',
    ...options
  })
  if (res.errMsg === 'showModal:ok') return res.confirm
  else return false
}

// alert
// export const alert = (err, title = "错误", options = {}) => {
export function alert(err, title = "错误", options = {}) {
  let msg = err
  if (Object.prototype.toString.call(err).indexOf('Error') > -1) msg = err.message
  uni.showModal({
    title,
    content: msg,
    showCancel: false,
    cancelColor: '#999999',
    confirmColor: '#4EB331',
    ...options
  })
}
// alert back
export const alertBack = (e, title = '错误', options = {}) => {
  let msg = ''
  if (typeof e === 'string') msg = e
  else if ('err' in e) msg = e.err
  else msg = e.message
  alert(msg, title, {
    complete() {
      uni.navigateBack({ delta: 1 })
    },
    ...options
  })
}

// loading
/*
  <zy-loading ref="loading"></zy-loading>
  this.$refs.loading.show()
  this.$refs.loading.hide()
*/

export const showLoad = async (title = '加载中...', mask = true) => uni.showLoading({
  title, mask
})

export const hideLoad = () => uni.hideLoading()

// 检测更新
export const checkProgramUpdate = () => {
  // 检测是否可以调用getUpdateManager检查更新
  if (!uni.canIUse('getUpdateManager')) return false

  const updateManager = uni.getUpdateManager()
  // 获取全局唯一的版本更新管理器，用于管理小程序更新
  updateManager.onCheckForUpdate(res => {
    // 监听向微信后台请求检查更新结果事件
    if (res.hasUpdate) {
      // 如果有新版本
      // 小程序有新版本，会主动触发下载操作
      updateManager.onUpdateReady(async () => {
        // 当新版本下载完成，会进行回调
        let confirm = await modal('更新提示', '新版本已经准备好，单击确定重启小程序')
        if (confirm) {
          updateManager.applyUpdate()
        }
      })
      // 小程序有新版本，会主动触发下载操作（无需开发者触发）
      updateManager.onUpdateFailed(async () => {
        // 当新版本下载失败，会进行回调
        await modal('提示', '检查到有新版本，但下载失败，请稍后尝试')
      })
    }
  })
}

/**
 * 获取元素的宽高等信息
 * @param {*} selector 选择器
 * @param {*} filter 过滤字段
 */
export const queryEleInfo = (context, selector, filter) => new Promise((resolve) => {
  let query = ''

  // #ifndef MP-ALIPAY
  query = uni.createSelectorQuery().in(context)
  // #endif

  // #ifdef MP-ALIPAY
  query = uni.createSelectorQuery()
  // #endif

  query.select(selector).boundingClientRect(data => {
    resolve(filter ? data[filter] : data)
  }).exec()
})

// 获取服务提供商
export const getProvider = async (service = 'payment') => {
  try {
    let res = await uni.getProvider({ service })
    if (res.errMsg === 'getProvider:ok') return res
    else throw res
  } catch (e) {
    console.error(e)
    throw e
  }
}

/**
 * 获取code
 */
export const getCode = async (service = 'payment') => {
  let provider = await getProvider(service)

  let onlyAuthorize = false

  // #ifdef APP-PLUS || APP
  onlyAuthorize = true
  // #endif

  let res = await uni.login({
    "provider": provider[0],
    "onlyAuthorize": onlyAuthorize
  })
  if (res.errMsg !== 'login:ok') {
    throw res
  } else {
    uni.setStorageSync('jscode', res.code)
    return res.code
  }
}

// 复制
export const copyData = (data) => new Promise(resolve => {
  uni.setClipboardData({
    data,
    success() {
      resolve()
    }
  })
})

// app打开小程序
export const openWeixinMiniprogram = (url, id = 'gh_0d7e2243b51f') => {
  // #ifdef APP-PLUS || APP
  // 打开菜市小程序
  if (plus.runtime.isApplicationExist({ pname: 'com.tencent.mm', action: 'weixin://' })) {  // 判断用户是否安装了微信
    plus.share.getServices(function (res) {
      var sweixin = null;
      for (var i = 0; i < res.length; i++) {
        var t = res[i];
        if (t.id == 'weixin') {
          sweixin = t;
        }
      }
      if (sweixin) {
        sweixin.launchMiniProgram({
          id: id,                 //这里写你的小程序原始id（以gh开头）
          type: 0,				        //这里是不同的环境（ 0-正式版； 1-测试版； 2-体验版。 默认值为0。）
          path: url,              //这里是指 定页的路径，如需传参直接字符串拼接（首页可以省略）
        })
      }
    }, function (res) {
      toast('提示', '打开小程序失败')
    })
  } else {
    toast('温馨提示', '请先下载微信')
  }
  // #endif
}

// 跳转页面
export const jumpPage = (type, url, time = 0) => {
  let timer = null
  if (timer) clearTimeout(timer)
  timer = setTimeout(() => {
    uni[type]({
      url,
      complete() {
        clearTimeout(timer)
      }
    })
  }, time)
}

// 获取位置权限
export const uniGetPosition = async () => {
  let res = await uni.getLocation({
    type: 'gcj02'
  })
  return res || {}
}

// 统一支付
import { utilsMd5 } from '@/utils/md5.js'
import { businessKey, debug } from '@/config.js'
export const handleCreatePay = async (orderInfo, prepayID, codeURL, payInfo) => {
  try {
    // 获取token
    let token = ''
    if (debug) token = debugData.token
    else {
      token = uni.getStorageSync('token') ? uni.getStorageSync('token') : store.getters['login/tmpData'].token
    }
    let timeStamp = ''
    let randomNum = ''
    let strPay = ''
    let nonceStr = ''
    let packageA = ''
    let paySign = ''
    let signType = 'MD5'
    if (codeURL) {
      // 通联收银 payType 2
      // console.log('codeURL 存在', codeURL)
      timeStamp = codeURL.timeStamp
      nonceStr = codeURL.nonceStr
      packageA = codeURL.package
      signType = codeURL.signType
      paySign = codeURL.paySign
    } else {
      // 京西支付 payType 1
      // 时间戳
      timeStamp = Math.round(new Date().getTime() / 1000).toString()
      // 随机数
      randomNum = parseInt(Math.random() * 5) + 1
      // 随机字符串
      strPay = timeStamp + token + randomNum
      // 加密字符串
      nonceStr = utilsMd5.hex_md5(strPay)
      // 数据包
      packageA = `prepay_id=${prepayID}`
      // 支付签名
      paySign = utilsMd5.hex_md5(`appId=wx4b5930c13f8b1170&nonceStr=${nonceStr}&package=${packageA}&signType=MD5&timeStamp=${timeStamp}&key=${businessKey}`)
    }
    let { provider } = await getProvider()

    let res = ''

    // #ifdef MP-WEIXIN
    res = await uni.requestPayment({
      provider: provider[0],
      orderInfo,
      timeStamp,
      nonceStr,
      package: packageA,
      signType,
      paySign
    })
    // #endif

    // #ifdef MP-ALIPAY
    res = await uni.requestPayment({
      provider: provider[0],
      orderInfo: codeURL
    })
    // #endif

    // #ifdef MP-TOUTIAO
    res = await uni.pay({
      orderInfo: {
        order_id: String(payInfo.payOrderID),
        order_token: String(payInfo.codeURL),
      },
      service: 5
    });
    // #endif


    // #ifdef MP-KUAISHOU
    // console.log('快手小程序的参数,订单id', payInfo.prepayID, 'payInfo.codeURL', payInfo.codeURL)
    res = await uni.pay({
      serviceId: '1',
      orderInfo: {
        order_no: String(payInfo.prepayID),
        order_info_token: String(payInfo.codeURL),
      }
    });
    // #endif

    // #ifndef MP-TOUTIAO || MP-KUAISHOU
    if (!res.errMsg.includes('ok')) throw err
    // #endif

  } catch (e) {
    console.log('handleCreatePay', e)
    throw {
      errKey: 'requestPayment',
      err: e
    }
  }
}

// 设置购物车底部菜单数量
export const setTabBarBadge = (type, count) => {
  // #ifndef MP-TOUTIAO || APP-PLUS

  // #endif
}
