import 'package:absenkuv3/Bloc/Dropdown/DropdownProdukLayananBloc.dart';
import 'package:absenkuv3/Bloc/SalesActivity/LayananDraftBloc.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mDataProduct.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mDataLayanan.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mSplashScreen.dart';
import 'package:absenkuv3/Setting/value_image.dart';
import 'package:absenkuv3/UI/Modul/Dropdown/DropdownDataProduct.dart';
import 'package:absenkuv3/UI/Template/dialog/alertDialog.dart';
import 'package:absenkuv3/UI/Template/style.dart';
import 'package:absenkuv3/UI/Template/templateButton.dart';
import 'package:absenkuv3/UI/Template/templateConfirmationDialog.dart';
import 'package:absenkuv3/UI/Template/templateTextFormAkun.dart';
import 'package:extended_masked_text/extended_masked_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

typedef void DataProdukLayananPageCallback(List<Layanan> val);

class DataProdukLayananPage extends StatefulWidget {
  GlobalKey<ScaffoldState> _scaffoldKey;
  DataProdukLayananPageCallback? dataCallback;
  // List<Data>? data;

  DataProdukLayananPage(this._scaffoldKey, {this.dataCallback});

  @override
  State<DataProdukLayananPage> createState() => _DataProdukLayananPageState();
}

class _DataProdukLayananPageState extends State<DataProdukLayananPage> {
  TextEditingController nominal = MoneyMaskedTextController(thousandSeparator: '.', leftSymbol: 'Rp ', precision: 0, decimalSeparator: '');
  TextEditingController totalHarga = MoneyMaskedTextController(thousandSeparator: '.', leftSymbol: 'Rp ', precision: 0, decimalSeparator: '');
  TextEditingController total = MoneyMaskedTextController(thousandSeparator: '.', leftSymbol: 'Rp ', precision: 0, decimalSeparator: '');
  TextEditingController jmlProduk = TextEditingController();
  TextEditingController diskon = TextEditingController();
  DataProduct jenisProduct = DataProduct();

  Future<bool> keluar() async {
    return false;
  }

