import 'dart:ffi';

import 'package:absenkuv3/Bloc/CustomFunction.dart';
import 'package:absenkuv3/Bloc/Dropdown/DropdownProdukLayananBloc.dart';
import 'package:absenkuv3/Bloc/SalesActivity/ApproverBloc.dart';
import 'package:absenkuv3/Bloc/SalesActivity/DataLayananDetailByIdBloc.dart';
import 'package:absenkuv3/Bloc/SalesActivity/KambanBloc.dart';
import 'package:absenkuv3/Bloc/SalesActivity/LayananDraftBloc.dart' as draft;
import 'package:absenkuv3/Repository/Model/SalesActivity/mDataKanban.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mDataLayanan.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mDataProduct.dart';
import 'package:absenkuv3/Repository/Model/SalesActivity/mMasterTahapan.dart';
import 'package:absenkuv3/Repository/Model/mFilter.dart';
import 'package:absenkuv3/Repository/Model/mSplashScreen.dart';
import 'package:absenkuv3/UI/Modul/Dropdown/DropdownDataProduct.dart';
import 'package:absenkuv3/UI/Modul/SalesActivity/cardLayananPage.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/templateDashLine.dart';
import 'package:absenkuv3/UI/Template/templateTextFieldForm.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';

class TemplateCRUDLayanan {

