import 'package:auto_size_text/auto_size_text.dart'; import 'package:cheminova/controller/get_order_placed_controller.dart'; import 'package:cheminova/controller/rd_get_order_controller.dart'; import 'package:cheminova/models/oder_place_model.dart'; import 'package:cheminova/models/order_item_model.dart'; import 'package:cheminova/models/place_order_list_model.dart'; import 'package:cheminova/models/rd_get_order_model.dart'; import 'package:cheminova/models/rd_order_item_model.dart'; import 'package:cheminova/models/rd_placed_order_model.dart'; import 'package:cheminova/screens/rd%20orders/partial_processing_dialog_screen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:intl/intl.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../controller/cart_controller.dart'; import '../../controller/rd_processing_order_controller.dart'; import '../../models/product_model1.dart'; import '../../utils/show_snackbar.dart'; class RdOrderDetailScreen extends StatefulWidget { //final Product? productModel; // PlacedOrderList and PlacedOrderModel are optional parameters passed to this screen PlacedOrdersResponse? placedOrderList; // PlacedOrderModel? placedOrderModel; // Constructor for initializing the screen with placed order details RdOrderDetailScreen({super.key,this.placedOrderList}); @override State createState() => _RdOrderDetailScreenState(); } class _RdOrderDetailScreenState extends State { // Controllers for managing cart and placed orders final GetProductRDController _getPlacedOrderController = Get.put(GetProductRDController()); final RDOrderPlacedController controller = Get.put(RDOrderPlacedController()); String? orderId; final List statusOptions = [ "new", "pending", "processing", "dispatched", "cancelled", "delivered", ]; String selectedStatus = "All"; String _groupValue = "cheque"; // Function to format date from the API to a more readable format String formatDate(String apiDate) { DateTime parsedDate = DateTime.parse(apiDate); String formattedDate = DateFormat('dd-MMM-yyyy').format(parsedDate); return formattedDate; } // Function to capitalize the first letter of a string String capitalizeFirstLetter(String text) { if (text.isEmpty) return text; return text[0].toUpperCase() + text.substring(1).toLowerCase(); } void _onPaymentModeChanged(String? value) { setState(() { _groupValue = value!; }); _saveSelectedPaymentMode(); } void _saveSelectedPaymentMode() async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString('selectedPaymentMode', _groupValue); } void _loadSelectedPaymentMode() async { SharedPreferences prefs = await SharedPreferences.getInstance(); setState(() { _groupValue = prefs.getString('selectedPaymentMode') ?? 'cheque'; }); } // Function to collect unique order IDs and corresponding order details Future adduni()async { final Set uniqueOrderIds = {}; final List uniqueOrders = []; // Loop through placed orders and add unique orders to the list for (var order in _getPlacedOrderController.productRDList) { if (uniqueOrderIds.add(order.uniqueId)) { uniqueOrders.add(order); } } final order = uniqueOrders[0]; // Combine product names, categories, and quantities into strings final productNames = order.orderItem .map((item) => (item.name)) .join(', '); final categotyName = order.orderItem .map((item) => (item.categoryName)) .join(', '); final quantity = order.orderItem .map((item) => (item.quantity)) .join(', '); } @override void initState() { // TODO: implement initState super.initState(); selectedStatus= widget.placedOrderList?.status ?? 'new'; // controller.fetchOrderItems(widget.placedOrderList!.id); } // Method to show confirmation dialog void _showConfirmationDialog() { String dialogTitle; String dialogContent; TextEditingController reasonController = TextEditingController(); // Set dialog title and content based on selected status switch (selectedStatus) { case "processing": dialogTitle = "Update Order Status"; dialogContent = "Are you sure you want to update the status to processing?"; break; case "partial processing": dialogTitle = "Update to Partial Processing"; dialogContent = "Are you sure you want to update the status to 'Partial Processing'?"; break; case "cancelled": dialogTitle = "Cancellation Reason"; dialogContent = "Please provide a reason for cancelling the order:"; break; default: dialogTitle = "Update Order Status"; dialogContent = "Are you sure you want to update the status to '$selectedStatus'?"; break; } showDialog( context: context, builder: (context) { return AlertDialog( title: Text(dialogTitle), content: selectedStatus == "cancelled" ? Column( mainAxisSize: MainAxisSize.min, children: [ Text(dialogContent), SizedBox(height: 10), // Space between text and text field TextField( controller: reasonController, // Text controller for cancellation reason decoration: InputDecoration( labelText: 'Cancellation Reason', border: OutlineInputBorder(), ), ), ], ) : Text(dialogContent), actions: [ TextButton( onPressed: () async { // Check if the selected status is "cancelled" and if necessary reason is provided if (selectedStatus == "cancelled" && reasonController.text.isEmpty) { // Show a warning if the reason is empty Get.snackbar("Error", "Please provide a reason for cancelling the order."); return; } // Handle "partial processing" status if (selectedStatus == "partial processing") { // Navigate to the Partial Processing screen without dismissing the dialog Get.to(() => PartialProcessingDialogScreen(productModel: widget.placedOrderList)); return; // Exit to ensure dialog doesn't close yet } List orderItems = _getPlacedOrderController.productRDList.map((product) { return RDOrderItem( productId: product.orderItem[0].productId, sku: product.orderItem[0].sku, name: product.orderItem[0].name, // You had an empty name in your code categoryName: product.orderItem[0].categoryName, brandName: product.orderItem[0].brandName, price: product.orderItem[0].price, gst: product.orderItem[0].gst, hsnCode: product.orderItem[0].hsnCode, // Fixed hsnCode, hashCode was incorrect description: product.orderItem[0].description, image: [], // Ensure images are properly handled quantity: product.orderItem[0].quantity, remainingQuantity: product.orderItem[0].remainingQuantity, processquantity: product.orderItem[0].processquantity, ); }).toList(); // Updating the placedOrder1 with orderId and items controller.placedOrder1.value = PlacedOrdersProcessing( orderId: _getPlacedOrderController.productRDList[0].id, invoiceItems: orderItems, ); // Debugging: Print the JSON payload print(controller.placedOrder1.value.toJson()); await controller.placeRDOrder(); // Call your update status method here showSnackbar("Order processed and invoice created successfully"); // Delay closing the dialog to ensure the user sees the success message Future.delayed(Duration(seconds: 1), () { Get.back(); // Close the dialog after a delay }); setState(() {}); // Refresh the UI }, child: Text("Confirm"), ), TextButton( onPressed: () { Get.back(); // Close the dialog }, child: Text("Cancel"), ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leading: GestureDetector( onTap: () {}, child: Padding( padding: const EdgeInsets.all(16.0), child: SvgPicture.asset( 'assets/svg/menu.svg', ), ), ), actions: [ GestureDetector( onTap: () => Get.back(), child: Padding( padding: const EdgeInsets.all(8.0), child: SvgPicture.asset( 'assets/svg/back_arrow.svg', ), ), ), ], title: const Text( "Order Detail", ), ), body: Stack( fit: StackFit.expand, children: [ Image.asset( 'assets/images/image_1.png', fit: BoxFit.cover, ), SafeArea( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.start, children: [ SizedBox( height: Get.height * 0.02, ), Card( margin: const EdgeInsets.symmetric(horizontal: 18), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(19), side: const BorderSide(color: Color(0xFFFDFDFD)), ), color: const Color(0xFFB4D1E5).withOpacity(0.9), child: Padding( padding: const EdgeInsets.all(12.0), child: Column( mainAxisSize: MainAxisSize.min, children: [ Card( child: Column( children: [ SizedBox( width: Get.width, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Text( "Order Summary", style: GoogleFonts.roboto( fontSize: Get.width * 0.05, fontWeight: FontWeight.bold, ), ), ), ), _buildRow("Order ID:", widget.placedOrderList!.uniqueId, Get.width * 0.04), _buildRow("Order Date:", formatDate("${widget.placedOrderList!.createdAt}"), Get.width * 0.04), _buildRow("Total Items:", "${widget.placedOrderList!.orderItem.length}", Get.width * 0.04), _buildRow("Sub Total:", "₹ ${widget.placedOrderList!.subtotal}", Get.width * 0.04), _buildRow("GST:", "₹ ${widget.placedOrderList!.gstTotal}", Get.width * 0.04), _buildRow("Total Amount:", "₹ ${widget.placedOrderList!.grandTotal}", Get.width * 0.04), ], ), ), const SizedBox(height: 8), Card( child: SizedBox( height: Get.height * 0.22, child: Padding( padding: EdgeInsets.all(Get.width * 0.02), child: ListView.builder( padding: EdgeInsets.zero, itemCount: widget.placedOrderList?.orderItem.length ?? 0, itemBuilder: (context, index) { final orderItem = widget.placedOrderList!.orderItem[index]; return orderItem != null ? Card( margin: const EdgeInsets.symmetric(vertical: 5.0), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ Image.asset( "assets/images/product.png", // Add the image URL here height: 50, width: 50, fit: BoxFit.cover, ), const SizedBox(width: 10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( capitalizeFirstLetter(orderItem.name), style: GoogleFonts.roboto( fontSize: Get.width * 0.04, fontWeight: FontWeight.bold, ), ), Text( "Quantity: ${orderItem.quantity}", style: GoogleFonts.roboto( fontSize: Get.width * 0.03, ), ), Text("Price: ${orderItem.price}"), Text("Subtotal : ${widget.placedOrderList!.subtotal}"), Text("Gst : ${orderItem.gst}%"), Text("GST : ${widget.placedOrderList!.gstTotal}"), Text("Total Amount : ${widget.placedOrderList!.grandTotal}"), ], ), ), ], ), ), ) : const SizedBox.shrink(); }, ), ), ), ), const SizedBox(height: 8), SizedBox( height: Get.height* 0.19, child: Card( child: Column( children: [ SizedBox( width: Get.width, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Text( "Customer Details", style: GoogleFonts.roboto( fontSize: Get.width * 0.05, fontWeight: FontWeight.w500, ), ), ), ), _buildRow("Name:", "VAIBHAV", Get.width * 0.04), _buildRow("Email:", "vaibhav.gurjar20001@gmail.com", Get.width * 0.04), _buildRow("Mobile Number:", "7779797976", Get.width * 0.04), ], ), ), ), const SizedBox(height: 8), Card( child: Column( children: [ SizedBox( width: Get.width, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Text( "Billing Information", style: GoogleFonts.roboto( fontSize: Get.width * 0.05, fontWeight: FontWeight.w500, ), ), ), ), _buildInfoRow("Address", widget.placedOrderList!.billTo, Get.width * 0.04) ], ), ), const SizedBox(height: 8), // Card for displaying shipping information Card( child: Column( children: [ SizedBox( width: Get.width, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Text( "Shipping Information", style: GoogleFonts.roboto( fontSize: Get.width * 0.05, fontWeight: FontWeight.w500, ), ), ), ), _buildInfoRow("Address", widget.placedOrderList!.shipTo, Get.width * 0.04) ], ), ), const SizedBox(height: 8), Card( child: Column( children: [ SizedBox( width: Get.width, height: Get.height*0.05, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Row( children: [ Text( "Payment Mode : ", style: GoogleFonts.roboto( fontSize: Get.width * 0.04, fontWeight: FontWeight.w500, ), ), Text(capitalizeFirstLetter(widget.placedOrderList!.paymentMode)), // Text("${widget.placedOrderList!.paymentMode}",maxLines: 4, // overflow:TextOverflow.ellipsis,) ], ), ), ), ], ), ), const SizedBox(height: 8), Card( child: Column( children: [ SizedBox( width: Get.width, height: Get.height*0.05, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Row( children: [ Text( "Order Status :", style: GoogleFonts.roboto( fontSize: Get.width * 0.04, fontWeight: FontWeight.w500, ), ), SizedBox(width: Get.width*0.01,), Text(capitalizeFirstLetter(selectedStatus)), // Text("${widget.placedOrderList!.status}",maxLines: 4, // overflow:TextOverflow.ellipsis,) ], ), ), ), ], ), ), const SizedBox(height: 8), SizedBox( height: Get.height * 0.05, child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ const Text( "Status: ", style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox(width: 10), // Space between label and dropdown Expanded( child: DropdownButtonFormField( value: selectedStatus, decoration: InputDecoration( filled: true, fillColor: Colors.white, // White background contentPadding: EdgeInsets.symmetric( vertical: 10, horizontal: 12), border: OutlineInputBorder( borderRadius: BorderRadius.circular(10), borderSide: BorderSide( color: Colors.grey, width: 1, ), ), ), items: [ "new", "processing", "partial processing", "cancelled", ].map((String status) { return DropdownMenuItem( value: status, child: Text(capitalizeFirstLetter(status)), ); }).toList(), onChanged: (newValue) { setState(() { selectedStatus = newValue!; }); }, ), ), ], ), ), if (selectedStatus == "processing" || selectedStatus == "partial processing" || selectedStatus == "cancelled") SizedBox( width: Get.width * 0.4, child: Padding( padding: const EdgeInsets.all(8.0), child: ElevatedButton( onPressed: () { // Show confirmation dialog _showConfirmationDialog(); }, // Get.to(() => // RdOrderDetailScreen( // placedOrderList: uniqueOrders[index])), // Navigate to detail screen style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: const Color(0xFF004791), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10)), ), child: Text("Update Status", style: GoogleFonts.roboto(fontSize: 14, fontWeight: FontWeight.w400)), ), ), ) ], ), ), ), SizedBox(height: Get.height * 0.04), ], ), ), ), ], ), ); } } Widget _buildRow(String label, String value, double fontSize) { return SizedBox( width: Get.width, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( label, style: GoogleFonts.roboto( fontSize: fontSize, fontWeight: FontWeight.bold, ), ), Text(value), ], ), ), ); } Widget _buildInfoRow(String label, String value, double fontSize) { return SizedBox( width: Get.width, child: Padding( padding: const EdgeInsets.fromLTRB(8, 8, 8, 0), child: Row( children: [ Text( "$label ", style: GoogleFonts.roboto( fontSize: fontSize, fontWeight: FontWeight.bold, ), ), Expanded( child: Text( value, maxLines: 4, overflow: TextOverflow.ellipsis, ), ), ], ), ), ); }