let isIos = false;

// #ifdef APP-PLUS
isIos = plus.os.name === "iOS";
// #endif

// 判断安卓主方法
function requestAndroidPermission(permissionID, ifRequest) {
  return new Promise((resolve, reject) => {
    plus.android.requestPermissions([permissionID], onSuccess, onError);
    function onSuccess(res) {
      const grantedList = res.granted;
      const deniedList = res.deniedPresent;
      const deniedAlwaysList = res.deniedAlways;
      console.log("res", res, grantedList.includes(permissionID));
      if (grantedList.includes(permissionID)) {
        resolve(true);
      } else {
        resolve(false);
        ifRequest && gotoAppPermissionSetting();
      }
    }
    function onError(err) {
      reject(err);
    }
  });
}

// 分别判断Ios
function judgeIosPermissionPush(ifRequest) {
  return new Promise((resolve) => {
    let UIApplication = plus.ios.import("UIApplication");
    let app = UIApplication.sharedApplication();
    let enabledTypes = 0;
    if (app.currentUserNotificationSettings) {
      let settings = app.currentUserNotificationSettings();
      enabledTypes = settings.plusGetAttribute("types");
      if (enabledTypes == 0) {
        ifRequest && gotoAppPermissionSetting();
        resolve(false);
      } else {
        resolve(true);
      }
      plus.ios.deleteObject(settings);
    } else {
      enabledTypes = app.enabledRemoteNotificationTypes();
      if (enabledTypes == 0) {
        ifRequest && gotoAppPermissionSetting();
        resolve(false);
      } else {
        resolve(true);
      }
    }
    plus.ios.deleteObject(app);
    plus.ios.deleteObject(UIApplication);
  });
}

// 判断定位权限是否开启
function judgeIosPermissionLocation(ifRequest) {
  return new Promise((resolve) => {
    let cllocationManger = plus.ios.import("CLLocationManager");
    let status = cllocationManger.authorizationStatus();
    if (status == 2) {
      ifRequest && gotoAppPermissionSetting();
      resolve(false);
    } else {
      resolve(true);
    }
    plus.ios.deleteObject(cllocationManger);
  });
}

// 判断麦克风权限是否开启
function judgeIosPermissionRecord(ifRequest) {
  return new Promise((resolve) => {
    let avaudiosession = plus.ios.import("AVAudioSession");
    let avaudio = avaudiosession.sharedInstance();
    let permissionStatus = avaudio.recordPermission();
    if (permissionStatus == 1684369017 || permissionStatus == 1970168948) {
      ifRequest && gotoAppPermissionSetting();
      resolve(false);
    } else {
      resolve(true);
    }
    plus.ios.deleteObject(avaudiosession);
  });
}

// 判断相机权限是否开启
function judgeIosPermissionCamera(ifRequest) {
  return new Promise((resolve) => {
    let AVCaptureDevice = plus.ios.import("AVCaptureDevice");
    let authStatus = AVCaptureDevice.authorizationStatusForMediaType("vide");
    if (authStatus == 3) {
      resolve(true);
    } else {
      ifRequest && gotoAppPermissionSetting();
      resolve(false);
    }
    plus.ios.deleteObject(AVCaptureDevice);
  });
}

// 判断相册权限是否开启
function judgeIosPermissionPhotoLibrary(ifRequest) {
  return new Promise((resolve) => {
    let PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
    let authStatus = PHPhotoLibrary.authorizationStatus();
    if (authStatus == 3) {
      resolve(true);
    } else {
      ifRequest && gotoAppPermissionSetting();
      resolve(false);
    }
    plus.ios.deleteObject(PHPhotoLibrary);
  });
}

// 判断通讯录权限是否开启
function judgeIosPermissionContact(ifRequest) {
  return new Promise((resolve) => {
    let CNContactStore = plus.ios.import("CNContactStore");
    let cnAuthStatus = CNContactStore.authorizationStatusForEntityType(0);
    if (cnAuthStatus == 3) {
      resolve(true);
    } else {
      ifRequest && gotoAppPermissionSetting();
      resolve(false);
    }
    plus.ios.deleteObject(CNContactStore);
  });
}

