/**
 * Created by JianJia.Zhou<jianjia.zhou> on 2022/5/26.
 */
export function copyText(text, tips) {
  uni.setClipboardData({
    data: text,
    success: function() {
      uni.hideLoading()
      uni.showToast({
        title: tips || '复制成功',
        icon: 'none'
      })
    }
  })
}

export function checkOS() {
  if (uni.getSystemInfoSync().platform === 'ios') {
    uni.showModal({
      title: '提示',
      content: '由于相关规范，iOS功能暂不可用',
      showCancel: false,
      success: function(res) {
        // res.confirm res.cancel
      }
    })
    return false
  }
  return true
}

const shareMessage = user => {
  // #ifdef  MP-KUAISHOU
  const title ="四海剧场"
    // #endif
    // #ifdef  MP-TOUTIAO | MP-WEIXIN
  const title ="张四爷剧场"
  // #endif
  console.log('-->data', user)
  return {
    path: `/pages/index/index?user_id=${user.id}`,
    title: title,
    desc: title
    // imageUrl: ''
  }
}

const tranNumber = (num, point = 2) => {
  let numStr = parseFloat(num).toString()
  // 万以内直接返回
  if (numStr.length < 5) {
    return numStr;
  }
  //大于5位数是万 (以1W分割 1W以下全部显示)
  else if (numStr.length > 4) {
    let decimal = numStr.substring(numStr.length - 4, numStr.length - 4 + point)
    return parseFloat(parseInt(num / 10000) + '.' + decimal) + '万';
  }
}

const saveImage = url => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: url,
      // #ifdef MP-TOUTIAO
      header: {
        "content-type": "application/json",
      },
      // #endif
      success: (res) => {
        if (res.statusCode === 200) {
          console.log('下载成功');
          uni.authorize({
            // #ifdef MP-WEIXIN
            scope: 'scope.writePhotosAlbum',
            // #endif
            // #ifdef MP-TOUTIAO
            scope: "scope.album",
            // #endif
            success() {
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: function(red) {
                  uni.$u.toast(`保存成功`)
                  //uni.$u.toast(`保存路径:${red.savedFilePath}`)
                  resolve()
                },
                fail: function(err) {
                  console.log('-->save error',err)
                  uni.$u.toast(`保存失败`)
                  reject()
                }
              });
            },
            fail: err => {
              console.log('-->authorize fail',err)
              uni.$u.toast(`授权失败`+JSON.stringify(err))
              reject()
            }
          })
        }else{
          uni.$u.toast(`保存失败`)
          reject()
        }
      },
      fail: err => {
        uni.$u.toast(`保存失败`+JSON.stringify(err))
        reject()
      }
    });
  })
}

export default {
  copyText,
  checkOS,
  shareMessage,
  tranNumber,
  saveImage
}
