import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:siopas/models/customer_model.dart'; import 'package:siopas/models/disposal_model.dart'; import 'package:siopas/models/m_asset_status_model.dart'; import 'package:siopas/models/transfer_peti_model.dart'; import 'package:siopas/models/type_peti_model.dart'; import 'package:siopas/models/warehouse_mode.dart'; import 'package:siopas/pages/transfer_peti/controller/transfer_peti_controller.dart'; import 'package:siopas/services/controllerApi.dart'; import 'package:siopas/pages/peminjaman_barang/controller/peminjaman_controller.dart'; import 'package:intl/intl.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:siopas/models/asset_status_model.dart'; import 'package:collection/collection.dart'; import '../../models/condition_peti_model.dart'; import '../../widget/loading_shimmer_show.dart'; import '../home/controller/home_controller.dart'; import 'show.dart'; class TransferPetiPage extends StatefulWidget { TransferPetiPage({super.key}); final ControllerHome controllerHome = ControllerHome(); // Declare here @override State createState() => TransferPetiPageState(); } class TransferPetiPageState extends State { String? token; bool loading = true; // Reinit atau Upload Only WarehouseModel? warehouseSqfliteApi; WarehouseModel? warehouseTujuanSqfliteApi; List? customerSqfliteApi; PetiAssetModel? petiSqfliteApi; ConditionPetiModel? conditionPetiSqfliteApi; DisposalPetiModel? disposalSqfliteApi; List? _valpeti; List? _valwarehouse; List? _valconditionPeti; List? _valdisposal; // Datatable int _currentPage = 1; int _pageSize = 10; List? _data; List? _petiData; List? _tipePetiData; List? _customerData; List? _warehouseData; List? _conditionData; Timer? _timer; bool _isLoading = false; int _transferPetiCount = 0; String _searchQuery = ''; @override void initState() { super.initState(); _getUserToken(); // Memulai loading setState(() { _isLoading = true; }); Future.wait([ _initData(), warehouseListAPI(), customerListAPI(), petiListAPI(), datatablesTransferPetiList(), datatablesPetiList(), datatablesCustomerList(), datatablesWarehouseList(), initializeDateFormatting('id_ID', null), ]).then((_) { // Mengakhiri loading setelah semua tugas selesai setState(() { _isLoading = false; }); }); // Inisialisasi _data di sini jika diperlukan _data = []; } Future _initData() async { try { _transferPetiCount = await widget.controllerHome.getTransferCount(); } catch (error) { print('Error fetching pengembalianCount: $error'); } // ... tambahkan inisialisasi lainnya } void _getUserToken() async { SharedPreferences prefs = await SharedPreferences.getInstance(); if (mounted) { setState(() { token = prefs.getString('token'); }); } } // Reinit atau Upload Only ------------------------------------------------------------------------ Future warehouseListAPI() async { if (mounted) { await ControllerApi().fetchWarehouseDataAPI().then((value) { setState(() { _valwarehouse = (value as List) .map((item) => WarehouseModel.fromJson(item)) .toList(); loading = false; }); }); } } Future customerListAPI() async { if (mounted) { await ControllerApi().fetchCustomerDataAPI().then((value) { setState(() { customerSqfliteApi = (value as List) .map((item) => CustomerModel.fromJson(item)) .toList(); loading = false; }); }); } } Future petiListAPI() async { if (mounted) { await ControllerApi().fetchPetiDataAPI().then((value) { setState(() { _valpeti = (value as List) .map((item) => PetiAssetModel.fromJson(item)) .toList(); loading = false; }); }); } } // Datatables ------------------------------------------------------------------------ Future datatablesTransferPetiList() async { await ControllerTransferPeti() .fetchTransferPetiLocalController() .then((value) { setState(() { _data = (value as List) .map((e) => TransferPetiModel.fromJson(e)) .toList(); loading = false; }); }); } Future datatablesPetiList() async { await Controller().fetchPetiData().then((value) { setState(() { _petiData = (value as List) .map((e) => PetiAssetModel.fromJson(e)) .toList(); loading = false; }); }); } Future datatablesCustomerList() async { await Controller().fetchCustomerData().then((value) { setState(() { _customerData = (value as List) .map((e) => CustomerModel.fromJson(e)) .toList(); loading = false; }); }); } Future datatablesWarehouseList() async { await Controller().fetchWarehouseData().then((value) { setState(() { _warehouseData = (value as List) .map((e) => WarehouseModel.fromJson(e)) .toList(); loading = false; }); }); } String _formatDate(String? date) { if (date != null) { DateTime parsedDate = DateTime.parse(date); String formattedDate = DateFormat('EEEE, dd MMMM yyyy', 'id_ID').format(parsedDate); return formattedDate; } else { return ''; } } List get _filteredData { return _data != null ? _data!.where((item) { // Sesuaikan dengan properti yang ingin Anda cari return (_customerData ?.firstWhere( (customer) => customer.id == item.name_customer, orElse: () => CustomerModel(name: '')) ?.name ?? '') .toLowerCase() .contains(_searchQuery.toLowerCase()) || _formatDate(item.date.toString()) .toLowerCase() .contains(_searchQuery.toLowerCase()) || (_petiData?.firstWhere((peti) => peti.id == item.peti_id, orElse: () => PetiAssetModel(fix_lot: ''))?.fix_lot ?? '') .toLowerCase() .contains(_searchQuery.toLowerCase()) || (_warehouseData ?.firstWhere((warehouse) => warehouse.id == item.source_warehouse, orElse: () => WarehouseModel(name: '')) ?.name ?? '') .toLowerCase() .contains(_searchQuery.toLowerCase()) || (_warehouseData ?.firstWhere( (warehouse) => warehouse.id == item.destination_warehouse, orElse: () => WarehouseModel(name: '')) ?.name ?? '') .toLowerCase() .contains(_searchQuery.toLowerCase()); }).toList() : []; } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { // Mencegah kembali ke halaman sebelumnya return false; }, child: DefaultTabController( length: 1, child: Scaffold( appBar: appBar(context), body: _isLoading ? Column( children: [ // shimmerSearch(), Expanded( child: ListView.builder( itemCount: 4, // Set the number of shimmer cards based on your data count itemBuilder: (context, index) { return ShimmerLoadingAssetStatusTransferPetiCard(); }, ), ), ], ) : bodyTransferPeti(), bottomNavigationBar: bottomAppBar(context), ), ), ); } AppBar appBar(BuildContext context) { return AppBar( backgroundColor: Colors.indigo[700], elevation: 0, title: Text('Data Transfer Peti', style: TextStyle( fontSize: 16, )), leading: IconButton( icon: Icon(Icons.arrow_back, color: Colors.white), onPressed: () { Navigator.pushNamed(context, '/home'); }, ), bottom: TabBar( indicator: BoxDecoration( color: Color.fromARGB(255, 255, 165, 9), ), tabs: [ Tab( height: 65, child: Container( padding: const EdgeInsets.symmetric(horizontal: 16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(0), border: Border.all(color: Colors.grey, width: 1.0), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( child: TextField( style: TextStyle(fontSize: 18), decoration: InputDecoration( hintText: 'Masukkan data pencarian...', prefixIcon: Icon(Icons.search), border: InputBorder.none, contentPadding: EdgeInsets.all(10), labelStyle: TextStyle( color: Colors.grey, fontSize: 12, ), hintStyle: TextStyle( color: Colors.grey, fontSize: 12, ), ), onChanged: (value) { setState(() { _searchQuery = value.isNotEmpty ? value : ''; // Memperbarui dengan null jika value kosong }); }, ), ), Text( 'Total: $_transferPetiCount', style: TextStyle(color: Colors.black), ), ], ), ), ), ], ), ); } BottomAppBar bottomAppBar(BuildContext context) { return BottomAppBar( color: Color.fromARGB(255, 5, 28, 158), // Warna latar belakang child: Container( height: 65.0, child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( customBorder: CircleBorder(), onTap: () { // Aksi ketika ikon diklik Navigator.pushNamed(context, '/transfer-peti/edit'); }, child: Container( width: 45, height: 45, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.greenAccent[700], ), child: Icon( Icons.add, size: 30, color: Colors.white, ), ), ), ], ), ), ); } Column bodyTransferPeti() { return Column( children: [ Expanded( child: TabBarView( children: [ SingleChildScrollView( child: Column( children: _filteredData.isNotEmpty ? _filteredData.asMap().entries.map((entry) { final index = entry.key + 1; final item = entry.value; return TransferPetiCard( transferPeti: item, petiData: _petiData ?? [], tipePetiData: _tipePetiData ?? [], customerData: _customerData ?? [], warehouseData: _warehouseData ?? [], conditionData: _conditionData ?? [], index: index, ); }).toList() // : [Text('No results')], : [ Center( child: Column( children: [ Image.asset( 'assets/item/empty.png', width: 250, // Set the width as needed height: 250, // Set the height as needed ), Text( 'Tidak ada data ditemukan', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ], ), ), ], ), ), ], ), ), ], ); } } class TransferPetiCard extends StatelessWidget { final TransferPetiModel transferPeti; final List petiData; final List tipePetiData; final List customerData; final List warehouseData; final List conditionData; final int index; // Tambahkan parameter nomor urutan TransferPetiCard({ required this.transferPeti, required this.petiData, required this.tipePetiData, required this.customerData, required this.warehouseData, required this.conditionData, required this.index, // Inisialisasi parameter nomor urutan }); @override Widget build(BuildContext context) { PetiAssetModel? petiSqfliteApi = petiData.firstWhereOrNull( (peti) => peti.id == transferPeti.peti_id, ); WarehouseModel? warehouseSqfliteApi = warehouseData.firstWhereOrNull( (warehouse) => warehouse.id == transferPeti.source_warehouse, ); WarehouseModel? warehouseTujuanSqfliteApi = warehouseData.firstWhereOrNull( (warehouse) => warehouse.id == transferPeti.destination_warehouse, ); CustomerModel? customerSqfliteApi = customerData.firstWhereOrNull( (customer) => customer.id == transferPeti.name_customer, ); String _formatDate(String? date) { if (date != null) { DateTime parsedDate = DateTime.parse(date); String formattedDate = DateFormat('EEEE, dd MMMM yyyy', 'id_ID').format(parsedDate); return formattedDate; } else { return ''; } } Future _deleteTransferPeti() async { try { // Panggil fungsi untuk menghapus Pengembalian berdasarkan ID await ControllerTransferPeti() .deleteTransferPetiById(transferPeti.id.toString()); // Navigasi kembali ke halaman sebelumnya atau halaman yang sesuai Navigator.pushReplacementNamed(context, '/transfer-peti'); } catch (e) { // Tangani kesalahan jika terjadi print('Gagal menghapus transfer peti: $e'); } } Future _showDeleteConfirmationDialog() async { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16.0), ), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Icon( Icons.info, color: Colors.blue, ), SizedBox(width: 8), Text( 'Konfirmasi Hapus', style: TextStyle( fontSize: 18, ), ), ], ), IconButton( icon: Icon( Icons.close, color: Colors.black54, ), onPressed: () { Navigator.of(context).pop(); }, ), ], ), content: SingleChildScrollView( child: ListBody( children: [ Text( 'Anda yakin ingin menghapus transfer peti ini? ${petiSqfliteApi!.fix_lot.toString()}', style: TextStyle( fontSize: 16, ), ), ], ), ), actions: [ Container( margin: EdgeInsets.only(right: 3.0), child: ElevatedButton( child: Text('Hapus'), onPressed: () { // Panggil fungsi untuk menghapus transfer peti berdasarkan ID _deleteTransferPeti(); EasyLoading.showSuccess( 'Berhasil menghapus data transfer peti'); }, style: ElevatedButton.styleFrom( primary: Colors.red, ), ), ), ], ); }, ); } return WillPopScope( onWillPop: () async { // Mencegah kembali ke halaman sebelumnya return false; }, child: Slidable( key: Key(transferPeti.id.toString()), endActionPane: ActionPane( motion: ScrollMotion(), children: [ SlidableAction( onPressed: (context) { _showDeleteConfirmationDialog(); }, backgroundColor: Color(0xFFFE4A49), foregroundColor: Colors.white, icon: Icons.delete, label: 'Hapus', ), ], ), child: GestureDetector( onTap: () { // Tindakan yang dilakukan saat card diklik if (transferPeti != null) { Navigator.push( context, MaterialPageRoute( builder: (context) => DetailTransferPetiPage( transferPetiId: int.parse(transferPeti.id.toString()), ), ), ); } }, child: Card( color: Colors.white60, elevation: 0.0, shape: RoundedRectangleBorder( side: BorderSide(color: Colors.grey, width: 1.0), ), child: Padding( padding: const EdgeInsets.only( top: 8.0, bottom: 8.0, left: 16.0, right: 16.0, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildAvatarAndIndex(index), Divider(), _buildInfoRow( 'Nama Customer:', '${customerSqfliteApi?.name ?? '-'}', 'Tanggal Transfer Peti:', '${_formatDate(transferPeti.date.toString())}', 13, ), _buildInfoRow( 'Asal Gudang:', '${warehouseSqfliteApi?.name ?? '-'}', 'Tujuan Gudang:', '${warehouseTujuanSqfliteApi?.name ?? '-'}', 13), ], ), ), ), ), ), ); } Widget _buildAvatarAndIndex(int index) { PetiAssetModel? petiSqfliteApi = petiData.firstWhereOrNull( (peti) => peti.id == transferPeti.peti_id, ); return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildAvatar(index), Expanded( child: Padding( padding: const EdgeInsets.only( left: 8.0, top: 8.0, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( '${petiSqfliteApi?.fix_lot ?? '-'}', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 14.5, ), ), ], ), ), ), ], ); } Widget _buildAvatar(int index) { return Container( child: CircleAvatar( radius: 11, backgroundColor: Colors.indigo[700], child: Text( '$index', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 13, color: Colors.white, ), ), ), ); } Widget _buildInfoRow(String title1, String content1, String title2, String content2, double fontSize) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title1, style: TextStyle( fontWeight: FontWeight.bold, fontSize: fontSize, ), ), SizedBox(height: 3), Text( content1, style: TextStyle( fontSize: fontSize - 0.5, // Mengurangkan ukuran font agar cocok dengan judul ), ), ], ), ), SizedBox(width: 10), // Memberi jarak antara dua kolom Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title2, style: TextStyle( fontWeight: FontWeight.bold, fontSize: fontSize, ), ), SizedBox(height: 3), Text( content2, style: TextStyle( fontSize: fontSize - 0.5, // Mengurangkan ukuran font agar cocok dengan judul ), ), ], ), ), ], ); } }