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;
    }
    _firstAmount.value = goodsInfoList.first;
    _secondAmount.value = goodsInfoList.last;

    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();
      }
    });
  }

  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());
    }
  }
}
