import 'dart:async';

import 'package:account_center/account_center.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:account_center/common/utils/alert_util.dart';
import 'package:account_center/page/account_center/account_info/account_info_logic.dart';
import 'package:account_center/page/account_center/account_info/identification_util.dart';
import 'package:account_center/page/account_center/widget/Identity_doing.dart';
import 'package:account_center/page/account_center/widget/identity_success.dart';
import 'package:account_center/widget/confirm_dialog.dart';
import 'package:flutter/material.dart';

class IdentityUserIdCardLogic extends GetxController {
  var nameController = TextEditingController();
  var nameNode = FocusNode();

  var numberController = TextEditingController();
  var numberNode = FocusNode();

  var phoneController = TextEditingController();
  var phoneNode = FocusNode();

  var codeController = TextEditingController();
  var codeNode = FocusNode();

  var startTimeController = TextEditingController();

  var endTimeController = TextEditingController();

  /// 识别失败
  var isShowIdentityErr = false;

  var urlIdCardUp = '';
  var upIdentityErr = false;
  var upIdentityMessage = '';

  dynamic upData;

  var urlIdCardDown = '';
  var downIdentityErr = false;
  var downIdentityMessage = '';

  dynamic downData;

  /// 是否是更新有效期
  bool isChangeDate = false;
  dynamic oldData;

  var check = false;

  @override
  void onInit() {
    isChangeDate = Get.arguments?['isChangeDate'] ?? false;
    phoneController.text = getUserMobile() ?? '';
    super.onInit();
  }

  @override
  void onReady() {
    _requestIdentityInfo();
    super.onReady();
  }

  void selectIdCardUp(url) {
    urlIdCardUp = url;
    LoadingUtils.showLoading();
    fetch(Method.post, url: HttpApi.saveUserIdCardImgFace, params: {
      'userNo': getUserNo(),
      'idCardImgUrl': urlIdCardUp,
      'host': ossDomain,
      'side': 1
    }, onSuccess: (data) {
      LoadingUtils.dismiss();
      nameController.text = data['name'];
      numberController.text = data['idCardNo'];
      upData = data;
      upIdentityErr = false;
      upIdentityMessage = '';
      update();
    }, onError: (code, message) {
      LoadingUtils.dismiss();
      nameController.text = '';
      numberController.text = '';
      upData = null;
      upIdentityErr = true;
      upIdentityMessage = message;
      update();
    });
  }

  void selectIdCardDown(url) {
    urlIdCardDown = url;
    LoadingUtils.showLoading();
    fetch(Method.post, url: HttpApi.saveUserIdCardImgFace, params: {
      'userNo': getUserNo(),
      'idCardImgUrl': urlIdCardDown,
      'host': ossDomain,
      'side': 2
    }, onSuccess: (data) {
      LoadingUtils.dismiss();
      startTimeController.text = data['startDate'];
      endTimeController.text = data['endDate'];
      downData = data;
      downIdentityErr = false;
      downIdentityMessage = '';
      update();
    }, onError: (code, message) {
      LoadingUtils.dismiss();
      startTimeController.text = '';
      endTimeController.text = '';
      downData = null;
      downIdentityErr = true;
      downIdentityMessage = message;
      update();
    });
  }

  bool isOrcSuccess() {
    /// 是否上传过身份图片
    if (urlIdCardUp.isEmpty || urlIdCardDown.isEmpty) {
      return false;
    }

    /// 身份证图片是否识别成功
    if (upIdentityErr || downIdentityErr) {
      return false;
    }

    /// 是否修改过识别结果数据
    if (nameController.text != upData['name'] ||
        numberController.text != upData['idCardNo'] ||
        (startTimeController.text != downData['startDate'] &&
            startTimeController.text != downData['cardBeginDate']) ||
        (endTimeController.text != downData['endDate'] &&
            endTimeController.text != downData['cardEndDate'])) {
      return false;
    }

    return true;
  }

  void confirm() {
    if (codeController.text.isEmpty) {
      check = true;
      update();
      AlertUtil.showCenterToast('请输入验证码');
      return;
    }
    if (isOrcSuccess()) {
      _orcIdentity();
    } else {
      _peopleIdentity();
    }
  }

