
import Taro from '@tarojs/taro'
import { authorize } from './wxAuth'

// eslint-disable-next-line no-undef
const host = HOST;
// eslint-disable-next-line no-undef
const ossPath = OSS_PATH;

let platform = null;

function getPlatform() {
  if (!platform) {
    platform = Taro.getSystemInfoSync().platform;
  }
  return platform;
}

export function getImgURL(img) {
  if (!img) return undefined;

  if (img.indexOf(ossPath) > -1) {
    const plat = getPlatform();
    if (plat.toLocaleLowerCase().indexOf('ios') > -1) {
      return `${img}?x-oss-process=style/thumb`
    } else {
      return `${img}?x-oss-process=style/webp`
    }
  }

  if (img.indexOf('http') === 0) return img;
  return `${host}${img}`;
}

/**
 * base64 转文件
 * @param {*} base64Str 
 * @returns 
 */
export function base64ToFile(base64Str) {
  return new Promise((resolve, reject) => {
    const fileName = (new Date()).valueOf() + '-' + Math.random().toString(36).substring(2) + '.png'
    const filePath = Taro.env.USER_DATA_PATH + '/' + fileName
  
    Taro.getFileSystemManager().writeFile({
      filePath,
      data: base64Str,
      encoding: 'base64',
      success: () => {
        resolve(filePath)
      },
      fail: (err) => {
        console.error(err)
        reject(err)
      },
      complete: (res) => {
        console.log('-----writeFile---', filePath, res)
      }
    })
  })
}

/**
 * 保存到相册
 * @param {*} tempPath 
 * @returns 
 */
export function save2Album(tempPath) {
  return new Promise((resolve, reject) => {
    authorize('scope.writePhotosAlbum').then(() => {
      console.log('-----------save2Album---------->', tempPath)

      // 再保存到相册
      Taro.saveImageToPhotosAlbum({
        filePath: tempPath,
        success: () => {
          resolve()
        },
        fail: (err) => {
          console.error(err)
          let message = err.errMsg || err.message || err
          if (message.indexOf('cancel') > -1) {
            message = '您已取消'
          }
          Taro.showToast({
            title: message,
            icon: 'none',
          })
          reject(err)
        },
        complete: (res) => {
          console.log('---------complete----------->', res)
        }
      })
    }).catch((err) => {
      console.error(err)
      let message = err.errMsg || err.message || err
      if (message.indexOf('cancel') > -1) {
        message = '您已取消'
      }

      Taro.showToast({
        title: message,
        icon: 'none',
      })
      reject(err)
    })
  })
}
