part of recharge;

class CoinRechargeController extends GetxController {
  final BuildContext context;
  CoinRechargeController({required this.context});
  dynamic _purchaseUpdatedSubscription;
  dynamic _purchaseErrorSubscription;
  dynamic _connectionSubscription;
  PurchasedItem? _resultItem;

  List<IAPItem> _items = [];
  List<PurchasedItem> _purchases = [];
  ///未完成的订单
  List<PurchasedItem> _pendingPurchases = [];

  // 支付宝
  Tobias tobias = Tobias();
  // 微信
  Fluwx fluwx  = Fluwx();

  // 创建订单模型
  late PayOrderModel payOrderModel;


  List<PayModel> pays =  Platform.isIOS ?[
  ]:[
    // PayModel(type: 1, name: '微信', icon: 'assets/images/pay_wechat.png', selected: true),
    PayModel(type: 2, name: '支付宝', icon: 'assets/images/pay_ali.png', selected: true),
  ];
  List<CoinModel> data = [];

  late CoinModel rechargeModel = CoinModel();


  // 支付方式
  late PayModel _payModel = pays.first;
  PayModel get payModel => _payModel;

  @override
  void onInit() {
    initPlatformState();
    _getPendingPurchase();
    super.onInit();
  }


  @override
  void onReady() {
    _getlist();
    super.onReady();
  }
  @override
  void onClose() {
    if (_connectionSubscription != null) {
      _connectionSubscription.cancel();
      _connectionSubscription = null;
    }
    if (_purchaseUpdatedSubscription != null) {
      _purchaseUpdatedSubscription.cancel();
      _purchaseUpdatedSubscription = null;
    }
    if (_purchaseErrorSubscription != null) {
      _purchaseErrorSubscription.cancel();
      _purchaseErrorSubscription = null;
    }

    super.onClose();
  }

  void setPayModel(PayModel payModel){
    for (PayModel model in pays) {
      if (model.type == payModel.type){
        model.selected = true;
        _payModel = model;
      }
      else{
        model.selected = false;
      }
    }
    update();
  }

  void choose(CoinModel coinModel){
    for (CoinModel model in data) {
      model.selected = (model == coinModel);
    }
    rechargeModel = coinModel;
    update();
  }


  /// 获取充值列表
  void _getlist()async{
    String type = '';
    if(Platform.isIOS){
      type = 'ios';
    }
    if(Platform.isAndroid){
      type = 'android';
    }
    final result = await MineAPI.coinsRechargeList(type: type);
    data = result;

    if(Platform.isIOS){
      _getProduct();
    }
    update();
  }

  Future<void> initPlatformState() async{
    var result = await FlutterInappPurchase.instance.initialize();
    print('--------------initPlatformState-------------------------$result');


    _connectionSubscription = FlutterInappPurchase.connectionUpdated.listen((connected) {
          print('connected: $connected');
    });

    _purchaseUpdatedSubscription = FlutterInappPurchase.purchaseUpdated.listen((productItem) {
        CustomToast.dismiss();
        if(productItem != null){
          _resultItem = productItem;
          _requestOrderStatus();
        }
    });

    _purchaseErrorSubscription = FlutterInappPurchase.purchaseError.listen((purchaseError) {
        CustomToast.dismiss();
        Toast.show(purchaseError!.message.toString());
    });
  }

  /// 获取商品列表
  Future _getProduct() async {

    List<String> productList = data
        .where((coinModel) => coinModel.identifying != null)
        .map((coinModel) => coinModel.identifying!)
        .toList();

    print('-------------productList-------------------$productList');
    List<IAPItem> items = await FlutterInappPurchase.instance.getProducts(productList);
    for (var item in items) {
      _items.add(item);
    }

    print('-------------_items-------------------$items');

    _items = items;
    _purchases = [];
    // update();
  }

