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/identification_util.dart';
import 'package:account_center/page/account_company/company_auth/company_verify_result.dart';
import 'package:account_center/page/account_company/company_auth/widget/certification_dialog.dart';
import 'package:account_center/page/account_company/company_home/company_manage_logic.dart';
import 'package:account_center/widget/confirm_dialog_async.dart';
import 'package:flutter/material.dart';

import '../company_home/widget/info_alert.dart';
import './model/business_info_model.dart';
import './model/legal_person_info_model.dart';
import 'model/agent_info_model.dart';
import 'model/bank_info_model.dart';
import 'widget/account_info/bank_list.dart';
import 'widget/account_info/bank_list_logic.dart';
import 'widget/common/comapny_http.dart';
import 'widget/common/company_define.dart';

class CompanyAuthLogic extends GetxController {
  final ScrollController controller = ScrollController();

  final GlobalKey companyImgKey = GlobalKey();
  final GlobalKey companyInfoKey = GlobalKey();
  final GlobalKey legalImgKey = GlobalKey();

  /// 当前认证进度 -1-确认代理人信息 0-待认证; 1-已上传并确认信息,待填写对公账户; 2-已填写完银行信息,打款中(或打款失败); 3-已打款, 待验证打款金额;4-已认证完成 5-打款失败
  int currStep = 0;

  /// 认证来源
  CompanyAuthFrom authFrom = CompanyAuthFrom.none;

  /// 企业信息
  BusinessInfoModel? businessInfoModel = BusinessInfoModel();

  /// 法人信息
  LegalPersonInfoModel? legalPersonInfoModel = LegalPersonInfoModel();

  /// 代理人信息
  AgentInfoModel? agentInfoModel = AgentInfoModel();

  /// 对公账户信息
  BankInfoModel bankInfoModel = BankInfoModel();

  /// 身份证正面识别错误信息
  String? idFaceSideError;

  /// 身份证背面识别错误信息
  String? idBackSideError;

  /// 营业执照识别错误信息
  String? businessLicenseError;

  /// 企业打款验证金额
  String? amount;

  @override
  void onInit() {
    authFrom = Get.arguments?['authFrom'] ?? CompanyAuthFrom.none;
    super.onInit();
    if (authFrom != CompanyAuthFrom.newCompany) {
      getCompanyInfo();
      getAgentInfo();
    }
  }

  /// 展示支持银行列表弹窗
  void getSuportBankList() {
    Get.bottomSheet(
      BankListAlert(
        logic: BankListLogic(),
        selectBank: bankInfoModel.toJson(),
        selectCallBack: (value) {
          bankInfoModel.fromJson(value);
          update();
        },
      ),
      isScrollControlled: true,
    );
  }

  /// 未实名弹窗
  void showRealNameAlert() {
    Get.bottomSheet(
      InfoAlert(
        description: '未完成代理人实名认证，请完成后进行操作',
        actions: [
          AlertAction(
            title: '取消',
            tapCallback: () {
              Get.back();
            },
          ),
          AlertAction(
            title: '去认证',
            type: AlertActionType.light,
            tapCallback: () {
              Get.back();
              Get.toNamed(RouteConfig.identityUserIdCardPage)?.then((value) {
                getAgentInfo();
              });
            },
          ),
        ],
      ),
      isScrollControlled: true,
      enableDrag: false,
      isDismissible: false,
    );
  }

  void getCompanyInfo() {
    CompanyHttps.getCompanyInfo(
      getCompanyNo() ?? '',
      onSuccess: (data) {
        businessInfoModel?.fromJson(data);
        legalPersonInfoModel?.fromJson(data);

        /// 重新认证时，从第一步开始，其他情况可以继续认证
        if (authFrom == CompanyAuthFrom.update) {
          currStep = 0;
          getAgentInfo();
        } else {
          currStep = data?['realNameFlowStatus'] ?? 0;
          if (currStep == 4) {
            gotoResultView(AuthAndSignStatus.authSucc);
            return;
          } else if (currStep == 2 || currStep == 3 || currStep == 5) {
            getCompanyRealNameTransferBankInfo();
          }
        }
        checkCardImgValid();
        if (businessInfoModel?.companyBusinessImg?.isNotEmpty == true) {
          businessUrlCallBack(businessInfoModel?.companyBusinessImg);
        }
        update();
      },
    );
  }

  /// 获取代理人信息
  void getAgentInfo() {
    CompanyHttps.judgeAgentAndAuthStatus(
      getCompanyNo(),
      onSuccess: (data) {
        agentInfoModel?.fromJson(data);
        if (agentInfoModel?.agentFlag == false) {
          /// 非代理人
          AlertUtil.showCenterToast('您不是代理人，无法进行操作');
          return;
        }
        if (agentInfoModel?.realNameFlag == false) {
          showRealNameAlert();
          return;
        }
        update();
      },
    );
  }

