Untitled

 avatar
unknown
dart
2 years ago
39 kB
4
Indexable
import 'dart:convert';
import 'dart:developer';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_paytabs_bridge/BaseBillingShippingInfo.dart';
import 'package:flutter_paytabs_bridge/IOSThemeConfiguration.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkApms.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkConfigurationDetails.dart';
import 'package:flutter_paytabs_bridge/PaymentSdkTokeniseType.dart';
import 'package:flutter_paytabs_bridge/flutter_paytabs_bridge.dart';
import 'package:foot_fit/common_class/md_extension.dart';
import 'package:foot_fit/view/home_view/our_services/order_submit_view.dart';
import 'package:foot_fit/view/home_view/our_services/use_point_view.dart';
// import 'package:paymob_flutter_lib/models/payment.dart';
// import 'package:paymob_flutter_lib/models/payment_result.dart';
// import 'package:paymob_flutter_lib/paymob_flutter_lib.dart';

import '../../../common_class/md_color_extension.dart';
import '../../../common_class/md_globs.dart';
import '../../../common_class/md_service_call.dart';
import '../../common_widget/popup_layout.dart';
import '../../common_widget/round_button.dart';

class CheckOutView extends StatefulWidget {
  final Map bObj;
  final Map sObj;

  const CheckOutView({super.key, required this.bObj, required this.sObj});

  @override
  State<CheckOutView> createState() => _CheckOutViewState();
}

class _CheckOutViewState extends State<CheckOutView> {
  //final _paymobFlutterLibPlugin = PaymobFlutterLib();
  TextEditingController txtPromoCode = TextEditingController();

  List<Map> periodArr = [
    {"name": "1 Day", "value": "1 Day", "value_key": "one_date_"},
    {"name": "1 Month", "value": "1 Month", "value_key": "one_month_"},
    {"name": "3 Month", "value": "3 Month", "value_key": "three_month_"},
    {"name": "6 Month", "value": "6 Month", "value_key": "six_month_"},
    {"name": "1 Year", "value": "1 Year", "value_key": "year_month_"}
  ];

  List<Map> weekArr = [
    {
      "name": "2",
      "value": "2",
      "value_key": "session_two_price",
      "point_key": "session_two_point",
    },
    {
      "name": "3",
      "value": "3",
      "value_key": "session_three_price",
      "point_key": "session_three_point",
    },
    {
      "name": "4",
      "value": "4",
      "value_key": "session_four_price",
      "point_key": "session_four_point",
    },
    {
      "name": "Unlimited",
      "value": "Unlimited",
      "value_key": "session_unlimited_price",
      "session_key": "unlimited_total_session",
      "point_key": "session_unlimited_point",
    }
  ];

  Map? selectPeriod;
  Map? selectWeek;

  bool isApplyCode = false;

  Map promoDic = {};

  @override
  void initState() {
    super.initState();
    selectPeriod = periodArr.first;
    selectWeek = {
      "name": "1",
      "value": "1",
      "value_key": "session_price",
      "point_key": "session_point",
    };
    MDServiceCall.fireEvent(Event.checkout);
  }

