import { Platform, AppVisibility, Notify, Dialog } from "quasar";

export function openAppSetting() {
  return new Promise((resolve, reject) => {
    window.cordova.plugins.settings.open(
      ["application_details", true],
      () => {
        resolve(false);
      },
      function () {
        reject(false);
      }
    );
  });
}

export function requestPermissions(permissions, success, error) {
  if (Platform.is.android) {
    let permissionName = permissions;
    if (permissions instanceof Array) {
      permissionName = permissions.shift();
    } else {
      permissions = "";
    }
    cordova.plugins.permissions.requestPermission(
      getPermissionCode(permissionName),
      (status) => {
        if (status.hasPermission) {
          if (permissions.length) {
            requestPermissions(permissions, success, error);
          } else {
            success();
          }
        } else {
          error &&
            error({
              hasPermission: false,
              permission: permissionName
            });
        }
      },
      (err) => {
        error &&
          error({
            hasPermission: err.hasPermission,
            permission: permissionName
          });
      }
    );
  } else {
    return success();
  }
}

export function getPermissionCode(name) {
  return cordova.plugins.permissions[name.toUpperCase()];
}

export function getLocalFileURL(filename) {
  return new Promise((resolve, reject) => {
    window.resolveLocalFileSystemURL(
      filename,
      (entry) => {
        // var nativePath = entry.toURL();
        entry.file((file) => {
          // 读取文件
          // resolve(file)
          let reader = new FileReader();
          reader.onloadend = () => {
            if (reader.result) {
              let blob = new Blob([new Uint8Array(reader.result)], {
                type: file.type
              });
              blob.name = file.name;
              resolve(blob);
            } else {
              reject(new Error("file reader result is empty"));
            }
          };
          reader.onerror = reject;
          reader.readAsArrayBuffer(file);
        }, reject);
      },
      reject
    );

    // window.resolveLocalFileSystemURL(filePath,(dirEntry)=>{
    //   // 获取文件所在的根目录
    //   dirEntry.getFile(filename,{},(fileEntry)=>{
    //     // 获得文件入口
    //     fileEntry.file((file)=>{
    //       this.$q.notify(file)
    //       // 读取文件
    //       let reader = new FileReader();
    //       reader.onloadend = ()=>{
    //         this.$emit('captureAudio',reader.result);
    //       }
    //       reader.onerror = reject
    //       reader.readAsDataURL(file)
    //     },reject)
    //   },reject)
    // },reject)
  });
}

function showPermissionDialog(msg) {
  Dialog.create({
    title: "权限申请",
    message: msg + "，您可以在“设置”中更改权限配置。",
    ok: "去设置",
    cancel: "取消"
  }).onOk(() => {
    openAppSetting();
  });
}
export function captureImage(sourceType) {
  return new Promise((resolve, reject) => {
    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: () => { } }
                // ]});
                resolve(dataUrl);
              })
              .catch((e) => {
                // this.$q.notify({message:e.message,timeout:0,actions: [
                //   { label: 'OK', handler: () => { } }
                // ]});
                reject(err);
              });
          },
          (err) => {
            // 如果失败
            console.warn("Could not access device camera.", err);

            if (err == "has no access to camera" || err == 20) {
              // 没有权限,弹出提示
              showPermissionDialog("您已拒绝应用访问相机");
            }
            reject(err);
          },
          {
            // 相机选项
            sourceType: Camera.PictureSourceType.CAMERA,
            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"
            ? "您已拒绝应用使用存储权限"
            : "您已拒绝应用读取存储的权限"
        );
        reject(err);
      }
    );
  });
}

export const IS_MOBILE = Platform.is.mobile;
// let isDeviceready = false
// document.addEventListener("deviceready",function(){
//   isDeviceready = true
//   console.log("=========device ready========")
// })
export function notification(options) {
  let isBackgroundMode = !AppVisibility.appVisible
  try{
    isBackgroundMode = cordova.plugins.backgroundMode.isActive()
  }
  catch(err){
  }
  try {
    if (process.env.MODE == "cordova") {
      // if (isBackgroundMode) {
        cordova.plugins.notification.local.schedule([
          {
            icon: window.location.origin + '/icons/favicon-96x96.png',
            title: options.title,
            text: options.description,
            foreground: true,
            // alarmVolume: 1,
            sound: true,
            vibrate: true,
            // autoLaunch:true,
            launch:true,
            priority:4,
            // sticky: true,
            wakeup:true,
            // triggerInApp:false,
            number: options.badge || 0,
            // actions:[{ id: "yes", title: "点击查看", launch: true },]
          }
        ]);
      // }
      // else {
      //   if (options.sound) {
      //     navigator.vibrate(1000);
      //     navigator.notification.beep(1);
      //   }
      // }
      // navigator.notification.alert(
      //   options.description,  // message
      //   ()=>{},         // alertDismissed callback
      //   options.title,            // title
      //   '知道了'                  // buttonName
      // );
    } else {
      // Notify.create({
      //   icon:'notifications_active',
      //   message:options.title,
      //   caption: options.description,
      //   multiLine: true,
      //   // type: 'warning',
      //   color: options.color,
      //   // textColor: '',
      //   position: 'top',
      //   classes:'full-width',
      // })
    }
  } catch (e) {}
}

function hasNotifyPermission() {
  // If requesting via plug-in, a system dialog does pop up for the first time. Later its only possible to tweak the settings through the system settings.
  return new Promise((resolve, reject) => {
    cordova.plugins.notification.local.requestPermission(function (granted) {
      if (granted) {
        return resolve(granted);
      }
      reject();
    });
  });
}
export function requestNotifyPermission() {
  return hasNotifyPermission().catch(() => {
    return new Promise((resolve, reject) => {
      Dialog.create({
        // persistent: true,
        // seamless: true,
        // message: '<div class="text-center"><div class="text-h6">通知权限开启提醒</div>开启推送通知，及时获取消息提醒</div>',
        // html: true,
        // "contentClass":"has-mask",
        title: "通知权限开启提醒",
        message: "开启推送通知，及时获取消息提醒",
        ok: {
          label: "立即开启",
          // flat: true,
          // rounded:true,
          // outline:true,
          unelevated: true,
          color: "primary"
        },
        cancel: {
          label: "残忍拒绝",
          flat: true,
          color: "grey-6"
        }
      })
        .onOk(() => {
          // https://www.npmjs.com/package/cordova-plugin-native-settings
          resolve(openAppSetting());
        })
        .onCancel(() => {
          reject(false);
        })
        .onDismiss(() => {
          reject(false);
        });
    });
  });
}