  /// 查询企业认证打款信息
  void getCompanyRealNameTransferBankInfo({Function? succ}) {
    CompanyHttps.getCompanyRealNameTransferBankInfo(getCompanyNo(),
        onSuccess: (data) {
      bankInfoModel.bank = data?['bankName'] ?? '-';
      bankInfoModel.bankName = data?['bankSubbranch'] ?? '-';
      bankInfoModel.cardNumber = data?['bankPublicNumber'] ?? '-';
      bankInfoModel.transferFailMessage = data?['transferFailMessage'] ?? '';
      bankInfoModel.transferStatus = data?['transferStatus'] ?? 0;
      bankInfoModel.payeeName = data?['payeeName'] ?? '-';
      bankInfoModel.companyName = data?['companyName'] ?? '-';
      bankInfoModel.city = data?['bankCity'] ?? '-';
      bankInfoModel.cnapsCode = data?['bankCnapsCode'] ?? '-';
      bankInfoModel.province = data?['bankProvince'] ?? '-';
      bankInfoModel.expiredTime = data?['expiredTime'] ??
          DateTime.now().add(Duration(hours: 24)).toYMDHms;
      if (bankInfoModel.transferStatus == 0) {
        AlertUtil.showCenterToast('正在打款中，请耐心等待');
        currStep = 2;
      } else if (bankInfoModel.transferStatus == 2) {
        currStep = 1;
      } else if (bankInfoModel.transferStatus == 1) {
        if (succ != null) {
          succ();
        }
      }
      update();
    });
  }

  /// 营业执照上传完成回调
  void businessUrlCallBack(url) {
    businessInfoModel?.companyBusinessImg = url;
    update();

    CompanyHttps.getBusinessLicenseOcrInfo(
      url,
      getCompanyNo(),
      onSuccess: (data) {
        businessLicenseError = '';
        businessInfoModel?.businessAddress = data?['businessAddress'];
        businessInfoModel?.endTime = data?['businessEndDate'];
        businessInfoModel?.startTime = data?['businessStartDate'];
        businessInfoModel?.isIndefinite = data?['businessLongTermFlag'] == 1;
        businessInfoModel?.businessScope = data?['businessScope'];

        /// 返回的空的
        // businessInfoModel?.companyBusinessImg = data?['companyBusinessImg'];
        businessInfoModel?.companyName = data?['companyName'];
        businessInfoModel?.groupCode = data?['groupCode'];
        businessInfoModel?.legalName = data?['legalName'];
        businessInfoModel?.registeredCapital = data?['registeredCapital'];
        businessInfoModel?.registrationDate = data?['registrationDate'];
        update();
      },
      onError: (code, msg) {
        businessLicenseError = msg;
        update();
      },
    );
  }

  /// 法人身份证正面上传回调
  void legalIdCardOnCallBack(url) {
    legalPersonInfoModel?.faceUrl = url;
    update();
    checkCardImgValid();
  }

  /// 法人身份证反面上传回调
  void legalIdCardBackCallBack(url) {
    legalPersonInfoModel?.backUrl = url;
    update();
    checkCardImgValid();
  }

  /// 检测身份证正反面照片上传情况
  void checkCardImgValid() {
    if (getTXTString(legalPersonInfoModel?.faceUrl).isEmpty ||
        getTXTString(legalPersonInfoModel?.backUrl).isEmpty) {
      return;
    }
    CompanyHttps.getLegalPersonIdCardOcrInfo(
      getCompanyNo(),
      legalPersonInfoModel?.faceUrl,
      legalPersonInfoModel?.backUrl,
      onSuccess: (data) {
        /// 错误信息置空
        idBackSideError = '';
        idFaceSideError = '';

        /// 更新最新对象信息
        legalPersonInfoModel?.backUrl = data?['cardBackImg'];
        legalPersonInfoModel?.faceUrl = data?['cardFaceImg'];
        legalPersonInfoModel?.startTime = data?['cardBeginDate'];
        legalPersonInfoModel?.endTime = data?['cardEndDate'];
        legalPersonInfoModel?.idCard = data?['idCardNo'];
        legalPersonInfoModel?.isIndefinite = data?['longTermFlag'] == 1;
        legalPersonInfoModel?.name = data?['name'];
        update();
      },
      onError: (code, msg) {
        /// 身份证识别错误信息
        idBackSideError = msg;
        idFaceSideError = msg;
        update();
      },
    );
  }

