import 'dart:async';

import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:injectable/injectable.dart';
import 'package:get/get.dart';
import 'package:keyboard/module/store/suprise/surprise_dialog.dart';
import '../../../base/base_controller.dart';
import '../../../data/bean/goods_info.dart';
import '../../../data/repository/store_repository.dart';
import '../../../utils/async_util.dart';
import '../../../utils/error_handler.dart';
import 'package:keyboard/utils/atmob_log.dart';
// 这里控制两个弹窗的数据
@injectable
class GoodsSurpriseController extends BaseController {
  final tag = 'GoodsSurpriseController';
  static const int countdownTime = 10 * 60 * 100; // 10分钟（毫秒单位，10ms 为 1 计数）
  final RxInt timeLeft = countdownTime.obs; // 剩余时间（10ms 为单位）
  Timer? _timer;
  final StoreRepository storeRepository;

  CancelableFuture? _storeDataFuture;

  RxList<GoodsInfo> get goodsInfoList =>
      storeRepository.newDiscountGoodsInfoList;

  final Rxn<GoodsInfo> _firstAmount = Rxn<GoodsInfo>();

  GoodsInfo? get firstAmount => _firstAmount.value;

  final Rxn<GoodsInfo> _secondAmount = Rxn<GoodsInfo>();

  GoodsInfo? get secondAmount => _secondAmount.value;

  GoodsSurpriseController(this.storeRepository);

  @override
  void onInit() {
    startCountdown();
    if (goodsInfoList.isEmpty) {
      return;
    }
    if (goodsInfoList.length < 2) {

      AtmobLog.e(tag,"商品列表少于2个，无法处理");
      return;
    }
    // 第一个直接拿第一个
    _firstAmount.value = goodsInfoList.first;
    // 第二个找一个 code 不一样的
    _secondAmount.value = goodsInfoList.firstWhereOrNull(
          (item) => item.code != _firstAmount.value?.code,
    );

    // 打印
    print('qqq firstAmount: ${_firstAmount.value?.toJson()}');
    print('qqq secondAmount: ${_secondAmount.value?.toJson()}');
    if (_secondAmount.value == null) {
      // 如果没有找到不同的 code，默认取第二个
      _secondAmount.value = goodsInfoList[1];
    }


    super.onInit();
  }

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

  void startCountdown() {
    _timer = Timer.periodic(const Duration(milliseconds: 10), (timer) {
      if (timeLeft.value > 0) {
        timeLeft.value--;
      } else {
        timer.cancel();
        SmartDialog.dismiss();
      }
    });
  }

  void onCountdownEnd() {
    SmartDialog.dismiss(tag: SurpriseDialog.tag);
  }

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

  Future<void> getItemRetention() async {
    storeRepository.getItemRetention();
  }

  void refreshStoreData() {
    _storeDataFuture?.cancel();
    _storeDataFuture = AsyncUtil.retryWithExponentialBackoff(
      () => _requestGoodsInfoList(),
      4,
    );
    _storeDataFuture?.catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  Future<void> _requestGoodsInfoList() async {
    try {
      final response = await storeRepository.getItemRetention();

      if (response.firstAmount != null) {
        _firstAmount.value = response.firstAmount;
        print('firstAmount: ${response.firstAmount?.toJson()}');
      }

      if (response.secondAmount != null) {
        _secondAmount.value = response.secondAmount;
        print('secondAmount: ${response.secondAmount?.toJson()}');
      }
    } catch (e) {
      AtmobLog.e(tag, e.toString());
    }
  }
}