  void _orcIdentity() {
    LoadingUtils.showLoading();
    fetch(Method.post, url: HttpApi.saveUserIdCardInfo, params: {
      'userNo': getUserNo(),
      'cardFaceImg': urlIdCardUp,
      'cardBackImg': urlIdCardDown,
      'cardBeginDate': startTimeController.text,
      'cardEndDate':
          endTimeController.text == '长期' ? null : endTimeController.text,
      'idCardNo': numberController.text,
      'longTermFlag': endTimeController.text == '长期' ? 1 : 0,
      'name': nameController.text,
      'nationality': upData?['nationality'],
      'address': upData?['address'],
      'birthday': upData?['birthday'],
      'issue': downData?['issue'],
      'captcha': codeController.text,
    }, onSuccess: (response) {
      LoadingUtils.dismiss();
      if (isChangeDate) {
        Get.off(IdentitySuccess());
        return;
      }
      ConfirmDialog(
        content:
            '您好！根据《中华人民共和国网络安全法》和其他相关法律法规的规定：办理个人实名认证需要国家指定机构授权，如确认办理将跳转到第三方平台进行授权。',
        confirm: () {
          toEsign();
        },
        cancelButtonText: '我再想想',
      ).show();
    }, onError: (code, message) {
      LoadingUtils.dismiss();
    });
  }

  void toEsign() {
    KeyBoardUtils.hideKeyboard();
    IdentificationUtil.startFaceVerify().then((value) {
      if (value != null) {
        Get.back(result: value);
        findOtherLogic<AccountInfoLogic>()?.checkResult(value);
      }
    });
  }

  void _peopleIdentity() {
    if (urlIdCardUp.isEmpty) {
      AlertUtil.showCenterToast('请上传身份证正面照片');
      return;
    }
    if (urlIdCardDown.isEmpty) {
      AlertUtil.showCenterToast('请上传身份证反面照片');
      return;
    }
    if (nameController.text.isEmpty) {
      AlertUtil.showCenterToast('请输入姓名');
      return;
    }
    if (numberController.text.isEmpty) {
      AlertUtil.showCenterToast('请输入身份证号码');
      return;
    }
    var numberLength = numberController.text.length;
    if (numberLength != 18) {
      AlertUtil.showCenterToast('请输入正确的身份证号码');
      return;
    }

    if (startTimeController.text.isEmpty) {
      AlertUtil.showCenterToast('请输入有效期开始时间');
      return;
    }
    if (endTimeController.text.isEmpty) {
      AlertUtil.showCenterToast('请输入有效期结束时间');
      return;
    }

    var endTime = endTimeController.text;
    if (endTime != '长期') {
      if (DateTime.parse(endTime.replaceAll('/', '-')).isBefore(
          DateTime.parse(startTimeController.text.replaceAll('/', '-')))) {
        return AlertUtil.showCenterToast('有效期结束时间不能早于开始时间');
      }
    }
    LoadingUtils.showLoading();
    fetch(Method.post, url: HttpApi.saveUserIdCardAuditRecord, params: {
      'userNo': getUserNo(),
      'cardFaceImg': urlIdCardUp,
      'cardBackImg': urlIdCardDown,
      'cardBeginDate': startTimeController.text,
      'cardEndDate': endTimeController.text,
      'idCardNo': numberController.text,
      'longTermFlag': endTimeController.text == '长期' ? 1 : 0,
      'name': nameController.text,
      'nationality': upData?['nationality'],
      'address': upData?['address'],
      'birthday': upData?['birthday'],
      'issue': downData?['issue'],
      'captcha': codeController.text,
    }, onSuccess: (response) {
      LoadingUtils.dismiss();
      if (isChangeDate) {
        Get.off(IdentitySuccess());
      } else {
        Get.off(IdentityDoing());
      }
    }, onError: (code, message) {
      LoadingUtils.dismiss();
    });
  }

  void _requestIdentityInfo() {
    fetch(Method.get, url: HttpApi.getUserIdCardInfo, queryParameters: {
      'userNo': getUserNo(),
    }, onSuccess: (response) {
      if (response == null) {
        return;
      }
      urlIdCardUp = response['cardFaceImg'];
      nameController.text = response['name'];
      numberController.text = response['idCardNo'];
      urlIdCardDown = response['cardBackImg'];
      startTimeController.text = response['cardBeginDate'];
      endTimeController.text = response['cardEndDate'] ??
          (response['longTermFlag'] == 1 ? '长期' : '');
      upData = response;
      downData = response;
      oldData = response;
      update();
    }, onError: (code, message) {
      update();
    });
  }

  Future<bool> sendCode() {
    var completer = Completer<bool>();
    fetch(Method.get, url: '/msl-user/captchaSms/sendUserIdCardUpdateCaptcha',
        onSuccess: (response) {
      completer.complete(true);
    }, onError: (code, message) {
      completer.complete(false);
    });
    return completer.future;
  }
}
