import 'package:injectable/injectable.dart';
import 'package:keyboard/data/api/atmob_api.dart';
import 'package:keyboard/data/api/response/item_list_response.dart';
import 'package:keyboard/data/api/response/order_pay_response.dart';
import 'package:keyboard/utils/http_handler.dart';
import 'package:get/get.dart';
import '../../base/app_base_request.dart';
import '../../utils/async_util.dart';
import '../../utils/atmob_log.dart';
import '../../utils/error_handler.dart';
import '../../utils/payment_status_manager.dart';
import '../api/request/order_pay_request.dart';
import '../api/request/order_status_request.dart';
import '../api/response/item_retention_response.dart';
import '../api/response/member_new_user_response.dart';
import '../bean/character_info.dart';
import '../bean/goods_info.dart';
import '../bean/pay_way_info.dart';
import '../consts/error_code.dart';
import 'account_repository.dart';

@lazySingleton
class StoreRepository {
  final tag = 'StoreRepository';

  final AtmobApi atmobApi;
  final AccountRepository accountRepository;

  CancelableFuture? goodsInfoFuture;

  final RxList<GoodsInfo> _newDiscountGoodsInfoList = <GoodsInfo>[].obs;

  RxList<GoodsInfo> get newDiscountGoodsInfoList => _newDiscountGoodsInfoList;

  final RxList<PayWayInfo> _newDiscountPayWayList = <PayWayInfo>[].obs;

  RxList<PayWayInfo> get newDiscountPayWayList => _newDiscountPayWayList;

  final RxList<CharacterInfo> _charactersList = <CharacterInfo>[].obs;

  RxList<CharacterInfo> get charactersList => _charactersList;

  StoreRepository(this.atmobApi, this.accountRepository) {
    print('$tag....init');
    refreshNewDiscountGoodsInfoList();
  }

  void refreshNewDiscountGoodsInfoList() {
    goodsInfoFuture?.cancel();
    goodsInfoFuture = AsyncUtil.retryWithExponentialBackoff(
      () => getMemberNewUserGoodsList(),
      4,
      predicate: (error) {
        if (error is ServerErrorException) {
          return error.code != ErrorCode.noLoginError;
        }
        return true;
      },
    );
    goodsInfoFuture?.catchError((error) {
      ErrorHandler.toastError(error);
    });

  }

  Future<ItemListResponse> getGoodsInfoList() async {
    return await atmobApi
        .getGoodsList(AppBaseRequest())
        .then(HttpHandler.handle(true));
  }

  Future<MemberNewUserResponse> getMemberNewUserGoodsList() async {
    return await atmobApi
        .getMemberUserResponse(AppBaseRequest())
        .then(HttpHandler.handle(true))
        .then((data) {
          _newDiscountGoodsInfoList.clear();
          _newDiscountPayWayList.clear();
          _charactersList.clear();
          if (data.goodsInfoList?.isNotEmpty == true) {
            _newDiscountGoodsInfoList.addAll(data.goodsInfoList!);
          }
          if (data.payInfoList?.isNotEmpty == true) {
            _newDiscountPayWayList.addAll(data.payInfoList!);
          }
          if (data.characterInfos?.isNotEmpty == true) {
            _charactersList.addAll(data.characterInfos!);
          }
          return data;
        });
  }

  Future<OrderPayResponse> submitAndRequestPay({
    required int goodsId,
    required int payPlatform,
    required int payMethod,
  }) {
    return atmobApi
        .orderPay(
          OrderPayRequest(
            goodsId: goodsId,
            payPlatform: payPlatform,
            payMethod: payMethod,
          ),
        )
        .then(HttpHandler.handle(false));
  }

  Future<int> orderStatus(String outTradeNo, {String? receiptData}) {
    return atmobApi
        .orderStatus(OrderStatusRequest(outTradeNo, receiptData))
        .then(HttpHandler.handle(false))
        .then((data) {
          if (data.payStatus == PaymentStatus.payStatusSuccess) {
            accountRepository.refreshUserInfo();
          }
          return data.payStatus;
        });
  }

  Future<ItemRetentionResponse> getItemRetention() {
    return atmobApi
        .getItemRetention(AppBaseRequest())
        .then(HttpHandler.handle(true));
  }
}
