import 'dart:io';

import 'package:apple_pay/apple_pay.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/repositories/account_repository.dart';
import 'package:location/data/repositories/member_repository.dart';

import '../../../data/bean/goods_bean.dart';
import '../../../data/bean/member_status_info.dart';
import '../../../data/bean/pay_item_bean.dart';
import '../../../data/consts/web_url.dart';
import '../../../dialog/loading_dialog.dart';
import '../../../handler/error_handler.dart';
import '../../../helper/member_pay_helper.dart';
import '../../../resource/assets.gen.dart';
import '../../../resource/string.gen.dart';
import '../../../utils/async_util.dart';
import '../../../utils/toast_util.dart';
import '../../browser/browser_view.dart';

@injectable
class MemberActivityController extends BaseController {
  final Rxn<GoodsBean> _selectedGoods = Rxn<GoodsBean>();

  GoodsBean? get selectedGoods => _selectedGoods.value;

  MemberStatusInfo? get memberStatusInfo =>
      accountRepository.memberStatusInfo.value;

  final List<ImageProvider> funImages = [
    Assets.images.imgMemberActivityBanner1.provider(),
    Assets.images.imgMemberActivityBanner2.provider(),
    Assets.images.imgMemberActivityBanner3.provider(),
    Assets.images.imgMemberActivityBanner4.provider(),
  ];

  final RxList<GoodsBean> goodsList = <GoodsBean>[].obs;
  final List<PayItemBean> payItemList = <PayItemBean>[];
  CancelableFuture? _memberDataFuture;

  final AccountRepository accountRepository;
  final MemberRepository memberRepository;
  final MemberPayHelper memberPayHelper;

  Duration? get activityDuration => memberRepository.activityDuration.value;

  MemberActivityController(
      this.accountRepository, this.memberRepository, this.memberPayHelper);

  @override
  void onReady() {
    super.onReady();
    refreshMemberData();
    precacheImage(
        Assets.images.iconMemberSpecialProductsSelect.provider(), Get.context!);
    precacheImage(
        Assets.images.iconMemberSpecialProductsNormal.provider(), Get.context!);
  }

  void refreshMemberData() {
    _memberDataFuture?.cancel();
    _memberDataFuture =
        AsyncUtil.retryWithExponentialBackoff(() => _requestMemberData(), 4);
    _memberDataFuture?.catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  Future<void> _requestMemberData() {
    return memberRepository
        .guideItemList(itemListType: Platform.isIOS ? 2 : 0)
        .then((response) {
      goodsList.clear();
      payItemList.clear();
      _selectedGoods.value = null;
      if (response.payInfoList?.isNotEmpty == true) {
        payItemList.addAll(response.payInfoList!);
      }
      if (response.goodsList?.isNotEmpty == true) {
        goodsList.addAll(response.goodsList!);
        _selectedGoods.value = goodsList.first;
      }
      if (goodsList.isNotEmpty && payItemList.isNotEmpty) {
        memberRepository.setLastSelectedMember(
            goodsList.first, payItemList.first);
      }
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onBack() {
    Get.back();
  }

  void onBuyClick() {
    if (payItemList.isEmpty) {
      ToastUtil.show(StringName.memberActivityNoPayway);
      return;
    }
    memberPayHelper.launchPay(selectedGoods, payItemList.first);
  }

  void onGoodsItemClick(GoodsBean goodsInfo) {
    _selectedGoods.value = goodsInfo;
    onBuyClick();
  }

  void onPrivacyPolicyClick() {
    BrowserPage.start(WebUrl.privacyPolicy);
  }

  void onTermOfServiceClick() {
    BrowserPage.start(WebUrl.userAgreement);
  }

  void onRenewalAgreementClick() {
    BrowserPage.start(WebUrl.renewalAgreement);
  }

  void onRecoverClick() async {
    if (payItemList.isNotEmpty) {
      ToastUtil.show(StringName.memberActivityNoPayway);
      return;
    }
    PayItemBean paymentWay = payItemList.first;

    CustomLoadingDialog.show();

    Future.delayed(const Duration(seconds: 20), () {
      CustomLoadingDialog.hide();
    });

    final result = await ApplePay().restore();
    if (result["success"] == true) {
      var receipt = result['receipt'];
      print('查找恢复记录成功: ${result['receipt']}');
      checkRestoreStatus(receipt, paymentWay);
    } else {
      CustomLoadingDialog.hide();
      ToastUtil.show("恢复失败");
      print('恢复失败: ${result['error']}');
    }
  }

  Future<void> checkRestoreStatus(
      String? receiptData, PayItemBean paymentWay) async {
    if (receiptData == null) {
      return;
    }
    memberRepository.subscriptionResume(3, receiptData).then((data) async {
      CustomLoadingDialog.hide();
      ToastUtil.show("恢复成功");
      await AccountRepository.getInstance().getMemberStatus();
      Get.back();
    }).catchError((error) {
      CustomLoadingDialog.hide();
      ToastUtil.show("恢复失败");
    });
  }

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