  Future showDialogEditLayanan(BuildContext context, GlobalKey<ScaffoldState> _scaffoldKey, String idPipelineMain, String idPipelineLayanan, Layanan data, String jenis, bool bottomSheet, String page){
    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();
    String refresh = "";

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

      nominal.text = data.harga!;
      jmlProduk.text = data.jumlah!;
      if(dis != "0") {
        diskon.text = data.diskon!.replaceAll(".00", "");
      }
      totalHarga.text = data.hargaTotal.toString().replaceAll(",00", "");
      jenisProduct = DataProduct(
        idProductM: data.idProductM,
        nama: data.namaLayanan,
        kode: data.kodeLayanan,
        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]'), '')),
      );
    }

    return showModalBottomSheet(
        context: context,
        showDragHandle: true,
        isDismissible: false,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18)
        ),
        builder: (BuildContext _context){
          return Container(
            // height: MediaQuery.of(context).size.height * 0.6,
            child: Stack(
              children: [
                Container(
                  margin: EdgeInsets.fromLTRB(27, 0, 27, 0),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text("Ubah 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),
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 35),
                  child: StatefulBuilder(
                      builder: (BuildContext con, StateSetter setState) {
                        return SingleChildScrollView(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: [


                              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
                              ),
                              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<draft.LayananDraftBloc>(context)
                                          .add(draft.editLayananEvent(context, _scaffoldKey, jenisProduct, idPipelineMain, idPipelineLayanan, bottomSheet, page));
                                      refresh = "refresh";
                                    }
                                  },
                                  label: jenis == "EDIT" ? "SIMPAN" : "SIMPAN",
                                  color: CustomStyle.color1,
                                  heightButton: 28,
                                  radius: CustomStyle.boxRadius + 4,
                                  bold: true,
                                  fontSize: CustomStyle.fontSizeSmall - 1,
                                  iconSize: 16,
                                  paddingTopBottom: 0,
                                ),
                              )
                            ],
                          ),
                        );
                      }
                  ),
                ),
              ],
            ),
          );
        }
    ).then((value) => refresh);
  }

  Future showDialogAddLayanan(BuildContext context, GlobalKey<ScaffoldState> _scaffoldKey, String idPipelineMain, String idTahapan){
    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();
    String refresh = "";

    double _nominal = 0;
    double _totalHarga = 0;
    double _diskon = 0;

    return 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 = 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,
                          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){
                              _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
                        ),
                      ],
                    ),
                    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<draft.LayananDraftBloc>(context)
                                    .add(draft.addLayananEvent(context, _scaffoldKey, jenisProduct, idPipelineMain, idTahapan));
                                refresh =  "refresh";
                                // refresh = ;
                              }
                            },
                            label: "SIMPAN",
                            color: CustomStyle.color1,
                            heightButton: 28,
                            radius: CustomStyle.boxRadius + 4,
                            bold: true,
                            fontSize: CustomStyle.fontSizeSmall - 1,
                            iconSize: 16,
                            paddingTopBottom: 0,
                          ),
                        )
                    )
                  ],
                );
              }
          );
        }
    ).then((value) => refresh);

    // return refresh;
  }

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

  Future showDialogPindahTahapan(BuildContext context, List<DataTahapan> dataTahapan, DataKanban _dataKanban, String idSelected, String selectedName, String color, String textColor, String page, String pageSelected){
    GlobalKey<ScaffoldState> __scaffoldKey = GlobalKey();
    GlobalKey<ScaffoldState> ___scaffoldKey = GlobalKey();
    DataTahapan? _selected;
    TextEditingController keterangan = TextEditingController();

    List valueRefresh = [];
    valueRefresh.add(false);
    valueRefresh.add("");

    return 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: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Container(
                              margin: EdgeInsets.fromLTRB(27, 0, 27, 0),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text("Pindah Tahapan", 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),
                            SizedBox(height: 7),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Container(
                                    margin: EdgeInsets.fromLTRB(27, 0, 27, 0),
                                    child: Text("Tahapan Sekarang", style: TextStyle(fontSize: 13, color: Colors.grey))),
                                Container(
                                    margin: EdgeInsets.fromLTRB(27, 0, 27, 0),
                                    padding: EdgeInsets.fromLTRB(17, 7, 17, 7),
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(9),
                                      color: Color(int.parse(color)),
                                    ),
                                    child: Text(selectedName, style: TextStyle(fontSize: 14, color: Color(int.parse(textColor))))),
                              ],
                            ),
                            // SizedBox(height: 3),

                            SizedBox(height: 3),
                            Divider(thickness: 1),
                            Container(
                                margin: EdgeInsets.fromLTRB(27, 0, 27, 0),
                                child: Text("Pindah Ke", style: TextStyle(fontSize: 13, color: Colors.grey))),
                            SizedBox(height: 3),
                            Expanded(
                              child: Container(
                                margin: EdgeInsets.only(bottom: 60, top: 7),
                                child: ListView.builder(
                                    itemCount: dataTahapan.length,
                                    // physics: NeverScrollableScrollPhysics(),
                                    shrinkWrap: true,
                                    itemBuilder: (context, index){
                                      return Container(
                                        margin: EdgeInsets.fromLTRB(27, 0, 27, 3),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                          children: [
                                            Text(dataTahapan[index].nama!),
                                            dataTahapan[index].id == idSelected
                                                ? Container(
                                              width: 19,
                                              height: 19,
                                              margin: EdgeInsets.only(right: 14, bottom: 9, top: 9),
                                              decoration: BoxDecoration(
                                                shape: BoxShape.circle,
                                                border: Border.all(color: Colors.grey.shade600),
                                                color: Colors.grey.shade400,
                                              ),
                                            )
                                                : Radio<DataTahapan>(
                                              visualDensity: VisualDensity(vertical: -3),
                                              value: dataTahapan[index],
                                              onChanged: (DataTahapan? value) {
                                                setState(() {
                                                  _selected = value;
                                                });
                                              },
                                              groupValue: _selected,
                                            ),
                                          ],
                                        ),
                                      );
                                    }
                                ),
                              ),
                            )
                          ],
                        ),
                        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(_selected == null){
                                    showSnackBarDelayed(__scaffoldKey, "Pilih tujuan tahapan terlebih dahulu", context, backgroundColor: Colors.red, textColor: Colors.white);
                                  }else if(_selected!.id == idSelected){
                                    showSnackBarDelayed(__scaffoldKey, "Tahapan sekarang sama dengan tahapan tujuan", context, backgroundColor: Colors.red, textColor: Colors.white);
                                  }else{
                                    if(_selected!.jenis == 'wont'){
                                      showDialogUbahTahapanWont(
                                          context,
                                          ___scaffoldKey,
                                          _dataKanban,
                                          _selected,
                                          idSelected,
                                          selectedName,
                                          page,
                                          pageSelected,
                                          valueRefresh);
                                    }
                                    else if(_selected!.jenis == 'lost'){
                                      showModalBottomSheet(
                                          context: context,
                                          showDragHandle: true,
                                          isDismissible: false,
                                          shape: RoundedRectangleBorder(
                                              borderRadius: BorderRadius.circular(18)
                                          ),
                                          builder: (_context){
                                            return Scaffold(
                                              body: Container(
                                                height: double.infinity,
                                                margin: EdgeInsets.fromLTRB(9,0,9,13),
                                                child: SingleChildScrollView(
                                                  child: Column(
                                                    children: [
                                                      TemplateTextFieldForm(
                                                        adaValidasi: true,
                                                        controller: keterangan,
                                                        color: Colors.grey[600],
                                                        maxLine: 5,
                                                        minLine: 5,
                                                        titleText: "Keterangan",
                                                        radius: CustomStyle.formRadius,
                                                        hintText: "Keterangan",
                                                      ),
                                                      Container(
                                                        margin: EdgeInsets.only(top: 197),
                                                        child: TemplateButton(
                                                          expand: true,
                                                          onClick: (){
                                                            if(keterangan.text.trim().isEmpty){
                                                              showSnackBarDelayed(__scaffoldKey, "Keterangan wajib diisi", _context, backgroundColor: Colors.red, textColor: Colors.white);
                                                            }else{
                                                              TemplateConfirmationDialog(
                                                                  "Apakah Anda yakin akan mengubah tahapan ini ke ${_selected!.nama}?",
                                                                      () {
                                                                    BlocProvider.of<KambanBloc>(context)
                                                                        .add(ubahTahapanKambanEvent(context, _dataKanban, idSelected, _dataKanban.statusPengajuan!.value, idSelected, selectedName, _selected!.id, _selected!.nama, page=='detail'?true:false, pageSelected, "", keterangan.text));
                                                                    valueRefresh[1] = "refresh";
                                                                  },
                                                                  context);
                                                            }
                                                          },
                                                          label: 'SUBMIT',
                                                        ),
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            );
                                          }
                                      );
                                    }
                                    else{
                                      TemplateConfirmationDialog(
                                          "Apakah Anda yakin akan mengubah tahapan ke ${_selected!.nama}?",
                                              () {
                                            BlocProvider.of<KambanBloc>(
                                                context)
                                                .add(ubahTahapanKambanEvent(
                                                context,
                                                _dataKanban,
                                                idSelected,
                                                _dataKanban.statusPengajuan!.value,
                                                idSelected,
                                                selectedName,
                                                _selected!.id,
                                                _selected!.nama,
                                                page == 'detail'?true:false, pageSelected, "", ""));
                                            valueRefresh[1] = "refresh";
                                          },
                                          context);
                                    }
                                  }

                                },
                                label: "SUBMIT",
                                color: CustomStyle.color1,
                                heightButton: 28,
                                radius: CustomStyle.boxRadius + 4,
                                bold: true,
                                fontSize: CustomStyle.fontSizeSmall - 1,
                                iconSize: 16,
                                paddingTopBottom: 0,
                              ),
                            )
                        )
                      ],
                    );
                  }
              ),
            ),
          );
        }
    ).then((value) => valueRefresh);
  }

  Future showDialogUbahTahapanWont(BuildContext context, GlobalKey<ScaffoldState> scaffoldKey, DataKanban _dataKanban, DataTahapan? _selected, String idSelected, String selectedName, String page, String pageSelected, List valueRefresh){
    TextEditingController keterangan = TextEditingController();
    BlocProvider.of<DataLayananDetailByIdBloc>(context).add(getDataLayananDetailByIdEvent(context, _dataKanban.idPipelineMain));
    return showModalBottomSheet(
        context: context,
        showDragHandle: true,
        isDismissible: false,
        isScrollControlled: true,
        backgroundColor: Colors.white,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18)
        ),
        builder: (BuildContext _context){
          return Container(
            height: MediaQuery.of(context).size.height/1.2,
            child: Scaffold(
              body: Container(
                child:  BlocBuilder<DataLayananDetailByIdBloc, DataLayananDetailByIdState>(
                    builder: (BuildContext con, stateLayananById) {
                      if(stateLayananById is getDataLayananDetailByIdSuccessState){
                        return Container(
                          child: Container(
                            height: double.infinity,
                            margin: EdgeInsets.fromLTRB(9,0,9,13),
                            child: SingleChildScrollView(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    margin: EdgeInsets.symmetric(horizontal: 23),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                      children: [
                                        Text('Produk/Layanan', style: TextStyle(
                                            fontWeight: FontWeight.w500,
                                            fontSize: 15
                                        )),
                                        GestureDetector(
                                            onTap: ()=> Navigator.pop(context),
                                            child: Icon(Icons.close, size: 21))
                                      ],
                                    ),
                                  ),
                                  SizedBox(height: 7),
                                  Divider(thickness: 1),
                                  Scrollbar(
                                    showTrackOnHover: true,
                                    interactive: true,
                                    child: Container(
                                      height: stateLayananById.dataLayananDetail!.length == 1
                                          ? 60
                                          : stateLayananById.dataLayananDetail!.length == 2
                                          ? 135
                                          : 220,
                                      margin: EdgeInsets.symmetric(horizontal: 23),
                                      color: Colors.grey.shade200,
                                      child: ListView.builder(
                                          itemCount: stateLayananById.dataLayananDetail!.length,
                                          shrinkWrap: true,
                                          key: scaffoldKey,
                                          // physics: NeverScrollableScrollPhysics(),
                                          itemBuilder: (context, ind){
                                            return Column(
                                              children: [
                                                CardLayananPage(
                                                    _dataKanban,
                                                    stateLayananById.dataLayananDetail![ind],
                                                    scaffoldKey,
                                                    true,
                                                    page,
                                                    true,
                                                    marginHorizontal: 0,
                                                    dataCallback: (val){
                                                      valueRefresh[0] = val[0];
                                                      valueRefresh[1] = val[1];
                                                      // if(val[0] == 'refresh'){
                                                      //   valueRefresh[0] = true;
                                                      // }
                                                    }),
                                                ind == stateLayananById.dataLayananDetail!.length-1
                                                    ? Container(height: 3, color: Colors.white)
                                                    : Container(
                                                    color: Colors.white,
                                                    child: Divider(thickness: 1))
                                              ],
                                            );
                                          }
                                      ),
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(top: 7),
                                    child: Container(
                                        margin: EdgeInsets.symmetric(horizontal: 23),
                                        child: Column(
                                          children: [
                                            TemplateDashLine(color: Colors.grey.shade400),
                                            Container(
                                              margin: EdgeInsets.only(top: 14),
                                              child: Row(
                                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                children: [
                                                  Text("Total Item ", style: TextStyle(fontSize: 12)),
                                                  Text("Rp ${stateLayananById.totalDataLayananDetail!.totalItem}", style: TextStyle(fontSize: 12)),
                                                  // Text("Rp ${_dataLayananDetail[ind].totalItem}", style: TextStyle(fontSize: 12)),
                                                ],
                                              ),
                                            ),
                                            Container(
                                              margin: EdgeInsets.only(top: 5),
                                              child: Row(
                                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                children: [
                                                  Text("Total Diskon ", style: TextStyle(fontSize: 12)),
                                                  Text("Rp ${stateLayananById.totalDataLayananDetail!.totalDiskon}", style: TextStyle(fontSize: 12)),
                                                  // Text("( Rp ${dataTotal!.totalDiskon} )", style: TextStyle(fontSize: 12)),
                                                ],
                                              ),
                                            ),
                                            Container(
                                              margin: EdgeInsets.only(top: 5),
                                              child: Row(
                                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                children: [
                                                  Text("Total Harga ", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700)),
                                                  Text("Rp ${stateLayananById.totalDataLayananDetail!.totalHarga}", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700)),
                                                  // Text("Rp ${_dataLayananDetail[ind].totalHarga}", style: TextStyle(fontSize: 12, fontWeight: FontWeight.w700)),
                                                ],
                                              ),
                                            ),
                                          ],
                                        )),
                                  ),
                                  SizedBox(height: 27),
                                  Container(
                                    margin: EdgeInsets.symmetric(horizontal: 23),
                                    child: TemplateTextFieldForm(
                                      adaValidasi: true,
                                      controller: keterangan,
                                      color: Colors.grey[600],
                                      maxLine: 5,
                                      minLine: 5,
                                      titleText: "Keterangan",
                                      radius: CustomStyle.formRadius,
                                      hintText: "Keterangan",
                                    ),
                                  ),
                                  Container(
                                    margin: EdgeInsets.only(
                                        top: stateLayananById.dataLayananDetail!.length == 1
                                            ? 265
                                            : stateLayananById.dataLayananDetail!.length == 2
                                            ? 197
                                            : 110),
                                    child: TemplateButton(
                                      expand: true,
                                      onClick: (){
                                        if(keterangan.text.trim().isEmpty){
                                          showSnackBarDelayed(scaffoldKey, "Keterangan wajib diisi", context, backgroundColor: Colors.red, textColor: Colors.white);
                                        }else{
                                          TemplateConfirmationDialog(
                                              "Apakah Anda yakin akan mengubah tahapan ini ke ${_selected!.nama}?",
                                                  () {
                                                BlocProvider.of<KambanBloc>(context)
                                                    .add(ubahTahapanKambanEvent(context, _dataKanban, idSelected, _dataKanban.statusPengajuan!.value, idSelected, selectedName, _selected!.id, _selected!.nama, page=='detail'?true:false, pageSelected, keterangan.text, ""));
                                                valueRefresh[1] = "refresh";
                                              },
                                              context);
                                        }
                                      },
                                      label: 'SUBMIT',
                                    ),
                                  )
                                ],
                              ),
                            ),
                          ),
                        );
                      }else{
                        return Center(child: CircularProgressIndicator(strokeWidth: 8));
                      }
                    }
                ),
              ),
            ),
          );
        }
    ).then((value) => valueRefresh);
  }

  // Future showDialogApproval(BuildContext context, List<DataTahapan> dataTahapan, DataKanban _dataKanban, String idSelected, String selectedName, String color, String textColor, String page, String pageSelected){
  Future showDialogApproval(BuildContext context, DataKanban _dataKanban, String idSelected, String jenisTahapan, String pageSelected){

    List valueRefresh = [];
    valueRefresh.add(false);
    valueRefresh.add("");

    return showModalBottomSheet(
        context: context,
        showDragHandle: true,
        isDismissible: false,
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(18)
        ),
        builder: (BuildContext _context){
          return Container(
            height: MediaQuery.of(context).size.height/8,
            // color: Colors.grey,
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 22, right: 5, top: 7, bottom: 7),
                    height: 51,
                    width: MediaQuery.of(context).size.width,
                    child: TemplateButton(
                      onClick: () async {
                        TemplateConfirmationDialog(
                            "Apakah Anda yakin akan menolak kanban ini?",
                                () {
                                  BlocProvider.of<ApproverBloc>(context)
                                      .add(TolakKanbanEvent(context, pageSelected, _dataKanban, _dataKanban.idPipelineMain!, _dataKanban.idPipelineMainLog!, idSelected, jenisTahapan, ModelFilter(), 'detail'));
                                  valueRefresh[1] = "refresh";
                            },
                            context);
                      },
                      label: "Tolak",
                      color: Colors.red,
                      heightButton: 28,
                      radius: CustomStyle.boxRadius + 4,
                      bold: true,
                      fontSize: CustomStyle.fontSizeSmall - 1,
                      iconSize: 16,
                      paddingTopBottom: 0,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    padding: EdgeInsets.only(left: 5, right: 22, top: 7, bottom: 7),
                    height: 51,
                    width: MediaQuery.of(context).size.width,
                    child: TemplateButton(
                      onClick: () async {
                        TemplateConfirmationDialog(
                            "Apakah Anda yakin akan menolak kanban ini?",
                                () {
                                  BlocProvider.of<ApproverBloc>(context)
                                      .add(SetujuiKanbanEvent(context, _dataKanban, _dataKanban.idPipelineMain!, _dataKanban.idPipelineMainLog!, idSelected, ModelFilter(monthYear: DateTime(int.parse(_dataKanban.tglInput!.split("-")[2]), int.parse(_dataKanban.tglInput!.split("-")[1]))), 'detail'));
                              valueRefresh[1] = "refresh";
                            },
                            context);
                      },
                      label: "Setujui",
                      color: CustomStyle.color1,
                      heightButton: 28,
                      radius: CustomStyle.boxRadius + 4,
                      bold: true,
                      fontSize: CustomStyle.fontSizeSmall - 1,
                      iconSize: 16,
                      paddingTopBottom: 0,
                    ),
                  ),
                ),
              ],
            ),
          );
        }
    ).then((value) => valueRefresh);
  }
}
