import 'dart:async';

import 'package:account_center/api/api_config.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_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/seal_result.dart';
import 'package:account_center/style/widget/button_public_radius.dart';
import 'package:flutter/material.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

class UserSealIdentificationLogic extends GetxController {
  dynamic userInfo;

  var codeController = TextEditingController();

  var codeNode = FocusNode();

  var check = false;

  String? get userPhone => userInfo?['mobile'];

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

  void _requestUserInfo() {
    fetch(Method.get,
        url: HttpApi.getUserRealNameInfo,
        queryParameters: {'userNo': getUserNo()}, onSuccess: (response) {
      userInfo = response;
      update();
    });
  }

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

  void confirm() {
    if (codeController.text.isEmpty) {
      ToastUtil.showToast('请填写验证码');
      check = true;
      update();
      return;
    }
    LoadingUtils.showLoading();
    fetch(
      Method.post,
      url: '/msl-user/app/user/seal/saveUserSealAuthorizationFlow',
      params: {
        'captcha': codeController.text,
        'userNo': getUserNo(),
        'redirectUrl': eSignRedirectUrl
      },
      onSuccess: (response) {
        LoadingUtils.dismiss();
        IdentificationUtil.startVerifyWeb(response['url']).then((value) {
          if (value != true) return;
          Future.delayed(Duration(seconds: 2), () {
            _showRefreshDialog(response['id']);
          });
        });
      },
      onError: (code, msg) {
        LoadingUtils.dismiss();
      },
    );
  }

  void _showRefreshDialog(id) {
    Get.dialog(
      Dialog(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 30),
          decoration: BoxDecoration(
              color: Colors.white, borderRadius: BorderRadius.circular(10)),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                height: 30,
              ),
              Container(
                padding: EdgeInsets.all(5),
                child: Text(
                  '签名授权结果查询',
                  style: TextStyle(color: Color(0xFF344254), fontSize: 16),
                ),
              ),
              SizedBox(
                height: 25,
              ),
              ButtonPublicRadius(
                text: '确定',
                onPress: () {
                  LoadingUtils.showLoading();
                  fetch(
                    Method.get,
                    url: '/msl-user/app/user/seal/getAuthorizationResult',
                    queryParameters: {'id': id},
                    onSuccess: (response) {
                      LoadingUtils.dismiss();
                      findOtherLogic<AccountInfoLogic>()?.onReady();
                      var success = response?['success'] == true;
                      Get.back();
                      Get.off(
                        SealIdentityResult(
                          isSuccess: success,
                          failReason: success ? null : response['message'],
                        ),
                      );
                    },
                    onError: (e, m) {
                      LoadingUtils.dismiss();
                    },
                  );
                },
                margin: EdgeInsets.all(0),
              ),
              SizedBox(
                height: 20,
              )
            ],
          ),
        ),
      ),
    );
  }
}
