import 'package:flutter/foundation.dart';
import 'contract_signing_service.dart';
import 'pre_planting_service.dart';

/// 合同检查结果
class ContractCheckResult {
  /// 是否有待签署的合同
  final bool hasPendingContracts;

  /// 是否需要先完成 KYC
  final bool requiresKyc;

  /// 需要 KYC 时的提示消息
  final String? kycMessage;

  /// 已付款但未完成 KYC 的订单数量
  final int paidOrderCount;

  /// 待签署的预种合并合同编号（有则跳到合并详情页）
  final String? pendingPrePlantingMergeNo;

  ContractCheckResult({
    required this.hasPendingContracts,
    required this.requiresKyc,
    this.kycMessage,
    this.paidOrderCount = 0,
    this.pendingPrePlantingMergeNo,
  });

  /// 是否需要强制操作（有待签署合同或需要 KYC）
  bool get requiresAction => hasPendingContracts || requiresKyc;
}

/// 合同检查服务
/// 用于在 App 启动时检查用户是否有未签署的合同或需要完成 KYC
class ContractCheckService {
  final ContractSigningService _contractSigningService;
  final PrePlantingService _prePlantingService;

  ContractCheckService({
    required ContractSigningService contractSigningService,
    required PrePlantingService prePlantingService,
  })  : _contractSigningService = contractSigningService,
        _prePlantingService = prePlantingService;

  /// 检查是否有待签署的合同（含预种合并合同）
  /// 返回 true 表示有待签署合同，需要强制签署
  Future<bool> hasPendingContracts() async {
    try {
      final unsignedTasks = await _contractSigningService.getUnsignedTasks();
      if (unsignedTasks.isNotEmpty) return true;
      final mergeNo = await _getPendingPrePlantingMergeNo();
      return mergeNo != null;
    } catch (e) {
      return false;
    }
  }

  /// 综合检查：待签署合同和 KYC 需求
  ///
  /// 返回检查结果，包含：
  /// - 是否有待签署的合同（含预种合并合同）
  /// - 是否需要先完成 KYC（有已付款订单但未完成 KYC）
  Future<ContractCheckResult> checkAll() async {
    try {
      // 1. 检查普通认种未签署合同
      final unsignedTasks = await _contractSigningService.getUnsignedTasks();
      if (unsignedTasks.isNotEmpty) {
        return ContractCheckResult(
          hasPendingContracts: true,
          requiresKyc: false,
        );
      }

      // 2. 检查预种待签合并合同
      final pendingMergeNo = await _getPendingPrePlantingMergeNo();
      if (pendingMergeNo != null) {
        return ContractCheckResult(
          hasPendingContracts: true,
          requiresKyc: false,
          pendingPrePlantingMergeNo: pendingMergeNo,
        );
      }

      // 3. 没有待签署合同，检查是否有需要 KYC 的情况
      final kycResult = await _contractSigningService.checkKycRequirement();

      return ContractCheckResult(
        hasPendingContracts: false,
        requiresKyc: kycResult.requiresKyc,
        kycMessage: kycResult.message,
        paidOrderCount: kycResult.paidOrderCount,
      );
    } catch (e) {
      return ContractCheckResult(
        hasPendingContracts: false,
        requiresKyc: false,
      );
    }
  }

  /// 获取待签署合同数量
  Future<int> getPendingContractCount() async {
    try {
      final unsignedTasks = await _contractSigningService.getUnsignedTasks();
      if (unsignedTasks.isNotEmpty) return unsignedTasks.length;
      final mergeNo = await _getPendingPrePlantingMergeNo();
      return mergeNo != null ? 1 : 0;
    } catch (e) {
      return 0;
    }
  }

  /// 查找第一个待签署的预种合并合同编号
  Future<String?> _getPendingPrePlantingMergeNo() async {
    try {
      final merges = await _prePlantingService.getMyMerges();
      final pending = merges.where(
        (m) => m.contractStatus == PrePlantingContractStatus.pending,
      );
      return pending.isEmpty ? null : pending.first.mergeNo;
    } catch (e) {
      return null;
    }
  }
}
