import { defineStore } from "pinia";

export const usePermissionStore = defineStore('permission', () => {

  // #ifdef APP-PLUS
  const plugin = uni.requireNativePlugin('Permission')
  // #endif
  
  const permissions = {
    camera: 'android.permission.CAMERA',
    image: 'android.permission.READ_MEDIA_IMAGES',
    video: 'android.permission.READ_MEDIA_VIDEO',
    audio: 'android.permission.READ_MEDIA_AUDIO',
    write: 'android.permission.WRITE_EXTERNAL_STORAGE',
    read: 'android.permission.READ_EXTERNAL_STORAGE',
    select: 'android.permission.READ_MEDIA_VISUAL_USER_SELECTED',
  }

  /**
   * 请求权限
   * @param permissions
   * @returns {Promise<unknown>}
   */
  const requestPermissions = (permissions) => {
    return new Promise(async (resolve, reject) => {
      // #ifdef APP
      plugin.requestPermissions({
        permissions,
      }, (result) => {
        if (result.success) resolve()
        else reject()
      })
      // #endif
      
      // #ifdef H5
      resolve()
      // #endif
    })
  }

  /**
   * 请求选择图片相关权限
   */
  const requestImagePermissions = () => {
    return new Promise(async (resolve, reject) => {
      // #ifdef APP
      plugin.requestImagePermissions((result) => {
        if (result.success) resolve()
        else reject()
      })
      // #endif

      // #ifdef H5
      resolve()
      // #endif
    })
  }

  return { permissions, requestPermissions, requestImagePermissions }
})