import 'dart:io';
import 'dart:math';

import 'package:fpdart/fpdart.dart';
import 'package:get/get.dart';
import 'package:kaer_with_panels/app/mixins/kr_app_bar_opacity_mixin.dart';
import 'package:kaer_with_panels/app/services/api_service/api.dart';
import 'package:kaer_with_panels/app/model/enum/kr_request_type.dart';
import 'package:kaer_with_panels/app/model/response/kr_is_register.dart';
import 'package:kaer_with_panels/app/model/response/kr_login_data.dart';
import 'package:kaer_with_panels/app/network/base_response.dart';
import 'package:kaer_with_panels/app/network/http_error.dart';
import 'package:kaer_with_panels/app/network/http_util.dart';
import 'package:kaer_with_panels/app/utils/kr_device_util.dart';

import '../../utils/kr_common_util.dart';
import '../../utils/kr_log_util.dart';

class KRAuthApi {
  /// 是否开启了审核开关
  Future<Either<HttpError, bool>> kr_isRegister(
      KRLoginType tpye, String account, String? areaCode) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['method'] = tpye.value;
    data['account'] = account;
   
     final deviceId = await KRDeviceUtil().kr_getDeviceId();
    KRLogUtil.kr_i('设备ID: $deviceId', tag: 'KRAuthApi');
     data["identifier"] = deviceId;

    data["user_agent"] = _kr_getUserAgent();
    data["os"] = _kr_getUserAgent();
    if (areaCode != null) {
      data['area_code'] = areaCode.toString();
    }

    BaseResponse<KRIsRegister> baseResponse = await HttpUtil.getInstance()
        .request<KRIsRegister>(Api.kr_isRegister, data,
            method: HttpMethod.POST, isShowLoading: true);

    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.kr_isRegister);
  }

  /// 注册
  Future<Either<HttpError, String>> kr_register(
      KRLoginType tpye,
      String account,
      String? areaCode,
      String? code,
      String? password,
      {String? inviteCode}) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['method'] = tpye.value;
    data['account'] = account;
    data['password'] = password;
    data["code"] = code;
    data["identifier"] = await KRDeviceUtil().kr_getDeviceId();
    data["os"] =  _kr_getUserAgent();

    if (inviteCode != null && inviteCode.isNotEmpty) {
      data["invite"] = inviteCode;
    }
    data["user_agent"] =  _kr_getUserAgent();
    if (tpye == KRLoginType.kr_telephone) {
      data['area_code'] = areaCode;
    }

    BaseResponse<KRLoginData> baseResponse = await HttpUtil.getInstance()
        .request<KRLoginData>(Api.kr_register, data,
            method: HttpMethod.POST, isShowLoading: true);
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.kr_token.toString());
  }

  /// 验证验证码
  Future<Either<HttpError, bool>> kr_checkVerificationCode( KRLoginType tpye,
      String account, String? areaCode, String code, int type) async {
     
    final Map<String, dynamic> data = <String, dynamic>{};
     data['method'] = tpye.value;
     if(tpye == KRLoginType.kr_telephone){
      data['account'] =   areaCode.toString() + account;
    
     }else{
      data['account'] = account;
     }
    data['code'] = code;
    data['type'] = type;
    BaseResponse<KRIsRegister> baseResponse = await HttpUtil.getInstance()
        .request<KRIsRegister>(Api.kr_checkVerificationCode, data,
            method: HttpMethod.POST, isShowLoading: true);
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }
    if(baseResponse.model.kr_isRegister){
      return right(true);
    }else{
      return left(HttpError(msg: "error.70001".tr, code: 70001));
    }

    
  }

  /// 登陆
  Future<Either<HttpError, String>> kr_login(KRLoginType tpye, bool isPsd,
      String account, String? areaCode, String? code, String? password) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['method'] = tpye.value;
    data['account'] = account;

    
     final deviceId = await KRDeviceUtil().kr_getDeviceId();
    KRLogUtil.kr_i('设备ID: $deviceId', tag: 'KRAuthApi');
     data["identifier"] = deviceId;
    data["user_agent"] = _kr_getUserAgent();
    data["os"] = _kr_getUserAgent();
    if (tpye == KRLoginType.kr_telephone) {
      data['area_code'] = areaCode;
    }

    if (isPsd) {
      data['password'] = password;
    } else {
      data["code"] = code;
    }

    BaseResponse<KRLoginData> baseResponse = await HttpUtil.getInstance()
        .request<KRLoginData>(Api.kr_login, data,
            method: HttpMethod.POST, isShowLoading: true);
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.kr_token.toString());
  }

  /// 发送验证码 type 1 注册 其他 2
  Future<Either<HttpError, bool>> kr_sendCode(
      KRLoginType tpye, String account, String? areaCode, int type) async {
    final Map<String, dynamic> data = <String, dynamic>{};

    if (tpye == KRLoginType.kr_email) {
      data['email'] = account;
    } else {
      data['telephone'] = account;
      data['telephone_area_code'] = areaCode.toString();
    }
    data['type'] = type;
    BaseResponse<dynamic> baseResponse = await HttpUtil.getInstance()
        .request<dynamic>(
            tpye == KRLoginType.kr_email
                ? Api.kr_sendEmailCode
                : Api.kr_sendPhoneCode,
            data,
            method: HttpMethod.POST,
            isShowLoading: true);
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    // KRCommonUtil.kr_showToast(baseResponse.model.toString());
    // KRIsRegister model = (baseResponse..model) as KRIsRegister;
    return right(true);
  }

  /// 删除账号
  Future<Either<HttpError, String>> kr_deleteAccount(KRLoginType tpye,
       String code) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['method'] = tpye.value;
   
    data['code'] = code;
  
      BaseResponse<dynamic> baseResponse = await HttpUtil.getInstance()
        .request<dynamic>(Api.kr_deleteAccount, data,
            method: HttpMethod.DELETE, isShowLoading: true);
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right("");
    
  } 

  /// 忘记密码-设置新密码
  Future<Either<HttpError, String>> kr_setNewPsdByForgetPsd(KRLoginType tpye,
      String account, String? areaCode, String? code, String? password) async {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['method'] = tpye.value;
    data['account'] = account;
    data['password'] = password;
    data["code"] = code;
   data["identifier"] = await KRDeviceUtil().kr_getDeviceId();
    data["user_agent"] = _kr_getUserAgent();
    data["os"] = _kr_getUserAgent();
    if (tpye == KRLoginType.kr_telephone) {
      data['area_code'] = areaCode;
    }

    BaseResponse<KRLoginData> baseResponse = await HttpUtil.getInstance()
        .request<KRLoginData>(Api.kr_setNewPsdByForgetPsd, data,
            method: HttpMethod.POST, isShowLoading: true);
    if (!baseResponse.isSuccess) {
      return left(
          HttpError(msg: baseResponse.retMsg, code: baseResponse.retCode));
    }

    return right(baseResponse.model.kr_token.toString());
  }

   String _kr_getUserAgent() {
    if (Platform.isAndroid) {
      return 'android';
    } else if (Platform.isIOS) {
      return 'ios';
    } else if (Platform.isMacOS) {
      return 'mac';
    } else if (Platform.isWindows) {
      return 'windows';
    } else if (Platform.isLinux) {
      return 'linux';
    } else if (Platform.isFuchsia) {
      return 'harmony';
    } else {
      return 'unknown';
    }
  }
}
