import 'dart:async';

import 'package:account_center/account_center.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/widget/common/comapny_http.dart';
import 'package:flutter/services.dart';

import '../../../widget/confirm_dialog.dart';

class CompanySignLogic extends GetxController {
  dynamic confirmInfo;

  String? get busniessName => confirmInfo?['companyName'];

  String? get busniessCode => confirmInfo?['groupCode'];

  String? get legalName => confirmInfo?['legalName'];

  String? get agentName => confirmInfo?['agentName'];

  String? get agentIdCard => confirmInfo?['agentIdCardNo'];

  String? get agentPhone => confirmInfo?['agentMobile'];

  String get btnTitle {
    if (_count == 60) {
      return '获取验证码';
    } else {
      return '重新获取(${_count}s)';
    }
  }

  int _count = 60;
  Timer? _timer;
  String? sms;

  @override
  void onInit() {
    super.onInit();

    _getconfirmInfo();
  }

  /// 获取企业信息
  void _getconfirmInfo() {
    CompanyHttps.getCompanySealAuthorizationConfirmInfo(
      getCompanyNo(),
      onSuccess: (data) {
        confirmInfo = data;
        update();
      },
    );
  }

  /// 短信验证码接受
  void receiveSms(String value) {
    sms = value;
    update();
  }

  /// 发送验证码
  void sendSms() {
    if (getTXTString(agentPhone).isEmpty) {
      AlertUtil.showCenterToast('代理人手机号为空，请联系管理员设置');
      return;
    }
    if (_count < 60) {
      return;
    }

    CompanyHttps.sendCompanySealAuthorizationCaptcha(
      agentPhone,
      getCompanyNo(),
      onSuccess: (data) {
        _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
          _count--;
          if (_count == 0) {
            _count = 60;
            _timer?.cancel();
          }
          update();
        });
      },
    );
  }

  /// 申请签章
  void applySign() {
    if (getTXTString(sms).isEmpty) {
      AlertUtil.showCenterToast('请填写验证码');
      return;
    }
    CompanyHttps.saveCompanySealAuthorizationFlow(
      sms,
      getCompanyNo(),
      onSuccess: (data) {
        Clipboard.setData(ClipboardData(text: data));
        IdentificationUtil.startVerifyWeb(data).then((_) {
          ConfirmDialog(
            content: '请确认您已完成授权认证',
            confirmButtonText: '我已完成授权',
            confirm: () {
              Get.offNamed(RouteConfig.companyAuthResult,
                  parameters: {'from': 'sign'});
            },
          ).show();
        });
      },
    );
  }
}