// 安卓判断通知权限是否开启
function judgeIosPermissionNotification(ifRequest) {
  return new Promise((resolve) => {
    let main = plus.android.runtimeMainActivity();
    let pkName = main.getPackageName();
    let uid = main.getApplicationInfo().plusGetAttribute("uid");
    let NotificationManagerCompat = plus.android.importClass("android.support.v4.app.NotificationManagerCompat");
    //android.support.v4升级为androidx
    if (NotificationManagerCompat == null) {
      NotificationManagerCompat = plus.android.importClass("androidx.core.app.NotificationManagerCompat");
    }
    let areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();

    console.log("areNotificationsEnabled", areNotificationsEnabled);
    // 未开通‘允许通知'权限，则弹窗提醒开通，并点击确认后，跳转到系统设置页面进行设置
    if (areNotificationsEnabled) {
      resolve(true);
    } else {
      resolve(false);
    }
  });
}

// 判断所有权限
function getPermission(permission, ifRequest = false) {
  switch (permission) {
    case "location":
      if (isIos) {
        return judgeIosPermissionLocation(ifRequest);
      } else {
        return requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION", ifRequest);
      }
      break;
    case "camera":
      if (isIos) {
        return judgeIosPermissionCamera(ifRequest);
      } else {
        return requestAndroidPermission("android.permission.CAMERA", ifRequest);
      }
      break;
    case "photo":
      if (isIos) {
        return judgeIosPermissionPhotoLibrary(ifRequest);
      } else {
        return requestAndroidPermission("android.permission.READ_EXTERNAL_STORAGE", ifRequest);
      }
      break;
    case "record":
      if (isIos) {
        return judgeIosPermissionRecord(ifRequest);
      } else {
        return requestAndroidPermission("android.permission.RECORD_AUDIO", ifRequest);
      }
      break;
    case "contact":
      if (isIos) {
        return judgeIosPermissionContact(ifRequest);
      } else {
        return requestAndroidPermission("android.permission.READ_CONTACTS", ifRequest);
      }
      break;
    case "call":
      if (isIos) {
        return Promise.resolve(true);
      } else {
        return requestAndroidPermission("android.permission.CALL_PHONE", ifRequest);
      }
      break;
    case "push":
      if (isIos) {
        return judgeIosPermissionPush(ifRequest);
      } else {
        return judgeIosPermissionNotification(ifRequest);
      }
      break;
    default:
      break;
  }
}

// 去设置
function gotoAppPermissionSetting() {
  if (isIos) {
    let UIApplication = plus.ios.import("UIApplication");
    let application2 = UIApplication.sharedApplication();
    let NSURL2 = plus.ios.import("NSURL");
    // let setting2 = NSURL2.URLWithString("prefs:root=LOCATION_SERVICES");
    let setting2 = NSURL2.URLWithString("app-settings:");
    application2.openURL(setting2);

    plus.ios.deleteObject(setting2);
    plus.ios.deleteObject(NSURL2);
    plus.ios.deleteObject(application2);
  } else {
    let Intent = plus.android.importClass("android.content.Intent");
    let Settings = plus.android.importClass("android.provider.Settings");
    let Uri = plus.android.importClass("android.net.Uri");
    let mainActivity = plus.android.runtimeMainActivity();
    let intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    let uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
    intent.setData(uri);
    mainActivity.startActivity(intent);
  }
}

// 检查是否开启了定位
function checkSystemEnableLocation() {
  if (isIos) {
    let result = false;
    let cllocationManger = plus.ios.import("CLLocationManager");
    result = cllocationManger.locationServicesEnabled();
    plus.ios.deleteObject(cllocationManger);
    return result;
  } else {
    let context = plus.android.importClass("android.content.Context");
    let locationManager = plus.android.importClass("android.location.LocationManager");
    let main = plus.android.runtimeMainActivity();
    let mainSvr = main.getSystemService(context.LOCATION_SERVICE);
    let result = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
    return result;
  }
}

export default {
  getPermission,
  checkSystemEnableLocation,
  gotoAppPermissionSetting,
};
