import 'dart:async';
import 'dart:io' show Platform;

import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../services/api_service/kr_subscribe_api.dart';
import '../../../routes/app_pages.dart';
import '../../../model/response/kr_order_status.dart';
import '../../../utils/kr_event_bus.dart';
import '../../../utils/kr_common_util.dart';
import '../../../localization/app_translations.dart';
import '../../../utils/kr_log_util.dart';

/// 订单状态控制器
class KROrderStatusController extends GetxController {
  /// API服务
  final KRSubscribeApi kr_subscribeApi = KRSubscribeApi();

  /// 支付是否成功
  final RxBool kr_isPaymentSuccess = false.obs;

  /// 是否正在加载
  final RxBool kr_isLoading = true.obs;

  /// 支付URL
  final String kr_paymentUrl = Get.arguments['url'] as String;

  /// 订单信息
  final String kr_order = Get.arguments['order'];

  /// 支付方式类型
  final String kr_paymentType = Get.arguments['payment_type'] as String;

  /// 定时器
  Timer? kr_timer;

  /// 订单状态常量
  static const int kr_statusPending = 1;    // 待支付
  static const int kr_statusPaid = 2;       // 已支付
  static const int kr_statusClose = 3;      // 已关闭
  static const int kr_statusFailed = 4;     // 支付失败
  static const int kr_statusFinished = 5;   // 已完成

  /// 状态标题
  final RxString kr_statusTitle = AppTranslations.kr_orderStatus.initialTitle.obs;

  /// 状态描述
  final RxString kr_statusDescription = AppTranslations.kr_orderStatus.initialDescription.obs;

  /// 状态图标名称
  final RxString kr_statusIcon = 'payment_success'.obs;

  @override
  void onInit() {
    super.onInit();
    kr_startCheckingPaymentStatus();
  }

  @override
  void onReady() {
    super.onReady();
    // 只有在非余额支付且有支付URL时才处理支付跳转
    if (kr_paymentUrl.isNotEmpty && kr_paymentType != 'balance') {
      if (Platform.isAndroid || Platform.isIOS) {
        // 移动端使用 WebView
        Get.toNamed(
          Routes.KR_WEBVIEW,
          arguments: {
            'url': kr_paymentUrl,
            'order': kr_order,
          },
        );
      } else {
        // 桌面端使用外部浏览器
        final Uri uri = Uri.parse(kr_paymentUrl);
        launchUrl(uri, mode: LaunchMode.externalApplication);
      }
    }
  }

  @override
  void onClose() {
    kr_timer?.cancel();
    super.onClose();
  }

  /// 开始检查支付状态
  void kr_startCheckingPaymentStatus() {
    // 根据支付方式类型设置不同的查询间隔
    final Duration interval = kr_paymentType == 'balance' 
        ? const Duration(seconds: 2)  // 余额支付每2秒查询一次
        : const Duration(seconds: 5); // 其他支付方式每5秒查询一次
    
    kr_timer = Timer.periodic(interval, (timer) {
      kr_checkPaymentStatus();
    });
  }

  /// 检查支付状态
  Future<void> kr_checkPaymentStatus() async {
    try {
      final result = await kr_subscribeApi.kr_orderDetail(kr_order);

      result.fold(
        (error) {
          KRLogUtil.kr_e('检查支付状态失败: $error', tag: 'OrderStatusController');
          kr_isLoading.value = false;
          kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle;
          kr_statusDescription.value = AppTranslations.kr_orderStatus.checkFailedDescription;
          kr_statusIcon.value = 'payment_success';
        },
        (kr_orderStatus) {
          KRLogUtil.kr_i('检查支付状态: ${kr_orderStatus.toJson()}', tag: 'OrderStatusController');
          switch (kr_orderStatus.kr_status) {
            case kr_statusPending:
              // 待支付状态，继续轮询
              kr_statusTitle.value = AppTranslations.kr_orderStatus.pendingTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.pendingDescription;
              kr_statusIcon.value = 'payment_success';
              break;
            case kr_statusPaid:
              // 已支付状态，继续轮询直到完成
              kr_statusTitle.value = AppTranslations.kr_orderStatus.paidTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.paidDescription;
              kr_statusIcon.value = 'payment_success';
              break;
            case kr_statusFinished:
              // 订单完成
              kr_isPaymentSuccess.value = true;
              kr_isLoading.value = false;
              kr_timer?.cancel();
              kr_statusTitle.value = AppTranslations.kr_orderStatus.successTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.successDescription;
              kr_statusIcon.value = 'payment_success';
              KREventBus().kr_sendMessage(KRMessageType.kr_payment);
              break;
            case kr_statusClose:
              // 订单已关闭
              kr_isLoading.value = false;
              kr_timer?.cancel();
              kr_statusTitle.value = AppTranslations.kr_orderStatus.closedTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.closedDescription;
              kr_statusIcon.value = 'payment_success';
              break;
            case kr_statusFailed:
              // 支付失败
              kr_isLoading.value = false;
              kr_timer?.cancel();
              kr_statusTitle.value = AppTranslations.kr_orderStatus.failedTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.failedDescription;
              kr_statusIcon.value = 'payment_success';
              break;
            default:
              // 未知状态
              kr_isLoading.value = false;
              kr_timer?.cancel();
              kr_statusTitle.value = AppTranslations.kr_orderStatus.unknownTitle;
              kr_statusDescription.value = AppTranslations.kr_orderStatus.unknownDescription;
              kr_statusIcon.value = 'payment_success';
              break;
          }
        },
      );
    } catch (error) {
      KRLogUtil.kr_e('检查支付状态失败: $error', tag: 'OrderStatusController');
      kr_isLoading.value = false;
      kr_statusTitle.value = AppTranslations.kr_orderStatus.checkFailedTitle;
      kr_statusDescription.value = AppTranslations.kr_orderStatus.checkFailedDescription;
      kr_statusIcon.value = 'payment_success';
    }
  }

  /// 检查支付状态
  Future<void> kr_checkPaymentStatusWithRetry() async {
    try {
      // ... 其他代码 ...
    } catch (err) {
      KRLogUtil.kr_e('检查支付状态失败: $err', tag: 'OrderStatusController');
    }
  }
}
