// import uniPages from 'uni-pages?{"type":"style"}'
import { isObject, isString } from 'utils/data-type'
import pages from '../pages.json'

export const useUniApi = () => {
  /**
   * 跳转页面
   * @param {Object | String} options 跳转参数
   */
  const navigateTo = (options) => {
    if (!options) {
      return
    }

    const { list } = pages.tabBar
    const paths = list.map((item) => `/${item.pagePath}`)

    if (isObject(options)) {
      const { url } = options
      if (paths.includes(url)) {
        uni.switchTab(options)
      } else {
        uni.navigateTo(options)
      }
    } else if (isString(options)) {
      if (paths.includes(options)) {
        uni.switchTab({
          url: options
        })
      } else {
        uni.navigateTo({
          url: options
        })
      }
    }
  }

  /**
   * 预览图片
   * @param {String} url 图片地址
   */
  const previewImage = (url) => {
    if (!url) {
      return
    }
    uni.previewImage({
      urls: [url]
    })
  }

  // 扫码
  const scanCode = () => {
    return new Promise((resolve, reject) => {
      uni.scanCode({
        success: resolve,
        fail: reject
      })
    })
  }

  return {
    navigateTo,
    previewImage,
    scanCode
  }
}