  @override
  Widget build(BuildContext context) {
    var media = MediaQuery.of(context).size;
    var rowSpace = media.width * 0.012;

    var price = double.tryParse(
            "${widget.sObj["${selectPeriod?["value_key"] ?? ""}${selectWeek?["value_key"] ?? ""}"] ?? "0.0"}") ??
        0.0;
    var disPrice = double.tryParse("${promoDic[KKey.amount]} ") ?? 0.0;

    //price
    var displayPrice = isApplyCode ? (price - disPrice) : price;
    List<dynamic> daysOpened = (widget.bObj[KKey.schedule] as List? ?? [])
        .where((element) => element[KKey.openClose] != 0)
        .toList();

    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0,
        elevation: 2,
        backgroundColor: Colors.white,
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            padding: EdgeInsets.zero,
            icon: const Icon(
              Icons.arrow_back,
              color: Colors.black,
            )),
        title: Text(
          'Check Out'.tr(),
          style: const TextStyle(
              fontFamily: "Geogrotesque Cyr",
              fontWeight: FontWeight.bold,
              fontSize: 25,
              color: Colors.black),
        ),
      ),
      // AppBarView(
      //   leftIcon: 'assets/img/back.png',
      //   leftAction: () {
      //     Navigator.of(context).pop();
      //   },
      //   leftIconWidth: 15,
      //   title: Text(
      //     "Check Out".tr(),
      //     textAlign: TextAlign.center,
      //   ),
      // ),
      backgroundColor: TColor.bg,
      body: SingleChildScrollView(
        child: Column(children: [
          Container(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              width: media.width,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(top: 28),
                    child: Text(
                      "Days".tr(),
                      textAlign: isEN ? TextAlign.left : TextAlign.right,
                      style: TextStyle(
                          color: TColor.primaryText,
                          fontSize: 20,
                          fontWeight: FontWeight.w500),
                    ),
                  ),

                  const SizedBox(height: 16),

                  // ChipsChoice<int>.single(
                  //             value: 0,
                  //             wrapped: true,
                  //             padding: EdgeInsets.zero,
                  //             spacing: 4,
                  //             runSpacing: 0,
                  //             choiceStyle:

                  //             C2ChipStyle(
                  //               backgroundOpacity: 1,
                  //               backgroundColor: TColor.primary,

                  //               margin: EdgeInsets.zero,
                  //               elevation: 0,

                  //               foregroundStyle: const TextStyle(fontSize: 13),
                  //               borderRadius:  BorderRadius.circular(20)

                  //               // elevation: 0,
                  //             ),
                  //             onChanged: (val) {},
                  //             choiceItems: C2Choice.listFrom<int, dynamic>(
                  //               source: [{"name":"Monday", "id":1 }],
                  //               value: (i, v) => int.tryParse("${v[KKey.id] ?? "0"}") ?? 0,
                  //               label: (i, e) => "${e[KKey.name] ?? ""}".tr(),
                  //             ),
                  //           ),

                  // Column(
                  //   children: (widget.bObj[KKey.schedule] as List? ?? [])
                  //       .map((obj) {
                  //     var isClose = (obj[KKey.openClose] as int? ?? 0) == 0;
                  //
                  //     return Padding(
                  //       padding: EdgeInsets.symmetric(vertical: rowSpace),
                  //       child: Row(
                  //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  //         children: [
                  //           SizedBox(
                  //             width: 80,
                  //             child: Text(
                  //               obj[KKey.lName] as String? ?? "",
                  //               textAlign:
                  //                   isEN ? TextAlign.left : TextAlign.right,
                  //               style: TextStyle(
                  //                   fontFamily: "Geogrotesque Cyr",
                  //                   fontWeight: FontWeight.bold,
                  //                   fontSize: 14,
                  //                   color: TColor.primaryText),
                  //             ),
                  //           ),
                  //           Expanded(
                  //             child: Text(
                  //               isClose
                  //                   ? "Closed".tr()
                  //                   : "${obj[KKey.startHour] as String? ?? ""} - ${obj[KKey.endHour] as String? ?? ""}",
                  //               maxLines: 1,
                  //               textAlign: TextAlign.center,
                  //               style: TextStyle(
                  //                   color: TColor.primaryText,
                  //                   fontSize: 13,
                  //                   fontWeight: FontWeight.w500),
                  //             ),
                  //           ),
                  //           Expanded(
                  //             child: Text(
                  //               isClose
                  //                   ? ""
                  //                   : "${obj[KKey.startHourTwo] as String? ?? ""} - ${obj[KKey.endHourTwo] as String? ?? ""}",
                  //               maxLines: 1,
                  //               textAlign: TextAlign.center,
                  //               style: TextStyle(
                  //                   color: TColor.primaryText,
                  //                   fontSize: 13,
                  //                   fontWeight: FontWeight.w500),
                  //             ),
                  //           ),
                  //         ],
                  //       ),
                  //     );
                  //   }).toList(),
                  // ),

                  GridView.count(
                    shrinkWrap: true,
                    // Create a grid with 2 columns. If you change the scrollDirection to
                    // horizontal, this produces 2 rows.
                    crossAxisCount: 2,
                    physics: const NeverScrollableScrollPhysics(),
                    crossAxisSpacing: 20,
                    childAspectRatio: (16 / 6),
                    // Generate 100 widgets that display their index in the List.
                    children: List.generate(daysOpened.length, (index) {
                      log('messagesssdd ${daysOpened[index]}');
                      return Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16),
                        decoration: BoxDecoration(
                            color: const Color(0xff919191).withOpacity(0.2),
                            borderRadius: BorderRadius.circular(4)),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              daysOpened[index][KKey.lName] as String? ?? "",
                              maxLines: 1,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: TColor.primaryText,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500),
                            ),
                            Text(
                              "${daysOpened[index][KKey.startHour] as String? ?? ""} - ${daysOpened[index][KKey.endHour] as String? ?? ""}",
                              maxLines: 1,
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: TColor.primaryText,
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500),
                            ),
                          ],
                        ),
                      );
                    }),
                  ),

                  const SizedBox(height: 28),

                  Text(
                    '${"Period".tr()} 🗓️',
                    textAlign: isEN ? TextAlign.left : TextAlign.right,
                    style: TextStyle(
                        color: TColor.primaryText,
                        fontSize: 20,
                        fontWeight: FontWeight.w500),
                  ),

                  const SizedBox(height: 14),

                  Row(
                    // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: periodArr.map((obj) {
                      var isSelected = obj == selectPeriod;

                      return Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 3.0),
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              if (selectPeriod == periodArr.first &&
                                  obj != periodArr.first) {
                                selectWeek = null;
                              }

                              selectPeriod = obj;

                              if (selectPeriod == periodArr.first) {
                                selectWeek = {
                                  "name": "1",
                                  "value": "1",
                                  "value_key": "session_price",
                                  "point_key": "session_point",
                                };
                              }

                              selectWeek ??= weekArr.first;
                            });
                          },
                          child: Container(
                            width: media.width * 0.16,
                            height: media.width * 0.16,
                            alignment: Alignment.center,
                            // padding: EdgeInsets.all(media.width * 0.01),
                            decoration: BoxDecoration(
                              color: isSelected
                                  ? TColor.primary
                                  : TColor.wTextColor,
                              borderRadius: BorderRadius.circular(10),
                              // boxShadow: const [
                              //   BoxShadow(
                              //       blurRadius: 3,
                              //       spreadRadius: 1,
                              //       color: Colors.black26)
                              // ],
                            ),
                            child: Text(
                              (obj["name"] as String? ?? "").tr(),
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  color: isSelected
                                      ? TColor.primaryText
                                      : Colors.black,
                                  fontSize: 16,
                                  fontWeight: FontWeight.w500),
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  ),

                  const SizedBox(height: 28),

                  Text(
                    "Sessions / Week".tr(),
                    textAlign: isEN ? TextAlign.left : TextAlign.right,
                    style: TextStyle(
                        color: TColor.primaryText,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
                  ),

                  Padding(
                    padding: const EdgeInsets.only(top: 16),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: weekArr.map((obj) {
                        var isSelected = obj == selectWeek;
                        var isDisable = selectPeriod == null ||
                            selectPeriod == periodArr.first;

                        return Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 3),
                          child: GestureDetector(
                            onTap: () {
                              if (isDisable) {
                                return;
                              }

                              setState(() {
                                selectWeek = obj;
                              });
                            },
                            child: Container(
                              width: media.width * 0.17,
                              height: media.width * 0.17,
                              alignment: Alignment.center,
                              // padding: EdgeInsets.all(media.width * 0.01),
                              decoration: BoxDecoration(
                                color: isDisable
                                    ? const Color(0xff919191).withOpacity(0.2)
                                    : isSelected
                                        ? TColor.primary
                                        : Colors.white,
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Text(
                                (obj["name"] as String? ?? "").tr(),
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    color: TColor.primaryText,
                                    fontSize: 14,
                                    fontWeight: FontWeight.w500),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                ],
              )),
          Container(
            width: media.width,
            padding: const EdgeInsets.only(left: 24, right: 24, top: 28),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Subscription amount'.tr(),
                  style: TextStyle(
                      color: TColor.primaryText,
                      fontSize: 20,
                      fontWeight: FontWeight.w500),
                ),
                Text(
                  "Final total includes Tax Or any other text (Optional)".tr(),
                  textAlign: isEN ? TextAlign.left : TextAlign.right,
                  style: TextStyle(
                      color: TColor.primaryText,
                      fontSize: 14,
                      fontWeight: FontWeight.w500),
                ),
                promoCodeWidget(),
                // InnerTextField(
                //   controller: txtPromoCode,
                //   hintText: "Promo Code",
                //   right: TextButton(
                //     onPressed: () {
                //       goPromoCode();
                //     },
                //     child: Text(
                //       (isApplyCode ? "Remove" : "Apply").tr(),
                //       style: const TextStyle(
                //           fontSize: 18, fontWeight: FontWeight.bold),
                //     ),
                //   ),
                // ),
                const SizedBox(height: 24),
                Visibility(
                  visible: isApplyCode,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Total".tr(),
                        textAlign: isEN ? TextAlign.left : TextAlign.right,
                        style: TextStyle(
                            color: TColor.primaryText,
                            fontSize: 16,
                            fontWeight: FontWeight.w700),
                      ),
                      Text(
                        "${price.toStringAsFixed(2)} ${widget.bObj[KKey.currency] ?? "USD"}",
                        textAlign: isEN ? TextAlign.left : TextAlign.right,
                        style: TextStyle(
                            color: TColor.primaryText,
                            fontSize: 16,
                            fontWeight: FontWeight.w700),
                      ),
                    ],
                  ),
                ),
                Visibility(
                  visible: isApplyCode,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "Promo Code Applied Price".tr(),
                        textAlign: isEN ? TextAlign.left : TextAlign.right,
                        style: TextStyle(
                            color: TColor.primaryText,
                            fontSize: 16,
                            fontWeight: FontWeight.w700),
                      ),
                      Text(
                        "-${disPrice.toStringAsFixed(2)} ${widget.bObj[KKey.currency] ?? "USD"}",
                        textAlign: isEN ? TextAlign.left : TextAlign.right,
                        style: TextStyle(
                            color: TColor.primaryText,
                            fontSize: 16,
                            fontWeight: FontWeight.w700),
                      ),
                    ],
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      "Payable Amount".tr(),
                      textAlign: isEN ? TextAlign.left : TextAlign.right,
                      style: TextStyle(
                          color: TColor.primaryText,
                          fontSize: 16,
                          fontWeight: FontWeight.w700),
                    ),
                    Text(
                      "${displayPrice.toStringAsFixed(2)} ${widget.bObj[KKey.currency] ?? "USD"}",
                      textAlign: isEN ? TextAlign.left : TextAlign.right,
                      style: TextStyle(
                          color: TColor.primaryText,
                          fontSize: 16,
                          fontWeight: FontWeight.w700),
                    ),
                  ],
                ),
                // SizedBox(
                //   height: media.width * 0.01,
                // ),
                // Text(
                //   "Final total includes Tax Or any other text (Optional)".tr(),
                //   textAlign: isEN ? TextAlign.left : TextAlign.right,
                //   style: TextStyle(
                //       color: TColor.primaryText,
                //       fontSize: 14,
                //       fontWeight: FontWeight.w500),
                // ),
                const SizedBox(height: 24),
                Row(
                  children: [
                    Visibility(
                      visible:
                          "${widget.bObj[KKey.isPaymentPoint] ?? "0"}" == "1",
                      child: Expanded(
                        child: RoundButton(
                          title: "Points",
                          shapeBorder: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(16),
                          ),
                          type: RoundButtonType.primary,
                          onPressed: () {
                            goSubmitPoint(displayPrice);
                          },
                        ),
                      ),
                    ),
                    SizedBox(
                      width: ("${widget.bObj[KKey.isPaymentPoint] ?? "0"}" ==
                                  "1") &&
                              ("${widget.bObj[KKey.isPaymentCash] ?? "0"}" ==
                                  "1")
                          ? media.width * 0.03
                          : 0,
                    ),
                    Visibility(
                      visible:
                          "${widget.bObj[KKey.isPaymentCash] ?? "0"}" == "1",
                      child: Expanded(
                        child: RoundButton(
                          title: "Cash",
                          shapeBorder: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(16),
                          ),
                          type: RoundButtonType.primary,
                          onPressed: () {
                            goSubmit("cash");
                          },
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: ("${widget.bObj[KKey.isPaymentPoint] ?? "0"}" ==
                              "1") ||
                          ("${widget.bObj[KKey.isPaymentCash] ?? "0"}" == "1")
                      ? media.width * 0.03
                      : 0,
                ),
                Visibility(
                    visible:
                        "${widget.bObj[KKey.isPaymentOnline] ?? "0"}" == "1",
                    child: RoundButton(
                      title: "Online Payment",
                      shapeBorder: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(16),
                      ),
                      type: RoundButtonType.primary,
                      onPressed: () {
                        goSubmit("online");
                      },
                    )),
                const SizedBox(height: 24),
              ],
            ),
          )
        ]),
      ),
    );
  }

  Padding promoCodeWidget() {
    return Padding(
      padding: const EdgeInsets.only(top: 16),
      child: TextField(
        controller: txtPromoCode,
        decoration: InputDecoration(
            filled: true,
            //<-- SEE HERE
            fillColor: Colors.white,
            hintText: "Promo Code",
            hintStyle:
                const TextStyle(fontWeight: FontWeight.w500, fontSize: 16),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(16),
              borderSide: BorderSide(
                  width: 1,
                  color:
                      const Color(0xff000000).withOpacity(0.5)), //<-- SEE HERE
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(16),
              borderSide: BorderSide(
                  width: 1,
                  color:
                      const Color(0xff000000).withOpacity(0.5)), //<-- SEE HERE
            ),
            suffixIcon: InkWell(
              onTap: () {
                goPromoCode();
              },
              child: Container(
                width: 50,
                decoration: BoxDecoration(
                    color: TColor.primary,
                    borderRadius: BorderRadius.circular(8)),
                height: 50,
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 9),
                child: Center(
                  child: Text(
                    (isApplyCode ? "Remove" : "Apply").tr(),
                    style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w500),
                  ),
                ),
              ),
            )),
      ),
    );
  }

  void goPromoCode() {
    if (isApplyCode) {
      txtPromoCode.text = "";
      isApplyCode = false;
      setState(() {});
      return;
    }

    if (!isApplyCode && txtPromoCode.text.isEmpty) {
      mdShowAlert(MDGlobs.appName, MSG.enterPromocode, () {});
      return;
    }

    serviceCallPromoCode({
      "service_id": "${widget.sObj[KKey.id] ?? ""}",
      "promo_code": txtPromoCode.text
    });
  }

  void goSubmitPoint(double amount) async {
    if (selectPeriod == null) {
      mdShowAlert(MDGlobs.appName, MSG.selectPeriod, () {});
      return;
    }

    if (selectPeriod != periodArr.first && selectWeek == null) {
      mdShowAlert(MDGlobs.appName, MSG.selectWeek, () {});
      return;
    }

    await Navigator.of(context).push(PopupLayout(
        child: UsePointView(
      obj: {KKey.totalPoint: widget.bObj[KKey.totalPoint], KKey.amount: amount},
      didUse: () {
        goSubmit("point");
      },
    )));
  }

  void goSubmit(String paymentType) {
    if (selectPeriod == null) {
      mdShowAlert(MDGlobs.appName, MSG.selectPeriod, () {});
      return;
    }

    if (selectPeriod != periodArr.first && selectWeek == null) {
      mdShowAlert(MDGlobs.appName, MSG.selectWeek, () {});
      return;
    }
    //TODO:payment
    if (paymentType == "cash") {
      serviceCallList({
        "period": "${selectPeriod?["value"] ?? ""}",
        "session": "${selectWeek?["value"] ?? ""}",
        "payment_type": paymentType,
        "promo_code": txtPromoCode.text,
        "service_id": "${widget.sObj[KKey.id] ?? ""} "
      }, paymentType);
    } else {}

    var week = "${selectWeek?["value"] ?? ""}";

    serviceCallList({
      "period": "${selectPeriod?["value"] ?? ""}",
      "session": week,
      "payment_type": paymentType,
      "promo_code": txtPromoCode.text,
      "service_id": "${widget.sObj[KKey.id] ?? ""}",
      "price_key":
          "${selectPeriod?["value_key"] ?? ""}${selectWeek?["value_key"] ?? ""}",
      "point_key":
          "${selectPeriod?["value_key"] ?? ""}${selectWeek?["point_key"] ?? ""}",
      "session_key": week == "Unlimited"
          ? "${selectPeriod?["value_key"] ?? ""}${selectWeek?["session_key"] ?? ""}"
          : "",
      //session_key
    }, paymentType);
  }

  void goOnlinePayment() {
    // Navigator.of(context).push(
    //     MaterialPageRoute(builder: (context) => const OnlinePaymentView()));
  }

  void goUserPoint() async {
    // Navigator.of(context)
    //     .push(MaterialPageRoute(builder: (context) => const OurServiceView()));
  }

  //var billingDetails = BillingDetails("John Smith", "email@domain.com",
  // "+97311111111", "st. 12", "eg", "dubai", "dubai", "12345");

  PaymentSdkConfigurationDetails generateConfig(Map pObj) {
    var billingDetails = kDebugMode
        ? BillingDetails(
            "${MDServiceCall.userObj[KKey.name] ?? ""}",
            "${MDServiceCall.userObj[KKey.email] ?? ""}",
            "${MDServiceCall.userObj[KKey.mobileCode] as String? ?? "+91"}${MDServiceCall.userObj[KKey.mobile] as String? ?? ""}",
            "st. 12",
            "eg",
            "dubai",
            "dubai",
            "12345")
        : BillingDetails(
            "${MDServiceCall.userObj[KKey.name] ?? ""}",
            "${MDServiceCall.userObj[KKey.email] ?? ""}",
            "${MDServiceCall.userObj[KKey.mobileCode] as String? ?? "+91"}${MDServiceCall.userObj[KKey.mobile] as String? ?? ""}",
            "",
            "",
            "",
            "",
            "");

    List<PaymentSdkAPms> apms = [];
    apms.add(PaymentSdkAPms.AMAN);
    var configuration = PaymentSdkConfigurationDetails(
        profileId: "${pObj[KKey.profileId] ?? ""}",
        serverKey: "${pObj[KKey.serverKey] ?? ""}",
        clientKey: "${pObj[KKey.clientKey] ?? ""}",
        cartId: "${pObj[KKey.id] ?? ""}",
        cartDescription: "${pObj[KKey.cartDescription] ?? ""}",
        merchantName: "${pObj[KKey.merchantName] ?? ""}",
        screentTitle: "Pay with Card".tr(),
        amount: double.parse(
          "${pObj[KKey.amount] ?? ""}",
        ),
        showBillingInfo: true,
        forceShippingInfo: false,
        currencyCode: "${pObj[KKey.currencyCode] ?? ""}",
        merchantCountryCode: "${pObj[KKey.merchantCountryCode] ?? ""}",
        merchantApplePayIndentifier: "merchant.footfit.com",
        billingDetails: billingDetails,
        alternativePaymentMethods: apms,
        linkBillingNameWithCardHolderName: true);

    var theme = IOSThemeConfigurations();

    theme.logoImage = "assets/app_icon.png";
    theme.secondaryColor = "#333333";
    theme.titleFontColor = "#ECC800";
    theme.secondaryFontColor = "#333333";
    theme.inputsCornerRadius = 15;
    theme.buttonColor = "#ECC800";
    theme.buttonFontColor = "#333333";

    configuration.iOSThemeConfigurations = theme;
    configuration.tokeniseType = PaymentSdkTokeniseType.MERCHANT_MANDATORY;
    return configuration;
  }

  // void paymobPressd(Map pObj) async {
  //   try {
  //     PaymentResult? result =
  //         await _paymobFlutterLibPlugin.startPayActivityNoToken(Payment(
  //       paymentKey: pObj[KKey.paymentKey] as String? ?? "",
  //       saveCardDefault: false,
  //       showSaveCard: false,
  //       themeColor: const Color(0xFF002B36),
  //       language: "en",
  //       actionbar: true,
  //     ));
  //     if (!mounted) return;

  //     print("transID : ${result?.id}");
  //     print(result);

  //     serviceCallCheckoutPaymentCheck({
  //       "subscription_id": "${pObj[KKey.id] ?? ""}",
  //       "transaction_id": result?.id ?? "",
  //       "type": "paymob",
  //       "data": jsonEncode(result?.payload ?? {})
  //     });

  //     // setState(() {
  //     //   _result = result?.dataMessage;
  //     //   _token = result?.token;
  //     //   _maskedPan = result?.maskedPan;
  //     // });
  //   } on PlatformException catch (err) {
  //     // Handle err

  //     mdShowAlert(MDGlobs.appName, MSG.fail, () {});
  //     print("PlatformException 1");
  //     print(err);
  //     setState(() {
  //       // _error = '${err.message}';
  //     });
  //   } catch (e) {
  //     print(e);
  //     if (!mounted) return;
  //     mdShowAlert(MDGlobs.appName, MSG.fail, () {});
  //     // setState(() {
  //     //   _error = '$e';
  //     // });
  //   }
  // }

  void payOnlinePressed(Map pObj) {
    FlutterPaytabsBridge.startCardPayment(generateConfig(pObj), (event) {
      setState(() {
        if (event["status"] == "success") {
          // Handle transaction details here.
          var transactionDetails = event["data"];
          print(transactionDetails);
          if (transactionDetails["isSuccess"]) {
            print("successful transaction");
            if (transactionDetails["isPending"]) {
              print("transaction pending");
            }

            serviceCallCheckoutPaymentCheck({
              "subscription_id": "${pObj[KKey.id] ?? ""}",
              "transaction_id":
                  transactionDetails["transactionReference"] as String? ?? "",
              "data": jsonEncode(transactionDetails)
            });
          } else {
            mdShowAlert(MDGlobs.appName, MSG.fail, () {});
            print("failed transaction");
          }

          // print(transactionDetails["isSuccess"]);
        } else if (event["status"] == "error") {
          mdShowAlert(MDGlobs.appName, MSG.fail, () {});
          // Handle error here.
        } else if (event["status"] == "event") {
          mdShowAlert(MDGlobs.appName, MSG.fail, () {});
          // Handle events here.
        }
      });
    });
  }

  //MARK: ServiceCall
  void serviceCallList(Map<String, String> parameter, String paymentType) {
    MDGlobs.showHUD();

    MDServiceCall.serviceCallImageDicPost(parameter, SVKey.svCheckout,
        isToken: true, withSuccess: (responseObj) async {
      MDGlobs.hideHUD();

      debugPrint(responseObj.toString());
      if ((responseObj[KKey.status] as bool? ?? false)) {
        if (paymentType == "cash") {
          Navigator.of(context).push(
              MaterialPageRoute(builder: (context) => const OrderSubmitView()));
        } else if (paymentType == "online") {
          var payloadObj = responseObj[KKey.payload] as Map? ?? {};
          if ((payloadObj[KKey.paymentOnlineType] as String? ?? "") ==
              "paymob") {
            // paymobPressd(payloadObj);
          } else if ((payloadObj[KKey.paymentOnlineType] as String? ?? "") ==
              "paytab") {
            payOnlinePressed(payloadObj);
          }

          // Navigator.of(context).push(MaterialPageRoute(
          //     builder: (context) => const OnlinePaymentView()));
        } else {
          Navigator.of(context).push(
              MaterialPageRoute(builder: (context) => const OrderSubmitView()));
        }
        if (mounted) {
          setState(() {});
        }
      } else {
        mdShowAlert(MDGlobs.appName,
            responseObj[KKey.message] as String? ?? MSG.fail, () {});
      }

      // print(responseObj);
    }, failure: (err) async {
      MDGlobs.hideHUD();

      mdShowAlert(MDGlobs.appName, err.toString(), () {});
      // print(err);
    });
  }

  void serviceCallCheckoutPaymentCheck(Map<String, String> parameter) {
    MDGlobs.showHUD();

    MDServiceCall.serviceCallImageDicPost(
        parameter, SVKey.svCheckoutPaymentCheck, isToken: true,
        withSuccess: (responseObj) async {
      MDGlobs.hideHUD();

      debugPrint(responseObj.toString());
      if ((responseObj[KKey.status] as bool? ?? false)) {
        Navigator.of(context).push(
            MaterialPageRoute(builder: (context) => const OrderSubmitView()));
      } else {
        mdShowAlert(MDGlobs.appName,
            responseObj[KKey.message] as String? ?? MSG.fail, () {});
      }

      // print(responseObj);
    }, failure: (err) async {
      MDGlobs.hideHUD();

      mdShowAlert(MDGlobs.appName, err.toString(), () {});
      // print(err);
    });
  }

  void serviceCallPromoCode(Map<String, String> parameter) {
    MDGlobs.showHUD();

    MDServiceCall.serviceCallImageDicPost(parameter, SVKey.svGetPromocode,
        isToken: true, withSuccess: (responseObj) async {
      MDGlobs.hideHUD();

      debugPrint(responseObj.toString());
      if ((responseObj[KKey.status] as bool? ?? false)) {
        promoDic = responseObj[KKey.payload] as Map? ?? {};
        isApplyCode = true;

        if (mounted) {
          setState(() {});
        }
      } else {
        isApplyCode = false;
        if (mounted) {
          setState(() {});
        }
        mdShowAlert(MDGlobs.appName,
            responseObj[KKey.message] as String? ?? MSG.fail, () {});
      }

      // print(responseObj);
    }, failure: (err) async {
      MDGlobs.hideHUD();

      mdShowAlert(MDGlobs.appName, err.toString(), () {});
      // print(err);
    });
  }
}
Editor is loading...