import 'dart:async';

import 'package:account_center/account_center.dart';
import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/product_menu_control.dart';
import 'package:account_center/common/sp/sp_key.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:account_center/page/account_company/company_home/widget/agent_confirm_dialog.dart';
import 'package:account_center/widget/confirm_dialog_async.dart';
import 'package:flutter/services.dart';

class CompanyManageLogic extends GetxController {
  static CompanyManageLogic? instance;

  /// 企业编号
  String companyNo = '';
  dynamic companyDetail = {};
  dynamic userInfo = {};

  /// 是否代理人登录
  bool get isAgentLogic => userInfo?['agentFlag'] ?? true;

  /// 是否完成企业认证
  bool get isRealNameFlag => userInfo?['realNameFlag'] ?? true;

  String get companyName {
    String name = companyDetail?['companyShortName'] ?? '';
    if (name.isEmpty) {
      name = companyDetail?['companyName'] ?? '';
    }
    if (name.isEmpty) {
      name = '-';
    }
    return name;
  }

  String get companyLogo => companyDetail?['companyLogo'] ?? '';

  /// 公司地址
  String get companyAddress {
    String address = companyDetail?['companyProvince'] ?? '';
    address = '$address${companyDetail['companyCity'] ?? ''}';
    address = '$address${companyDetail['companyCounty'] ?? ''}';
    address = '$address${companyDetail['companyAddress'] ?? ''}';
    return address.isEmpty ? '-' : address;
  }

  /// 是否完成企业认证
  bool get isAuthenCompany => companyDetail?['realNameStatus'] == 30;

  /// 签章是否授权
  bool get isAuthStamp => companyDetail?['sealAuthorizationStatus'] == 1;

  /// 电子签章是否授权
  String get stampStatus {
    if (isAuthStamp) {
      return '查看签章';
    } else {
      return '未授权';
    }
  }

  /// 实名认证流程状态: 0-待认证; 1-已上传并确认信息,待填写对公账户; 2-已填写完银行信息,打款中(或打款失败); 3-已打款, 待验证打款金额; 4-已认证完成 5-打款失败，
  String get companyAuth {
    if (companyDetail?['realNameStatus'] == 30) {
      return '已认证';
    } else if (companyDetail?['realNameStatus'] == 10) {
      return '认证中';
    } else {
      return '未认证';
    }
  }

  @override
  void onInit() {
    companyNo = Get.arguments['companyNo'];
    instance = this;
    super.onInit();
    _checkIsAgentLogic();
  }

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

  @override
  void onClose() {
    instance = null;
    super.onClose();
  }

  /// 检测是否是代理人登录操作
  void _checkIsAgentLogic() {
    CompanyHttps.judgeAgentAndAuthStatus(
      companyNo,
      onSuccess: (data) {
        userInfo = data;
        update();
      },
    );
  }

  //切换公司
  void _changeCompany({String identityType = "company"}) {
    fetch(Method.get, url: HttpApi.updateAccessUserRedisData, queryParameters: {
      "companyNo": companyNo,
      "identityType": identityType,
    }, onSuccess: (data) {
      getCompanyUserByNo();
    });
  }

  //获取企业信息
  Future<bool> getCompanyUserByNo() {
    var completer = Completer<bool>();
    CompanyHttps.getCompanyInfo(
      companyNo,
      onSuccess: (data) {
        if (data == null) return;
        companyDetail = data;
        SpUtil.putString(SPKey.companyName, data['companyName'] ?? "");
        SpUtil.putString(SPKey.companyNo, data['companyNo'] ?? "");
        update();
        getLoginUserMenus();
        completer.complete(true);
      },
      onError: (code, msg) {
        completer.complete(false);
      },
    );

    return completer.future;
  }

  Future<void> refreshCompanyInfo() async {
    LoadingUtils.showLoading();
    await getCompanyUserByNo();
    LoadingUtils.dismiss();
  }

  //获取登录人权限菜单
  void getLoginUserMenus() {
    fetchList(
      Method.get,
      url: HttpApi.getLoginUserMenus,
      queryParameters: {'centerAccount': 2, 'companyNo': companyNo},
      onSuccess: (data) {
        menuCodes.clear();
        menuCodes.addAll(data.map((e) => e.toString()));
        update();
      },
    );
  }

  Future<bool> transferCompany(value) {
    var completer = Completer<bool>();
    fetch(Method.put,
        url: '/msl-user/company/updateCompanyContact',
        queryParameters: {
          'companyNo': companyNo,
          'userNo': value['userNo'],
        }, onSuccess: (data) {
      AlertUtil.showCenterToast('操作成功');
      getCompanyUserByNo().then((value) {
        completer.complete(value);
      });
    }, onError: (code, msg) {
      completer.complete(false);
    });
    return completer.future;
  }

  /// 企业未认证情况下，提示先进行企业认证
  void showAuthAlert() {
    if (!isAgentLogic) {
      AlertUtil.showCenterToast('当前登录账号非代理人，无法进行操作');
      return;
    }
    AlertUtil.showCenterToast('未完成企业认证，请完成后进行授权');
  }