  /// 创建订单
  void createRechargeOrder() async {
    String type = '';
    if(Platform.isIOS){
      type = '3';
    }
    else{
      type = payModel.type.toString();
    }
    final result = await MineAPI.createRechargeOrder(identifying: rechargeModel.identifying??'', type: type);

    print('-----------------------------------${result.ordersnum}--------------------------------${result.msg}');
    payOrderModel = result;
    // 创建订单成功开启支付流程
    if (payOrderModel.ordersnum !=null){
      if(payOrderModel.ordersnum!.isNotEmpty){
        // 苹果
        if(Platform.isIOS){
          // 发起苹果支付
          IAPItem targetItem = _items.firstWhere(
                (item) => item.productId == rechargeModel.identifying,
          );
          _requestPurchase(targetItem);
        }
        // 安卓
        else if(Platform.isAndroid){
          // 发起支付宝支付
           if (payModel.type == 2){
             requestAliPay();
           }
           else if (payModel.type == 1){
             requestWechat();
           }

        }
      }
    }

  }
  /// 获取后台关于当前单号的结算结果
  void _requestOrderStatus() async {
    final result = await ShopAPI.orderStatus(orderNumber: payOrderModel.ordersnum??'',receipt:_resultItem != null?_resultItem!.transactionReceipt.toString():'');

    // 查询订单支付成功
    if (result.paySuccess == 1){
      Toast.show('购买紫荆币成功');
      if(context.mounted){
        context.pop(true);
      }
      if (Platform.isIOS){
        // 清除
        if (StorageService.to.getObject(kFailOrder) != null){
          List<Map<String,String>> failOrderList = StorageService.to.getObject(kFailOrder) as List<Map<String, String>>;
          List<Map<String,String>> temp = [];
          temp.addAll(failOrderList);
          for (var element in failOrderList) {
            if(element['orderNum'] == result.ordersnum){
              temp.remove(element);
            }
          }
          StorageService.to.setObject(kFailOrder, temp);
        }
        FlutterInappPurchase.instance.finishTransactionIOS(_resultItem!.transactionId!);
      }
    }
    // 查询订单支付失败
    else {
      Toast.show('购买紫荆币失败');
      if(Platform.isIOS){
        // 保存未支付的订单
        Map<String,String> failOrder = {
          'orderNum':payOrderModel.ordersnum??'',
          'transactionReceipt':_resultItem!.transactionReceipt.toString(),
          'transactionId':_resultItem!.transactionId.toString()
        };
        List<Map> failOrderList = [];
        failOrderList.add(failOrder);
        StorageService.to.setObject(kFailOrder, failOrderList);
      }
      else {
        
      }
    }
  }

  /// 苹果支付
  void _requestPurchase(IAPItem item) {
    CustomToast.loading();
    FlutterInappPurchase.instance
        .requestPurchase(item.productId!);
  }

  /// 支付宝支付
  void requestAliPay(){
    tobias.pay(payOrderModel.encryptionOrder!).then((payResult){
      if (payResult['resultStatus'] == '9000') {
        _requestOrderStatus();
      } else {
        Toast.show(payResult['memo'].toString());
      }
    });
  }

  /// 微信支付
  void requestWechat(){
    Payment payment = Payment(
        appId: payOrderModel.appid??'',
        partnerId: payOrderModel.partnerid??'',
        prepayId: payOrderModel.prepayid??'',
        packageValue: payOrderModel.package??'',
        nonceStr: payOrderModel.noncestr??'',
        timestamp: payOrderModel.timestamp!.toInt(),
        sign: payOrderModel.sign??''
    );
    fluwx.pay(which: payment);
    fluwx.addSubscriber((response) {
      if (response.errCode == 0) {
        _requestOrderStatus();
      }
      else{
        Toast.show('${response.errStr}');
      }
    });
  }


  ///获取未完成的购买
  Future _getPendingPurchase() async {
    List<PurchasedItem>? items = await FlutterInappPurchase.instance.getPurchaseHistory();
    for (var item in items!) {
      _pendingPurchases.add(item);
    }
    if(StorageService.to.getObject(kFailOrder) !=null){
      List<Map<String,String>> failOrderList = StorageService.to.getObject(kFailOrder) as List<Map<String, String>>;
      for (var item in _pendingPurchases) {
        for (var element in failOrderList) {
          if(element['transactionId'] == item.transactionId){
            _requestOrderStatus();
          }
        }
      }
    }
  }

}