import { reactive, ref } from 'vue'
import { requestPermissions, openAppSetting, getLocalFileURL} from 'src/utils/mobile.js'
import { useQuasar } from 'quasar'


export function useCamera() {
  const $q = useQuasar()
  function showPermissionDialog(msg){
    $q.dialog({
        title: '权限申请',
        message: msg+'，您可以在“设置”中更改权限配置。',
        ok: '去设置',
        cancel: '取消'
      })
      .onOk(() => {
        openAppSetting()
      })
  }
  const images = reactive([''])
  function captureImage(sourceType) {
    requestPermissions(['CAMERA','WRITE_EXTERNAL_STORAGE','READ_EXTERNAL_STORAGE'],()=>{
      navigator.camera.getPicture(
        data => {
          getLocalFileURL(data)
            .then(dataUrl => {
              // 如果成功
              // this.$q.notify({message:dataUrl,timeout:0,actions: [
              //   { label: 'OK', handler: () => { } }
              // ]});
              images.push(dataUrl)
            })
            .catch(e => {
              // this.$q.notify({message:e.message,timeout:0,actions: [
              //   { label: 'OK', handler: () => { } }
              // ]});
            })
        },
        err => {
          // 如果失败
          console.warn('Could not access device camera.', err)

          if (err == 'has no access to camera' || err == 20) {
            // 没有权限,弹出提示
            showPermissionDialog("您已拒绝应用访问相机")
          }
        },
        {
          // 相机选项
          sourceType: 1,
          encodingType: Camera.EncodingType.JPEG,
          destinationType: Camera.DestinationType.FILE_URI,
          quality: 80,
          correctOrientation: true,
          targetWidth: 700,
          targetHeight: 700
        }
      )
    },(err)=>{
      showPermissionDialog(err.permission == 'CAMERA'?'您已拒绝应用使用摄像头权限':err.permission == 'WRITE_EXTERNAL_STORAGE'?"您已拒绝应用使用存储权限":"您已拒绝应用读取存储的权限")
    })
  }
  return {
    images,
    captureImage,
    deleteImage(index){
      images.splice(index,1)
    }
  }
}
