import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'Util/UnitModel.dart';
import 'Util/photo_viewer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'Util/DBHelper.dart';
import 'Util/Util.dart';
import 'main.dart';
import 'package:intl/intl.dart';
//import 'package:autocomplete_textfield/autocomplete_textfield.dart';

class UnitDetails extends StatefulWidget {
  Unit unit;
  UnitDetails({this.unit});
  @override
  _UnitDetailsState createState() => _UnitDetailsState();
}

class _UnitDetailsState extends State<UnitDetails> {
  final tipeController = TextEditingController();
  final rangkaController = TextEditingController();
  final colorController = TextEditingController();
  final kodeController = TextEditingController();
  final mesinController = TextEditingController();
  final tahunController = TextEditingController();
  final stateController = TextEditingController();

//  insertUnit _unitDetails;
  bool isChanged = false;
  Util util = new Util();
  List<Uint8List> images = [];
  List<int> blobIds = [];
  List<int> deleteBlobIds = [];
  List<jenisDrop> dropMenu = [];
  List<String> jenisImages = [];
  int jenisLength=0;
  Unit _currentUnit;
  List<blobImage> blobList = [];
//  List<Unit> allUnits = [];

  loadUnitDetails(context)async{
//    if(widget.idInsert!=null){
////      var result = await DBHelper.database.getInsertUnit(widget.idInsert);
////      if(result!=null){
////        _unitDetails = result;
////        mesinController.text = _unitDetails.mesin;
////        tipeController.text= _unitDetails.tipe;
////        rangkaController.text = _unitDetails.rangka;
////        colorController.text = _unitDetails.warna;
////        tahunController.text = _unitDetails.tahun;
////        kodeController.text = _unitDetails.kode;
////        stateController.text = _unitDetails.state;
////
////        result = await DBHelper.database.getAllBlobImage(_unitDetails.id);
////        if(result!=null){
////          for(int i =0; i<result.length;i++){
////            images.add(result[i].blob_file);
////            blobIds.add(result[i].blob_id);
////            jenisImages.add(result[i].jenis);
////          }
////        }
////        setState(() {
////        });
////      }
////      else{
////        util.showFlushbar(context, 'Unit can\'t be found');
////      }
//      await DBHelper.database.closeDb();
//    }
//    else{
//      var result = await DBHelper.database.getUnitdetailMaster(widget.idRef);
//      if (result!=null){
        _currentUnit = widget.unit;
        tipeController.text= _currentUnit.tipe;
        rangkaController.text = _currentUnit.rangka;
        colorController.text = _currentUnit.warna;
        kodeController.text = _currentUnit.kode;
        mesinController.text = _currentUnit.mesin;
        tahunController.text = _currentUnit.tahun;
        stateController.text = _currentUnit.state;
//      }
//    }
    await loadBlob();
  }
//  loadTipe() async{
//    allUnits.clear();
//    allUnits = await DBHelper.database.getAllUnits();
//  }
  loadBlob()async{
    var result = await DBHelper.database.getBlobUnits(mesinController.text);
    if(result!=null){
      setState(() {
          blobList = result;
      });
//      for(int i =0; i<result.length;i++){
//        images.add(result[i].blob_file);
//        blobIds.add(result[i].blob_id);
//        jenisImages.add(result[i].jenis);
//      }
//      dropMenu = result;
//      jenisLength = result.length;
//      if(jenisImages.length!=0){
//        for (int i =0;i<jenisImages.length;i++){
//          dropMenu.removeWhere((element) => element.value==jenisImages[i]);
//        }
//      }
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      util.showLoading(context);
      await Future.sync(()async{await loadUnitDetails(context);});
      Navigator.pop(context);
    });
  }
  @override
  Widget build(BuildContext context) {
//    if(allUnits.length!=0){
//      print(allUnits[0].tipe);
////      loadTipe();
//    }
    return Scaffold(
      resizeToAvoidBottomPadding: true,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0.0,
        iconTheme: IconThemeData(
          color: Colors.indigo,
        ),
        title: Text((widget.unit.flag=='FALSE')?'Inserting New Unit':'Editing Unit',style: TextStyle(color: Colors.indigo),),
      ),
      body: WillPopScope(
        onWillPop: ()async{
          if(widget.unit.flag=='TRUE'){
            if(isChanged){
              await showDialog(context: context,builder: (context)=>
                  Material(
                    color: Colors.white.withOpacity(0.9),
                    child: Center(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                            borderRadius: BorderRadius.circular(5)
                        ),
                        height: MediaQuery.of(context).size.height/4.8,
                        width: MediaQuery.of(context).size.width*0.75,
                        child: Column(
                          children: <Widget>[
                            Flexible(
                              flex:3,
                              child: Container(
                                padding: EdgeInsets.only(top:10,left: 10,right: 10),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
//                          color: Colors.indigo,
                                    borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                                ),
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(Icons.warning,size: 70,color: Colors.indigo,),
                                  ],
                                ),
                              ),
                            ),
                            Flexible(
                              flex: 1,
                              child: Container(
                                  padding: EdgeInsets.only(left: 20,right: 20),
                                  alignment: Alignment.centerLeft,
                                  child: Text('Data belum disimpan. Lanjutkan ?',style: TextStyle(fontWeight: FontWeight.w500,fontSize: 14,color: Colors.black.withOpacity(0.6)),)
                              ),
                            ),
                            Flexible(
                              flex: 1,
                              child: Container(
                                padding: EdgeInsets.only(bottom:10),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: <Widget>[
                                    FlatButton(
                                      child: Text('Proceed'),
//                  color: Colors.red,
                                      onPressed: (){
                                        Navigator.pop(context);
                                        Navigator.pop(context);
                                      },
                                    ),
                                    FlatButton(
                                      child: Text('Cancel'),
//                  color: Colors.grey,
                                      onPressed: (){
                                        Navigator.pop(context);
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
              );
            }
            else Navigator.pop(context);
          }
          else{
            bool not_empty = (stateController.text!='-'&&mesinController.text!='-'&&tahunController.text!='-'&&kodeController.text!='-'&&colorController.text!='-'&&rangkaController.text!='-'&&tipeController.text!='-');
            if(blobList.where((element) => element.blob_file!=null).length!=0){
              await showDialog(context: context,builder: (context)=>
                  Material(
                    color: Colors.white.withOpacity(0.9),
                    child: Center(
                      child: Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                            borderRadius: BorderRadius.circular(5)
                        ),
                        height: MediaQuery.of(context).size.height/4.8,
                        width: MediaQuery.of(context).size.width*0.75,
                        child: Column(
                          children: <Widget>[
                            Flexible(
                              flex:3,
                              child: Container(
                                padding: EdgeInsets.only(top:10,left: 10,right: 10),
                                alignment: Alignment.center,
                                decoration: BoxDecoration(
//                          color: Colors.indigo,
                                    borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                                ),
                                child: Column(
                                  mainAxisSize: MainAxisSize.min,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(Icons.warning,size: 70,color: Colors.indigo,),
                                  ],
                                ),
                              ),
                            ),
                            Flexible(
                              flex: 1,
                              child: Container(
                                  padding: EdgeInsets.only(left: 20,right: 20),
                                  alignment: Alignment.centerLeft,
                                  child: Text('Data belum disimpan. Lanjutkan ?',style: TextStyle(fontWeight: FontWeight.w500,fontSize: 14,color: Colors.black.withOpacity(0.6)),)
                              ),
                            ),
                            Flexible(
                              flex: 1,
                              child: Container(
                                padding: EdgeInsets.only(bottom:10),
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: <Widget>[
                                    FlatButton(
                                      child: Text('Back',style: TextStyle(color: Colors.indigo),),
                                      onPressed: (){
                                        Navigator.pop(context);
                                        Navigator.pop(context);
                                      },
                                    ),
                                    FlatButton(
                                      child: Text('Cancel',style: TextStyle(color: Colors.indigo)),
                                      onPressed: (){
                                        Navigator.pop(context);
                                      },
                                    ),
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
              );
            }
            else Navigator.pop(context);
          }
          return false;
        },
        child: Container(
          padding: EdgeInsets.only(left:10,right: 10,bottom: 10),
          child: Column(
            children: <Widget>[
//              SizedBox(height: MediaQuery.of(context).size.height/25,),
              Expanded(
                child: Row(
                  children: <Widget>[
                    Flexible(
                      flex: 4,
                      child: Container(
                        height: MediaQuery.of(context).size.height,
                        child:
                          ListView.builder(
//                        itemCount: ((images.length+1)>jenisLength)?jenisLength:images.length+1,
                              itemCount: blobList.length,
                              itemBuilder: (context, index){
//                          Uint8List image = ((images.length==0)||(images.length<(index+1)))?null:images[index];
                                Uint8List image = blobList[index].blob_file;
                            return Padding(
                              padding: const EdgeInsets.only(top: 10,right: 10),
                              child: Material(
                                child: InkWell(
                                  onTap: ()async{
                                    if(image==null){
//                                var selected = await showDialog(
//                                  context: context,
//                                  builder: (context){
//                                    var selected = dropMenu[0].value;
//                                    return WillPopScope(
//                                      onWillPop: ()async{
//                                        Navigator.pop(context,false);
//                                        return false;
//                                      },
//                                      child: AlertDialog(
//                                        content: StatefulBuilder(
//                                          builder: (context,setState){
//                                            return DropdownButtonFormField(
//                                              decoration: InputDecoration.collapsed(),
//                                              value: selected,
//                                              onChanged: (value){
//                                                setState(() {
//                                                  selected = value;
//                                                });
//                                              },
//                                              items: dropMenu.map((item) {
//                                                return new DropdownMenuItem<String>(
//                                                  value: item.value,
//                                                  child: Row(
//                                                    children: <Widget>[
//                                                      Text(item.value),
////                                                      (item.optional=='TRUE')?Container():Text(' *',style: TextStyle(color: Colors.red),)
//                                                    ],
//                                                  ),
//                                                );
//                                              }).toList(),
//                                            );
//                                          },
//                                        ),
//                                        actions: <Widget>[
//                                          FlatButton(
//                                            child: Text('Done'),
//                                            onPressed: ()async{
//                                              jenisImages.add(selected);
//
//                                              Navigator.pop(context,true);
//                                            },
//                                          ),
//                                          FlatButton(
//                                            child: Text('Cancel'),
//                                            onPressed: (){
//                                              Navigator.pop(context,false);
//                                            },
//                                          ),
//                                        ],
//                                      ),
//                                    );
//                                  }
//                                );
//                                if (selected){
                                        File temp = await ImagePicker.pickImage(source: ImageSource.camera,maxWidth: 800,imageQuality: 80);
                                        if(temp!=null){
                                          isChanged = true;
                                          blobList[index].blob_file = temp.readAsBytesSync();
                                          temp.deleteSync();
//                                    if(widget.idInsert!=null) {
//                                      blobIds.add(null);
//                                      isChanged = true;
//                                    }
                                          setState(() {
                                          });
                                        }
//                                  else {
//                                    jenisImages.removeLast();
//                                  }
//                                  await loadDropMenu();
//                                }
                                    }
                                    else {
//                                List<jenisDrop> dropNewMenu = new List<jenisDrop>.from(dropMenu);
//                                dropNewMenu.add(new jenisDrop(value: jenisImages[index]));
                                      var result = await Navigator.push(context, MaterialPageRoute(builder: (context) => PhotoViewer(image,id: widget.unit.id.toString()+'.$index',jenis: blobList[index].jenis,)));
                                      if(result!=null){
                                          blobList[index] = result['byte'];
                                          isChanged = true;
//                                  images[index] = result['byte'];
//                                  jenisImages[index] = result['jenis'];
//                                  await loadDropMenu();
//                                  if(widget.idInsert!=null) {
//                                    isChanged = true;
//                                  }
                                        setState(() {
                                        });
                                      }
                                    }
                                  },
                                  splashColor: Colors.grey,
                                  child: Column(
                                    children: <Widget>[
                                      Container(padding: EdgeInsets.all(5),child: Text(blobList[index].jenis)),
                                      Stack(
                                        children: <Widget>[
                                          Container(
                                            decoration: BoxDecoration(
                                              color: Colors.grey.withOpacity(0.7),
                                              image: (image!=null)?DecorationImage(
                                                  image: MemoryImage(image),
                                                  fit: BoxFit.cover
                                              ):null,
                                            ),
                                            height: MediaQuery.of(context).size.width*0.35,
                                            width: MediaQuery.of(context).size.width*0.35,
                                            child: (image==null)?Icon(Icons.add):null,
                                          ),
                                          (image!=null)?Container(
                                            height: MediaQuery.of(context).size.width*0.35,
                                            width: MediaQuery.of(context).size.width*0.35,
                                            alignment: Alignment.topRight,
                                            child: InkWell(
                                              onTap: ()async{
//                                      if(widget.idInsert!=null){
//                                        isChanged = true;
//                                        deleteBlobIds.add(blobIds[index]);
//                                        blobIds.removeAt(index);
//                                      }
                                              setState(() {
                                                blobList[index].blob_file = null;
//                                        images.removeAt(index);
//                                        jenisImages.removeAt(index);
                                              });
//                                      await loadDropMenu();
                                              },
                                              child: Container(
                                                  padding: EdgeInsets.all(5),
                                                  child: Icon(Icons.cancel,color: Colors.red,)),
                                            ),
                                          ):Container(),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            );
                          })
                      ),
                    ),
                    Flexible(
                      flex: 6,
                      child: Container(
                        alignment: Alignment.topLeft,
                        padding: EdgeInsets.only(top: 10),
                        child: SingleChildScrollView(
                          scrollDirection: Axis.vertical,
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
//                        Divider(),
//                        Row(
//                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                          children: <Widget>[
//                            Expanded(
//                              child:
//                              textfield??Container(),
//                            ),
//                          ],
//                        ),
                              Padding(
                                padding: const EdgeInsets.all(5.0),
                                child: Text('Units Details',style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold),),
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('Tipe : '),
                                  Expanded(
                                        child:
                                        TextFormField(
                                          enabled: false,
                                          style: TextStyle(color: Colors.grey),
                                          controller: tipeController,
                                            decoration: InputDecoration.collapsed(hintText: null),
                                        ),
                                      ),
                                ],
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('Mesin : '),
                                  Expanded(
                                    child: TextFormField(
                                      enabled: false,
                                      style: TextStyle(color: Colors.grey),
                                      controller: mesinController,
                                      decoration: InputDecoration.collapsed(hintText: null),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('Rangka : '),
                                  Expanded(
                                    child: TextFormField(
                                      enabled: false,
                                      style: TextStyle(color: Colors.grey),
                                      controller: rangkaController,
                                      decoration: InputDecoration.collapsed(hintText: null),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('Kode : '),
                                  Expanded(
                                    child: TextFormField(
                                      enabled: false,
                                      style: TextStyle(color: Colors.grey),
                                      controller: kodeController,
                                      decoration: InputDecoration.collapsed(hintText: null),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('Tahun : '),
                                  Expanded(
                                    child: TextFormField(
                                      enabled: false,
                                      style: TextStyle(color: Colors.grey),
                                      controller: tahunController,
                                      decoration: InputDecoration.collapsed(hintText: null),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('Warna : '),
                                  Expanded(
                                    child: TextFormField(
                                      enabled: false,
                                      style: TextStyle(color: Colors.grey),
                                      controller: colorController,
                                      decoration: InputDecoration.collapsed(hintText: null),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Text('State : '),
                                  Expanded(
                                    child: TextFormField(
                                      enabled: false,
                                      style: TextStyle(color: Colors.grey),
                                      controller: stateController,
                                      decoration: InputDecoration.collapsed(hintText: null),
                                    ),
                                  ),
                                ],
                              ),
                              Divider(),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  FlatButton(
                                    child: Text((widget.unit.flag=='FALSE')?'Add':'Save'),
                                    onPressed: ()async{
                                      bool succeed = false;
                                      String errMsg = '';
                                        util.showLoading(context);
                                        await Future.sync(()async{
                                          if(currentPosisiton!=null) {
                                            if(blobList.where((element) => element.blob_file!=null).length==blobList.length){
                                              for(int i = 0 ; i<blobList.length;i++){
                                                blobList[i].lat = currentPosisiton.latitude.toString();
                                                blobList[i].long = currentPosisiton.longitude.toString();
                                                var result = await DBHelper.database.updateBlob(blobList[i]);
                                                succeed = (result!=null);
                                                if(!succeed) {
                                                  i = blobList.length;
                                                }
                                              }
                                              if(succeed){
                                                _currentUnit.timestamp = DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.now());
                                                _currentUnit.flag = 'TRUE';
                                                var result = await DBHelper.database.updateUnit(_currentUnit);
                                                succeed = (result!=null);
                                              }
                                            }
                                            else{
                                              succeed = false;
                                              errMsg ='Please take all the pictures';
                                            }
                                          }
                                          else{
                                            succeed = false;
                                            errMsg ='Failed getting current location. Please check gps.';
                                          }
                                        });
                                        Navigator.pop(context);
//                                  if(!ModalRoute.of(context).isCurrent)Navigator.popUntil(context,ModalRoute.withName('/unitdetails') );
                                        if(!ModalRoute.of(context).isCurrent)Navigator.pop(context);
                                        if(succeed) Navigator.pop(context,succeed);
                                        util.showFlushbar(context, (succeed)?'Data updated':errMsg,color: (succeed)?Colors.grey:Colors.red);

//                                bool valid = false;
//                                String errMsg= '';
//                                if(widget.idInsert==null){
//                                  bool not_empty = (stateController.text!='-'&&mesinController.text!='-'&&tahunController.text!='-'&&kodeController.text!='-'&&colorController.text!='-'&&rangkaController.text!='-'&&tipeController.text!='-');
//                                  if(not_empty&&images.length==jenisLength){
//                                    valid = true;
//                                  }
//                                  else{
//                                    if(!not_empty) errMsg='Please fill all the Unit details';
//                                    else errMsg='You must atleast take required pictures of unit';
//                                  }
//                                }
//                                else{
//                                  checkChanges();
//                                  valid = true;
//                                }
//                                if(valid){
//                                  bool succeed = false;
//                                  util.showLoading(context);
//                                  await Future.sync(()async{
//                                    if(currentPosisiton!=null){
//                                      if(widget.idInsert==null){
//                                        var result = await DBHelper.database.checkUnitbyMesin(mesinController.text.replaceAll('-', ''));
//                                        if(result==0){
//                                          insertUnit input = new insertUnit(
//                                            mesin: mesinController.text,
//                                            timestamp:DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.now()),
//                                          );
//                                          var insertID = await DBHelper.database.newInsertUnit(input);
//                                          if(insertID!=null){
//                                            for(int i=0;i<images.length;i++){
//                                              blobImage newBlob = new blobImage(
//                                                  blob_file: images[i],
//                                                  mesin_id: insertID,
//                                                  lat: currentPosisiton.latitude.toString(),
//                                                  long: currentPosisiton.longitude.toString(),
//                                                  jenis: jenisImages[i],
//                                              );
//                                              var result = await DBHelper.database.newInsertBlob(newBlob);
//                                              succeed = (result!=null);
//                                              if(!succeed) {
//                                                i = images.length;
//                                              }
//                                            }
//                                          }
//                                          await DBHelper.database.closeDb();
//                                        }
//                                        else{
//                                          errMsg = "Data mesin ${mesinController.text} sudah diinput";
//                                        }
//                                      }
//                                      else{
//                                        if(isChanged){
//                                          if(images.length==jenisLength){
//                                            _unitDetails.mesin = mesinController.text;
//                                            _unitDetails.timestamp = DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.now());
//                                            var updateresult = await DBHelper.database.updateInsertUnit(_unitDetails);
//                                            if(updateresult!=null){
//                                              print(deleteBlobIds);
//                                              for(int j=0;j<deleteBlobIds.length;j++){
//                                                var result = await DBHelper.database.deleteBlob(deleteBlobIds[j]);
//                                                succeed = (result!=null);
//                                                if(!succeed) {
//                                                  j = deleteBlobIds.length;
//                                                }
//                                              }
//                                              for(int i=0;i<images.length;i++){
//                                                blobImage newBlob = new blobImage(
//                                                  blob_id: blobIds[i],
//                                                  blob_file: images[i],
//                                                  mesin_id: _unitDetails.id,
//                                                  lat : currentPosisiton.latitude.toString(),
//                                                  long : currentPosisiton.longitude.toString(),
//                                                  jenis: jenisImages[i],
//                                                );
//                                                var result = await DBHelper.database.insertUpdateBlob(newBlob);
//                                                succeed = (result!=null);
//                                                if(!succeed) {
//                                                  i = images.length;
//                                                }
//                                              }
//                                            }
//                                            await DBHelper.database.closeDb();
//                                          }
//                                          else errMsg = 'You must atleast take required pictures of unit';
//                                        }
//                                        else succeed =true;
//                                      }
//                                    }
//                                    else{
//                                      errMsg = 'Failed fetching location. Please make sure gps enabled';
//                                    }
//                                  });
//                                  Navigator.pop(context);
////                                  print('aaaaaaaaaaaaaa ${ModalRoute.of(context).isCurrent}');
//                                  if(!ModalRoute.of(context).isCurrent)Navigator.popUntil(context, ModalRoute.withName('/unitdetails'));
//                                  if(succeed){
//                                    Navigator.pop(context,succeed);
//                                    print(currentPosisiton);
//                                    util.showFlushbar(context, 'Row ${widget.idInsert==null?'Inserted':'Updated'}');
//                                  }
//                                  else{
//                                    util.showFlushbar(context, 'Failed to  ${widget.idInsert==null?'insert':'update'} row. ${errMsg??''}',color: Colors.red);
//                                  }
//                                }
//                                else{
//                                  util.showFlushbar(context,errMsg);
//                                }
                                    },
                                    color: Colors.green,
                                  ),
                                  FlatButton(
                                    child: Text('Cancel'),
                                    onPressed: ()async {
                                      if(widget.unit.flag=='TRUE'){
                                        if(isChanged){
                                          await showDialog(context: context,builder: (context)=>
                                              Material(
                                                color: Colors.white.withOpacity(0.9),
                                                child: Center(
                                                  child: Container(
                                                    decoration: BoxDecoration(
                                                        color: Colors.white,
                                                        boxShadow: [
                                                          BoxShadow(
                                                            color: Colors.grey.withOpacity(0.5),
                                                            spreadRadius: 2,
                                                            blurRadius: 2,
                                                            offset: Offset(0, 0), // changes position of shadow
                                                          ),
                                                        ],
                                                        borderRadius: BorderRadius.circular(5)
                                                    ),
                                                    height: MediaQuery.of(context).size.height/4.8,
                                                    width: MediaQuery.of(context).size.width*0.75,
                                                    child: Column(
                                                      children: <Widget>[
                                                        Flexible(
                                                          flex:3,
                                                          child: Container(
                                                            padding: EdgeInsets.only(top:10,left: 10,right: 10),
                                                            alignment: Alignment.center,
                                                            decoration: BoxDecoration(
//                          color: Colors.indigo,
                                                                borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                                                            ),
                                                            child: Column(
                                                              mainAxisSize: MainAxisSize.min,
                                                              crossAxisAlignment: CrossAxisAlignment.center,
                                                              children: <Widget>[
                                                                Icon(Icons.warning,size: 70,color: Colors.indigo,),
                                                              ],
                                                            ),
                                                          ),
                                                        ),
                                                        Flexible(
                                                          flex: 1,
                                                          child: Container(
                                                              padding: EdgeInsets.only(left: 20,right: 20),
                                                              alignment: Alignment.centerLeft,
                                                              child: Text('Data belum disimpan. Lanjutkan ?',style: TextStyle(fontWeight: FontWeight.w500,fontSize: 14,color: Colors.black.withOpacity(0.6)),)
                                                          ),
                                                        ),
                                                        Flexible(
                                                          flex: 1,
                                                          child: Container(
                                                            padding: EdgeInsets.only(bottom:10),
                                                            child: Row(
                                                              mainAxisAlignment: MainAxisAlignment.end,
                                                              children: <Widget>[
                                                                FlatButton(
                                                                  child: Text('Proceed'),
                                                                  onPressed: (){
                                                                    Navigator.pop(context);
                                                                    Navigator.popUntil(context,ModalRoute.withName('/stocking'));
                                                                  },
                                                                ),
                                                                FlatButton(
                                                                  child: Text('Cancel'),
//                  color: Colors.grey,
                                                                  onPressed: (){
                                                                    Navigator.pop(context);
                                                                  },
                                                                ),
                                                              ],
                                                            ),
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                ),
                                              ),
                                          );
                                        }
                                        else Navigator.pop(context);
                                      }
                                      else {
//                                  bool not_empty = (stateController.text!='-'&&mesinController.text!='-'&&tahunController.text!='-'&&kodeController.text!='-'&&colorController.text!='-'&&rangkaController.text!='-'&&tipeController.text!='-');
                                        if(blobList.where((element) => element.blob_file!=null).length!=0){
                                          await showDialog(context: context,builder: (context)=>
                                              Material(
                                                color: Colors.white.withOpacity(0.9),
                                                child: Center(
                                                  child: Container(
                                                    decoration: BoxDecoration(
                                                        color: Colors.white,
                                                        boxShadow: [
                                                          BoxShadow(
                                                            color: Colors.grey.withOpacity(0.5),
                                                            spreadRadius: 2,
                                                            blurRadius: 2,
                                                            offset: Offset(0, 0), // changes position of shadow
                                                          ),
                                                        ],
                                                        borderRadius: BorderRadius.circular(5)
                                                    ),
                                                    height: MediaQuery.of(context).size.height/4.8,
                                                    width: MediaQuery.of(context).size.width*0.75,
                                                    child: Column(
                                                      children: <Widget>[
                                                        Flexible(
                                                          flex:3,
                                                          child: Container(
                                                            padding: EdgeInsets.only(top:10,left: 10,right: 10),
                                                            alignment: Alignment.center,
                                                            decoration: BoxDecoration(
//                          color: Colors.indigo,
                                                                borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                                                            ),
                                                            child: Column(
                                                              mainAxisSize: MainAxisSize.min,
                                                              crossAxisAlignment: CrossAxisAlignment.center,
                                                              children: <Widget>[
                                                                Icon(Icons.warning,size: 70,color: Colors.indigo,),
                                                              ],
                                                            ),
                                                          ),
                                                        ),
                                                        Flexible(
                                                          flex: 1,
                                                          child: Container(
                                                              padding: EdgeInsets.only(left: 20,right: 20),
                                                              alignment: Alignment.centerLeft,
                                                              child: Text('Data belum disimpan. Lanjutkan ?',style: TextStyle(fontWeight: FontWeight.w500,fontSize: 14,color: Colors.black.withOpacity(0.6)),)
                                                          ),
                                                        ),
                                                        Flexible(
                                                          flex: 1,
                                                          child: Container(
                                                            padding: EdgeInsets.only(bottom:10),
                                                            child: Row(
                                                              mainAxisAlignment: MainAxisAlignment.end,
                                                              children: <Widget>[
                                                                FlatButton(
                                                                  child: Text('Back'),
                                                                  onPressed: (){
                                                                    Navigator.pop(context);
                                                                    Navigator.popUntil(context,ModalRoute.withName('/stocking'));
                                                                  },
                                                                ),
                                                                FlatButton(
                                                                  child: Text('Cancel'),
                                                                  onPressed: (){
                                                                    Navigator.pop(context);
                                                                  },
                                                                ),
                                                              ],
                                                            ),
                                                          ),
                                                        )
                                                      ],
                                                    ),
                                                  ),
                                                ),
                                              ),
                                          );
                                        }
                                        else Navigator.pop(context);
                                      }
                                    },
                                    color: Colors.redAccent,
                                  )
                                ],
                              )
                            ],
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}