  @override
  void initState() {
    super.initState();
     BlocProvider.of<LayananDraftBloc>(context)
        .add(getListLayananDraftEvent(context, ModelFilter(monthYear: DateTime.now())));
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<LayananDraftBloc, LayananDraftState>(
        builder: (BuildContext context, LayananDraftState state) {
          if (state is getListLayananDraftSuccessState) {
            widget.dataCallback!(state.data!);
            total.text = state.totalHarga.toString();
            return Container(
                margin: EdgeInsets.symmetric(vertical: 13, horizontal: 7),
                child: Column(
                  children: [
                    Container(
                      margin: EdgeInsets.symmetric(horizontal: 23),
                      padding: EdgeInsets.only(bottom: 13),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('${state.totalLayanan} Layanan', style: TextStyle(color: Colors.grey.shade600)),
                              SizedBox(height: 3),
                              Text('${state.totalHarga}', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: CustomStyle.color1)),
                            ],
                          ),
                          TemplateButton(
                            onClick: () {
                              jenisProduct = DataProduct();
                              nominal.clear();
                              jmlProduk.clear();
                              diskon.clear();
                              totalHarga.clear();
                              totalHarga.text = "-";

                              showDialogAddLayanan(context);
                            },
                            label: "Tambah Produk",
                            color: CustomStyle.color1,
                            heightButton: 31,
                            radius: CustomStyle.boxRadius + 4,
                            bold: true,
                            icon: Icons.add_circle_outline_outlined,
                            fontSize: CustomStyle.fontSizeSmall - 1,
                            iconSize: 21,
                            paddingTopBottom: 0,
                          )
                        ],
                      ),
                    ),
                    Divider(color: Colors.grey.shade300,thickness: 2, height: 2),
                    Container(
                      height: MediaQuery.of(context).size.height/1.52,
                      child: ListView.builder(
                          itemCount: state.data!.length,
                          physics: AlwaysScrollableScrollPhysics(),
                          shrinkWrap: true,
                          itemBuilder: (con, index){
                            return Container(
                              margin: EdgeInsets.fromLTRB(23,7,23,7),
                              // decoration: BoxDecoration(
                              //     border: Border.all(color: Colors.grey.shade300, width: 1.5),
                              //     borderRadius: BorderRadius.circular(18)
                              // ),
                              // color: Colors.white,
                              child: Column(
                                children: [
                                  // Container(
                                  //   padding: EdgeInsets.all(13),
                                  //   child: Row(
                                  //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  //     children: [
                                  //       Column(
                                  //         crossAxisAlignment: CrossAxisAlignment.start,
                                  //         children: [
                                  //           Text("Produk/Layanan", style: TextStyle(fontSize: 11.5, color: Colors.grey)),
                                  //           Text("${state.data![index].namaLayanan}", style: TextStyle(fontSize: 14, fontWeight: FontWeight.w700)),
                                  //         ],
                                  //       ),
                                  //       PopupMenuButton<String>(
                                  //         onSelected: (value) => doAction(context, value, state.data![index]),
                                  //         itemBuilder: (BuildContext context) {
                                  //           return ['Edit','Hapus'].map((String choice) {
                                  //             return PopupMenuItem<String>(
                                  //               value: choice,
                                  //               child: Text(choice),
                                  //             );
                                  //           }).toList();
                                  //         },
                                  //         child: Icon(
                                  //           Icons.more_vert_sharp,
                                  //           color: CustomStyle.fontColorGrey,
                                  //         ),
                                  //       ),
                                  //     ],
                                  //   ),
                                  // ),
                                  // SizedBox(height: 13),
                                  SizedBox(height: 7),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Text("${state.data![index].namaLayanan}", style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500)),
                                      // Expanded(child: Text("Absenku Andromeda Bimasakti Milkomeda Jaya Jaya Jaya", style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500))),
                                      PopupMenuButton<String>(
                                        onSelected: (value) => doAction(context, value, state.data![index]),
                                        itemBuilder: (BuildContext context) {
                                          return ['Edit','Hapus'].map((String choice) {
                                            return PopupMenuItem<String>(
                                              value: choice,
                                              child: Text(choice),
                                            );
                                          }).toList();
                                        },
                                        child: Icon(
                                          Icons.more_vert_sharp,
                                          color: CustomStyle.fontColorGrey,
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(height: 13),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Text("Rp ${state.data![index].harga} x ${state.data![index].jumlah}", style: TextStyle(fontSize: 12)),
                                      Text("Rp ${state.data![index].jumlahHarga}", style: TextStyle(fontSize: 12)),
                                    ],
                                  ),
                                  state.data![index].diskon == "0.00" ? Container() :
                                  Column(
                                    children: [
                                      SizedBox(height: 5),
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text("      Diskon : ${state.data![index].diskon}%", style: TextStyle(fontSize: 12)),
                                          Text("Rp ${state.data![index].jumlahDiskon}", style: TextStyle(fontSize: 12)),
                                        ],
                                      ),
                                    ],
                                  ),
                                  // SizedBox(height: 5),
                                  Container(height: 17, ),
                                  state.data!.length-1 == index ? Container():
                                  Divider(color: Colors.grey, height: 1),
                                  // Container(
                                  //   padding: EdgeInsets.all(13),
                                  //   child: Row(
                                  //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  //     children: [
                                  //       Text("Nominal", style: TextStyle(fontSize: 12, color: Colors.grey.shade600)),
                                  //       Text("${state.data![index].harga}", style: TextStyle(fontSize: 12)),
                                  //     ],
                                  //   ),
                                  // ),
                                  // Container(
                                  //   padding: EdgeInsets.fromLTRB(13, 0, 13, 13),
                                  //   child: Row(
                                  //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  //     children: [
                                  //       Text("Jumlah", style: TextStyle(fontSize: 12, color: Colors.grey.shade600)),
                                  //       Text("${state.data![index].jumlah}", style: TextStyle(fontSize: 12)),
                                  //     ],
                                  //   ),
                                  // ),
                                  // Container(
                                  //   padding: EdgeInsets.fromLTRB(13, 0, 13, 13),
                                  //   child: Row(
                                  //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  //     children: [
                                  //       Text("Diskon", style: TextStyle(fontSize: 12, color: Colors.grey.shade600)),
                                  //       Text("${state.data![index].diskon}%", style: TextStyle(fontSize: 12)),
                                  //     ],
                                  //   ),
                                  // ),
                                  // Container(
                                  //   padding: EdgeInsets.fromLTRB(13, 0, 13, 13),
                                  //   child: Row(
                                  //     mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  //     children: [
                                  //       Text("Total Harga", style: TextStyle(fontSize: 12, color: Colors.grey.shade600)),
                                  //       Text("${state.data![index].hargaTotal}", style: TextStyle(fontSize: 12)),
                                  //     ],
                                  //   ),
                                  // ),
                                ],
                              ),
                            );
                          }),
                    )
                  ],
                ));
          }else if (state is LayananDraftProgressState)
            return Container(
              height: MediaQuery.of(context).size.height/1.5,
              child: Center(
                child: CircularProgressIndicator(
                  strokeWidth: 8,
                ),
              ),
            );
          else{
            widget.dataCallback!([]);
            return Container(
                height: MediaQuery.of(context).size.height/1.5,
                child: Container(
                  margin: EdgeInsets.symmetric(vertical: 13, horizontal: 7),
                  child: Stack(
                    children: [
                      Column(
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(horizontal: 23),
                            padding: EdgeInsets.only(bottom: 13),
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text('${state.totalLayanan??"0"} Layanan', style: TextStyle(color: Colors.grey.shade600)),
                                    SizedBox(height: 3),
                                    Text('${state.totalHarga??"Rp 0"}', style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: CustomStyle.color1)),
                                  ],
                                ),
                                TemplateButton(
                                  onClick: () {
                                    jenisProduct = DataProduct();
                                    nominal.clear();
                                    jmlProduk.clear();
                                    diskon.clear();
                                    totalHarga.clear();
                                    totalHarga.text = "-";

                                    showDialogAddLayanan(context);
                                  },
                                  label: "Tambah Produk",
                                  color: CustomStyle.color1,
                                  heightButton: 31,
                                  radius: CustomStyle.boxRadius + 4,
                                  bold: true,
                                  icon: Icons.add_circle_outline_outlined,
                                  fontSize: CustomStyle.fontSizeSmall - 1,
                                  iconSize: 21,
                                  paddingTopBottom: 0,
                                )
                              ],
                            ),
                          ),
                          Divider(color: Colors.grey.shade300,thickness: 2, height: 2),
                        ],
                      ),

                      Container(
                        margin: EdgeInsets.only(top: 51),
                        child: Center(
                          child: Image.asset(
                            ValueImage.noData,
                            height: 250,
                          ),
                        ),
                      ),
                    ],
                  ),
                ));
          }
        }
    );
  }

  void showDialogAddLayanan(BuildContext context){
    double _nominal = 0;
    double _totalHarga = 0;
    double _diskon = 0;

    showModalBottomSheet(
        context: context,
        showDragHandle: true,
        isDismissible: false,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18)
        ),
        builder: (BuildContext _context){
          return Scaffold(
            body: WillPopScope(
              onWillPop: keluar,
              child: StatefulBuilder(
                  builder: (BuildContext con, StateSetter setState) {
                    return Stack(
                      children: [
                        SingleChildScrollView(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [
                              Container(
                                margin: EdgeInsets.fromLTRB(27, 0, 27, 0),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    Text("Tambah Produk/Layanan", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14),),
                                    GestureDetector(
                                        onTap: ()=> Navigator.pop(context),
                                        child: Icon(Icons.close, size: 21))
                                  ],
                                ),
                              ),
                              SizedBox(height: 7),
                              Divider(thickness: 1, color: Colors.grey.shade400),
                              BlocListener<DropdownProdukLayananBloc, DropdownProdukLayananState>(
                                listener: (BuildContext context, DropdownProdukLayananState state) {
                                  if (state is DropdownProdukLayananSuccessState && state.selectedValue != null) {
                                    setState(() {
                                      jenisProduct = state.selectedValue!;
                                      _nominal = double.parse(jenisProduct.harga.toString());
                                      nominal.text = _nominal.toString().split(".")[0];

                                      if(jmlProduk.text.trim().isEmpty){
                                        jmlProduk.text = '1';
                                      }

                                      if(nominal.text.replaceAll(RegExp('[^0-9]'), '').isNotEmpty && jmlProduk.text.trim().isNotEmpty){
                                        _totalHarga = (_nominal * double.parse(jmlProduk.text));
                                        totalHarga.text = _totalHarga.toString().split(".")[0];

                                        if(diskon.text.trim().isNotEmpty){
                                          _diskon = double.parse(diskon.text);
                                          double diskonHarga = (_diskon * (_nominal * double.parse(jmlProduk.text)) / 100);
                                          _totalHarga = ((_nominal * double.parse(jmlProduk.text)) - diskonHarga);
                                          totalHarga.text = _totalHarga.toString().split(".")[0];
                                        }
                                      }
                                    });
                                  }
                                },
                                child: DropdownDataProduct(
                                  'Pilih Produk/Layanan',
                                  initialData: jenisProduct.nama==null?null:jenisProduct.nama,
                                  color: Colors.grey[600],
                                  marginHorizontal: 27,
                                ),
                              ),
                              TemplateTextFormAkun(
                                adaValidasi: true,
                                controller: nominal,
                                enabled: jenisProduct.nama==null?false:true,
                                flagColorBackground: true,
                                color: Colors.black,
                                marginHorizontal: 27,
                                keyboardNumber: true,
                                fontSize: 13,
                                titleText: 'Nominal',
                                radius: CustomStyle.formRadius,
                                onChange: (val){
                                  if(val!.replaceAll(RegExp('[^0-9]'), '').isNotEmpty && jmlProduk.text.trim().isNotEmpty){
                                    _nominal = double.parse(val.replaceAll(RegExp('[^0-9]'), ''));
                                    _totalHarga = (_nominal * double.parse(jmlProduk.text));
                                    totalHarga.text = _totalHarga.toString().split(".")[0];

                                    if(diskon.text.trim().isNotEmpty){
                                      double diskonHarga = ((_diskon * (_nominal * double.parse(jmlProduk.text))) / 100);
                                      _totalHarga = ((_nominal * double.parse(jmlProduk.text)) - diskonHarga);
                                      totalHarga.text = _totalHarga.toString().split(".")[0];
                                    }
                                  }
                                },
                              ),
                              TemplateTextFormAkun(
                                adaValidasi: true,
                                controller: jmlProduk,
                                color: Colors.black,
                                marginHorizontal: 27,
                                keyboardNumber: true,
                                fontSize: 13,
                                enabled: (jenisProduct.nama == null || nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty) ? false: true,
                                flagColorBackground: true,
                                titleText: 'Jumlah Produk',
                                radius: CustomStyle.formRadius,
                                onChange: (val){
                                  if(nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isNotEmpty && jmlProduk.text.trim().isNotEmpty){
                                    _totalHarga = (double.parse(val.toString()) * _nominal);
                                    totalHarga.text = _totalHarga.toString().split(".")[0];

                                    if(diskon.text.trim().isNotEmpty){
                                      double diskonHarga = ((double.parse(diskon.text) * _totalHarga) / 100);
                                      _totalHarga = ((double.parse(val.toString()) * _nominal) - diskonHarga);
                                      totalHarga.text = _totalHarga.toString().split(".")[0];
                                    }
                                  }
                                },
                              ),
                              TemplateTextFormAkun(
                                adaValidasi: false,
                                controller: diskon,
                                color: Colors.black,
                                marginHorizontal: 27,
                                keyboardNumber: true,
                                enabled: (jenisProduct.nama == null || nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty) ? false: true,
                                fontSize: 13,
                                titleText: 'Diskon (%)',
                                flagColorBackground: true,
                                radius: CustomStyle.formRadius,
                                onChange: (val){
                                  if(diskon.text.trim().isEmpty){
                                    _diskon = 0;
                                  }else{
                                    _diskon = double.parse(diskon.text);
                                  }
                                  if(diskon.text.length > 5){
                                    diskon.text = diskon.text.substring(0,diskon.text.length-1);
                                    _diskon = double.parse(diskon.text);
                                  }
                                  if(_diskon > 100.0){
                                    diskon.text = diskon.text.substring(0,diskon.text.length-1);
                                    _diskon = double.parse(diskon.text);
                                  }
                                  // if(diskon.text.trim().isNotEmpty && jmlProduk.text.trim().isNotEmpty && nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isNotEmpty){
                                    double diskonHarga = ((_diskon * _nominal * double.parse(jmlProduk.text)) / 100);
                                    _totalHarga = ((double.parse(jmlProduk.text) * _nominal) - diskonHarga);
                                    totalHarga.text = _totalHarga.toString().split(".")[0];
                                  // }
                                },
                              ),
                              TemplateTextFormAkun(
                                  adaValidasi: false,
                                  controller: totalHarga,
                                  color: Colors.black,
                                  marginHorizontal: 27,
                                  keyboardNumber: true,
                                  flagColorBackground: true,
                                  enabled: false,
                                  fontSize: 13,
                                  titleText: 'Total Harga',
                                  radius: CustomStyle.formRadius
                              ),
                              Container(
                                padding: EdgeInsets.only(left: 22, right: 22, top: 7, bottom: 7),
                                decoration: BoxDecoration(
                                  boxShadow: [
                                    BoxShadow(
                                        color: Colors.grey.shade300,
                                        spreadRadius: 2
                                    ),
                                  ],
                                  color: Colors.white,
                                ),
                                height: 51,
                                width: MediaQuery.of(context).size.width,
                                child: TemplateButton(
                                  onClick: () async {
                                    if(jenisProduct.nama == null){
                                      showDialog(
                                          barrierDismissible: false,
                                          context: context,
                                          builder: (BuildContext context) =>
                                              AlertDialogCustom(
                                                  data: BasicRespon(
                                                      success: false,
                                                      message: 'Pilih Produk/Layanan Terlebih Dahulu'
                                                  ),
                                                  titleMessage: "PERINGATAN",
                                                  onClick: () {
                                                    Navigator.pop(context);
                                                  })
                                      );
                                    }else if(nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty){
                                      showDialog(
                                          barrierDismissible: false,
                                          context: context,
                                          builder: (BuildContext context) =>
                                              AlertDialogCustom(
                                                  data: BasicRespon(
                                                      success: false,
                                                      message: 'Nominal Harus Diisi Terlebih Dahulu'
                                                  ),
                                                  titleMessage: "PERINGATAN",
                                                  onClick: () {
                                                    Navigator.pop(context);
                                                  })
                                      );
                                    }else if(jmlProduk.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty){
                                      showDialog(
                                          barrierDismissible: false,
                                          context: context,
                                          builder: (BuildContext context) =>
                                              AlertDialogCustom(
                                                  data: BasicRespon(
                                                      success: false,
                                                      message: 'Jumlah Produk Harus Diisi Terlebih Dahulu'
                                                  ),
                                                  titleMessage: "PERINGATAN",
                                                  onClick: () {
                                                    Navigator.pop(context);
                                                  })
                                      );
                                    }else{
                                      jenisProduct = DataProduct(
                                          harga: int.parse(nominal.text.replaceAll(RegExp('[^0-9]'), '')),
                                          kode: jenisProduct.kode,
                                          nama: jenisProduct.nama,
                                          idProductM: jenisProduct.idProductM,
                                          idProductGroupM: jenisProduct.idProductGroupM,
                                          diskon: diskon.text.trim().isEmpty ? 0 : int.parse(diskon.text),
                                          jmlProduk: int.parse(jmlProduk.text),
                                          totalHarga: int.parse(totalHarga.text.replaceAll(RegExp('[^0-9]'), ''))
                                      );

                                      BlocProvider.of<LayananDraftBloc>(context)
                                          .add(addLayananDraftEvent(context, widget._scaffoldKey, jenisProduct));
                                    }
                                  },
                                  label: "SIMPAN",
                                  color: CustomStyle.color1,
                                  heightButton: 28,
                                  radius: CustomStyle.boxRadius + 4,
                                  bold: true,
                                  fontSize: CustomStyle.fontSizeSmall - 1,
                                  iconSize: 16,
                                  paddingTopBottom: 0,
                                ),
                              )
                            ],
                          ),
                        ),
                        // Positioned(
                        //     bottom: 0,
                        //     child: Container(
                        //       padding: EdgeInsets.only(left: 22, right: 22, top: 7, bottom: 7),
                        //       decoration: BoxDecoration(
                        //         boxShadow: [
                        //           BoxShadow(
                        //               color: Colors.grey.shade300,
                        //               spreadRadius: 2
                        //           ),
                        //         ],
                        //         color: Colors.white,
                        //       ),
                        //       height: 51,
                        //       width: MediaQuery.of(context).size.width,
                        //       child: TemplateButton(
                        //         onClick: () async {
                        //           if(jenisProduct.nama == null){
                        //             showDialog(
                        //                 barrierDismissible: false,
                        //                 context: context,
                        //                 builder: (BuildContext context) =>
                        //                     AlertDialogCustom(
                        //                 data: BasicRespon(
                        //                     success: false,
                        //                     message: 'Pilih Produk/Layanan Terlebih Dahulu'
                        //                 ),
                        //                 titleMessage: "PERINGATAN",
                        //                 onClick: () {
                        //                   Navigator.pop(context);
                        //                 })
                        //             );
                        //           }else if(nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty){
                        //             showDialog(
                        //                 barrierDismissible: false,
                        //                 context: context,
                        //                 builder: (BuildContext context) =>
                        //                     AlertDialogCustom(
                        //                         data: BasicRespon(
                        //                             success: false,
                        //                             message: 'Nominal Harus Diisi Terlebih Dahulu'
                        //                         ),
                        //                         titleMessage: "PERINGATAN",
                        //                         onClick: () {
                        //                           Navigator.pop(context);
                        //                         })
                        //             );
                        //           }else if(jmlProduk.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty){
                        //             showDialog(
                        //                 barrierDismissible: false,
                        //                 context: context,
                        //                 builder: (BuildContext context) =>
                        //                     AlertDialogCustom(
                        //                         data: BasicRespon(
                        //                             success: false,
                        //                             message: 'Jumlah Produk Harus Diisi Terlebih Dahulu'
                        //                         ),
                        //                         titleMessage: "PERINGATAN",
                        //                         onClick: () {
                        //                           Navigator.pop(context);
                        //                         })
                        //             );
                        //           }else{
                        //             jenisProduct = DataProduct(
                        //                 harga: int.parse(nominal.text.replaceAll(RegExp('[^0-9]'), '')),
                        //                 kode: jenisProduct.kode,
                        //                 nama: jenisProduct.nama,
                        //                 idProductM: jenisProduct.idProductM,
                        //                 idProductGroupM: jenisProduct.idProductGroupM,
                        //                 diskon: diskon.text.trim().isEmpty ? 0 : int.parse(diskon.text),
                        //                 jmlProduk: int.parse(jmlProduk.text),
                        //                 totalHarga: int.parse(totalHarga.text.replaceAll(RegExp('[^0-9]'), ''))
                        //             );
                        //
                        //             BlocProvider.of<LayananDraftBloc>(context)
                        //                 .add(addLayananDraftEvent(context, widget._scaffoldKey, jenisProduct));
                        //           }
                        //         },
                        //         label: "Tambah",
                        //         color: CustomStyle.color1,
                        //         heightButton: 28,
                        //         radius: CustomStyle.boxRadius + 4,
                        //         bold: true,
                        //         fontSize: CustomStyle.fontSizeSmall - 1,
                        //         iconSize: 16,
                        //         paddingTopBottom: 0,
                        //       ),
                        //     )
                        // )
                      ],
                    );
                  }
              ),
            ),
          );
        }
    );
  }

  void doAction(BuildContext context, String value, Layanan layanan) {
    if (value == 'Edit'){
      showDialogEditLayanan(context, layanan, "EDIT");
    }else{
      TemplateConfirmationDialog(
          "Apakah Anda yakin akan menghapus layanan ini?",
              () => BlocProvider.of<LayananDraftBloc>(context)
                  .add(deleteLayananDraftEvent(context, widget._scaffoldKey, layanan)),
          context);
    }
  }


  void showDialogEditLayanan(BuildContext context, Layanan layanan, String jenis){
    TextEditingController _nominal = MoneyMaskedTextController(thousandSeparator: '.', leftSymbol: 'Rp ', precision: 0, decimalSeparator: '');
    TextEditingController _totalHarga = MoneyMaskedTextController(thousandSeparator: '.', leftSymbol: 'Rp ', precision: 0, decimalSeparator: '');
    TextEditingController _jmlProduk = TextEditingController();
    TextEditingController _diskon = TextEditingController();
    DataProduct _jenisProduct = DataProduct();

    if(jenis == 'EDIT'){
      String dis = layanan.diskon!.replaceAll(".00", "");

      _nominal.text = layanan.harga!.replaceAll(",00", "");
      _jmlProduk.text = layanan.jumlah!.toString();
      if(dis != "0") {
        _diskon.text = layanan.diskon!.replaceAll(".00", "");
      }
      _totalHarga.text = layanan.hargaTotal.toString().replaceAll(",00", "");
      _jenisProduct = DataProduct(
        idProductM: layanan.idProductM,
        nama: layanan.namaLayanan,
        diskon: _diskon.text.trim().isEmpty?0:int.parse(_diskon.text),
        jmlProduk: int.parse(_jmlProduk.text),
        totalHarga: int.parse(_totalHarga.text.replaceAll(RegExp('[^0-9]'), '')),
        harga: int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), ''))
      );
    }

    showModalBottomSheet(
        context: context,
        showDragHandle: true,
        isDismissible: false,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18)
        ),
        builder: (BuildContext _context){
          return StatefulBuilder(
              builder: (BuildContext con, StateSetter setState) {
                return Stack(
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Container(
                          margin: EdgeInsets.fromLTRB(27, 0, 27, 0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("Tambah Produk/Layanan", style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14),),
                              GestureDetector(
                                  onTap: ()=> Navigator.pop(context),
                                  child: Icon(Icons.close, size: 21))
                            ],
                          ),
                        ),
                        SizedBox(height: 7),
                        Divider(thickness: 1, color: Colors.grey.shade400),
                        BlocListener<DropdownProdukLayananBloc, DropdownProdukLayananState>(
                          listener: (BuildContext context, DropdownProdukLayananState state) {
                            if (state is DropdownProdukLayananSuccessState && state.selectedValue != null) {
                              setState(() {
                                _jenisProduct = state.selectedValue!;
                                _nominal.text = _jenisProduct.harga.toString();
                                if(_nominal.text.replaceAll(RegExp('[^0-9]'), '').isNotEmpty && _jmlProduk.text.trim().isNotEmpty){
                                  _totalHarga.text = (int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), '')) * int.parse(_jmlProduk.text)).toString();

                                  if(_diskon.text.trim().isNotEmpty){
                                    String diskonHarga = ((int.parse(_diskon.text) * (int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), '')) * int.parse(_jmlProduk.text))) / 100).toString().split(".")[0];
                                    _totalHarga.text = ((int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), '')) * int.parse(_jmlProduk.text)) - int.parse(diskonHarga)).toString();
                                  }
                                }
                              });
                            }
                          },
                          child: DropdownDataProduct(
                            'Pilih Produk/Layanan',
                            initialData: _jenisProduct.nama==null?null:_jenisProduct.nama,
                            color: Colors.grey[600],
                            marginHorizontal: 27,
                          ),
                        ),
                        TemplateTextFormAkun(
                          adaValidasi: true,
                          controller: _nominal,
                          color: Colors.black,
                          marginHorizontal: 27,
                          keyboardNumber: true,
                          enabled: _jenisProduct.nama==null?false:true,
                          flagColorBackground: true,
                          fontSize: 13,
                          titleText: 'Nominal',
                          radius: CustomStyle.formRadius,
                          onChange: (val){
                            if(val!.replaceAll(RegExp('[^0-9]'), '').isNotEmpty && _jmlProduk.text.trim().isNotEmpty){
                              _totalHarga.text = (int.parse(val.replaceAll(RegExp('[^0-9]'), '')) * int.parse(_jmlProduk.text)).toString();

                              if(_diskon.text.trim().isNotEmpty){
                                String diskonHarga = ((int.parse(_diskon.text) * (int.parse(val.replaceAll(RegExp('[^0-9]'), '')) * int.parse(_jmlProduk.text))) / 100).toString().split(".")[0];
                                _totalHarga.text = ((int.parse(val.replaceAll(RegExp('[^0-9]'), '')) * int.parse(_jmlProduk.text)) - int.parse(diskonHarga)).toString();
                              }
                            }
                          },
                        ),
                        TemplateTextFormAkun(
                          adaValidasi: true,
                          controller: _jmlProduk,
                          color: Colors.black,
                          marginHorizontal: 27,
                          keyboardNumber: true,
                          fontSize: 13,
                          enabled: (_jenisProduct.nama == null || _nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty) ? false: true,
                          flagColorBackground: true,
                          titleText: 'Jumlah Produk',
                          radius: CustomStyle.formRadius,
                          onChange: (val){
                            if(_nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isNotEmpty && _jmlProduk.text.trim().isNotEmpty){
                              _totalHarga.text = (int.parse(val.toString()) * int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), ''))).toString();

                              if(_diskon.text.trim().isNotEmpty){
                                String diskonHarga = (int.parse(_diskon.text) * int.parse(_totalHarga.text.replaceAll(RegExp('[^0-9]'), '')) / 100).toString().split(".")[0];
                                _totalHarga.text = ((int.parse(val.toString()) * int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), ''))) - int.parse(diskonHarga)).toString();
                              }
                            }
                          },
                        ),
                        TemplateTextFormAkun(
                          adaValidasi: false,
                          controller: _diskon,
                          color: Colors.black,
                          marginHorizontal: 27,
                          keyboardNumber: true,
                          enabled: (_jenisProduct.nama == null || _nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty) ? false: true,
                          fontSize: 13,
                          titleText: 'Diskon (%)',
                          flagColorBackground: true,
                          radius: CustomStyle.formRadius,
                          onChange: (val){
                            double a = double.parse(_diskon.text);
                            if(_diskon.text.length > 5){
                              _diskon.text = _diskon.text.substring(0,_diskon.text.length-1);
                            }
                            if(a > 100.0){
                              _diskon.text = _diskon.text.substring(0,_diskon.text.length-1);
                            }
                            if(_diskon.text.trim().isNotEmpty && _jmlProduk.text.trim().isNotEmpty && _nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isNotEmpty){
                              String diskonHarga = ((int.parse(val.toString()) * int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), '') == "" ? "0" : _nominal.text.replaceAll(RegExp('[^0-9]'), '')) * int.parse(_jmlProduk.text)) / 100).toString().split(".")[0];
                              _totalHarga.text = ((int.parse(_jmlProduk.text) * int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), ''))) - int.parse(diskonHarga)).toString();
                            }
                          },
                        ),
                        TemplateTextFormAkun(
                            adaValidasi: false,
                            controller: _totalHarga,
                            color: Colors.black,
                            marginHorizontal: 27,
                            keyboardNumber: true,
                            flagColorBackground: true,
                            enabled: false,
                            fontSize: 13,
                            titleText: 'Total Harga',
                            radius: CustomStyle.formRadius
                        ),
                      ],
                    ),
                    Positioned(
                        bottom: 0,
                        child: Container(
                          padding: EdgeInsets.only(left: 22, right: 22, top: 7, bottom: 7),
                          decoration: BoxDecoration(
                            boxShadow: [
                              BoxShadow(
                                  color: Colors.grey.shade300,
                                  spreadRadius: 2
                              ),
                            ],
                            color: Colors.white,
                          ),
                          height: 51,
                          width: MediaQuery.of(context).size.width,
                          child: TemplateButton(
                            onClick: () async {
                              if(_jenisProduct.nama == null){
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext context) =>
                                        AlertDialogCustom(
                                            data: BasicRespon(
                                                success: false,
                                                message: 'Pilih Produk/Layanan Terlebih Dahulu'
                                            ),
                                            titleMessage: "PERINGATAN",
                                            onClick: () {
                                              Navigator.pop(context);
                                            })
                                );
                              }else if(_nominal.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty){
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext context) =>
                                        AlertDialogCustom(
                                            data: BasicRespon(
                                                success: false,
                                                message: 'Nominal Harus Diisi Terlebih Dahulu'
                                            ),
                                            titleMessage: "PERINGATAN",
                                            onClick: () {
                                              Navigator.pop(context);
                                            })
                                );
                              }else if(_jmlProduk.text.trim().replaceAll(RegExp('[^0-9]'), '').isEmpty){
                                showDialog(
                                    barrierDismissible: false,
                                    context: context,
                                    builder: (BuildContext context) =>
                                        AlertDialogCustom(
                                            data: BasicRespon(
                                                success: false,
                                                message: 'Jumlah Produk Harus Diisi Terlebih Dahulu'
                                            ),
                                            titleMessage: "PERINGATAN",
                                            onClick: () {
                                              Navigator.pop(context);
                                            })
                                );
                              }else{
                                _jenisProduct = DataProduct(
                                    harga: int.parse(_nominal.text.replaceAll(RegExp('[^0-9]'), '')),
                                    kode: _jenisProduct.kode,
                                    nama: _jenisProduct.nama,
                                    idProductM: _jenisProduct.idProductM,
                                    idProductGroupM: _jenisProduct.idProductGroupM,
                                    diskon: _diskon.text.trim().isEmpty ? 0 : int.parse(_diskon.text),
                                    jmlProduk: int.parse(_jmlProduk.text),
                                    totalHarga: int.parse(_totalHarga.text.replaceAll(RegExp('[^0-9]'), ''))
                                );

                                BlocProvider.of<LayananDraftBloc>(context)
                                    .add(editLayananDraftEvent(context, widget._scaffoldKey, _jenisProduct, layanan.idPipelineLayanan, layanan.idKaryawan, layanan.idCompany));
                              }
                            },
                            label: jenis == "EDIT" ? "SIMPAN" : "SIMPAN",
                            color: CustomStyle.color1,
                            heightButton: 28,
                            radius: CustomStyle.boxRadius + 4,
                            bold: true,
                            fontSize: CustomStyle.fontSizeSmall - 1,
                            iconSize: 16,
                            paddingTopBottom: 0,
                          ),
                        )
                    )
                  ],
                );
              }
          );
        }
    );
  }
}