  /// 申请企业签章
  Future<void> applyCompanyStamp() async {
    if (!isAuthenCompany) {
      showAuthAlert();
      return;
    }
    if (isAuthStamp) {
      Get.toNamed(RouteConfig.stampManage)?.then((_) {
        getCompanyUserByNo();
      });
    } else {
      AlertUtil.showLoading();
      // 检测代理人信息
      var adminCheck = await _adminCheck();
      AlertUtil.dismissLoading();
      if (adminCheck.isError) {
        return;
      }
      var esignAgentName = adminCheck.data?['esignAgentName'];
      var esignAgentMobile = adminCheck.data?['esignAgentMobile'];
      AgentHandIntent? agentHandIntent;
      if (adminCheck.data?['accountEqualsFlag'] != true) {
        // 代理人信息不一致，需要确认处理逻辑
        agentHandIntent = await Get.dialog(
          AgentConfirmDialog(
            data: {
              'esignAgentName': esignAgentName,
              'esignAgentMobile': esignAgentMobile,
            },
          ),
          barrierDismissible: false,
        );
        if (agentHandIntent == null) {
          return;
        }
      }
      if (agentHandIntent == AgentHandIntent.goOfficialWebsite) {
        //去官网修改代理人
        return;
      }

      // 获取认证流程url
      AlertUtil.showLoading();
      var authFlow = await startAuthFlow(esignAgentName, esignAgentMobile);
      AlertUtil.dismissLoading();
      if (authFlow.isError) {
        return;
      }

      var url = authFlow.data?['operateUrl'];

      if (agentHandIntent == AgentHandIntent.copyLink) {
        // 复制链接,发送给代理人
        Clipboard.setData(
          ClipboardData(text: url),
        );
        ToastUtil.showToast('复制成功');
        return;
      }

      // 发起认证
      var openSuccess = await IdentificationUtil.startVerifyWeb(url);
      if (openSuccess) {
        await Future.delayed(Duration(milliseconds: 1000));
        var confirm = await ConfirmDialogAsync(
          content: '查询认证结果',
        ).show();
        if (confirm == true) {
          LoadingUtils.showLoading();
          await fetchAsync(Method.get,
              url: '/msl-user/app/company/seal/getCompanySealAuthStatus',
              queryParameters: {
                'companyNo': companyNo,
              }).then((value) {
            if (value.isSuccess) {
              ToastUtil.showToast(
                  value.data?['status'] == 10 ? '认证成功' : '认证失败');
            }
          });
          LoadingUtils.dismiss();
          getCompanyUserByNo();
        }
      }
    }
  }

  Future<FetchResult> _adminCheck() {
    return fetchAsync(Method.get,
        url: '/msl-user/app/company/seal/getEsignAdmin',
        queryParameters: {
          'companyNo': companyNo,
        });
  }

  Future<FetchResult> startAuthFlow(esignAgentName, esignAgentMobile) {
    return fetchAsync(
      Method.post,
      url: '/msl-user/app/company/seal/saveSealAuthFlow',
      params: {
        'companyNo': companyNo,
        'redirectUrl': eSignRedirectUrl,
        'appScheme': AccountCenter.appScheme,
        'esignAdminName': esignAgentName,
        'esignAdminMobile': esignAgentMobile,
      },
    );
  }

  /// 签章使用记录
  void stampUseHistory() {
    Get.toNamed(RouteConfig.stampUseHistory)?.then((_) {
      getCompanyUserByNo();
    });
  }

  /// 邀请成员
  void inviteMemberAction() {
    Get.toNamed(RouteConfig.inviteMemberPage,
        arguments: {'companyNo': companyNo})?.then((_) {
      getCompanyUserByNo();
    });
  }

  /// 企业认证
  void companyAuthAction() {
    if (isAuthenCompany) {
      return;
    }
    if (!isAgentLogic) {
      AlertUtil.showCenterToast('当前登录账号非代理人，无法进行操作');
      return;
    }
    if (!isRealNameFlag) {
      AlertUtil.showCenterToast('企业代理人未完成实名认证，请完成后再进行企业认证');
      return;
    }
    gotoCompanyAuth();
  }

  /// 前往企业实名认证
  Future<void> gotoCompanyAuth() async {
    if (companyDetail?['realNameStatus'] == 10) {
      LoadingUtils.showLoading();
      var result = await fetchAsync(
        Method.get,
        url: '/msl-user/app/company/realName/getAuthFlowStatus',
        queryParameters: {
          'companyNo': companyNo,
        },
      );
      LoadingUtils.dismiss();
      if (result.isSuccess) {
        var realNameUrl = result.data['realNameUrl'];
        await _startVerify(realNameUrl);
      }
      return;
    }
    Get.toNamed(RouteConfig.companyAuthGuide, preventDuplicates: false)
        ?.then((_) {
      getCompanyUserByNo();
    });

    // if (companyDetail?['realName'] != 0) {
    //   Get.toNamed(RouteConfig.companyAuth,
    //       arguments: {'authFro': CompanyAuthFrom.none})?.then((_) {
    //     getCompanyUserByNo();
    //   });
    // } else {
    //   Get.toNamed(RouteConfig.companyAuthGuide, preventDuplicates: false)
    //       ?.then((_) {
    //     getCompanyUserByNo();
    //   });
    // }
  }

  Future<void> _startVerify(realNameUrl) async {
    var bool = await IdentificationUtil.startVerifyWeb(realNameUrl);
    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();
      if (result == 1) {
        _startVerify(realNameUrl);
      } else if (result == 2) {
        _changeCompany();
      }
    }
  }

  Future<void> requestCompanyRealResult() async {
    var result = await fetchAsync(Method.get,
        url: '/msl-user/app/company/realName/getAuthFlowStatus',
        queryParameters: {
          'companyNo': companyNo,
        });
    if (result.isSuccess) {
      var success = result.data?['realNameStatus'] == 30;
      ToastUtil.showToast('认证${success ? '成功' : '失败'}');
    }
  }
}
