import 'package:flutter/cupertino.dart';
import 'package:mobsms/mobsms.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';
import 'package:zhiying_comm/pages/login_page/model/login_style_model.dart';
import 'package:zhiying_comm/util/dialog/loading/loading.dart';
import 'package:zhiying_comm/util/empty_util.dart';
import 'package:zhiying_comm/util/enum_util.dart';
import 'package:zhiying_comm/util/global_config.dart';
import 'package:zhiying_comm/util/log/let_log.dart';
import 'package:zhiying_comm/util/mob_util/secverify/quick_login_util.dart';
import 'package:zhiying_comm/util/net_util.dart';
import 'package:zhiying_comm/util/shared_prefe_util.dart';
import 'package:fluttertoast/fluttertoast.dart';

///
/// MOB SDK 工具类
///
class MobUtil {
  ///
  /// MOB 各个sdk初始化
  ///
  ///
  static void init() {
    // 秒验的初始化
    QuickLoginUtil.getInstance().init();
  }

  ///
  /// 退出QQ登录
  ///
  static void cancelQQAuth(){
    SharesdkPlugin.cancelAuth(ShareSDKPlatforms.qq, (SSDKResponseState state, Map user, SSDKError error) {
      Logger.debug('state = ${state}\n rawData = ${error?.rawData?.toString()}');
    });
  }

  ///
  /// 退出微信登录
  ///
  static void cancelWeChatAuth(){
    SharesdkPlugin.cancelAuth(ShareSDKPlatforms.wechatSession, (SSDKResponseState state, Map user, SSDKError error) {
      Logger.debug('state = ${state}\n rawData = ${error?.rawData?.toString()}');
    });
  }

  ///
  /// 取消授权
  ///
  static void cancelAuth(ShareSDKPlatform platform) {
    SharesdkPlugin.cancelAuth(platform, (SSDKResponseState state, Map user, SSDKError error) {
      // showAlert(state, error.rawData, context);
      Logger.debug('state = ${state}\n rawData = ${error?.rawData?.toString()}');
    });
  }



  ///
  /// 打开秒验页面
  ///
  /// context: 当前应用的上下文
  /// model: 快速登录的样式
  ///
  static void openQuickLoginPage(BuildContext context, Quick model) {
    QuickLoginUtil.getInstance().openQuickLogin(context, model);
  }

  ///
  /// 获取短信
  /// 流程：先根据类型请求后台获取是否余额充足，根据返回的模版类型进行MOB SDK的验证码下发。
  ///
  /// phone: 手机号
  /// zoneCode: 地区号码
  /// templateID: 模板ID
  ///
  /// 例子：获取绑定手机号验证码：bool result = await MobUtil.getTextCode('手机号码', zoneCode = '86', smsCodeType = SMSCodeType.BIND_ALIPAY);
  ///
  static Future<bool> getTextCode(final String phone, {String zoneCode = '86', SMSCodeType smsCodeType = SMSCodeType.NORMAL}) async {
    bool result = false;
    String vCodeType = await _getSMSStrategy(phone, type: smsCodeType);
    if (EmptyUtil.isEmpty(vCodeType)) return result;
    Logger.debug('phone = $phone, zoneCode = $zoneCode, vCodeType = $vCodeType');
    await Smssdk.getTextCode(phone, zoneCode, vCodeType, (ret, err) {
      if (err != null) {
        result = false;
        Logger.debug('get vcode fail err = ${err?.toString()}, ret = ${ret?.toString()}' );
        if(!EmptyUtil.isEmpty(err)){
          Fluttertoast.showToast(msg: '获取验证码失败：${err['msg']}');
        }else {
          Fluttertoast.showToast(msg: '获取验证码失败～');
        }

      } else {
        String rst = ret.toString();
        if (rst == null || rst == "") {
          rst = '获取验证码成功! ret = ${ret?.toString()}, err = ${err?.toString()} ';
        }
        Logger.debug(rst);
        result = true;
      }
    });
    return Future.value(result);
  }

  /// 询问验证码是否可以下发
  static Future<String> _getSMSStrategy(final String phone, {SMSCodeType type = SMSCodeType.NORMAL}) async {
    try {
      String vCodeType = enumToString(type)?.toLowerCase();
      if (EmptyUtil.isEmpty(vCodeType)) {
        vCodeType = enumToString(SMSCodeType.NORMAL).toLowerCase();
      }
      String url = type == SMSCodeType.AUTO ? '/api/v1/mob/sms/tmp/${vCodeType}?phone=${phone}' : '/api/v1/mob/sms/tmp/$vCodeType';
      var result = await NetUtil.post(url, method: NetMethod.GET);
      if (NetUtil.isSuccess(result) && !EmptyUtil.isEmpty(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA])) {
        return result[GlobalConfig.HTTP_RESPONSE_KEY_DATA];
      }
    } catch (e, s) {
      Logger.error(e, s);
    }
    return null;
  }

  static Future storeInvitedCode(String code) {
    return SharedPreferencesUtil.setStringValue('mobInvitedCode', code);
  }

  // 获取一件锁粉邀请码
  static Future<String> getInvitedCode() async {
    return SharedPreferencesUtil.getStringValue('mobInvitedCode');
  }

  /// 隐私协议授权
  static void submitPrivacyGrantResult(bool permission) {
    SharesdkPlugin.uploadPrivacyPermissionStatus(permission ? 1 : 0, (bool success) {
      if (success == true) {
        Logger.log('隐私协议授权提交结果: 成功');
      } else {
        Logger.log('隐私协议授权提交结果: 失败');
      }
    });
  }

  ///
  /// 提交验证码
  ///
  /// phone： 手机号码
  /// code: 验证码
  /// zoneCode: 区号
  ///
// static Future<bool> commitCode(final String phone, String code, {String zoneCode = '86'}) async {
//   bool result = false;
//   await Smssdk.commitCode(phone, zoneCode, code, (ret, err) {
//     if (err != null) {
//       // showAlert(err.toString(),context);
//       result = false;
//     } else {
//       // showAlert('提交验证码成功!',context);
//       result = true;
//       // _countMobSMS(phone, code, zoneCode: zoneCode);
//     }
//   });
//   return Future.value(result);
// }

  /// 统计MOB验证码提交
// static void _countMobSMS(final String phone, final String code, {String zoneCode = '86'}) async {
//   try {
//     NetUtil.post('/api/v1/funtions/mobsms', params: {'phone': phone, "code": code, 'zone': zoneCode}, showToast: false);
//   } catch (e, s) {
//     Logger.error(e, s);
//   }
// }

}

enum SMSCodeType {
  // 普通验证码
  NORMAL,
  // 登录
  LOGIN,
  // 注册模版验证码
  REGISTER,
  // 绑定支付宝验证码
  BIND_ALIPAY,
  // 绑定手机号验证码
  BIND_PHONE,
  // 取消绑定支付宝验证码
  UNBIND_ALIPAY,
  // 取消绑定手机号
  UNBIND_PHONE,
  // 后台自动判断登录还是注册
  AUTO,
}
