import Taro from '@tarojs/taro';

/**
 * 获取微信配置
 * @param scope
 * @param tips
 * @param force
 * @returns
 */
export function getWxSetting(scope: keyof Taro.AuthSetting) {
  return new Promise<boolean>(resolve => {
    Taro.getSetting({
      success(res) {
        if (!res?.authSetting[scope]) {
          resolve(false);
        } else {
          resolve(true);
        }
      },
      fail() {
        resolve(false);
      },
    });
  });
}

export function authorize(scope: keyof Taro.AuthSetting, tips: string, force = true) {
  return new Promise<boolean>(resolve => {
    Taro.authorize({
      scope,
      success() {
        return resolve(true);
      },
      fail() {
        if (!force) return resolve(false);

        Taro.showModal({
          title: '提示',
          content: tips,
          showCancel: false,
          success: () => {
            Taro.openSetting({
              success(result) {
                if (!result.authSetting[scope]) resolve(false);
                else resolve(true);
              },
            });
          },
          fail: () => resolve(false),
        });
      },
    });
  });
}
