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/common/sp/sp_util.dart';
import 'package:account_center/page/account_center/account_center_logic.dart';
import 'package:account_center/page/account_center/account_info/identification_util.dart';
import 'package:account_center/page/account_center/widget/identity_face_fail.dart';
import 'package:account_center/page/account_center/widget/identity_success.dart';
import 'package:account_center/page/account_center/widget/seal_preview.dart';
import 'package:account_center/widget/confirm_dialog.dart';
import 'package:account_center/widget/select_image_utils.dart';
import 'package:flutter/material.dart';

import 'account_info_state.dart';

class AccountInfoLogic extends GetxController {
  final AccountInfoState state = AccountInfoState();
  final accountCenterLogic = findOtherLogic<AccountCenterLogic>();
  dynamic userInfo;
  bool isDefaultAvatar = false;
  int realNameFlowNode = -1;

  String? get failReason => userInfo?['auditRemark'];

  /// 签名是否授权
  bool get isSignAuthorization => userInfo?['sealId'] != null;

  String get userSignStatusName => isSignAuthorization ? '查看' : '未授权';

  @override
  void onReady() {
    _getLoginUserInfo();
    super.onReady();
  }

  //获取登录人的信息
  Future<int> _getLoginUserInfo() async {
    Completer<int> completer = Completer<int>();
    fetch(Method.get,
        url: HttpApi.getUserDetailInfo,
        queryParameters: {"userNo": getUserNo()}, onSuccess: (data) {
      userInfo = data;
      state.avatar = data['headImg'] ?? '';
      state.name = data['userName'] ?? '';
      state.phone = data['userMobile'] ?? '';
      SpUtil.putString(SPKey.userMobile, state.phone);
      realNameFlowNode = data?['realNameFlowNode'] ?? 1;
      isDefaultAvatar = data['defaultHeadImgFlag'] == true;
      update();

      completer.complete(realNameFlowNode);
    }, onError: (code, msg) {
      completer.complete(realNameFlowNode);
    });
    return completer.future;
  }

  bool isRealNamed() {
    return userInfo?['realNameFlowNode'] == 6;
  }

  bool hasNewRealMessage() {
    return userInfo?['unReadIdCardAuditResult'] == true ||
        userInfo?['unReadIdCardAuditResult'] == true;
  }

  //修改头像
  void changeAvatar() {
    selectPicType(
        onSuccess: (data) {
          fetch(Method.get,
              url: HttpApi.saveHeadImg,
              queryParameters: {"imgUrl": data}, onSuccess: (data) {
            ToastUtil.showToast('修改成功');
            onReady();
            accountCenterLogic?.onReady();
          });
        },
        onReset: isDefaultAvatar
            ? null
            : () {
                ConfirmDialog(
                    content: '确定要重置头像吗？',
                    confirm: () {
                      LoadingUtils.showLoading();
                      fetch(
                        Method.put,
                        url: HttpApi.resetDefaultHeadImg,
                        onSuccess: (data) {
                          onReady();
                          accountCenterLogic?.onReady();
                          ToastUtil.showToast('恢复默认头像成功');
                          LoadingUtils.dismiss();
                        },
                        onError: (code, error) {
                          LoadingUtils.dismiss();
                        },
                      );
                    }).show();
              });
  }

  void changeName(String text) {
    state.name = text;
    update();
  }

  void toUserSignPage() {
    if (realNameFlowNode != 5) {
      ToastUtil.showToast('请先完成实名认证');
      return;
    }
    if (isSignAuthorization) {
      Get.dialog(Dialog(
        child: SealPreview(
          url: userInfo['sealImage'] ?? '',
          id: userInfo['sealId'] ?? '',
        ),
      ));
    } else {
      Get.toNamed(RouteConfig.userSeal)?.then((value) {
        _getLoginUserInfo();
      });
    }
  }

  void toSignRecordPage() {
    Get.toNamed(RouteConfig.signHistory, arguments: userInfo);
  }

  void toUserIdentification() {
    IdentificationUtil.toIdentificationPage(realNameFlowNode)?.then((value) {
      if (value != null) {
        checkResult(value);
      } else {
        _getLoginUserInfo();
      }
    });
  }

  void checkResult(dynamic value) {
    IdentificationUtil.getFaceIdentifyResult(value).then((value) {
      _getLoginUserInfo();
      if (value['code'] == 2) {
        Get.to(IdentitySuccess());
      } else if (value['code'] == 1) {
        Get.to(
          IdentityFaceFail(
            failReason: value?['subCode']?.toString() ?? '',
          ),
        );
      } else {
        ToastUtil.showToast('认证失败');
      }
    });

    // 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: () {
    //               IdentificationUtil.getFaceIdentifyResult(value).then((value) {
    //                 _getLoginUserInfo();
    //                 if (value['code'] == 2) {
    //                   Get.back();
    //                   Get.to(IdentitySuccess());
    //                 } else if (value['code'] == 1) {
    //                   Get.back();
    //                   Get.to(
    //                     IdentityFaceFail(
    //                       failReason: value?['subCode']?.toString() ?? '',
    //                     ),
    //                   );
    //                 }
    //               });
    //             },
    //             margin: EdgeInsets.all(0),
    //           ),
    //           SizedBox(
    //             height: 20,
    //           )
    //         ],
    //       ),
    //     ),
    //   ),
    // );
  }
}
