part of user_order_coin_awaiting;

/// 紫荆币等待付款订单
class UserOrderCoinAwaitingController extends GetxController {
  late String _orderNum;
  final BuildContext context;
  String get orderNum => _orderNum; // 获取订单编号的方法
  UserOrderCoinAwaitingController(this.context);
  // 更新订单编号的方法
  void updateOrderNum(String newOrderNum) {
    _orderNum = newOrderNum;
  }
  late OrderInfoModel model;
  // 应付款、订单编号等
  List<OrderCompletedModel> orderAwaitings = [];

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

  late PayOrderModel payOrderModel;


  dynamic _purchaseUpdatedSubscription;
  dynamic _purchaseErrorSubscription;
  dynamic _connectionSubscription;
  PurchasedItem? _resultItem;

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

  List<CoinModel> data = [];


  @override
  void onInit() {
    if(Platform.isIOS){
      _getProduct();
      initPlatformState();
      _getPendingPurchase();
    }
    super.onInit();
  }

  @override
  void onReady() {
    getOrderInfo();
    super.onReady();
  }

  @override
  void onClose() {
    // controller.onRefresh();
    if (_connectionSubscription != null) {
      _connectionSubscription.cancel();
      _connectionSubscription = null;
    }
    if (_purchaseUpdatedSubscription != null) {
      _purchaseUpdatedSubscription.cancel();
      _purchaseUpdatedSubscription = null;
    }
    if (_purchaseErrorSubscription != null) {
      _purchaseErrorSubscription.cancel();
      _purchaseErrorSubscription = null;
    }

    super.onClose();
  }

  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<bool> cancelPay() async {
    final result = await MineAPI.cancelPay(ordersnum: orderNum);
    if (result) {
      Toast.show('取消成功');
    }
    return result;
  }

  /// 获取订单信息
  Future<void> getOrderInfo() async {
    data.clear();

    model = await MineAPI.getOrderInfo(orderNum: orderNum);
    String payWay ='';
    if(model.payType==1){
      payWay='微信';
    }else  if(model.payType==2){
      payWay='支付宝';
    }else  if(model.payType==3){
      payWay='紫荆币';
    }
    orderAwaitings = [
      OrderCompletedModel(name: '订单编号',value: model.ordersnum.toString()),
      OrderCompletedModel(name: '支付方式',value: payWay),
      OrderCompletedModel(name: '支付时间',value: model.payTime.toString()),
    ];

    data.add(CoinModel(identifying:model.goodsId));

    update();
  }


  /// 获取商品列表
  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();
  }

  Future<void> payOrder() async {
    // 苹果支付
    if (model.payType ==3){
      // 发起苹果支付
      IAPItem targetItem = _items.firstWhere(
            (item) => item.productId == model.goodsId,
      );
      _requestPurchase(targetItem);
    }
    else{
      payOrderModel = await MineAPI.getPayInfo(ordersNum: orderNum);
      // 支付宝
      if (model.payType == 2){
        final result = await tobias.isAliPayInstalled;
        if(!result){
          Toast.show('请先安装支付宝');
        }
        else{
          requestAliPay();
        }
      }
      // 微信
      else if (model.payType ==1){
        final result = await fluwx.isWeChatInstalled;
        if(!result){
          Toast.show('请先安装微信');
        }
        else{
          requestWechat();
        }
      }
    }


  }

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

  // 支付宝支付
  void requestAliPay(){
    Console.log('================================================================${payOrderModel.encryptionOrder!}');
    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}');
      }
    });
  }

  void requestOrderStatus() async {
    final result = await ShopAPI.orderStatus(orderNumber: model.ordersnum??'',receipt:_resultItem != null?_resultItem!.transactionReceipt.toString():'');
    if (result.paySuccess == 1){
      Toast.show('订单支付完成');
      if(context.mounted){
          context.pop(true);
      }
      if (model.payType == 3){
        // 清除
        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 (model.payType == 3){
        // 保存未支付的订单
        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);
      }
    }

  }

  ///获取未完成的购买
  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();
          }
        }
      }
    }
  }




}
