import 'package:apple_pay/apple_pay.dart';
import 'package:clean/base/base_controller.dart';
import 'package:clean/data/bean/payment_way.dart';
import 'package:clean/data/bean/store_item.dart';
import 'package:clean/data/consts/constants.dart';
import 'package:clean/data/repositories/store_repository.dart';
import 'package:clean/data/repositories/user_repository.dart';
import 'package:clean/dialog/loading_dialog.dart';
import 'package:clean/module/store/payment_status_manager.dart';
import 'package:clean/sdk/pay/applepay/apple_pay_info.dart';
import 'package:clean/sdk/pay/assist/product_type.dart';
import 'package:clean/utils/error_handler.dart';
import 'package:clean/utils/toast_util.dart';
import 'package:get/get.dart';

class DiscountController extends BaseController implements PaymentStatusCallback {

  final RxList<StoreItem> storeItems = <StoreItem>[].obs;

  final RxList<PaymentWay> paymentWays = <PaymentWay>[].obs;

  final Rxn<StoreItem> currentSelectedStoreItem = Rxn<StoreItem>();

  final Rxn<PaymentWay> currentSelectedPaymentWay = Rxn<PaymentWay>();

  RxBool isFree = false.obs;

  @override
  Future<void> onInit() async {
    super.onInit();
    initStoreIndexData();
  }

  void initStoreIndexData() {
    LoadingDialog.show();
    storeRepository.storeIndex().then((indexData) async {
      storeItems.clear();
      storeItems.addAll(indexData.items);
      currentSelectedStoreItem.value =
      storeItems.isNotEmpty ? storeItems.first : null;

      paymentWays.clear();
      paymentWays.addAll(indexData.paymentWays);
      currentSelectedPaymentWay.value =
      paymentWays.isNotEmpty ? paymentWays.first : null;

      var freeAppleId = "";
      for (var item in storeItems) {
        if (item.freeTrialName != null) {
          freeAppleId = item.appleGoodsId;
        }
      }

      isFree.value = await ApplePay().check(freeAppleId);

      LoadingDialog.hide();
    });
  }

  void onBuyClick() async {

    StoreItem? storeItem = currentSelectedStoreItem.value;
    if (storeItem == null) {
      // ToastUtil.showToast(StringName.storeChoiceGoods.tr);
      return;
    }
    PaymentWay? paymentWay = currentSelectedPaymentWay.value;
    if (paymentWay == null) {
      // ToastUtil.showToast(StringName.storeChoicePayment.tr);
      return;
    }
    int payPlatform = paymentWay.payPlatform;
    int payMethod = paymentWay.payMethod;
    LoadingDialog.show();
    try {
      // OrderPayResponse response =
      storeRepository.orderPay(storeItem.id, payPlatform, payMethod).then((response) async {

        dynamic payInfo;
        String outTradeNo = response.outTradeNo;
        if (payPlatform == PayPlatform.apple) {
          payInfo = ApplePayInfo(
              storeItem.appleGoodsId,
              storeItem.subscribable == 1
                  ? ProductType.nonConsumable
                  : ProductType.consumable,
              response.appAccountToken);
        }

        final result = await ApplePay().purchase(productId: storeItem.appleGoodsId, appAccountToken: response.appAccountToken);
        if (result["success"] == true) {
          var receipt = result['receipt'];
          print('购买成功: ${result['receipt']}');
          checkPaymentStatus(outTradeNo, paymentWay, storeItem, receiptData: receipt);
        } else {
          LoadingDialog.hide();
          ToastUtil.show("Pay Error, Please try again");
          print('购买失败: ${result['error']}');
        }
      }).catchError((error) {
        LoadingDialog.hide();
        ErrorHandler.toastError(error);
      });
    } catch (error) {
      LoadingDialog.hide();
    }
  }

  void checkPaymentStatus(
      String orderNo, PaymentWay paymentWay, StoreItem storeItemBean,
      {String? receiptData}) {
    paymentStatusManager.registerPaymentSuccessCallback(orderNo, this);
    paymentStatusManager.checkPaymentStatus(orderNo, paymentWay, storeItemBean,
        receiptData: receiptData);
  }

  @override
  void onPaymentSuccess(String orderNo, PaymentWay paymentWay, StoreItem storeItemBean) {
    // TODO: implement onPaymentSuccess
    LoadingDialog.hide();
    ToastUtil.show("Pay success");
    // 300ms后关闭弹窗
    Future.delayed(Duration(seconds: 3), () {
      userRepository.getUserInfo();
    });
    Get.back();
  }

  @override
  void onPaymentError(Error error) {
    // TODO: implement onPaymentError
    LoadingDialog.hide();
    ErrorHandler.toastError(error);
  }
}