  /// 提交企业资质等信息
  void uploadBusinessInfo() {
    switch (currStep) {
      /// 提交企业信息以及法人信息
      case 0:
        _submittedCompanyAuthInfo();
        break;

      /// 提交代理人信息
      case -1:
        if (agentInfoModel?.realNameFlag == false) {
          showRealNameAlert();
          return;
        }
        _confirmAgentInfo();
        break;

      /// 提交对公账户信息
      case 1:
      case 5:
        _submittedBankInfo();
        break;

      /// 查看打款结果
      case 2:
        if (bankInfoModel.transferStatus != 1) {
          getCompanyRealNameTransferBankInfo(succ: () {
            currStep = 3;
            update();
          });
        } else {
          currStep = 3;
          update();
        }

        break;

      /// 打款验证
      case 3:
        _submittedAmount();
        break;
      default:
    }
  }

  /// 提交企业认证资料
  void _submittedCompanyAuthInfo() {
    if (businessInfoModel?.companyBusinessImg?.isEmpty == true) {
      AlertUtil.showCenterToast('请上传营业执照照片');
      controller.jumpTo(0);
      return;
    }
    if (businessInfoModel?.isValid == false) {
      AlertUtil.showCenterToast(businessInfoModel?.errorMsg);
      controller.jumpTo((companyInfoKey.currentContext?.getY ?? 0) -
          (companyImgKey.currentContext?.getY ?? 0));
      return;
    }
    if (legalPersonInfoModel?.faceUrl?.isEmpty == true ||
        legalPersonInfoModel?.backUrl?.isEmpty == true) {
      AlertUtil.showCenterToast('请上传法人身份证照片');
      controller.jumpTo((legalImgKey.currentContext?.getY ?? 0) -
          (companyImgKey.currentContext?.getY ?? 0));
      return;
    }
    if (legalPersonInfoModel?.isValid == false) {
      AlertUtil.showCenterToast(legalPersonInfoModel?.errorMsg);
      return;
    }

    getAgentInfo();
    currStep = -1;
    update();

    // CompanyHttps.confirmCompanyRealNameInfo(
    //   businessInfoModel?.toJson(),
    //   legalPersonInfoModel?.toJson(),
    //   getCompanyNo(),
    //   onSuccess: (data) {
    //     getAgentInfo();
    //     currStep = -1;
    //     update();
    //   },
    // );
  }

  /// 确认代理人信息
  void _confirmAgentInfo() {
    if (getTXTString(agentInfoModel?.sms).isEmpty) {
      AlertUtil.showCenterToast('请填写代理人短信验证码');
      return;
    }
    CompanyHttps.saveCompanyRealNameFlow(
      agentInfoModel?.sms,
      getCompanyNo(),
      onSuccess: (data) {
        currStep = 1;
        update();
      },
    );
  }

  /// 提交对公账户信息
  void _submittedBankInfo() {
    if (!bankInfoModel.isValid) {
      AlertUtil.showCenterToast(bankInfoModel.errorMsg);
      return;
    }

    CompanyHttps.savePublicTransferAmount(
      {
        "bank": bankInfoModel.bank,
        "bankCardNo": bankInfoModel.cardNumber,
        "bankName": bankInfoModel.bankName,
        "city": bankInfoModel.city,
        "cnapsCode": bankInfoModel.cnapsCode,
        "companyNo": getCompanyNo(),
        "province": bankInfoModel.province,
      },
      onSuccess: (data) {
        getCompanyRealNameTransferBankInfo();
        currStep = 2;
        update();
      },
    );
  }

  /// 验证企业认证打款金额
  void _submittedAmount() {
    if (getTXTString(amount).isEmpty) {
      AlertUtil.showCenterToast('请填写收款账户收到的金额');
      return;
    }

    CompanyHttps.verifyRealNameTransferAmount(
      '0.$amount',
      getCompanyNo(),
      onSuccess: (data) {
        AuthAndSignStatus result = AuthAndSignStatus.authSucc;
        String errorMsg = '';
        if (data?['success'] == false) {
          if (data?['invalid'] == true) {
            result = AuthAndSignStatus.authFail;
            errorMsg = '验证金额已失效，请重新发起认证';
          } else {
            if (data?['verifyTimes'] >= 3) {
              result = AuthAndSignStatus.authFail;
              errorMsg = '金额验证错误超过3次，请重新填写资料';
            } else {
              AlertUtil.showCenterToast('验证金额有误，请重新填写');
              return;
            }
          }
        }
        gotoResultView(result, errorMsg: errorMsg);
      },
    );
  }

  void gotoResultView(AuthAndSignStatus result, {String errorMsg = ''}) {
    Get.offNamed(
      RouteConfig.companyAuthResult,
      arguments: {'errorMsg': errorMsg, 'result': result},
      parameters: {'from': 'auth'},
    );
  }

  /// 营业执照信息填写完成回调
  void updateBusinessInfo(int type, String? value) {
    if (type == 0) {
      businessInfoModel?.companyName = value;
    } else if (type == 1) {
      businessInfoModel?.groupCode = value;
    } else if (type == 2) {
      businessInfoModel?.registeredCapital = value;
    } else {
      businessInfoModel?.registrationDate = value;
    }
    update();
  }

