import 'package:account_center/account_center.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/page/account_center/account_info/identification_util.dart';
import 'package:account_center/page/account_company/company_auth/model/business_info_model.dart';
import 'package:account_center/page/account_company/company_home/company_manage_logic.dart';
import 'package:account_center/style/widget/button_public_radius.dart';
import 'package:account_center/widget/asset_image_widget.dart';
import 'package:account_center/widget/confirm_dialog_async.dart';
import 'package:account_center/widget/no_data.dart';
import 'package:flutter/material.dart';

class CompanyVerifyResult extends StatefulWidget {
  final BusinessInfoModel? businessInfoModel;
  const CompanyVerifyResult({
    super.key,
    this.businessInfoModel,
  });

  @override
  State<CompanyVerifyResult> createState() => _CompanyVerifyResultState();
}

class _CompanyVerifyResultState extends State<CompanyVerifyResult> {
  bool _isLoading = true;
  bool _isSuccess = false;
  bool _isError = false;
  String? realNameUrl;

  @override
  void initState() {
    _requestResult();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: const Text('认证结果'),
      ),
      body: _isError
          ? Center(
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                  NoData(
                    title: '查询失败',
                  ),
                  const SizedBox(height: 20),
                  ButtonPublicRadius(
                    text: '点击刷新',
                    onPress: () {
                      _requestResult();
                    },
                  ),
                ]))
          : _isLoading
              ? const Center(
                  child: CircularProgressIndicator(),
                )
              : Column(
                  children: [
                    SizedBox(
                      height: 40,
                    ),
                    AssetImageWidget(
                      imgFileName:
                          _isSuccess ? 'circle_success' : 'circle_failed',
                      width: 52,
                      height: 52,
                    ),
                    SizedBox(
                      height: 20,
                    ),
                    Text(
                      _isSuccess ? '恭喜您' : '很遗憾',
                      style: TextStyle(
                        fontSize: 17,
                        color: Color(0xFF171A1D),
                      ),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: Text(
                        widget.businessInfoModel?.companyName ?? '',
                        style: TextStyle(
                          fontSize: 13,
                          color: Color(
                            0xFF86909C,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      height: 40,
                    ),
                    if (_isSuccess)
                      ButtonPublicRadius(
                        text: '前往完成签章授权',
                        onPress: () async {
                          Get.back();
                          await findOtherLogic<CompanyManageLogic>()
                              ?.getCompanyUserByNo();
                          findOtherLogic<CompanyManageLogic>()
                              ?.applyCompanyStamp();
                        },
                      )
                    else
                      ButtonPublicRadius(
                        text: '重新授权',
                        onPress: () {
                          if (realNameUrl == null) {
                            ToastUtil.showToast('发起授权失败');
                            return;
                          }
                          _startVerify(realNameUrl);
                        },
                      ),
                  ],
                ),
    );
  }

  Future<void> _requestResult() async {
    setState(() {
      _isLoading = true;
      _isError = false;
    });
    var result = await fetchAsync(
      Method.get,
      url: '/msl-user/app/company/realName/getAuthFlowStatus',
      queryParameters: {
        'companyNo': widget.businessInfoModel?.companyNo,
      },
    );
    if (result.isSuccess) {
      realNameUrl = result.data['realNameUrl'];
      setState(() {
        _isLoading = false;
        _isSuccess = result.data?['realNameStatus'] == 30;
      });
    } else {
      setState(() {
        _isLoading = false;
        _isError = true;
      });
    }
  }

  Future<void> _startVerify(url) async {
    var bool = await IdentificationUtil.startVerifyWeb(url);
    if (bool == true) {
      await Future.delayed(Duration(milliseconds: 1000));
      var result = await ConfirmDialogAsync(
        content: '查询认证结果',
        leftText: '重新发起认证',
        leftTap: () {
          Get.back(result: 1);
        },
        rightText: '已完成授权',
        rightTap: () {
          Get.back(result: 2);
        },
      ).show();
      LoadingUtils.showLoading();
      await _requestResult();
      LoadingUtils.dismiss();
      if (result == 1) {
        if (!_isSuccess) {
          _startVerify(url);
        }
      } else if (result == 2) {
        if (!_isSuccess) {
          ToastUtil.showToast("未查询到授权结果");
        }
      }
    }
  }
}
