/*
 * @Description: 微信api封装
 */

export const getWxLocationApi = (type?: any) => {
  return new Promise(function (resolve, reject) {
    uni.getLocation({
      type: type || 'gcj02',
      success(res) {
        resolve(res)
      },
      fail(e) {
        getSettingApi(reject, e)
      }
    })
  })
}

function getSettingApi(reject: any, e: any) {
  uni.getSetting({
    success(res) {
      if (!res.authSetting['scope.userLocation']) {
        showModalApi(reject, e)
      }
    },
    fail(err) {
      uni.showModal({
        title: '错误提示',
        content: err || e || '获取配置信息错误，请检查定位是否开启'
      })
    }
  })
}

function showModalApi(reject: any, e: any) {
  uni.showModal({
    title: '友情提示',
    content: '小程序需要获取您的定位功能才可使用',
    success: function (res) {
      if (res.confirm) {
        //跳转到定位
        uni.openSetting({
          success(res) {
            console.log('openSetting', res.authSetting)
          },
          fail(err) {
            uni.showModal({
              title: '错误提示',
              content: err || '打开配置信息错误，请检查定位是否开启'
            })
          }
        })
      } else if (res.cancel) {
        reject(e)
        console.log('openSettingError', res)
      }
    }
  })
}

/**
 * 下载文件
 * @param {*} url
 */
export const downloadFile = (url: string) => {
  const promise = new Promise(function (resolve, reject) {
    uni.downloadFile({
      url, //仅为示例，并非真实的资源
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res)
        } else {
          reject(res)
        }
      },
      fail: (e) => {
        reject(e)
      }
    })
  })
  return promise
}

/**
 * 获取设置
 */
export const getSystemInfo = async () => {
  try {
    const res: any = await uni.getSystemInfoSync()
    res.toPx = res.windowWidth / 750
    return res
  } catch (error) {
    console.log('error', error)
  }
}

/**
 * 保存图片
 * @param {*} path 图片路径
 */
export const saveImageToPhotosAlbum = (path: string) => {
  const promise = new Promise(function (resolve, reject) {
    uni.saveImageToPhotosAlbum({
      filePath: path,
      success: function () {
        resolve(true)
      },
      fail: function (e) {
        reject(e)
      }
    })
  })
  return promise
}