  /// 营业执照有效期信息回调
  void updateBusinessValidity(
      String startTime, String endTime, bool isIndefinite) {
    businessInfoModel?.startTime = startTime;
    businessInfoModel?.endTime = endTime;
    businessInfoModel?.isIndefinite = isIndefinite;
    update();
  }

  /// 法人信息填写完成回调
  void updateLegalInfo(int type, String? value) {
    if (type == 0) {
      legalPersonInfoModel?.name = value;
    } else if (type == 1) {
      legalPersonInfoModel?.idCard = value;
    }
    update();
  }

  /// 法人有效期信息回调
  void updateLegalValidity(
      String startTime, String endTime, bool isIndefinite) {
    legalPersonInfoModel?.startTime = startTime;
    legalPersonInfoModel?.endTime = endTime;
    legalPersonInfoModel?.isIndefinite = isIndefinite;
    update();
  }

  /// 代理人短信验证码
  void receiveAgentSms(String? value) {
    agentInfoModel?.sms = value;
    update();
  }

  /// 银行卡号填写
  void updateBankInfo(String? value) {
    bankInfoModel.cardNumber = value;
    update();
  }

  /// 打款金额
  void receiveAmount(String? value) {
    amount = value;
    update();
  }

  Future<void> startEsignVerify() async {
    LoadingUtils.showLoading();
    var result = await startAuthFlow();

    LoadingUtils.dismiss();
    if (result.isSuccess) {
      if (result.data?['createSucceed'] == true) {
        await _startVerify(result.data?['authUrl']);
      } else {
        // Get.to(
        //   VerifyConfirm(
        //     action: () async {
        //       await _startAuthorization(result);
        //     },
        //   ),
        // );
        await _startAuthorization(result);
      }
    }
  }

  Future<void> _startAuthorization(FetchResult result) async {
    result.data?['companyNo'] = getCompanyNo();
    var codeCheckResult = await Get.dialog(
      CertificationDialog(
        data: result.data,
      ),
    );
    if (codeCheckResult == true) {
      Get.back();
      CompanyManageLogic.instance?.refreshCompanyInfo();
      AlertUtil.showCenterToast('授权成功');
    } else if (codeCheckResult == false) {
      AlertUtil.showCenterToast('认证次数已达上限，请重新认证');
    }
  }

  Future<FetchResult> startAuthFlow() {
    return fetchAsync(Method.post,
        url: '/msl-user/app/company/realName/saveCompanyAuthFlow',
        params: {
          "companyNo": getCompanyNo(),
          "businessLicenseInfoVo": {
            "companyName": businessInfoModel?.companyName,
            "groupCode": businessInfoModel?.groupCode,
            "businessStartDate": businessInfoModel?.startTime,
            "businessEndDate": businessInfoModel?.endTime,
            "businessLongTermFlag":
                businessInfoModel?.isIndefinite ?? false ? 1 : 0,
            "legalName": legalPersonInfoModel?.name,
            "businessAddress": businessInfoModel?.businessAddress,
            "businessScope": businessInfoModel?.businessScope,
            "registeredCapital": businessInfoModel?.registeredCapital,
            "registrationDate": businessInfoModel?.registrationDate,
            "companyBusinessImg": businessInfoModel?.companyBusinessImg
          },
          "legalIdCardInfoVo": {
            "name": legalPersonInfoModel?.name,
            "idCardNo": legalPersonInfoModel?.idCard,
            "cardFaceImg": legalPersonInfoModel?.faceUrl,
            "cardBackImg": legalPersonInfoModel?.backUrl,
            "cardBeginDate": legalPersonInfoModel?.startTime,
            "cardEndDate": legalPersonInfoModel?.endTime,
            "longTermFlag": legalPersonInfoModel?.isIndefinite ?? false ? 1 : 0,
            // "message": legalPersonInfoModel?.errorMsg
          },
          'redirectUrl': eSignRedirectUrl
        });
  }

  Future<void> _startVerify(url) async {
    var bool = await IdentificationUtil.startVerifyWeb(url);
    if (bool) {
      await Future.delayed(Duration(milliseconds: 1000));
      var result = await ConfirmDialogAsync(
        content: '是否完成企业认证？',
        leftText: '重新发起认证',
        leftTap: () {
          Get.back(result: 1);
        },
        rightText: '已完成授权',
        rightTap: () {
          Get.back(result: 2);
        },
      ).show(barrierDismissible: false);
      if (result == 1) {
        _startVerify(url);
      } else if (result == 2 || result == null) {
        Get.off(CompanyVerifyResult(businessInfoModel: businessInfoModel));
      }
    }
  }
}
