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_key.dart';
import 'package:account_center/page/account_center/account_info/identification_util.dart';
import 'package:account_center/page/account_company/company_auth/widget/common/gesture_tap.dart';
import 'package:flutter/cupertino.dart';

class RealNameWidget extends StatefulWidget {
  /// 独立使用需要传入token
  final String? token;
  final String userNo;
  final Widget Function(String status, dynamic userInfo) childBuilder;
  final Widget Function()? onTab;

  const RealNameWidget({
    Key? key,
    this.token,
    this.onTab,
    required this.userNo,
    required this.childBuilder,
  }) : super(key: key);

  @override
  State<RealNameWidget> createState() => _RealNameWidgetState();
}

class _RealNameWidgetState extends State<RealNameWidget> {
  dynamic userInfo;

  @override
  void initState() {
    if (widget.token != null) {
      SpUtil.putString(SPKey.token, widget.token!);
    }
    _getLoginUserInfo();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureTapWidget(
      onTap: () {
        if (status != 4 && status != 6) {
          widget.onTab?.call();
        }
        IdentificationUtil.toIdentificationPage(status)?.then((value) async {
          LoadingUtils.showLoading();
          if (value != null) {
            await Future.delayed(Duration(milliseconds: 1000));
            await IdentificationUtil.getFaceIdentifyResult(value);
            await _getLoginUserInfo();
            if (status == 4 || status == 6) {
              widget.onTab?.call();
            }
            setState(() {});
          }
          LoadingUtils.dismiss();
          setState(() {});
        });
      },
      child: widget.childBuilder(
          IdentificationUtil.getStatusName(status), userInfo),
    );
  }

  dynamic get status => userInfo?['realNameFlowNode'];

  //获取登录人的信息
  Future<dynamic> _getLoginUserInfo() async {
    Completer<int> completer = Completer<int>();
    var realNameFlowNode = -1;
    fetch(Method.get,
        url: HttpApi.getUserDetailInfo,
        queryParameters: {"userNo": widget.userNo}, onSuccess: (data) {
      setState(() {
        userInfo = data;
      });
      realNameFlowNode = data?['realNameFlowNode'] ?? 1;
      completer.complete(realNameFlowNode);
    }, onError: (code, msg) {
      completer.complete(realNameFlowNode);
    });
    return completer.future;
  }

  /// 正在点击
  bool isPressed = false;
}
