import 'dart:convert';
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_spinbox/flutter_spinbox.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'dart:html' as html;

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';

import '../providers/pdf_provider.dart';

class InterfazCuadriculaPage extends StatefulWidget {
  final Object info;
  final String token;
  final String idUsuario;
  final String idProyecto;
  final String noProyecto;
  final bool finalizado;
  final String archpdf;

  const InterfazCuadriculaPage({
    Key? key,
    required this.info,
    required this.token,
    required this.idUsuario,
    required this.idProyecto,
    required this.noProyecto,
    required this.finalizado,
    required this.archpdf
  }) : super(key: key);

  @override
  _InterfazCuadriculaPageState createState() => _InterfazCuadriculaPageState();
}

class _InterfazCuadriculaPageState extends State<InterfazCuadriculaPage> {
  //Variables finales
  final _pdfProvider = PDFProvider(); //Provider del PDF
  final _scrKey = GlobalKey(); //Controller para la screenshot
  final List<int> _numSalidas = []; //Opciones de salidas de la campana
  final List<String> _codosTipos = ["90°", "45°", "Ampliado", "Reducido"];
  final List<Map<String, Map<String, String>>> _historial = [];
  final List<Map<String, Map<String, String>>> _historialRe = [];
  final Map<String, Map<String, String>> _codosInstalados = {};
  final Map<String, Map<String, String>> _tramosRectos = {};
  final Map<String, Map<String, String>> _perdidasAdicionales = {};
  final TextEditingController _numCodosController = TextEditingController(); //Controlador para el número de codos
  final Color _colorFondoBarraO = const Color(0xFF242320); //Color del fondo de la barra Oscuro
  final Color _colorFondoBarraC = const Color(0xFFE3E1DA); //Color del fondo de la barra Claro
  final Color _colorIconoBarraO = Colors.white;   //Color de los iconos de la barra Oscuro
  final Color _colorIconoBarraC = Colors.black87; //Color de los iconos de la barra Claro
  final Color _colorFondoCuadrO = const Color(0xAA242320); //Color del fondo del sistema Oscuro
  final Color _colorFondoCuadrC = Colors.transparent;      //Color del fondo del sistema Claro

  //Variables dinámicas
  bool _estaConfigurando = true; //Indica si se está viendo configurando el proyecto
  bool _claro = false; //Selector del tema del sistema
  bool _confActivada = false;
  bool _isLoading = true;
  bool _finalizado = false;
  int _numSalidasSelec = 1; //Número de salidas de la campana
  int _numCuadriculas = 10; //Tamaño de la cuadricula
  int _numCodosConf = 0; //Número de codos configurados
  int _indexCodos = 0; //Selector del tipo de codo
  int _numRed = 0; //Número de reducciones
  int _numAmp = 0; //Número de ampliaciones
  int _numCodosPuestos = 0;
  int _movHistorial = 0;
  int _movHistRe = 0;
  double _campRad = 0.0;
  String _imgSize = ""; //Tamaño de las imágenes
  String _nombreElemento = "";
  String _dataDrag = "";
  String _tipoDataDrag = "";
  String _jsonCalculos = "";
  String _campFiltGrasa = "";
  String _movFinDir = "";
  String _movFinName = "";
  Color _colorCuad = Colors.white; //Color del borde del cuadro
  Color _colorCuadIn = Colors.white54; //Color del interior del cuadro
  Color _colorDrag = Colors.transparent;
  Map<int, Map<int, Map<String, dynamic>>> _properties = {};

  //Variables inicializadas después del estado inicial
  late String _tipoInstalacion;
  late String _tipoCampana;
  late String _eqCocina;
  late String _longitud;
  late String _ancho;
  late String _distCapt;
  late String _caudalEx;
  late String _cauInySug;
  late String _velAire;
  late String _ductoCuadradoCM;
  late String _ductoCuadradoIN;
  late String _ductoCircularCM;
  late String _ductoCircularIN;
  late String _ductoSeleccion;
  late String _unidadDucto;
  late String _unidadLongitud;

  @override
  void initState() {
    super.initState();
    _finalizado = widget.finalizado;

    final decoded = jsonDecode(widget.info.toString());
    final datos = decoded["datos"];
    _tipoInstalacion = datos["tipoInstalacion"];
    _tipoCampana = datos["tipoCampana"];
    _eqCocina = datos["eqCocina"];
    _longitud = datos["longitud"];
    _ancho = datos["ancho"];
    _distCapt = datos["distCapt"];
    _caudalEx = datos["caudalEx"];
    _cauInySug = datos["cauInySug"];
    _velAire = datos["velAire"];
    _ductoCuadradoCM = datos["ductoCuadradoCM"];
    _ductoCuadradoIN = datos["ductoCuadradoIN"];
    _ductoCircularCM = datos["ductoCircularCM"];
    _ductoCircularIN = datos["ductoCircularIN"];
    _ductoSeleccion = datos["ductoSeleccion"];
    _unidadDucto = datos["unidadesInstalado"];

    _unidadLongitud = _longitud.split(" ").last;

    for(int i = 1; i <= 3; i++){
      _numSalidas.add(i);
    }

    if(decoded.containsKey("campana")){
      final campana = decoded["campana"];
      _numSalidasSelec = int.parse(campana["salidas"]);
      _numCodosController.text = campana["codos"];
    }else{
      _numSalidasSelec = _numSalidas.first;
    }

    if(decoded.containsKey("cuadricula")){
      final cuadricula = decoded["cuadricula"];
      final historial = jsonDecode(cuadricula["historial"]);
      final properties = jsonDecode(cuadricula["properties"]);
      final tramosRectos = jsonDecode(cuadricula["tramosRectos"]);
      final codosInstalados = jsonDecode(cuadricula["codosInstalados"]);
      final perdidasAdicionales = jsonDecode(cuadricula["perdidasAdicionales"]);
      final reducciones = cuadricula["reducciones"];
      final ampliaciones = cuadricula["ampliaciones"];

      _numAmp = int.parse(ampliaciones);
      _numRed = int.parse(reducciones);

      tramosRectos.forEach((key, value){
        Map<String, String> tmp = {};
        value.forEach((key0, value0){
          tmp[key0] = value0;
        });
        _tramosRectos[key] = tmp;
      });

      codosInstalados.forEach((key, value){
        Map<String, String> tmp = {};
        value.forEach((key0, value0){
          tmp[key0] = value0;
        });
        _codosInstalados[key] = tmp;
        _numCodosPuestos++;
      });

      perdidasAdicionales.forEach((key, value){
        Map<String, String> tmp = {};
        value.forEach((key0, value0){
          tmp[key0] = value0;
        });
        _perdidasAdicionales[key] = tmp;
      });

      historial.forEach((value){
        Map<String, Map<String, String>> tmp = {};
        value.forEach((key0, value0){
          Map<String, String> tmp1 = {};
          value0.forEach((key1, value1){
            tmp1[key1] = value1;
          });
          tmp[key0] = tmp1;
        });
        _historial.add(tmp);
      });

      _movHistorial = _historial.length;

      properties.forEach((value){
        final prop = value.split("=>");
        final coordI = int.parse(prop[0]);
        final coordJ = int.parse(prop[1]);

        if(_properties[coordI] == null){
          _properties[coordI] = {};
        }

        if(_properties[coordI]![coordJ] == null){
          _properties[coordI]![coordJ] = {};
        }

        if(prop[2] == "color"){
          _properties[coordI]![coordJ]![prop[2]] = Color(int.parse(prop[3]));
        }else if(prop[2] == "used" || prop[2] == "enabled"){
          _properties[coordI]![coordJ]![prop[2]] = prop[3] == "true";
        }else{
          _properties[coordI]![coordJ]![prop[2]] = prop[3];
        }
      });
    }

    if(decoded.containsKey("calculos")){
      final calculos = decoded["calculos"];
      _jsonCalculos = calculos["resultados"];
    }

    if(_tipoInstalacion == "E"){
      if(_ductoSeleccion == "cuadrado"){
        int ductoCuadradoCM = int.parse(_ductoCuadradoCM.split(" ").first);
        int ductoCircularCM = ((math.pow((math.pow((ductoCuadradoCM*ductoCuadradoCM), 3)/(ductoCuadradoCM+ductoCuadradoCM)), 0.2))*1.265).round();
        int ductoCircularIN = (ductoCircularCM/2.54).round();

        _ductoCircularCM = "$ductoCircularCM cm";
        _ductoCircularIN = "$ductoCircularIN in";
      }
    }
  }

  Future<bool> _guardarProyecto(String datos, String estatus, String archpdf) async{
    final url = Uri.https("smart.solerpalau.mx", "PR/api/v1/quiosco/matrizMemoriasCalculo/actualizarProyecto");
    final res = await http.post(url,
      headers: {
        "Authorization": "Bearer ${widget.token}"
      },
      body: {
        "IDUSUARIO": widget.idUsuario,
        "IDPROYECTO": widget.idProyecto,
        "FMODIF": DateTime.now().toIso8601String().substring(0, 19),
        "ESTATUS": estatus,
        "DATOS": base64Encode(utf8.encode(datos)),
        "ARCHPDF": archpdf
      },
    );

    final decoded = jsonDecode(res.body);
    return decoded['response'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _estaConfigurando ? Center(
        child: AlertDialog(
          title: Text(
            "Configuración",
            style: GoogleFonts.roboto(),
          ),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(
                width: double.infinity,
                child: Text(
                  "Selecciona el número de tomas de aire de extracción de la campana:",
                  textAlign: TextAlign.left,
                  style: GoogleFonts.roboto(),
                ),
              ),
              const SizedBox(height: 8.0),
              DropdownButton<int>(
                value: _numSalidasSelec,
                onChanged: (nuevaMedida) => setState((){
                  _numSalidasSelec = nuevaMedida!;
                }),
                items: _numSalidas.map((e) => DropdownMenuItem<int>(
                  child: Text(
                    "$e salidas",
                    textAlign: TextAlign.center,
                    style: GoogleFonts.roboto(),
                  ),
                  value: e,
                )).toList(),
                isExpanded: true,
              ),
              Text(
                "Se recomienda que en campanas de 3 o más metros de longitud seleccione 2 o 3 salidas.",
                style: GoogleFonts.roboto(
                  fontStyle: FontStyle.italic,
                  fontSize: 10.0,
                ),
              ),
              const SizedBox(height: 8.0),
              Text(
                "Ingresa el número de codos que deseas instalar:",
                style: GoogleFonts.roboto(),
              ),
              const SizedBox(height: 8.0),
              TextField(
                controller: _numCodosController,
                maxLength: 2,
                decoration: InputDecoration(
                  hintText: "2 cifras máximo.",
                  hintStyle: GoogleFonts.roboto(
                    fontSize: 18.0,
                    fontStyle: FontStyle.italic,
                    color: Colors.grey,
                  ),
                ),
                keyboardType: TextInputType.number,
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
                ],
              ),
            ],
          ),
          actions: [
            TextButton(
              child: const Text("Regresar"),
              onPressed: () => Navigator.pop(context),
            ),
            TextButton(
              child: Text(
                "Aceptar",
                style: GoogleFonts.roboto(),
              ),
              onPressed: () async{
                if(_numCodosController.text.isEmpty){
                  Fluttertoast.showToast(
                    msg: "Por favor ingresa un número de codos.",
                    toastLength: Toast.LENGTH_SHORT,
                    timeInSecForIosWeb: 4,
                    gravity: ToastGravity.CENTER,
                    webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                  );
                }else{
                  int numCodos = int.parse(_numCodosController.text);

                  if(numCodos <= 3){
                    _numCuadriculas = 10;
                    _imgSize = "xl";
                  }else if(numCodos > 3 && numCodos <= 6){
                    _numCuadriculas = 20;
                    _imgSize = "la";
                  }else if(numCodos > 6 && numCodos <= 9){
                    _numCuadriculas = 30;
                    _imgSize = "no";
                  }else if(numCodos > 9 && numCodos <= 12){
                    _numCuadriculas = 40;
                    _imgSize = "no";
                  }else{
                    _numCuadriculas = 50;
                    _imgSize = "sm";
                  }

                  _numCodosConf = numCodos;

                  final historial = jsonEncode(_historial);
                  List<String> propertiesMap = [];

                  _properties.forEach((key, value) {
                    value.forEach((key0, value0) {
                      value0.forEach((key1, value1) {
                        if(key1 == "color"){
                          final colorInt = value1.value;
                          propertiesMap.add("$key=>$key0=>$key1=>$colorInt");
                        }else{
                          propertiesMap.add("$key=>$key0=>$key1=>$value1");
                        }
                      });
                    });
                  });

                  final properties = jsonEncode(propertiesMap);
                  final tramosRectos = jsonEncode(_tramosRectos);
                  final codosInstalados = jsonEncode(_codosInstalados);
                  final perdidasAdicionales = jsonEncode(_perdidasAdicionales);

                  Map<String, Map<String, String>> datos = {
                    "datos": {
                      "tipoInstalacion" : _tipoInstalacion,
                      "tipoCampana" : _tipoCampana,
                      "eqCocina" : _eqCocina,
                      "longitud" : _longitud,
                      "ancho" : _ancho,
                      "distCapt" : _distCapt,
                      "caudalEx" : _caudalEx,
                      "cauInySug" : _cauInySug,
                      "velAire" : _velAire,
                      "ductoCuadradoCM" : _ductoCuadradoCM,
                      "ductoCuadradoIN" : _ductoCuadradoIN,
                      "ductoCircularCM" : _ductoCircularCM,
                      "ductoCircularIN" : _ductoCircularIN,
                      "ductoSeleccion" : _ductoSeleccion,
                      "unidadesInstalado" : _unidadDucto
                    },
                    "campana": {
                      "salidas": "$_numSalidasSelec",
                      "codos": "$_numCodosConf"
                    },
                    "cuadricula": {
                      "historial" : historial,
                      "properties": properties,
                      "tramosRectos": tramosRectos,
                      "codosInstalados": codosInstalados,
                      "perdidasAdicionales": perdidasAdicionales,
                      "reducciones": "$_numRed",
                      "ampliaciones": "$_numAmp"
                    },
                    "calculos": {
                      "resultados": _jsonCalculos
                    }
                  };
                  String datosStr = jsonEncode(datos);
                  setState(() => _estaConfigurando = false);
                  final guardado = await _guardarProyecto(datosStr, _finalizado ? "F" : "D", widget.archpdf);

                  if(!guardado){
                    Fluttertoast.showToast(
                      msg: "Hubo un error al intentar guardar el proyecto, intentelo de nuevo más tarde.",
                      toastLength: Toast.LENGTH_SHORT,
                      timeInSecForIosWeb: 4,
                      gravity: ToastGravity.CENTER,
                      webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                    );
                    Navigator.pop(context);
                  }else{
                    setState(() => _isLoading = false);
                  }
                }
              },
            ),
          ],
        ),
      ) : _isLoading ? const Center(
        child: CircularProgressIndicator(),
      ) : LayoutBuilder(
        builder: (context, constraints){
          final width = constraints.maxWidth;
          final height = constraints.maxHeight;

          String tipoCampanaSplit = _tipoCampana.contains("Humo soldadura") ? _tipoCampana.replaceAll("Humo soldadura", "Industrial") : _tipoCampana;
          final tipoCampanaArr = tipoCampanaSplit.split(" ");
          String tipoCampanaStr = "";
          for(int i = 2; i < tipoCampanaArr.length; i++){
            tipoCampanaStr = "$tipoCampanaStr${tipoCampanaArr[i]}";
          }
          String tipoCampanaUso = "$tipoCampanaStr${tipoCampanaArr[1]}";
          String aerea = "Aerea${tipoCampanaArr[1]}";

          final heightCuad = height - 128.0 - 32.0;
          final squareSize = heightCuad / _numCuadriculas;
          final List<Widget> columnChildren = [];
          final mitadCuadricula = _numCuadriculas~/2;

          for(int i = 0; i < _numCuadriculas; i++){
            final List<Widget> rowChildren = [];
            if(_properties[i] == null) _properties[i] = {};

            for(int j = 0; j < _numCuadriculas; j++){
              if(_properties[i]![j] == null) {
                _properties[i]![j] = {
                  "color" : Colors.transparent,
                  "image" : "no-image",
                  "type" : "no-type",
                  "data" : "no-data",
                  "enabled" : false,
                  "used" : false,
                  "text" : ""
                };
              }
              if(j == mitadCuadricula && i == _numCuadriculas - 1 && _numSalidasSelec == 1){
                _properties[i]![j-2]!["image"] = "campana_1_$_imgSize.png";
                _properties[i]![j-2]!["enabled"] = false;
                _properties[i]![j-2]!["used"] = true;
                _properties[i]![j-2]!["data"] = "campana";

                _properties[i]![j-1]!["image"] = "campana_2_$_imgSize.png";
                _properties[i]![j-1]!["enabled"] = false;
                _properties[i]![j-1]!["used"] = true;
                _properties[i]![j-1]!["data"] = "campana";

                _properties[i]![j]!["image"] = "campana_3_$_imgSize.png";
                _properties[i]![j]!["enabled"] = false;
                _properties[i]![j]!["used"] = true;
                _properties[i]![j]!["data"] = "campana";

                _properties[i-1]![j-1]!["enabled"] = true;
              }
              if(j == mitadCuadricula + 1 && i == _numCuadriculas - 1 && _numSalidasSelec == 2){
                _properties[i]![j]!["image"] = "campana_3_$_imgSize.png";
                _properties[i]![j]!["enabled"] = true;
                _properties[i]![j]!["used"] = true;
                _properties[i]![j]!["data"] = "campana";

                _properties[i]![j-1]!["image"] = "campana_2_$_imgSize.png";
                _properties[i]![j-1]!["enabled"] = true;
                _properties[i]![j-1]!["used"] = true;
                _properties[i]![j-1]!["data"] = "campana";

                _properties[i]![j-2]!["image"] = "campana_4_$_imgSize.png";
                _properties[i]![j-2]!["enabled"] = true;
                _properties[i]![j-2]!["used"] = true;
                _properties[i]![j-2]!["data"] = "campana";

                _properties[i]![j-3]!["image"] = "campana_2_$_imgSize.png";
                _properties[i]![j-3]!["enabled"] = true;
                _properties[i]![j-3]!["used"] = true;
                _properties[i]![j-3]!["data"] = "campana";

                _properties[i]![j-4]!["image"] = "campana_1_$_imgSize.png";
                _properties[i]![j-4]!["enabled"] = true;
                _properties[i]![j-4]!["used"] = true;
                _properties[i]![j-4]!["data"] = "campana";

                _properties[i-1]![j-1]!["enabled"] = true;
                _properties[i-1]![j-3]!["enabled"] = true;
              }
              if(j == mitadCuadricula + 2 && i == _numCuadriculas - 1 && _numSalidasSelec == 3){
                _properties[i]![j]!["image"] = "campana_3_$_imgSize.png";
                _properties[i]![j]!["enabled"] = true;
                _properties[i]![j]!["used"] = true;
                _properties[i]![j]!["data"] = "campana";

                _properties[i]![j-1]!["image"] = "campana_2_$_imgSize.png";
                _properties[i]![j-1]!["enabled"] = true;
                _properties[i]![j-1]!["used"] = true;
                _properties[i]![j-1]!["data"] = "campana";

                _properties[i]![j-2]!["image"] = "campana_4_$_imgSize.png";
                _properties[i]![j-2]!["enabled"] = true;
                _properties[i]![j-2]!["used"] = true;
                _properties[i]![j-2]!["data"] = "campana";

                _properties[i]![j-3]!["image"] = "campana_2_$_imgSize.png";
                _properties[i]![j-3]!["enabled"] = true;
                _properties[i]![j-3]!["used"] = true;
                _properties[i]![j-3]!["data"] = "campana";

                _properties[i]![j-4]!["image"] = "campana_4_$_imgSize.png";
                _properties[i]![j-4]!["enabled"] = true;
                _properties[i]![j-4]!["used"] = true;
                _properties[i]![j-4]!["data"] = "campana";

                _properties[i]![j-5]!["image"] = "campana_2_$_imgSize.png";
                _properties[i]![j-5]!["enabled"] = true;
                _properties[i]![j-5]!["used"] = true;
                _properties[i]![j-5]!["data"] = "campana";

                _properties[i]![j-6]!["image"] = "campana_1_$_imgSize.png";
                _properties[i]![j-6]!["enabled"] = true;
                _properties[i]![j-6]!["used"] = true;
                _properties[i]![j-6]!["data"] = "campana";

                _properties[i-1]![j-1]!["enabled"] = true;
                _properties[i-1]![j-3]!["enabled"] = true;
                _properties[i-1]![j-5]!["enabled"] = true;
              }
              rowChildren.add(Container(
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: i == 0 || i%10 == 0 ? _colorCuad : Colors.transparent,
                      width: i == 0 ? 2.0 : i%10 == 0 ? 1.0 : 0.0,
                    ),
                    bottom: BorderSide(
                      color: i == _numCuadriculas-1 ? _colorCuad : _colorCuadIn,
                      width: i == _numCuadriculas-1 ? 2.0 : 1.0,
                    ),
                    left: BorderSide(
                      color: j == 0 || j%10 == 0 ? _colorCuad: Colors.transparent,
                      width: j == 0 ? 2.0 : j%10 == 0 ? 1.0 : 0.0,
                    ),
                    right: BorderSide(
                      color: j == _numCuadriculas-1 ? _colorCuad : _colorCuadIn,
                      width: j == _numCuadriculas-1 ? 2.0 : 1.0,
                    ),
                  ),
                ),
                width: squareSize,
                height: squareSize,
                child: DragTarget<String>(
                  onWillAccept: (value) => true,
                  onAccept: (value) => _onAccept(value, {'i': i, 'j': j}),
                  onLeave: (value) => false,
                  builder: (context, candidates, rejects){
                    if(candidates.isNotEmpty && !_properties[i]![j]!["enabled"] && !_properties[i]![j]!["used"]){
                      _properties[i]![j]!["color"] = const Color(0x88FF0000);
                    }else if(candidates.isNotEmpty && _properties[i]![j]!["enabled"] && !_properties[i]![j]!["used"]){
                      _properties[i]![j]!["color"] = const Color(0x8800FF00);
                    }else if(!_properties[i]![j]!["used"]){
                      _properties[i]![j]!["color"] = const Color(0x00000000);
                    }
                    return Container(
                      width: squareSize,
                      height: squareSize,
                      color: _properties[i]![j]!["image"] == "no-image" ? _properties[i]![j]!["color"] : Colors.transparent,
                      child: _builDragChild(_properties[i]![j]!, {'i': i, 'j': j}),
                    );
                  },
                ),
              ));
            }

            columnChildren.add(Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: rowChildren,
            ));
          }

          return Container(
            child: Column(
              children: [
                Container(
                  height: 128,
                  width: width,
                  decoration: BoxDecoration(
                    color: _claro ? _colorFondoBarraC : _colorFondoBarraO,
                    borderRadius: const BorderRadius.only(
                      bottomRight: Radius.circular(8.0),
                      bottomLeft: Radius.circular(8.0),
                    ),
                  ),
                  padding: const EdgeInsets.all(8.0),
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      children: [
                        SizedBox(
                          width: 232.0,
                          child: Column(
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Icon(
                                                Icons.undo,
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                size: 48.0,
                                              ),
                                            ),
                                            Text(
                                              "Deshacer",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _movHistorial > 0 ? () {
                                          final ultMov = _historial.last;

                                          if(ultMov.keys.first == "properties"){
                                            final props = ultMov["properties"]!["props"];
                                            final salAnt = ultMov["properties"]!["salAnt"];

                                            _numSalidasSelec = int.parse(salAnt!);
                                            final list = jsonDecode(props!);
                                            final Map<int, Map<int, Map<String, dynamic>>> properties = {};

                                            list.forEach((element){
                                              final valArr = element.split("=>");
                                              dynamic val;

                                              if(valArr[2] == "color"){
                                                val = Color(int.parse(valArr[3]));
                                              }else if(valArr[2] == "used" || valArr[2] == "enabled"){
                                                val = valArr[3] == "1";
                                              }else{
                                                val = valArr[3];
                                              }

                                              if(properties[int.parse(valArr[0])] == null) properties[int.parse(valArr[0])] = {};
                                              if(properties[int.parse(valArr[0])]![int.parse(valArr[1])] == null) properties[int.parse(valArr[0])]![int.parse(valArr[1])] = {};
                                              properties[int.parse(valArr[0])]![int.parse(valArr[1])]![valArr[2]] = val;
                                            });

                                            _properties = properties;
                                            setState(() {});
                                            return;
                                          }
                                          final coordI = int.parse(ultMov[ultMov.keys.first]!["i"]!);
                                          final coordJ = int.parse(ultMov[ultMov.keys.first]!["j"]!);
                                          _properties[coordI]![coordJ]!['color'] = "no-color";

                                          if(ultMov.keys.first == "ducto"){
                                            String lastKey = _tramosRectos.keys.last;
                                            String movStr = jsonEncode(_tramosRectos[lastKey]);

                                            _historialRe.add({
                                              ultMov.keys.first:{
                                                lastKey: movStr,
                                                "props": jsonEncode(_properties[coordI]![coordJ]),
                                                "coord": "i:$coordI,j:$coordJ"
                                              }
                                            });

                                            _movHistRe++;

                                            final movArr = _tramosRectos[lastKey];
                                            double longitud = double.parse(movArr!['longitud']!);
                                            List<String> dirArr = _properties[coordI]![coordJ]!['type'].split("_");
                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];

                                            if(longitud <= 1){
                                              if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI]![coordJ+1]!['enabled'] = false;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI]![coordJ-1]!['enabled'] = false;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI-1]![coordJ]!['enabled'] = false;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else{
                                                _properties[coordI+1]![coordJ]!['enabled'] = false;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }
                                            }else if(longitud > 1 && longitud <= 2){
                                              if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI]![coordJ+2]!['enabled'] = false;

                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI]![coordJ-2]!['enabled'] = false;

                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI-2]![coordJ]!['enabled'] = false;

                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else{
                                                _properties[coordI+2]![coordJ]!['enabled'] = false;

                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }
                                            }else{
                                              if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI]![coordJ+3]!['enabled'] = false;

                                                _properties[coordI]![coordJ+2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI]![coordJ-3]!['enabled'] = false;

                                                _properties[coordI]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI-3]![coordJ]!['enabled'] = false;

                                                _properties[coordI-2]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }else{
                                                _properties[coordI+3]![coordJ]!['enabled'] = false;

                                                _properties[coordI+2]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                              }
                                            }

                                            _tramosRectos.remove(lastKey);
                                            _historial.removeLast();
                                            _movHistorial--;
                                          }else if(ultMov.keys.first == "codo"){
                                            _numCodosPuestos--;
                                            String lastKey = _codosInstalados.keys.last;
                                            String movStr = jsonEncode(_codosInstalados[lastKey]);

                                            _historialRe.add({
                                              ultMov.keys.first:{
                                                lastKey: movStr,
                                                "props": jsonEncode(_properties[coordI]![coordJ]),
                                                "coord": "i:$coordI,j:$coordJ"
                                              }
                                            });

                                            _movHistRe++;

                                            _properties[coordI]![coordJ+1]!['enabled'] = false;
                                            _properties[coordI]![coordJ-1]!['enabled'] = false;
                                            _properties[coordI-1]![coordJ]!['enabled'] = false;
                                            _properties[coordI+1]![coordJ]!['enabled'] = false;

                                            _properties[coordI]![coordJ] = {
                                              "color" : Colors.transparent,
                                              "image" : "no-image",
                                              "type" : "no-type",
                                              "data" : "no-data",
                                              "enabled" : true,
                                              "used" : false
                                            };

                                            _codosInstalados.remove(lastKey);
                                            _historial.removeLast();
                                            _movHistorial--;
                                          }else if(ultMov.keys.first == "reduccion" || ultMov.keys.first == "ampliacion"){
                                            String lastKey = ultMov.keys.first == "reduccion" ? "numRed" : "numAmp";
                                            String movStr = ultMov.keys.first == "reduccion" ? "$_numRed" : "$_numAmp";

                                            _historialRe.add({
                                              ultMov.keys.first:{
                                                lastKey: movStr,
                                                "props": jsonEncode(_properties[coordI]![coordJ]),
                                                "coord": "i:$coordI,j:$coordJ"
                                              }
                                            });

                                            _movHistRe++;

                                            List<String> dirArr = _properties[coordI]![coordJ]!['type'].split("_");

                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];

                                            if(direccion == "hor" && orientacion == "der"){
                                              _properties[coordI]![coordJ+1]!['enabled'] = false;
                                            }else if(direccion == "hor" && orientacion == "izq"){
                                              _properties[coordI]![coordJ-1]!['enabled'] = false;
                                            }else if(direccion == "ver" && orientacion == "arr"){
                                              _properties[coordI-1]![coordJ]!['enabled'] = false;
                                            }else{
                                              _properties[coordI+1]![coordJ]!['enabled'] = false;
                                            }

                                            _properties[coordI]![coordJ] = {
                                              "color" : Colors.transparent,
                                              "image" : "no-image",
                                              "type" : "no-type",
                                              "data" : "no-data",
                                              "enabled" : true,
                                              "used" : false
                                            };

                                            if(ultMov.keys.first == "reduccion") {
                                              _numRed--;
                                            }else{
                                              _numAmp--;
                                            }

                                            if(_numAmp == 0) _indexCodos = 0;
                                            if(_numRed == 0) _indexCodos = 0;

                                            _historial.removeLast();
                                            _movHistorial--;
                                          }else if(ultMov.keys.first == "final"){
                                            final data = _properties[coordI]![coordJ]!['data'];
                                            int cJ = data == "codo" ? coordJ-1 : coordJ;
                                            _finalizado = false;

                                            if(cJ != coordJ) _properties[coordI]![cJ]!['color'] = "no-color";

                                            _historialRe.add({
                                              ultMov.keys.first: {
                                                _movFinName: _movFinDir,
                                                "props": jsonEncode(_properties[coordI]![cJ]),
                                                "coord": "i:$coordI,j:$coordJ"
                                              }
                                            });

                                            _movHistRe++;

                                            List<String> dirArr = _properties[coordI]![cJ]!['type'].split("_");
                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];

                                            if(_movFinName == "CM" && _properties[coordI]![cJ]!['type'] == "hor_izq"){
                                              _properties[coordI]![coordJ] = {
                                                "color" : Colors.transparent,
                                                "image" : "no-image",
                                                "type" : "no-type",
                                                "data" : "no-data",
                                                "enabled" : true,
                                                "used" : false
                                              };
                                              _properties[coordI+1]![coordJ-1] = {
                                                "color" : Colors.transparent,
                                                "image" : "no-image",
                                                "type" : "no-type",
                                                "data" : "no-data",
                                                "enabled" : false,
                                                "used" : false
                                              };
                                              _properties[coordI]![coordJ-1] = {
                                                "color" : Colors.transparent,
                                                "image" : "no-image",
                                                "type" : "no-type",
                                                "data" : "no-data",
                                                "enabled" : false,
                                                "used" : false
                                              };
                                              _properties[coordI-1]![coordJ-1] = {
                                                "color" : Colors.transparent,
                                                "image" : "no-image",
                                                "type" : "no-type",
                                                "data" : "no-data",
                                                "enabled" : false,
                                                "used" : false
                                              };
                                              _properties[coordI+1]![coordJ-2] = {
                                                "color" : Colors.transparent,
                                                "image" : "no-image",
                                                "type" : "no-type",
                                                "data" : "no-data",
                                                "enabled" : false,
                                                "used" : false
                                              };
                                              _properties[coordI]![coordJ-2] = {
                                                "color" : Colors.transparent,
                                                "image" : "no-image",
                                                "type" : "no-type",
                                                "data" : "no-data",
                                                "enabled" : false,
                                                "used" : false
                                              };
                                              _properties[coordI-1]![coordJ-2] = {
                                                "color" : Colors.transparent,
                                                "image" : "no-image",
                                                "type" : "no-type",
                                                "data" : "no-data",
                                                "enabled" : false,
                                                "used" : false
                                              };
                                            }else{
                                              if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI-1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI-1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                              }else if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI+1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI-1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI+1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI-1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                              }else{
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : true,
                                                  "used" : false
                                                };
                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI+1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                                _properties[coordI+1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "no-image",
                                                  "type" : "no-type",
                                                  "data" : "no-data",
                                                  "enabled" : false,
                                                  "used" : false
                                                };
                                              }
                                            }

                                            _movFinName = "";
                                            _movFinDir = "";
                                            _historial.removeLast();
                                            _movHistorial--;
                                          }else{
                                            String lastKey = _perdidasAdicionales.keys.last;
                                            String movStr = jsonEncode(_perdidasAdicionales[lastKey]);

                                            _historialRe.add({
                                              ultMov.keys.first:{
                                                lastKey: movStr,
                                                "props": jsonEncode(_properties[coordI]![coordJ]),
                                                "coord": "i:$coordI,j:$coordJ"
                                              }
                                            });

                                            _movHistRe++;

                                            List<String> dirArr = _properties[coordI]![coordJ]!['type'].split("_");
                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];

                                            if(direccion == "hor" && orientacion == "der"){
                                              _properties[coordI]![coordJ+1]!['enabled'] = false;
                                            }else if(direccion == "hor" && orientacion == "izq"){
                                              _properties[coordI]![coordJ-1]!['enabled'] = false;
                                            }else if(direccion == "ver" && orientacion == "arr"){
                                              _properties[coordI-1]![coordJ]!['enabled'] = false;
                                            }else{
                                              _properties[coordI+1]![coordJ]!['enabled'] = false;
                                            }

                                            _properties[coordI]![coordJ] = {
                                              "color" : Colors.transparent,
                                              "image" : "no-image",
                                              "type" : "no-type",
                                              "data" : "no-data",
                                              "enabled" : true,
                                              "used" : false
                                            };

                                            _perdidasAdicionales.remove(lastKey);
                                            _historial.removeLast();
                                            _movHistorial--;
                                          }

                                          setState(() {});
                                        } : null,
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Icon(
                                                Icons.redo,
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                size: 48.0,
                                              ),
                                            ),
                                            Text(
                                              "Rehacer",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _movHistRe > 0 ? (){
                                          final mov = _historialRe.last;
                                          final key = mov.keys.first;

                                          final val = mov[key];
                                          final tipoMov = val!.keys.first;

                                          final coords = val["coord"];
                                          final coordsArr = coords!.split(",");

                                          final coordI = int.parse(coordsArr[0].split(":")[1]);
                                          final coordJ = int.parse(coordsArr[1].split(":")[1]);

                                          if(tipoMov.contains("Tramo")){
                                            final valMov = val[tipoMov];
                                            final decoded = jsonDecode(valMov!);

                                            _tramosRectos[tipoMov] = {};
                                            decoded.forEach((key, value){
                                              _tramosRectos[tipoMov]![key] = value;
                                            });

                                            final props = val["props"];
                                            final propsDec = jsonDecode(props!);
                                            final lon = _tramosRectos[tipoMov]!["longitud"];
                                            final longitud = double.parse(lon!);
                                            final text = propsDec['text'] == null || propsDec['text'].isEmpty ? "$longitud $_unidadLongitud" : propsDec['text'];

                                            List<String> dirArr = propsDec['type'].split("_");
                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];

                                            if(longitud <= 1){
                                              if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI]![coordJ+1]!['enabled'] = true;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI]![coordJ-1]!['enabled'] = true;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI-1]![coordJ]!['enabled'] = true;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else{
                                                _properties[coordI+1]![coordJ]!['enabled'] = true;

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }
                                            }else if(longitud > 1 && longitud <= 2){
                                              final img = propsDec['image'] == "ducto_aba_$_imgSize.png" ? "ducto_arr_$_imgSize.png" : "ducto_aba_$_imgSize.png";
                                              if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI]![coordJ+2]!['enabled'] = true;

                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI]![coordJ-2]!['enabled'] = true;

                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI-2]![coordJ]!['enabled'] = true;

                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else{
                                                _properties[coordI+2]![coordJ]!['enabled'] = true;

                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }
                                            }else{
                                              final img = propsDec['image'] == "ducto_aba_$_imgSize.png" ? "ducto_arr_$_imgSize.png" : "ducto_aba_$_imgSize.png";
                                              final cen = "ducto_solo_$_imgSize.png";
                                              if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI]![coordJ+3]!['enabled'] = true;

                                                _properties[coordI]![coordJ+2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : cen,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI]![coordJ-3]!['enabled'] = true;

                                                _properties[coordI]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : cen,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : propsDec['text'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI-3]![coordJ]!['enabled'] = true;

                                                _properties[coordI-2]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : cen,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }else{
                                                _properties[coordI+3]![coordJ]!['enabled'] = true;

                                                _properties[coordI+2]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : img,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : cen,
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "text" : text,
                                                  "enabled" : false,
                                                  "used" : true
                                                };

                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : propsDec['image'],
                                                  "type" : propsDec['type'],
                                                  "data" : propsDec['data'],
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                              }
                                            }

                                            _historial.add({
                                              "ducto": {
                                                "i": "$coordI",
                                                "j": "$coordJ"
                                              }
                                            });
                                          }else if(tipoMov.contains("Codo")){
                                            final valMov = val[tipoMov];
                                            final decoded = jsonDecode(valMov!);

                                            _codosInstalados[tipoMov] = {};
                                            decoded.forEach((key, value){
                                              _codosInstalados[tipoMov]![key] = value;
                                            });

                                            final props = val["props"];
                                            final propsDec = jsonDecode(props!);
                                            final dir = propsDec["type"];

                                            if(dir == "der"){
                                              _properties[coordI]![coordJ+1]!["enabled"] = true;
                                            }else if(dir == "izq"){
                                              _properties[coordI]![coordJ-1]!["enabled"] = true;
                                            }else if(dir == "arr"){
                                              _properties[coordI-1]![coordJ]!["enabled"] = true;
                                            }else{
                                              _properties[coordI+1]![coordJ]!["enabled"] = true;
                                            }

                                            _properties[coordI]![coordJ] = {
                                              "color" : Colors.transparent,
                                              "image" : propsDec['image'],
                                              "type" : propsDec['type'],
                                              "data" : propsDec['data'],
                                              "text" : propsDec['text'],
                                              "enabled" : false,
                                              "used" : true
                                            };
                                            _numCodosPuestos++;
                                            _historial.add({
                                              "codo": {
                                                "i": "$coordI",
                                                "j": "$coordJ"
                                              }
                                            });
                                          }else if(tipoMov.contains("numRed") || tipoMov.contains("numAmp")){
                                            final valMov = val[tipoMov];

                                            if(tipoMov == "numRed"){
                                              _numRed = int.parse(valMov!);
                                            }else{
                                              _numAmp = int.parse(valMov!);
                                            }

                                            final props = val["props"];
                                            final propsDec = jsonDecode(props!);
                                            List<String> dirArr = propsDec['type'].split("_");

                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];

                                            if(direccion == "hor" && orientacion == "der"){
                                              _properties[coordI]![coordJ+1]!['enabled'] = true;
                                            }else if(direccion == "hor" && orientacion == "izq"){
                                              _properties[coordI]![coordJ-1]!['enabled'] = true;
                                            }else if(direccion == "ver" && orientacion == "arr"){
                                              _properties[coordI-1]![coordJ]!['enabled'] = true;
                                            }else{
                                              _properties[coordI+1]![coordJ]!['enabled'] = true;
                                            }

                                            _properties[coordI]![coordJ] = {
                                              "color" : Colors.transparent,
                                              "image" : propsDec['image'],
                                              "type" : propsDec['type'],
                                              "data" : propsDec['data'],
                                              "text" : propsDec['text'],
                                              "enabled" : false,
                                              "used" : true
                                            };
                                            _historial.add({
                                              "perdida": {
                                                "i": "$coordI",
                                                "j": "$coordJ"
                                              }
                                            });
                                          }else if(tipoMov.contains("Perdida")){
                                            final valMov = val[tipoMov];
                                            final valMovArr = jsonDecode(valMov!);
                                            final Map<String, String> perdConf ={
                                              'perdida': valMovArr['perdida']
                                            };

                                            if(_perdidasAdicionales.isEmpty){
                                              _perdidasAdicionales["Perdida 1"] = perdConf;
                                            }else{
                                              String perdida = _perdidasAdicionales.keys.last;
                                              int numPerdida = int.parse(perdida.split(" ").last);

                                              numPerdida++;

                                              _perdidasAdicionales["Perdida $numPerdida"] = perdConf;
                                            }

                                            final props = val["props"];
                                            final propsDec = jsonDecode(props!);
                                            List<String> dirArr = propsDec['type'].split("_");

                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];

                                            if(direccion == "hor" && orientacion == "der"){
                                              _properties[coordI]![coordJ+1]!['enabled'] = true;
                                            }else if(direccion == "hor" && orientacion == "izq"){
                                              _properties[coordI]![coordJ-1]!['enabled'] = true;
                                            }else if(direccion == "ver" && orientacion == "arr"){
                                              _properties[coordI-1]![coordJ]!['enabled'] = true;
                                            }else{
                                              _properties[coordI+1]![coordJ]!['enabled'] = true;
                                            }

                                            _properties[coordI]![coordJ] = {
                                              "color" : Colors.transparent,
                                              "image" : propsDec['image'],
                                              "type" : propsDec['type'],
                                              "data" : propsDec['data'],
                                              "text" : propsDec['text'],
                                              "enabled" : false,
                                              "used" : true
                                            };
                                            _historial.add({
                                              tipoMov == "numRed" ? "reduccion" : "ampliacion": {
                                                "i": "$coordI",
                                                "j": "$coordJ"
                                              }
                                            });
                                          }else if(tipoMov.contains("CM") || tipoMov.contains("CR")){
                                            final valMov = val[tipoMov];
                                            _finalizado = true;
                                            _movFinDir = valMov!;
                                            _movFinName = tipoMov;

                                            final props = val["props"];
                                            final propsDec = jsonDecode(props!);
                                            List<String> dirArr = propsDec['type'].split("_");

                                            final direccion = dirArr[0];
                                            final orientacion = dirArr[1];
                                            final elemento = _movFinName;

                                            if(tipoMov == "CM" && propsDec['type'] == "hor_izq"){
                                              if(orientacion == "arr"){
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "cont_$_imgSize.png",
                                                  "type" : "izq",
                                                  "data" : "codo",
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_1_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_2_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_3_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_4_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_5_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_6_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                              }else{
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "cont_$_imgSize.png",
                                                  "type" : "izq",
                                                  "data" : "codo",
                                                  "enabled" : false,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_1_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_2_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_3_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_4_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_5_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ-2] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_6_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                              }
                                            }else{
                                              if(direccion == "ver" && orientacion == "arr"){
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_1_$_imgSize.png",
                                                  "type" : "ver_arr",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_2_$_imgSize.png",
                                                  "type" : "ver_arr",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_3_$_imgSize.png",
                                                  "type" : "ver_arr",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_4_$_imgSize.png",
                                                  "type" : "ver_arr",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_5_$_imgSize.png",
                                                  "type" : "ver_arr",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_6_$_imgSize.png",
                                                  "type" : "ver_arr",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                              }else if(direccion == "hor" && orientacion == "der"){
                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_3_$_imgSize.png",
                                                  "type" : "hor_der",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_2_$_imgSize.png",
                                                  "type" : "hor_der",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_1_$_imgSize.png",
                                                  "type" : "hor_der",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_6_$_imgSize.png",
                                                  "type" : "hor_der",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_5_$_imgSize.png",
                                                  "type" : "hor_der",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_4_$_imgSize.png",
                                                  "type" : "hor_der",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                              }else if(direccion == "hor" && orientacion == "izq"){
                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_1_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_2_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_3_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_4_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_5_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI-1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_hor_6_$_imgSize.png",
                                                  "type" : "hor_izq",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                              }else{
                                                _properties[coordI]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_1_$_imgSize.png",
                                                  "type" : "ver_aba",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_2_$_imgSize.png",
                                                  "type" : "ver_aba",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_3_$_imgSize.png",
                                                  "type" : "ver_aba",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ-1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_4_$_imgSize.png",
                                                  "type" : "ver_aba",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_5_$_imgSize.png",
                                                  "type" : "ver_aba",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                                _properties[coordI+1]![coordJ+1] = {
                                                  "color" : Colors.transparent,
                                                  "image" : "${elemento}_ver_6_$_imgSize.png",
                                                  "type" : "ver_aba",
                                                  "data" : "final",
                                                  "enabled" : true,
                                                  "used" : true
                                                };
                                              }
                                            }
                                            _historial.add({
                                              "final": {
                                                "i": "$coordI",
                                                "j": "$coordJ"
                                              }
                                            });
                                          }

                                          _historialRe.removeLast();
                                          _movHistorial++;
                                          _movHistRe--;
                                          setState(() {});
                                        } : null,
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Icon(
                                                Icons.save,
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                size: 48.0,
                                              ),
                                            ),
                                            Text(
                                              "Guardar",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _movHistorial > 0 ? () async{
                                          final historial = jsonEncode(_historial);
                                          List<String> propertiesMap = [];
                                          Fluttertoast.showToast(
                                            msg: "Guardando proyecto...",
                                            toastLength: Toast.LENGTH_SHORT,
                                            timeInSecForIosWeb: 2,
                                            gravity: ToastGravity.CENTER,
                                            webBgColor: "linear-gradient(to right, #888888, #cccccc)",
                                          );
                                          _properties.forEach((key, value) {
                                            value.forEach((key0, value0) {
                                              value0.forEach((key1, value1) {
                                                if(key1 == "color"){
                                                  final colorInt = value1.value;
                                                  propertiesMap.add("$key=>$key0=>$key1=>$colorInt");
                                                }else{
                                                  propertiesMap.add("$key=>$key0=>$key1=>$value1");
                                                }
                                              });
                                            });
                                          });

                                          final tramosRectos = jsonEncode(_tramosRectos);
                                          final codosInstalados = jsonEncode(_codosInstalados);
                                          final perdidasAdicionales = jsonEncode(_perdidasAdicionales);

                                          final properties = jsonEncode(propertiesMap);

                                          Map<String, Map<String, String>> datos = {
                                            "datos": {
                                              "tipoInstalacion" : _tipoInstalacion,
                                              "tipoCampana" : _tipoCampana,
                                              "eqCocina" : _eqCocina,
                                              "longitud" : _longitud,
                                              "ancho" : _ancho,
                                              "distCapt" : _distCapt,
                                              "caudalEx" : _caudalEx,
                                              "cauInySug" : _cauInySug,
                                              "velAire" : _velAire,
                                              "ductoCuadradoCM" : _ductoCuadradoCM,
                                              "ductoCuadradoIN" : _ductoCuadradoIN,
                                              "ductoCircularCM" : _ductoCircularCM,
                                              "ductoCircularIN" : _ductoCircularIN,
                                              "ductoSeleccion" : _ductoSeleccion,
                                              "unidadesInstalado" : _unidadDucto
                                            },
                                            "campana": {
                                              "salidas": "$_numSalidasSelec",
                                              "codos": "$_numCodosConf"
                                            },
                                            "cuadricula": {
                                              "historial" : historial,
                                              "properties": properties,
                                              "tramosRectos": tramosRectos,
                                              "codosInstalados": codosInstalados,
                                              "perdidasAdicionales": perdidasAdicionales,
                                              "reducciones": "$_numRed",
                                              "ampliaciones": "$_numAmp"
                                            },
                                            "calculos": {
                                              "resultados": _jsonCalculos
                                            }
                                          };

                                          String infoStr = jsonEncode(datos);
                                          final guardado = await _guardarProyecto(infoStr, _finalizado ? "F" : "D", widget.archpdf);
                                          Fluttertoast.showToast(
                                            msg: guardado ? "El proyecto se guardó correctamente" : "Hubo un error al guardar el proyecto",
                                            toastLength: Toast.LENGTH_SHORT,
                                            timeInSecForIosWeb: 2,
                                            gravity: ToastGravity.CENTER,
                                            webBgColor: guardado ? "linear-gradient(to right, #266B1F, #98F58F)" : "linear-gradient(to right, #b40404, #ff0000)",
                                          );
                                        } : null,
                                      ),
                                    )
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              SizedBox(
                                child: Text(
                                  "Acciones",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                width: double.infinity,
                              ),
                            ],
                          ),
                        ),
                        VerticalDivider(color: _claro ? Colors.black38 : Colors.white54),
                        SizedBox(
                          width: 232.0,
                          child: Column(
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Icon(
                                                Icons.picture_as_pdf,
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                size: 48.0,
                                              ),
                                            ),
                                            Text(
                                              "PDF",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: !_finalizado ? null : () async{
                                          final historial = jsonEncode(_historial);
                                          List<String> propertiesMap = [];

                                          Fluttertoast.showToast(
                                            msg: "Generando PDF...",
                                            toastLength: Toast.LENGTH_SHORT,
                                            timeInSecForIosWeb: 3,
                                            gravity: ToastGravity.CENTER,
                                            webBgColor: "linear-gradient(to right, #888888, #cccccc)",
                                          );

                                          _properties.forEach((key, value) {
                                            value.forEach((key0, value0) {
                                              value0.forEach((key1, value1) {
                                                if(key1 == "color"){
                                                  final colorInt = value1.value;
                                                  propertiesMap.add("$key=>$key0=>$key1=>$colorInt");
                                                }else{
                                                  propertiesMap.add("$key=>$key0=>$key1=>$value1");
                                                }
                                              });
                                            });
                                          });

                                          final tramosRectos = jsonEncode(_tramosRectos);
                                          final codosInstalados = jsonEncode(_codosInstalados);
                                          final perdidasAdicionales = jsonEncode(_perdidasAdicionales);

                                          final properties = jsonEncode(propertiesMap);

                                          Map<String, Map<String, String>> datos = {
                                            "datos": {
                                              "tipoInstalacion" : _tipoInstalacion,
                                              "tipoCampana" : _tipoCampana,
                                              "eqCocina" : _eqCocina,
                                              "longitud" : _longitud,
                                              "ancho" : _ancho,
                                              "distCapt" : _distCapt,
                                              "caudalEx" : _caudalEx,
                                              "cauInySug" : _cauInySug,
                                              "velAire" : _velAire,
                                              "ductoCuadradoCM" : _ductoCuadradoCM,
                                              "ductoCuadradoIN" : _ductoCuadradoIN,
                                              "ductoCircularCM" : _ductoCircularCM,
                                              "ductoCircularIN" : _ductoCircularIN,
                                              "ductoSeleccion" : _ductoSeleccion,
                                              "unidadesInstalado" : _unidadDucto
                                            },
                                            "campana": {
                                              "salidas": "$_numSalidasSelec",
                                              "codos": "$_numCodosConf"
                                            },
                                            "cuadricula": {
                                              "historial" : historial,
                                              "properties": properties,
                                              "tramosRectos": tramosRectos,
                                              "codosInstalados": codosInstalados,
                                              "perdidasAdicionales": perdidasAdicionales,
                                              "reducciones": "$_numRed",
                                              "ampliaciones": "$_numAmp"
                                            },
                                            "calculos": {
                                              "resultados": _jsonCalculos
                                            }
                                          };

                                          String infoStr = jsonEncode(datos);
                                          _takeScreenshot();

                                          //final img = await _screenshotController.capture();
                                          final img = await _takeScreenshot();
                                          final imgb64 = base64Encode(img);

                                          final datosStr = jsonEncode(datos);
                                          //final infoEntrada = base64Encode(utf8.encode(widget.info.toString()));
                                          final infoEntrada = base64Encode(utf8.encode(datosStr));
                                          final infoCalculo = base64Encode(utf8.encode(_jsonCalculos));

                                          final ruta = {
                                            "idUsuario": widget.idUsuario,
                                            "idProyecto": widget.idProyecto,
                                            "noProyecto": widget.noProyecto
                                          };
                                          final rutab64 = base64Encode(utf8.encode(jsonEncode(ruta)));

                                          final infoPDF = base64Encode(utf8.encode(jsonEncode({
                                            "infoEntrada" : infoEntrada,
                                            "infoCalculo" : infoCalculo,
                                            "imagen" : imgb64,
                                            "ruta": rutab64
                                          })));
                                          String archpdf = "";

                                          final urlArch = await _pdfProvider.fetchAtenuador(infoPDF, 'campana');
                                          archpdf = urlArch;

                                          html.AnchorElement anchorElement = html.AnchorElement(href: archpdf);
                                          anchorElement.download = archpdf;
                                          anchorElement.target = "_blank";
                                          anchorElement.click();

                                          final guardado = await _guardarProyecto(infoStr, _finalizado ? "F" : "D", archpdf);
                                          Fluttertoast.showToast(
                                            msg: guardado ? "El proyecto se guardó correctamente" : "Hubo un error al guardar el proyecto",
                                            toastLength: Toast.LENGTH_SHORT,
                                            timeInSecForIosWeb: 2,
                                            gravity: ToastGravity.CENTER,
                                            webBgColor: guardado ? "linear-gradient(to right, #266B1F, #98F58F)" : "linear-gradient(to right, #b40404, #ff0000)",
                                          );
                                        },
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Icon(
                                                _confActivada ? Icons.calculate : Icons.settings,
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                size: 48.0,
                                              ),
                                            ),
                                            Text(
                                              _confActivada ? "Cálculos" : "Configuración",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: () => setState(() => _confActivada = !_confActivada),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Icon(
                                                Icons.close,
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                size: 48.0,
                                              ),
                                            ),
                                            Text(
                                              "Salir",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: () async{
                                          final salir = await showDialog(
                                            context: context,
                                            barrierDismissible: false,
                                            builder: (context) => AlertDialog(
                                              title: const Text("Salir del proyecto"),
                                              content: Text(
                                                "Antes de salir asegurate de guardar todos los cambios\n\n¿Deseas continuar?",
                                                textAlign: TextAlign.center,
                                                style: GoogleFonts.roboto(),
                                              ),
                                              actions: [
                                                TextButton(
                                                  child: const Text("Si"),
                                                  onPressed: () => Navigator.pop(context, true),
                                                ),
                                                TextButton(
                                                  child: const Text("No"),
                                                  onPressed: () => Navigator.pop(context, false),
                                                )
                                              ],
                                            ),
                                          );

                                          if(salir) Navigator.pop(context, "inicio");
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              SizedBox(
                                child: Text(
                                  "Operaciones",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                width: double.infinity,
                              )
                            ],
                          ),
                        ),
                        VerticalDivider(color: _claro ? Colors.black38 : Colors.white54),
                        SizedBox(
                          width: 392.0,
                          child: Column(
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado || _numCodosConf == _numCodosPuestos ? "cont_des.png" : "cont_xl.png"),
                                            ),
                                            Text(
                                              "Continuo",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado || _numCodosConf == _numCodosPuestos ? null : () => setState((){
                                          _nombreElemento = "Codo Continuo";
                                          _dataDrag = "codo";
                                          _colorDrag = Colors.blue;
                                          _tipoDataDrag = "continuo";
                                        }),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado || _numCodosConf == _numCodosPuestos ? "3pzs_des.png" : "3pzs_xl.png"),
                                            ),
                                            Text(
                                              "3 Piezas",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado || _numCodosConf == _numCodosPuestos ? null : () => setState((){
                                          _nombreElemento = "Codo 3 Piezas";
                                          _dataDrag = "codo";
                                          _colorDrag = Colors.blueAccent;
                                          _tipoDataDrag = "3piezas";
                                        }),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado || _numCodosConf == _numCodosPuestos ? "4pzs_des.png" : "4pzs_xl.png"),
                                            ),
                                            Text(
                                              "4 Piezas",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado || _numCodosConf == _numCodosPuestos ? null : () => setState((){
                                          _nombreElemento = "Codo 4 Piezas";
                                          _dataDrag = "codo";
                                          _colorDrag = Colors.blueGrey;
                                          _tipoDataDrag = "4piezas";
                                        }),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado || _numCodosConf == _numCodosPuestos ? "t_des.png" : "tipoT_xl.png"),
                                            ),
                                            Text(
                                              "Tipo T",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado || _numCodosConf == _numCodosPuestos ? null : () => setState((){
                                          _nombreElemento = "Codo Tipo T";
                                          _dataDrag = "codo";
                                          _colorDrag = Colors.lightBlueAccent;
                                          _tipoDataDrag = "tipoT";
                                        }),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado || _numCodosConf == _numCodosPuestos ? "cruz_des.png" : "cruz_xl.png"),
                                            ),
                                            Text(
                                              "Cruce",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado || _numCodosConf == _numCodosPuestos ? null : () => setState((){
                                          _nombreElemento = "Cruce";
                                          _dataDrag = "codo";
                                          _colorDrag = Colors.transparent;
                                          _tipoDataDrag = "cruz";
                                        }),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              SizedBox(
                                child: Text(
                                  "Codos",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                width: double.infinity,
                              )
                            ],
                          ),
                        ),
                        VerticalDivider(color: _claro ? Colors.black38 : Colors.white54),
                        SizedBox(
                          width: 232.0,
                          child: Column(
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado || _numRed == 0 ? "ducto_red_des.png" : "ducto_red_xl.png"),
                                            ),
                                            Text(
                                              "Reducido",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : _numRed > 0 ? () => setState((){
                                          _nombreElemento = "Ducto Reducido";
                                          _dataDrag = "ducto";
                                          _colorDrag = Colors.amber;
                                          _tipoDataDrag = "reducido";
                                        }) : null,
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado ? "ducto_des.png" : "ducto_xl.png"),
                                            ),
                                            Text(
                                              "Estándar",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : () => setState((){
                                          _nombreElemento = "Ducto ${_ductoSeleccion == "cuadrado" ? "Cuadrado" : "Circular"}";
                                          _dataDrag = "ducto";
                                          _colorDrag = Colors.amber;
                                          _tipoDataDrag = "Cuadrado";
                                        }),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado || _numAmp == 0 ? "ducto_amp_des.png" : "ducto_amp_xl.png"),
                                            ),
                                            Text(
                                              "Ampliado",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : _numAmp > 0 ? () => setState((){
                                          _nombreElemento = "Ducto Ampliado";
                                          _dataDrag = "ducto";
                                          _colorDrag = Colors.amber;
                                          _tipoDataDrag = "ampliado";
                                        }) : null,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              SizedBox(
                                child: Text(
                                  "Ductos",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                width: double.infinity,
                              )
                            ],
                          ),
                        ),
                        VerticalDivider(color: _claro ? Colors.black38 : Colors.white54),
                        SizedBox(
                          width: 232.0,
                          child: Column(
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado ? "red_des.png" : "red_xl.png"),
                                            ),
                                            Text(
                                              "Reducción",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : () => setState((){
                                          _nombreElemento = "Reducción";
                                          _dataDrag = "reduccion";
                                          _colorDrag = Colors.transparent;
                                          _tipoDataDrag = "";
                                        }),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado ? "amp_des.png" : "amp_xl.png"),
                                            ),
                                            Text(
                                              "Ampliación",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : () => setState((){
                                          _nombreElemento = "Ampliación";
                                          _dataDrag = "ampliacion";
                                          _colorDrag = Colors.transparent;
                                          _tipoDataDrag = "";
                                        }),
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset(_finalizado ? "filtro_des.png" : "filtro_xl.png"),
                                            ),
                                            Text(
                                              "Compuerta",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : () => setState((){
                                          _nombreElemento = "Compuerta Corta Fuegos";
                                          _dataDrag = "filtro";
                                          _colorDrag = Colors.transparent;
                                          _tipoDataDrag = "";
                                        }),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              SizedBox(
                                child: Text(
                                  "Accesorios",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                width: double.infinity,
                              )
                            ],
                          ),
                        ),
                        VerticalDivider(color: _claro ? Colors.black38 : Colors.white54),
                        SizedBox(
                          width: 256.0,
                          child: Column(
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset("CRVL-D.png"),
                                            ),
                                            Text(
                                              "CRV",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : _movHistorial > 0 ? () => setState((){
                                          _nombreElemento = "CRVL-D";
                                          _dataDrag = "final";
                                          _colorDrag = Colors.transparent;
                                          _tipoDataDrag = "";
                                        }) : null,
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset("CRWL-D.png"),
                                            ),
                                            Text(
                                              "CRW",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : _movHistorial > 0 ? () => setState((){
                                          _nombreElemento = "CRWL-D";
                                          _dataDrag = "final";
                                          _colorDrag = Colors.transparent;
                                          _tipoDataDrag = "";
                                        }) : null,
                                      ),
                                    ),
                                    const SizedBox(width: 8.0),
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Image.asset("CM.png"),
                                            ),
                                            Text(
                                              "CM",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: _finalizado ? null : _movHistorial > 0 ? () => setState((){
                                          _nombreElemento = "CM";
                                          _dataDrag = "final";
                                          _colorDrag = Colors.transparent;
                                          _tipoDataDrag = "";
                                        }) : null,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              SizedBox(
                                child: Text(
                                  "Productos S&P",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                width: double.infinity,
                              )
                            ],
                          ),
                        ),
                        VerticalDivider(color: _claro ? Colors.black38 : Colors.white54,),
                        SizedBox(
                          width: 72.0,
                          child: Column(
                            children: [
                              Expanded(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: TextButton(
                                        child: Column(
                                          children: [
                                            Expanded(
                                              child: Icon(
                                                _claro ? Icons.lightbulb : Icons.lightbulb_outline,
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                size: 48.0,
                                              ),
                                            ),
                                            Text(
                                              _claro ? "Claro" : "Oscuro",
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            )
                                          ],
                                        ),
                                        onPressed: () => setState((){
                                          _claro = !_claro;
                                          _colorCuad = _claro ? Colors.black : Colors.white;
                                          _colorCuadIn = _claro ? Colors.black26 : Colors.white54;
                                        }),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              SizedBox(
                                child: Text(
                                  "Tema",
                                  textAlign: TextAlign.center,
                                  style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                width: double.infinity,
                              )
                            ],
                          ),
                        ),
                        VerticalDivider(color: _claro ? Colors.black38 : Colors.white54,),
                      ],
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    width: width,
                    height: height - 128.0,
                    alignment: Alignment.center,
                    child: Row(
                      children: [
                        Container(
                          width: width/3,
                          padding: const EdgeInsets.fromLTRB(8.0, 0.0, 0.0, 0.0),
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                const SizedBox(height: 8.0),
                                SizedBox(
                                  child: Text(
                                    "Vista ${tipoCampanaStr == "Adosada3Paredes" ? "frontal" : "isométrica"} de la campana",
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.roboto(
                                      color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18.0,
                                    ),
                                  ),
                                  width: width/3,
                                ),
                                const SizedBox(height: 8.0),
                                Expanded(
                                  child: Image.asset("$tipoCampanaUso.png"),
                                ),
                                const SizedBox(height: 8.0),
                                SizedBox(
                                  child: Text(
                                    "Vista aérea de la campana",
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.roboto(
                                      color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18.0,
                                    ),
                                  ),
                                  width: width/3,
                                ),
                                const SizedBox(height: 8.0),
                                SizedBox(
                                  child: Image.asset("$aerea.png"),
                                  width: width/3,
                                ),
                                const SizedBox(height: 8.0),
                              ],
                            ),
                          ),
                          height: double.infinity,
                        ),
                        Container(
                          width: width - width/3 - width/5,
                          child: SingleChildScrollView(
                            scrollDirection: Axis.horizontal,
                            child: RepaintBoundary(
                              key: _scrKey,
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: columnChildren,
                              ),
                            ),
                          ),
                          alignment: Alignment.center,
                        ),
                        Container(
                          width: width/5,
                          height: double.infinity,
                          padding: const EdgeInsets.only(right: 8.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              const SizedBox(height: 8.0),
                              Text(
                                _nombreElemento.isEmpty ? "Seleccione un elemento de la barra para comenzar" : "Arrastre el elemento a la posición en la que desee colocarlo.",
                                textAlign: TextAlign.center,
                                style: GoogleFonts.roboto(
                                  color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 18.0,
                                ),
                              ),
                              const SizedBox(height: 8.0),
                              Text(
                                _nombreElemento,
                                textAlign: TextAlign.center,
                                style: GoogleFonts.roboto(
                                  color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16.0,
                                ),
                              ),
                              const SizedBox(height: 8.0),
                              AnimatedCrossFade(
                                firstChild: Container(),
                                secondChild: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Draggable<String>(
                                      data: _dataDrag,
                                      child: AnimatedContainer(
                                        duration: const Duration(milliseconds: 250),
                                        decoration: BoxDecoration(
                                          color: _nombreElemento.contains("Codo") ? Colors.transparent : _nombreElemento.contains("Ducto") ? Colors.transparent : _colorDrag,
                                          borderRadius: BorderRadius.circular(_campRad),
                                        ),
                                        width: squareSize,
                                        height: squareSize,
                                        child: _nombreElemento.contains("Codo") ? Image.asset(
                                          _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "90°" ? "cont_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "90°" ? "3pzs_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "90°" ? "4pzs_$_imgSize.png"
                                              : _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "45°" ? "cont_45_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "45°" ? "3pzs_45_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "45°" ? "4pzs_45_$_imgSize.png"
                                              : _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "Ampliado" ? "cont_amp_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "Ampliado" ? "3pzs_amp_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "Ampliado" ? "4pzs_amp_$_imgSize.png"
                                              : _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "Reducido" ? "cont_red_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "Reducido" ? "3pzs_red_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "Reducido" ? "4pzs_red_$_imgSize.png"
                                              : "tipoT_$_imgSize.png",
                                        ) : _nombreElemento.contains("Ducto") ? Image.asset(
                                          _nombreElemento == "Ducto Reducido" ? "ducto_red_$_imgSize.png"
                                              : _nombreElemento == "Ducto Ampliado" ? "ducto_amp_$_imgSize.png"
                                              : "ducto_$_imgSize.png",
                                        ) : _nombreElemento.contains("Reducción") ? Image.asset("red_$_imgSize.png")
                                          : _nombreElemento.contains("Ampliación") ? Image.asset("amp_$_imgSize.png")
                                          : _nombreElemento.contains("Compuerta Corta Fuegos") ? Image.asset("filtro_$_imgSize.png")
                                          : _nombreElemento.contains("CM") ? Image.asset("CM.png")
                                          : _nombreElemento.contains("CRVL-D") ? Image.asset("CRVL-D.png")
                                          : _nombreElemento.contains("CRWL-D") ? Image.asset("CRWL-D.png")
                                          : _nombreElemento.contains("Cruce") ? Image.asset("cruz_$_imgSize.png") : Container(),
                                      ),
                                      feedback: AnimatedContainer(
                                        duration: const Duration(milliseconds: 250),
                                        decoration: BoxDecoration(
                                          color: _nombreElemento.contains("Codo") ? Colors.transparent : _nombreElemento.contains("Ducto") ? Colors.transparent : _colorDrag,
                                          borderRadius: BorderRadius.circular(_campRad),
                                        ),
                                        width: squareSize,
                                        height: squareSize,
                                        child: _nombreElemento.contains("Codo") ? Image.asset(
                                          _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "90°" ? "cont_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "90°" ? "3pzs_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "90°" ? "4pzs_$_imgSize.png"
                                              : _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "45°" ? "cont_45_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "45°" ? "3pzs_45_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "45°" ? "4pzs_45_$_imgSize.png"
                                              : _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "Ampliado" ? "cont_amp_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "Ampliado" ? "3pzs_amp_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "Ampliado" ? "4pzs_amp_$_imgSize.png"
                                              : _nombreElemento == "Codo Continuo" && _codosTipos[_indexCodos] == "Reducido" ? "cont_red_$_imgSize.png"
                                              : _nombreElemento == "Codo 3 Piezas" && _codosTipos[_indexCodos] == "Reducido" ? "3pzs_red_$_imgSize.png"
                                              : _nombreElemento == "Codo 4 Piezas" && _codosTipos[_indexCodos] == "Reducido" ? "4pzs_red_$_imgSize.png"
                                              : "tipoT_$_imgSize.png",
                                        ) : _nombreElemento.contains("Ducto") ? Image.asset(
                                          _nombreElemento == "Ducto Reducido" ? "ducto_red_$_imgSize.png"
                                              : _nombreElemento == "Ducto Ampliado" ? "ducto_amp_$_imgSize.png"
                                              : "ducto_$_imgSize.png"
                                        ) : _nombreElemento.contains("Ducto") ? Image.asset("ducto_$_imgSize.png")
                                          : _nombreElemento.contains("Reducción") ? Image.asset("red_$_imgSize.png")
                                          : _nombreElemento.contains("Ampliación") ? Image.asset("amp_$_imgSize.png")
                                          : _nombreElemento.contains("Compuerta Corta Fuegos") ? Image.asset("filtro_$_imgSize.png")
                                          : _nombreElemento.contains("CM") ? Image.asset("CM.png")
                                          : _nombreElemento.contains("CRVL-D") ? Image.asset("CRVL-D.png")
                                          : _nombreElemento.contains("CRWL-D") ? Image.asset("CRWL-D.png")
                                          : _nombreElemento.contains("Cruce") ? Image.asset("cruz_$_imgSize.png") : Container(),
                                      ),
                                      childWhenDragging: Container(
                                        width: squareSize,
                                        height: squareSize,
                                        color: Colors.white24,
                                      ),
                                      onDragEnd: (details) => setState(() => _campRad = 0.0),
                                      maxSimultaneousDrags: 1,
                                    ),
                                    const SizedBox(height: 8.0),
                                    if(_dataDrag == "codo" && _nombreElemento != "Codo Tipo T" && _nombreElemento != "Cruce")
                                      Row(
                                        children: [
                                          IconButton(
                                            icon: Icon(
                                              Icons.chevron_left,
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                            ),
                                            onPressed: () => setState((){
                                              if(_numRed > 0 && _numAmp == 0){
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 1;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 3;
                                                    break;
                                                  case 3:
                                                    _indexCodos = 0;
                                                    break;
                                                }
                                              }else if(_numRed == 0 && _numAmp > 0){
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 1;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 2;
                                                    break;
                                                  case 2:
                                                    _indexCodos = 0;
                                                    break;
                                                }
                                              }else if(_numRed > 0 && _numAmp > 0){
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 1;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 2;
                                                    break;
                                                  case 2:
                                                    _indexCodos = 3;
                                                    break;
                                                  case 3:
                                                    _indexCodos = 0;
                                                    break;
                                                }
                                              }else{
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 1;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 0;
                                                    break;
                                                }
                                              }
                                            }),
                                          ),
                                          const SizedBox(width: 8.0),
                                          AnimatedContainer(
                                            duration: const Duration(milliseconds: 250),
                                            child: Text(
                                              _codosTipos[_indexCodos],
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                                fontSize: 16.0,
                                                fontWeight: FontWeight.bold,
                                              ),
                                            ),
                                          ),
                                          const SizedBox(width: 8.0),
                                          IconButton(
                                            icon: Icon(
                                              Icons.chevron_right,
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                            ),
                                            onPressed: () => setState((){
                                              if(_numRed > 0 && _numAmp == 0){
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 3;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 0;
                                                    break;
                                                  case 3:
                                                    _indexCodos = 1;
                                                    break;
                                                }
                                              }else if(_numRed == 0 && _numAmp > 0){
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 2;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 0;
                                                    break;
                                                  case 2:
                                                    _indexCodos = 1;
                                                    break;
                                                }
                                              }else if(_numRed > 0 && _numAmp > 0){
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 3;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 0;
                                                    break;
                                                  case 2:
                                                    _indexCodos = 1;
                                                    break;
                                                  case 3:
                                                    _indexCodos = 2;
                                                    break;
                                                }
                                              }else{
                                                switch(_indexCodos){
                                                  case 0:
                                                    _indexCodos = 1;
                                                    break;
                                                  case 1:
                                                    _indexCodos = 0;
                                                    break;
                                                }
                                              }
                                            }),
                                          ),
                                        ],
                                        mainAxisAlignment: MainAxisAlignment.center,
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                      ),
                                    if(_dataDrag == "codo" && _nombreElemento != "Codo Tipo T")
                                      const SizedBox(height: 8.0),
                                  ],
                                ),
                                duration: const Duration(milliseconds: 250),
                                crossFadeState: _nombreElemento.isEmpty ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                              ),
                              Text(
                                "Filtro inercial de grasa",
                                textAlign: TextAlign.center,
                                style: GoogleFonts.roboto(
                                  color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                  fontWeight: FontWeight.bold,
                                  fontSize: 18.0,
                                ),
                              ),
                              const SizedBox(height: 8.0),
                              DropdownButton<String>(
                                value: _campFiltGrasa.isEmpty ? null : _campFiltGrasa,
                                hint: Text(
                                  "Selecciona una opción.",
                                  style: GoogleFonts.roboto(
                                    color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                    fontStyle: FontStyle.italic,
                                  ),
                                ),
                                onChanged: (newValue) => setState(() => _campFiltGrasa = newValue!),
                                items: <String>["Si", "No"].map((e) => DropdownMenuItem<String>(
                                  child: Text(
                                    e,
                                    style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                  ),
                                  value: e,
                                )).toList(),
                                dropdownColor: _claro ? _colorFondoCuadrC : _colorFondoCuadrO,
                                icon: Icon(
                                  Icons.arrow_drop_down,
                                  color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                ),
                              ),
                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  Text(
                                    "Número de tomas de extracción:",
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.roboto(
                                      color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18.0,
                                    ),
                                  ),
                                  const SizedBox(width: 8.0),
                                  Expanded(
                                    child: Container(
                                      decoration: BoxDecoration(
                                        border: Border(
                                          bottom: BorderSide(
                                            color: _claro ? Colors.black54 : Colors.white60,
                                            width: 2.0,
                                          ),
                                        ),
                                      ),
                                      child: Row(
                                        children: [
                                          IconButton(
                                            icon: Icon(
                                              Icons.remove,
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                            ),
                                            onPressed: _numSalidasSelec > 1 ? () async{
                                              final continuar = await showDialog(
                                                context: context,
                                                barrierDismissible: false,
                                                builder: (context) => AlertDialog(
                                                  title: const Text("Alerta"),
                                                  content: Text(
                                                    "Esta acción eliminará los cambios realizados en su dibujo\n¿Desea continuar?",
                                                    textAlign: TextAlign.center,
                                                    style: GoogleFonts.roboto(),
                                                  ),
                                                  actions: [
                                                    TextButton(
                                                      child: const Text("Aceptar"),
                                                      onPressed: () => Navigator.pop(context, true),
                                                    ),
                                                    TextButton(
                                                      child: const Text("Cancelar"),
                                                      onPressed: () => Navigator.pop(context, false),
                                                    ),
                                                  ],
                                                ),
                                              );

                                              if(!continuar) return;
                                              int salAnt = _numSalidasSelec;
                                              int value = _numSalidasSelec - 1;
                                              _cambiarSalidas(value, salAnt);
                                            } : null,
                                          ),
                                          Expanded(
                                            child: Text(
                                              "$_numSalidasSelec",
                                              textAlign: TextAlign.center,
                                              style: GoogleFonts.roboto(
                                                color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              ),
                                            ),
                                          ),
                                          IconButton(
                                            icon: Icon(
                                              Icons.add,
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                            ),
                                            onPressed: _numSalidasSelec < 3 ? () async{
                                              final continuar = await showDialog(
                                                context: context,
                                                barrierDismissible: false,
                                                builder: (context) => AlertDialog(
                                                  title: const Text("Alerta"),
                                                  content: Text(
                                                    "Esta acción eliminará los cambios realizados en su dibujo\n¿Desea continuar?",
                                                    textAlign: TextAlign.center,
                                                    style: GoogleFonts.roboto(),
                                                  ),
                                                  actions: [
                                                    TextButton(
                                                      child: const Text("Aceptar"),
                                                      onPressed: () => Navigator.pop(context, true),
                                                    ),
                                                    TextButton(
                                                      child: const Text("Cancelar"),
                                                      onPressed: () => Navigator.pop(context, false),
                                                    ),
                                                  ],
                                                ),
                                              );

                                              if(!continuar) return;
                                              int salAnt = _numSalidasSelec;
                                              int value = _numSalidasSelec + 1;
                                              _cambiarSalidas(value, salAnt);
                                            } : null,
                                          ),
                                        ],
                                      ),
                                    ),
                                  )
                                ],
                              ),
                              const SizedBox(height: 8.0),
                              Row(
                                children: [
                                  Text(
                                    "Número de codos configurados:",
                                    textAlign: TextAlign.center,
                                    style: GoogleFonts.roboto(
                                      color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 18.0,
                                    ),
                                  ),
                                  const SizedBox(width: 8.0),
                                  Expanded(
                                    child: SpinBox(
                                      min: 1,
                                      max: 99,
                                      value: _numCodosConf.toDouble(),
                                      step: 1,
                                      onChanged: (value) => setState((){
                                        _numCodosConf = value.toInt();
                                        int numCuadAnt = _numCuadriculas;
                                        final properties = _properties;

                                        if(_numCodosConf <= 3){
                                          _numCuadriculas = 10;
                                          _imgSize = "xl";
                                        }else if(_numCodosConf > 3 && _numCodosConf <= 6){
                                          _numCuadriculas = 20;
                                          _imgSize = "la";
                                        }else if(_numCodosConf > 6 && _numCodosConf <= 9){
                                          _numCuadriculas = 30;
                                          _imgSize = "no";
                                        }else if(_numCodosConf > 9 && _numCodosConf <= 12){
                                          _numCuadriculas = 40;
                                          _imgSize = "no";
                                        }else{
                                          _numCuadriculas = 50;
                                          _imgSize = "sm";
                                        }

                                        _numCodosConf = _numCodosConf;
                                        _properties = {};
                                        _rehacerHistorial(numCuadAnt, _numCuadriculas, properties);
                                      }),
                                      incrementIcon: Icon(
                                        Icons.add,
                                        color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      ),
                                      decrementIcon: Icon(
                                        Icons.remove,
                                        color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      ),
                                      decoration: InputDecoration(
                                        border: UnderlineInputBorder(
                                          borderSide: BorderSide(
                                            color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                          ),
                                        ),
                                        enabledBorder: UnderlineInputBorder(
                                          borderSide: BorderSide(
                                            color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                          ),
                                        ),
                                        focusedBorder: UnderlineInputBorder(
                                          borderSide: BorderSide(
                                            color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                          ),
                                        ),
                                      ),
                                      textStyle: GoogleFonts.roboto(
                                        color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      ),
                                    ),
                                  )
                                ],
                              ),
                              const SizedBox(height: 8.0),
                              SizedBox(
                                width: double.infinity,
                                child: RichText(
                                  text: TextSpan(
                                    style: GoogleFonts.roboto(
                                      color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                      fontSize: 18.0,
                                    ),
                                    children: <TextSpan>[
                                      const TextSpan(
                                        text: "Número de codos puestos: ",
                                        style: TextStyle(fontWeight: FontWeight.bold),
                                      ),
                                      TextSpan(text: "$_numCodosPuestos")
                                    ],
                                  ),
                                ),
                              ),
                              const SizedBox(height: 16.0),
                              Expanded(
                                child: SingleChildScrollView(
                                  child: AnimatedCrossFade(
                                    firstChild: Column(
                                      children: [
                                        Text(
                                          "Cálculos",
                                          style: GoogleFonts.roboto(
                                            color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                            fontWeight: FontWeight.bold,
                                            fontSize: 18.0,
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        _childCalc()
                                      ],
                                    ),
                                    secondChild: Column(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        SizedBox(
                                          width: double.infinity,
                                          child: Text(
                                            "Configuración",
                                            textAlign: TextAlign.center,
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontWeight: FontWeight.bold,
                                              fontSize: 18.0,
                                            ),
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Tipo campana: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _tipoCampana)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Equipo de cocina: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _eqCocina)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Longitud: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _longitud)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Ancho: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _ancho)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Distancia de Captación: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _distCapt)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Caudal de Extracción: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _caudalEx)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Caudal de Inyección Sugerida: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _cauInySug)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Velocidad de Aire: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _velAire)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              const TextSpan(
                                                text: "Tipo de Ducto: ",
                                                style: TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _ductoSeleccion == "cuadrado" ? "Cuadrado" : "Circular")
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              TextSpan(
                                                text: _ductoSeleccion == "cuadrado" ? "Medida de Lado del Ducto (cm): " : "Medida del Diámetro del Ducto (cm): ",
                                                style: const TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _ductoSeleccion == "cuadrado" ? _ductoCuadradoCM : _ductoCircularCM)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                        RichText(
                                          text: TextSpan(
                                            style: GoogleFonts.roboto(
                                              color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                              fontSize: 16.0,
                                            ),
                                            children: <TextSpan>[
                                              TextSpan(
                                                text: _ductoSeleccion == "cuadrado" ? "Medida de Lado del Ducto (in): " : "Medida del Diámetro del Ducto (in): ",
                                                style: const TextStyle(fontWeight: FontWeight.bold),
                                              ),
                                              TextSpan(text: _ductoSeleccion == "cuadrado" ? _ductoCuadradoIN : _ductoCircularIN)
                                            ],
                                          ),
                                        ),
                                        const SizedBox(height: 16.0),
                                        Container(
                                          width: double.infinity,
                                          alignment: Alignment.center,
                                          child: ElevatedButton(
                                            onPressed: () async{
                                              final continuar = await showDialog(
                                                context: context,
                                                barrierDismissible: false,
                                                builder: (context) => AlertDialog(
                                                  title: const Text("Alerta"),
                                                  content: Text(
                                                    "Esta acción eliminará los cambios realizados en su dibujo\n¿Desea continuar?",
                                                    textAlign: TextAlign.center,
                                                    style: GoogleFonts.roboto(),
                                                  ),
                                                  actions: [
                                                    TextButton(
                                                      child: const Text("Aceptar"),
                                                      onPressed: () => Navigator.pop(context, true),
                                                    ),
                                                    TextButton(
                                                      child: const Text("Cancelar"),
                                                      onPressed: () => Navigator.pop(context, false),
                                                    ),
                                                  ],
                                                ),
                                              );

                                              if(continuar) Navigator.pop(context, "conf");
                                            },
                                            child: Text(
                                              "Cambiar Configuración",
                                              style: GoogleFonts.roboto(color: _claro ? _colorIconoBarraC : _colorIconoBarraO),
                                            ),
                                            style: ElevatedButton.styleFrom(primary: _claro ? _colorFondoBarraC : _colorFondoBarraO),
                                          ),
                                        ),
                                        const SizedBox(height: 8.0),
                                      ],
                                    ),
                                    duration: const Duration(milliseconds: 250),
                                    crossFadeState: !_confActivada ? CrossFadeState.showFirst : CrossFadeState.showSecond,
                                  ),
                                ),
                              ),
                              Container(
                                width: double.infinity,
                                decoration: BoxDecoration(
                                  border: Border.all(
                                    color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                  ),
                                ),
                                padding: const EdgeInsets.all(8.0),
                                child: RichText(
                                  text: TextSpan(
                                    children: [
                                      TextSpan(
                                        text: "Estado del proyecto: ",
                                        style: GoogleFonts.roboto(
                                          fontWeight: FontWeight.bold,
                                          color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                          fontSize: 16.0,
                                        ),
                                      ),
                                      TextSpan(
                                        text: _finalizado ? "Finalizado" : "Dibujando",
                                        style: GoogleFonts.roboto(
                                          color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
                                          fontSize: 16.0,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                                margin: const EdgeInsets.only(bottom: 8.0),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                )
              ],
            ),
            width: width,
            height: height,
            color: _claro ? _colorFondoCuadrC : _colorFondoCuadrO,
          );
        },
      ),
    );
  }

  Widget _builDragChild(Map<String, dynamic> data, Map<String, int> coords){
    final dataType = data['data'];
    final i = coords['i']!;
    final j = coords['j']!;

    if(dataType == 'campana'){
      return Image.asset(data['image']);
    }

    if(dataType == 'ducto'){
      if(data['type'].contains('ver')){
        return Stack(
          children: [
            Image.asset(data["image"]),
            Container(
              alignment: Alignment.center,
              child: Text(
                data["text"] ?? "",
                style: GoogleFonts.roboto(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 16.0,
                ),
              ),
            ),
          ],
        );
      }else{
        return Stack(
          children: [
            RotatedBox(
              quarterTurns: 1,
              child: Image.asset(data["image"]),
            ),
            Container(
              alignment: Alignment.center,
              child: Text(
                data["text"] ?? "",
                style: GoogleFonts.roboto(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 16.0,
                ),
              ),
            ),
          ],
        );
      }
    }

    if(dataType == 'ampliacion' || dataType == 'reduccion'){
      if(data['type'].contains('ver')){
        if(_properties[i + 1] == null || _properties[i - 1] == null){
          return Image.asset(data["image"]);
        }else{
          final tipoAba = _properties[i + 1]![j]!['image'];
          final tipoArr = _properties[i - 1]![j]!['image'];

          if(tipoAba.contains('_red') || tipoAba.contains('_amp')){
            return RotatedBox(
              quarterTurns: 2,
              child: Image.asset(data["image"]),
            );
          }else if(!tipoArr.contains('_red') || !tipoArr.contains('_amp')){
            final aba = _properties[i + 1]![j]!['used'];
            if(aba){
              return Image.asset(data["image"]);
            }else{
              return RotatedBox(
                quarterTurns: 2,
                child: Image.asset(data["image"]),
              );
            }
          }else{
            return Image.asset(data["image"]);
          }
        }
      }else{
        if(_properties[i]![j + 1] == null || _properties[i]![j - 1] == null){
          return RotatedBox(
            quarterTurns: 1,
            child: Image.asset(data["image"]),
          );
        }else{
          final der = _properties[i]![j + 1]!['used'];
          if(der){
            final tipoDer = _properties[i]![j + 1]!['image'];
            if(tipoDer.contains('_red') || tipoDer.contains('_amp')){
              return RotatedBox(
                quarterTurns: 1,
                child: Image.asset(data["image"]),
              );
            }else{
              return RotatedBox(
                quarterTurns: 3,
                child: Image.asset(data["image"]),
              );
            }
          }else{
            final tipoIzq = _properties[i]![j - 1]!['image'];
            if(tipoIzq.contains('_red') || tipoIzq.contains('_amp')){
              return RotatedBox(
                quarterTurns: 3,
                child: Image.asset(data["image"]),
              );
            }else{
              return RotatedBox(
                quarterTurns: 1,
                child: Image.asset(data["image"]),
              );
            }
          }
        }
      }
    }

    if(dataType == 'filtro'){
      final text = data["text"] ?? "";
      if(data['type'].contains('ver')){
        return Stack(
          children: [
            Image.asset(data["image"]),
            Container(
              alignment: Alignment.center,
              child: Text(
                text,
                textAlign: TextAlign.center,
                style: GoogleFonts.roboto(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 16.0,
                ),
              ),
            ),
          ],
        );
      }else{
        return Stack(
          children: [
            RotatedBox(
              quarterTurns: 1,
              child: Image.asset(data["image"]),
            ),
            Container(
              alignment: Alignment.center,
              child: Text(
                text,
                textAlign: TextAlign.center,
                style: GoogleFonts.roboto(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 16.0,
                ),
              ),
            ),
          ],
        );
      }
    }

    if(dataType == 'codo'){
      if(_properties[i]![j]!['image'].contains('cruz')){
        return Image.asset(_properties[i]![j]!["image"]);
      }else{
        final direccion = data['type'];
        final text = data['text'] ?? "";
        final izqUsed = _properties[i]![j - 1] == null ? false : _properties[i]![j - 1]!['used'];
        final derUsed = _properties[i]![j + 1] == null ? false : _properties[i]![j + 1]!['used'];
        final arrUsed = _properties[i - 1] == null ? false : _properties[i - 1]![j]!['used'];
        final abaUsed = _properties[i + 1] == null ? false : _properties[i + 1]![j]!['used'];

        if(direccion == 'izq'){
          if(arrUsed){
            return Stack(
              children: [
                RotatedBox(
                  quarterTurns: 2,
                  child: Image.asset(_properties[i]![j]!["image"]),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(0.0, 0.0, 16.0, 16.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                )
              ],
            );
          }
          if(abaUsed){
            return Stack(
              children: [
                Transform(
                  alignment: Alignment.center,
                  transform: Matrix4.rotationY(math.pi),
                  child: Image.asset(_properties[i]![j]!["image"]),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(0.0, 16.0, 16.0, 0.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                )
              ],
            );
          }
        }else if(direccion == 'arr'){
          if(izqUsed){
            return Stack(
              children: [
                RotatedBox(
                  quarterTurns: 2,
                  child: Image.asset(_properties[i]![j]!["image"]),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(0.0, 0.0, 16.0, 16.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                )
              ],
            );
          }
          if(derUsed){
            return Stack(
              children: [
                RotatedBox(
                  quarterTurns: 3,
                  child: Image.asset(_properties[i]![j]!["image"]),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(16.0, 0.0, 0.0, 16.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                )
              ],
            );
          }
        }else if(direccion == 'aba'){
          if(izqUsed){
            return Stack(
              children: [
                RotatedBox(
                  quarterTurns: 1,
                  child: Image.asset(_properties[i]![j]!["image"]),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(0.0, 16.0, 16.0, 0.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                )
              ],
            );
          }
          if(derUsed){
            return Stack(
              children: [
                Image.asset(_properties[i]![j]!["image"]),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(16.0, 16.0, 0.0, 0.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                )
              ],
            );
          }
        }else{
          if(arrUsed){
            return Stack(
              children: [
                RotatedBox(
                  quarterTurns: 3,
                  child: Image.asset(_properties[i]![j]!["image"]),
                ),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(16.0, 0.0, 0.0, 16.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                )
              ],
            );
          }
          if(abaUsed){
            return Stack(
              children: [
                Image.asset(_properties[i]![j]!["image"]),
                Container(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.fromLTRB(16.0, 16.0, 0.0, 0.0),
                  child: Text(
                    text,
                    style: GoogleFonts.roboto(
                      color: Colors.white,
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                    ),
                  ),
                ),
              ],
            );
          }
        }
      }
    }

    if(dataType == 'final'){
      return Container(
        child: _properties[i]![j]!["type"] == "hor_der" ? Transform(
          transform: Matrix4.rotationY(math.pi),
          alignment: Alignment.center,
          child: Image.asset(_properties[i]![j]!["image"]),
        ) : _properties[i]![j]!["type"] == "ver_aba" ? RotatedBox(
          quarterTurns: 2,
          child: Image.asset(_properties[i]![j]!["image"]),
        ) : Image.asset(_properties[i]![j]!["image"]),
      );
    }

    return Container();
  }

  void _onAccept(String value, Map<String, int> coords) async{
    final i = coords['i']!;
    final j = coords['j']!;

    final data = _properties[i]![j]!;
    final used = data['used'];

    if(used){
      Fluttertoast.showToast(
        msg: "Este cuadro ya está en uso",
        toastLength: Toast.LENGTH_SHORT,
        timeInSecForIosWeb: 2,
        gravity: ToastGravity.CENTER,
        webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
      );
      return;
    }

    final enabled = data['enabled'];

    if(enabled){
      if(value == 'codo'){
        final aba = _properties[i + 1] == null ? false : _properties[i + 1]![j]!['used'];
        final arr = _properties[i - 1] == null ? false : _properties[i - 1]![j]!['used'];
        final izq = _properties[i]![j - 1] == null ? false : _properties[i]![j - 1]!['used'];
        final der = _properties[i]![j + 1] == null ? false : _properties[i]![j + 1]!['used'];

        bool upDown = arr || aba;
        bool leftRight = izq || der;

        String direccion;
        Map<String, String> tipoCodo = {};

        if(_tipoDataDrag == 'continuo' || _tipoDataDrag == '3piezas' || _tipoDataDrag == '4piezas'){
          direccion = await showDialog(
            context: context,
            barrierDismissible: false,
            builder: (context) => AlertDialog(
              title: const Text("Selecciona la dirección del codo."),
              content: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  if(upDown && _properties[i]![j-1] != null)
                    TextButton(
                      onPressed: () => Navigator.pop(context, "izq"),
                      child: const Text("Izquierda"),
                    ),
                  if(upDown && _properties[i]![j+1] != null)
                    TextButton(
                      onPressed: () => Navigator.pop(context, "der"),
                      child: const Text("Derecha"),
                    ),
                  if(leftRight && _properties[i-1]![j] != null)
                    TextButton(
                      onPressed: () => Navigator.pop(context, "arr"),
                      child: const Text("Arriba"),
                    ),
                  if(leftRight && _properties[i+1]![j] != null)
                    TextButton(
                      onPressed: () => Navigator.pop(context, "aba"),
                      child: const Text("Abajo"),
                    )
                ],
              ),
            ),
          );

          final tipo = _codosTipos[_indexCodos];
          String codoTipo = "";

          if(_tipoDataDrag == 'continuo'){
            if(tipo == '90°' || tipo == 'Ampliado' || tipo == 'Reducido') codoTipo ="cCont";
            if(tipo == '45°') codoTipo ="cCont45";
          }else if(_tipoDataDrag == '3piezas'){
            if(tipo == '90°' || tipo == 'Ampliado' || tipo == 'Reducido') codoTipo ="c3Pzs";
            if(tipo == '45°') codoTipo ="c3Pzs45";
          }else{
            if(tipo == '90°' || tipo == 'Ampliado' || tipo == 'Reducido') codoTipo ="c4Pzs";
            if(tipo == '45°') codoTipo ="c4Pzs45";
          }

          tipoCodo['tipo'] = codoTipo;

          _properties[i]![j]!["type"] = direccion;
          _properties[i]![j]!["text"] = _codosTipos[_indexCodos];

          if(direccion == "izq"){
            _properties[i]![j-1]!["enabled"] = true;
          }else if(direccion == "der"){
            _properties[i]![j+1]!["enabled"] = true;
          }else if(direccion == "arr"){
            _properties[i-1]![j]!["enabled"] = true;
          }else if(direccion == "aba"){
            _properties[i+1]![j]!["enabled"] = true;
          }
        }else if(_tipoDataDrag == "tipoT"){
          if(izq && der){
            direccion = await showDialog(
              context: context,
              barrierDismissible: false,
              builder: (context){
                return AlertDialog(
                  title: const Text("Selecciona la dirección del codo."),
                  content: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextButton(
                        onPressed: () => Navigator.pop(context, "arr"),
                        child: const Text("Arriba"),
                      ),
                      TextButton(
                        onPressed: () => Navigator.pop(context, "aba"),
                        child: const Text("Abajo"),
                      )
                    ],
                  ),
                );
              },
            );

            _properties[i]![j]!["type"] = direccion;

            if(direccion == "arr"){
              _properties[i-1]![j]!["enabled"] = true;
            }else{
              _properties[i+1]![j]!["enabled"] = true;
            }
          }else if(arr && aba){
            direccion = await showDialog(
              context: context,
              barrierDismissible: false,
              builder: (context){
                return AlertDialog(
                  title: const Text("Selecciona la dirección del codo."),
                  content: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextButton(
                        onPressed: () => Navigator.pop(context, "izq"),
                        child: const Text("Izquierda"),
                      ),
                      TextButton(
                        onPressed: () => Navigator.pop(context, "der"),
                        child: const Text("Derecha"),
                      ),
                    ],
                  ),
                );
              },
            );

            _properties[i]![j]!["type"] = direccion;

            if(direccion == "izq"){
              _properties[i]![j-1]!["enabled"] = true;
            }else{
              _properties[i]![j+1]!["enabled"] = true;
            }
          }else if(arr || aba){
            _properties[i]![j-1]!["enabled"] = true;
            _properties[i]![j+1]!["enabled"] = true;
          }else if(der || izq){
            _properties[i-1]![j]!["enabled"] = true;
            _properties[i+1]![j]!["enabled"] = true;
          }

          tipoCodo = {
            "tipoCodo" : "tipoT"
          };
        }else{
          if(!izq) _properties[i]![j-1]!["enabled"] = true;
          if(!der) _properties[i]![j+1]!["enabled"] = true;
          if(!arr) _properties[i-1]![j]!["enabled"] = true;
          if(!izq) _properties[i+1]![j]!["enabled"] = true;

          tipoCodo = {
            "tipoCodo" : "cruz"
          };
        }

        String image = "";
        if(_tipoDataDrag == "continuo") image += "cont_";
        if(_tipoDataDrag == "3piezas") image += "3pzs_";
        if(_tipoDataDrag == "4piezas") image += "4pzs_";
        if(_tipoDataDrag == "tipoT") image += "tipoT_";
        if(_tipoDataDrag == "cruz") image += "cruz_";

        if(_codosTipos[_indexCodos] == '45°') image += "45_";
        if(_codosTipos[_indexCodos] == 'Ampliado') image += "amp_";
        if(_codosTipos[_indexCodos] == 'Reducido') image += "red_";

        image += "$_imgSize.png";

        _properties[i]![j]!["color"] = _colorDrag;
        _properties[i]![j]!["image"] = image;
        _properties[i]![j]!["used"] = true;
        _properties[i]![j]!["enabled"] = true;
        _properties[i]![j]!["data"] = _dataDrag;

        if(_codosInstalados.isEmpty){
          _codosInstalados["Codo 1"] = tipoCodo;
        }else{
          String codo = _codosInstalados.keys.last;
          int numCodo = int.parse(codo.split(" ").last);

          numCodo++;

          _codosInstalados["Codo $numCodo"] = tipoCodo;
        }

        _numCodosPuestos++;
      }

      if(value == 'ducto'){
        bool izq = _properties[i]![j-1] == null ? false : _properties[i]![j-1]!["used"];
        bool der = _properties[i]![j+1] == null ? false : _properties[i]![j+1]!["used"];
        bool arr = _properties[i-1] == null ? false : _properties[i-1]![j]!["used"];
        bool aba = _properties[i+1] == null ? false : _properties[i+1]![j]!["used"];

        Map<String, String> ductoConf = await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context){
            TextEditingController lonTramoRecto = TextEditingController();
            return AlertDialog(
              title: const Text("Ingresa la longitud del tramo recto."),
              content: Row(
                children: [
                  Text(
                    "Longitud:",
                    style: GoogleFonts.roboto(
                      fontWeight: FontWeight.bold,
                      fontSize: 18.0,
                    ),
                  ),
                  const SizedBox(width: 8.0),
                  Expanded(
                    child: TextField(
                      controller: lonTramoRecto,
                      decoration: InputDecoration(
                        hintText: _unidadLongitud == "m" ? "Unidades en metros." : "Unidades en pies.",
                        hintStyle: GoogleFonts.roboto(
                          fontSize: 18.0,
                          fontStyle: FontStyle.italic,
                          color: Colors.grey,
                        ),
                      ),
                      keyboardType: TextInputType.number,
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$'))
                      ],
                    ),
                  ),
                  const SizedBox(width: 8.0),
                  Container(
                    child: Text(
                      _unidadLongitud,
                      style: GoogleFonts.roboto(fontSize: 18.0),
                    ),
                    padding: const EdgeInsets.fromLTRB(0, 0, 24.0, 8.0),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Colors.black.withOpacity(0.18),
                          width: 2.0,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    if(lonTramoRecto.text.isEmpty){
                      Fluttertoast.showToast(
                        msg: "Debes indicar una longitud antes de continuar",
                        toastLength: Toast.LENGTH_SHORT,
                        timeInSecForIosWeb: 2,
                        gravity: ToastGravity.CENTER,
                        webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                      );
                    }else{
                      Navigator.pop(context, {"longitud" : lonTramoRecto.text});
                    }
                  },
                  child: const Text("Aceptar"),
                )
              ],
            );
          },
        );

        double longDouble = double.parse(ductoConf["longitud"]!);
        String ducto = _nombreElemento.contains("Reducido") ? "ducto_red" : _nombreElemento.contains("Ampliado") ? "ducto_amp" : "ducto";

        _properties[i]![j]!["color"] = _colorDrag;
        _properties[i]![j]!["used"] = true;
        _properties[i]![j]!["enabled"] = true;
        _properties[i]![j]!["data"] = _dataDrag;

        if(longDouble <= 1){
          if(izq && j+1 < _numCuadriculas){
            _properties[i]![j]!["type"] = "hor_der";
            _properties[i]![j+1]!["enabled"] = true;
            _properties[i]![j]!["image"] = "${ducto}_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";
          }else if(der && j-1 >= 0){
            _properties[i]![j]!["type"] = "hor_izq";
            _properties[i]![j-1]!["enabled"] = true;
            _properties[i]![j]!["image"] = "${ducto}_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";
          }else if(arr && i+1 < _numCuadriculas){
            _properties[i]![j]!["type"] = "ver_aba";
            _properties[i+1]![j]!["enabled"] = true;
            _properties[i]![j]!["image"] = "${ducto}_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";
          }else if(aba && i-1 >= 0){
            _properties[i]![j]!["type"] = "ver_arr";
            _properties[i-1]![j]!["enabled"] = true;
            _properties[i]![j]!["image"] = "${ducto}_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";
          }
        }else if(longDouble > 1 && longDouble <= 2){
          if(izq && j+1 < _numCuadriculas){
            _properties[i]![j]!["type"] = "hor_der";
            _properties[i]![j]!["image"] = "${ducto}_aba_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i]![j+1]!["color"] = _colorDrag;
            _properties[i]![j+1]!["used"] = true;
            _properties[i]![j+1]!["image"] = "${ducto}_arr_$_imgSize.png";
            _properties[i]![j+1]!["enabled"] = true;
            _properties[i]![j+1]!["type"] = "hor_der";
            _properties[i]![j+1]!["data"] = _dataDrag;

            _properties[i]![j+2]!["enabled"] = true;
          }else if(der && j-1 >= 0){
            _properties[i]![j]!["type"] = "hor_izq";
            _properties[i]![j]!["image"] = "${ducto}_arr_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i]![j-1]!["color"] = _colorDrag;
            _properties[i]![j-1]!["used"] = true;
            _properties[i]![j-1]!["image"] = "${ducto}_aba_$_imgSize.png";
            _properties[i]![j-1]!["enabled"] = true;
            _properties[i]![j-1]!["type"] = "hor_izq";
            _properties[i]![j-1]!["data"] = _dataDrag;

            _properties[i]![j-2]!["enabled"] = true;
          }else if(arr && i+1 < _numCuadriculas){
            _properties[i]![j]!["type"] = "ver_aba";
            _properties[i]![j]!["image"] = "${ducto}_arr_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i+1]![j]!["color"] = _colorDrag;
            _properties[i+1]![j]!["used"] = true;
            _properties[i+1]![j]!["image"] = "${ducto}_aba_$_imgSize.png";
            _properties[i+1]![j]!["enabled"] = true;
            _properties[i+1]![j]!["type"] = "ver_aba";
            _properties[i+1]![j]!["data"] = _dataDrag;

            _properties[i+2]![j]!["enabled"] = true;
          }else if(aba && i-1 >= 0){
            _properties[i]![j]!["type"] = "ver_arr";
            _properties[i]![j]!["image"] = "${ducto}_aba_$_imgSize.png";
            _properties[i]![j]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i-1]![j]!["color"] = _colorDrag;
            _properties[i-1]![j]!["used"] = true;
            _properties[i-1]![j]!["image"] = "${ducto}_arr_$_imgSize.png";
            _properties[i-1]![j]!["enabled"] = true;
            _properties[i-1]![j]!["type"] = "ver_arr";
            _properties[i-1]![j]!["data"] = _dataDrag;

            _properties[i-2]![j]!["enabled"] = true;
          }
        }else if(longDouble > 2){
          if(izq && j+1 < _numCuadriculas){
            _properties[i]![j]!["type"] = "hor_der";
            _properties[i]![j]!["image"] = "${ducto}_aba_$_imgSize.png";

            _properties[i]![j+1]!["color"] = _colorDrag;
            _properties[i]![j+1]!["used"] = true;
            _properties[i]![j+1]!["image"] = "${ducto}_solo_$_imgSize.png";
            _properties[i]![j+1]!["enabled"] = true;
            _properties[i]![j+1]!["type"] = "hor_der";
            _properties[i]![j+1]!["data"] = _dataDrag;
            _properties[i]![j+1]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i]![j+2]!["color"] = _colorDrag;
            _properties[i]![j+2]!["used"] = true;
            _properties[i]![j+2]!["image"] = "${ducto}_arr_$_imgSize.png";
            _properties[i]![j+2]!["enabled"] = true;
            _properties[i]![j+2]!["type"] = "hor_der";
            _properties[i]![j+2]!["data"] = _dataDrag;

            _properties[i]![j+3]!["enabled"] = true;
          }else if(der && j-1 >= 0){
            _properties[i]![j]!["type"] = "hor_izq";
            _properties[i]![j]!["image"] = "${ducto}_arr_$_imgSize.png";


            _properties[i]![j-1]!["color"] = _colorDrag;
            _properties[i]![j-1]!["used"] = true;
            _properties[i]![j-1]!["image"] = "${ducto}_solo_$_imgSize.png";
            _properties[i]![j-1]!["enabled"] = true;
            _properties[i]![j-1]!["type"] = "hor_izq";
            _properties[i]![j-1]!["data"] = _dataDrag;
            _properties[i]![j-1]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i]![j-2]!["color"] = _colorDrag;
            _properties[i]![j-2]!["used"] = true;
            _properties[i]![j-2]!["image"] = "${ducto}_aba_$_imgSize.png";
            _properties[i]![j-2]!["enabled"] = true;
            _properties[i]![j-2]!["type"] = "hor_izq";
            _properties[i]![j-2]!["data"] = _dataDrag;

            _properties[i]![j-3]!["enabled"] = true;
          }else if(arr && i+1 < _numCuadriculas){
            _properties[i]![j]!["type"] = "ver_aba";
            _properties[i]![j]!["image"] = "${ducto}_arr_$_imgSize.png";

            _properties[i+1]![j]!["color"] = _colorDrag;
            _properties[i+1]![j]!["used"] = true;
            _properties[i+1]![j]!["image"] = "${ducto}_solo_$_imgSize.png";
            _properties[i+1]![j]!["enabled"] = true;
            _properties[i+1]![j]!["type"] = "ver_aba";
            _properties[i+1]![j]!["data"] = _dataDrag;
            _properties[i+1]![j]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i+2]![j]!["color"] = _colorDrag;
            _properties[i+2]![j]!["used"] = true;
            _properties[i+2]![j]!["image"] = "${ducto}_aba_$_imgSize.png";
            _properties[i+2]![j]!["enabled"] = true;
            _properties[i+2]![j]!["type"] = "ver_aba";
            _properties[i+2]![j]!["data"] = _dataDrag;

            _properties[i+3]![j]!["enabled"] = true;
          }else if(aba && i-1 >= 0){
            _properties[i]![j]!["type"] = "ver_arr";
            _properties[i]![j]!["image"] = "${ducto}_aba_$_imgSize.png";

            _properties[i-1]![j]!["color"] = _colorDrag;
            _properties[i-1]![j]!["used"] = true;
            _properties[i-1]![j]!["image"] = "${ducto}_solo_$_imgSize.png";
            _properties[i-1]![j]!["enabled"] = true;
            _properties[i-1]![j]!["type"] = "ver_arr";
            _properties[i-1]![j]!["data"] = _dataDrag;
            _properties[i-1]![j]!["text"] = "$longDouble $_unidadLongitud";

            _properties[i-2]![j]!["color"] = _colorDrag;
            _properties[i-2]![j]!["used"] = true;
            _properties[i-2]![j]!["image"] = "${ducto}_arr_$_imgSize.png";
            _properties[i-2]![j]!["enabled"] = true;
            _properties[i-2]![j]!["type"] = "ver_arr";
            _properties[i-2]![j]!["data"] = _dataDrag;

            _properties[i-3]![j]!["enabled"] = true;
          }
        }

        if(_tramosRectos.isEmpty){
          _tramosRectos["Tramo 1"] = ductoConf;
        }else{
          String tramo = _tramosRectos.keys.last;
          int numTramo = int.parse(tramo.split(" ").last);

          numTramo++;

          _tramosRectos["Tramo $numTramo"] = ductoConf;
        }
      }

      if(value == 'filtro'){
        bool izq = _properties[i]![j-1] == null ? false : _properties[i]![j-1]!["used"];
        bool der = _properties[i]![j+1] == null ? false : _properties[i]![j+1]!["used"];
        bool arr = _properties[i-1] == null ? false : _properties[i-1]![j]!["used"];
        bool aba = _properties[i+1] == null ? false : _properties[i+1]![j]!["used"];

        Map<String, String> perdConf = await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context){
            TextEditingController perdida = TextEditingController();
            return AlertDialog(
              title: Text("Ingresa la perdida por $value."),
              content: Row(
                children: [
                  Text(
                    "Pérdida:",
                    style: GoogleFonts.roboto(
                      fontWeight: FontWeight.bold,
                      fontSize: 18.0,
                    ),
                  ),
                  const SizedBox(width: 8.0),
                  Expanded(
                    child: TextField(
                      controller: perdida,
                      decoration: InputDecoration(
                        hintText: "Unidades en pulgadas columna de agua.",
                        hintStyle: GoogleFonts.roboto(
                          fontSize: 18.0,
                          fontStyle: FontStyle.italic,
                          color: Colors.grey,
                        ),
                      ),
                      keyboardType: TextInputType.number,
                      inputFormatters: [
                        FilteringTextInputFormatter.allow(RegExp(r'^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$'))
                      ],
                    ),
                  ),
                  const SizedBox(width: 8.0),
                  Container(
                    child: Text(
                      "in c.d.a",
                      style: GoogleFonts.roboto(fontSize: 18.0),
                    ),
                    padding: const EdgeInsets.fromLTRB(0, 0, 24.0, 8.0),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Colors.black.withOpacity(0.18),
                          width: 2.0,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    if(perdida.text.isEmpty){
                      Fluttertoast.showToast(
                        msg: "Debes indicar una longitud antes de continuar",
                        toastLength: Toast.LENGTH_SHORT,
                        timeInSecForIosWeb: 2,
                        gravity: ToastGravity.CENTER,
                        webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                      );
                    }else{
                      Navigator.pop(context, {"perdida" : perdida.text,});
                    }
                  },
                  child: const Text("Aceptar"),
                )
              ],
            );
          },
        );

        if(_perdidasAdicionales.isEmpty){
          _perdidasAdicionales["Perdida 1"] = perdConf;
        }else{
          String perdida = _perdidasAdicionales.keys.last;
          int numPerdida = int.parse(perdida.split(" ").last);

          numPerdida++;

          _perdidasAdicionales["Perdida $numPerdida"] = perdConf;
        }

        if(izq && j+1 < _numCuadriculas){
          _properties[i]![j+1]!["enabled"] = true;
          _properties[i]![j]!["type"] = "hor_der";
        }else if(der && j-1 >= 0){
          _properties[i]![j-1]!["enabled"] = true;
          _properties[i]![j]!["type"] = "hor_izq";
        }else if(arr && i+1 < _numCuadriculas){
          _properties[i+1]![j]!["enabled"] = true;
          _properties[i]![j]!["type"] = "ver_aba";
        }else if(aba && i-1 >= 0){
          _properties[i-1]![j]!["enabled"] = true;
          _properties[i]![j]!["type"] = "ver_arr";
        }

        _properties[i]![j]!["color"] = _colorDrag;
        _properties[i]![j]!["used"] = true;
        _properties[i]![j]!["enabled"] = true;
        _properties[i]![j]!["data"] = value;
        _properties[i]![j]!["image"] = "filtro_$_imgSize.png";
        _properties[i]![j]!["text"] = "${perdConf['perdida']} in c.d.a";
      }

      if(value == "reduccion" || value == "ampliacion"){
        bool izq = _properties[i]![j-1] == null ? false : _properties[i]![j-1]!["used"];
        bool der = _properties[i]![j+1] == null ? false : _properties[i]![j+1]!["used"];
        bool arr = _properties[i-1] == null ? false : _properties[i-1]![j]!["used"];
        bool aba = _properties[i+1] == null ? false : _properties[i+1]![j]!["used"];

        if(izq && j+1 < _numCuadriculas){
          _properties[i]![j+1]!["enabled"] = true;
          _properties[i]![j]!["type"] = "hor_der";
        }else if(der && j-1 >= 0){
          _properties[i]![j-1]!["enabled"] = true;
          _properties[i]![j]!["type"] = "hor_izq";
        }else if(arr && i+1 < _numCuadriculas){
          _properties[i+1]![j]!["enabled"] = true;
          _properties[i]![j]!["type"] = "ver_aba";
        }else if(aba && i-1 >= 0){
          _properties[i-1]![j]!["enabled"] = true;
          _properties[i]![j]!["type"] = "ver_arr";
        }

        _properties[i]![j]!["color"] = _colorDrag;
        _properties[i]![j]!["used"] = true;
        _properties[i]![j]!["enabled"] = true;
        _properties[i]![j]!["data"] = value;
        _properties[i]![j]!["image"] = value == "reduccion" ? "red_$_imgSize.png" : "amp_$_imgSize.png";

        if(value == "reduccion") _numRed++;
        if(value == "ampliacion") _numAmp++;
      }

      if(value == 'final'){
        int hab = 0;
        _properties.forEach((key, value) {
          value.forEach((key0, value0) {
            if(value0["enabled"] && !value0["used"]){
              hab++;
            }
          });
        });

        if(hab > 1){
          Fluttertoast.showToast(
            msg: "¡Parece que tienes más de una salida!, para finalizar el dibujo debes unirlas.",
            toastLength: Toast.LENGTH_SHORT,
            timeInSecForIosWeb: 4,
            gravity: ToastGravity.CENTER,
            webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
          );
          return;
        }

        final finalizar = await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => AlertDialog(
            title: const Text("Finalizar dibujo"),
            content: Text(
              "Al insertar este elemento ya no podrá seguir dibujando. \n\n¿Desea continuar?",
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(),
            ),
            actions: [
              TextButton(
                child: const Text("Aceptar"),
                onPressed: () => Navigator.pop(context, true),
              ),
              TextButton(
                child: const Text("Cancelar"),
                onPressed: () => Navigator.pop(context, false),
              )
            ],
          ),
        );

        if(!finalizar) return;

        //Primero se busca la orientacion del elemento
        final aba = _properties[i+1]![j]!["used"];
        final arr = _properties[i-1]![j]!["used"];
        final der = _properties[i]![j+1]!["used"];

        if(aba){
          final elemento = _nombreElemento == "CRWL-D" ? "CRVL-D" : _nombreElemento;
          _movFinDir = "ver_arr";
          _movFinName = elemento;

          if(elemento != "CM"){
            //El último elemento puesto está abajo, por lo tanto se busca que haya 6 recuadros libres encima de este elemento
            final c1 = _properties[i]![j-1] == null ? true : _properties[i]![j-1]!["used"]; //Izquierda del original
            final c2 = _properties[i]![j+1] == null ? true : _properties[i]![j+1]!["used"]; //Derecha del original
            final c3 = _properties[i-1]![j-1] == null ? true : _properties[i-1]![j-1]!["used"]; //Esquina superior izquierda del original
            final c4 = _properties[i-1]![j] == null ? true : _properties[i-1]![j]!["used"]; //Arriba del original
            final c5 = _properties[i-1]![j+1] == null ? true : _properties[i-1]![j+1]!["used"]; //Esquina superior derecha del original

            //verificamos que todos los recuadros estén desocupados
            if(!c1 && !c2 && !c3 && !c4 && !c5){
              //Si se cumple entonces ponemos el elemento
              _properties[i]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_1_$_imgSize.png",
                "type" : "ver_arr",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_2_$_imgSize.png",
                "type" : "ver_arr",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j+1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_3_$_imgSize.png",
                "type" : "ver_arr",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i-1]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_4_$_imgSize.png",
                "type" : "ver_arr",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i-1]![j] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_5_$_imgSize.png",
                "type" : "ver_arr",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i-1]![j+1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_6_$_imgSize.png",
                "type" : "ver_arr",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
            }else{
              //Si no, le notificamos al usuario que hay algún elemento estorbando o bien, su cuadricula es demasiado pequeña
              Fluttertoast.showToast(
                msg: "El elemento elegido no puede ser insertado en esta zona porque un elemento interfiere, o bien se sale de la cuadrícula.\n"
                    "Por favor libere una zona de 3x2 cuadros.",
                toastLength: Toast.LENGTH_SHORT,
                timeInSecForIosWeb: 2,
                gravity: ToastGravity.CENTER,
                webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
              );
              return;
            }
          }else{
            final c1 = _properties[i+1]![j-1] == null ? true : _properties[i]![j-1]!["used"]; //Izquierda del original
            final c2 = _properties[i]![j-1] == null ? true : _properties[i]![j+1]!["used"]; //Derecha del original
            final c3 = _properties[i-1]![j-1] == null ? true : _properties[i-1]![j-1]!["used"]; //Esquina superior izquierda del original
            final c4 = _properties[i+1]![j-2] == null ? true : _properties[i-1]![j]!["used"]; //Arriba del original
            final c5 = _properties[i]![j-2] == null ? true : _properties[i-1]![j+1]!["used"]; //Esquina superior derecha del original
            final c6 = _properties[i-1]![j-2] == null ? true : _properties[i-1]![j+1]!["used"]; //Esquina superior derecha del original

            if(!c1 && !c2 && !c3 && !c4 && !c5 && !c6){
              //Si se cumple entonces ponemos el elemento
              _properties[i]![j] = {
                "color" : Colors.transparent,
                "image" : "cont_$_imgSize.png",
                "type" : "izq",
                "data" : "codo",
                "enabled" : false,
                "used" : true
              };
              _properties[i+1]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_1_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_2_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i-1]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_3_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i+1]![j-2] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_4_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j-2] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_5_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i-1]![j-2] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_6_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
            }else{
              //Si no, le notificamos al usuario que hay algún elemento estorbando o bien, su cuadricula es demasiado pequeña
              Fluttertoast.showToast(
                msg: "El elemento elegido no puede ser insertado en esta zona porque un elemento interfiere, o bien se sale de la cuadrícula.\n"
                    "Por favor libere una zona de 3x2 cuadros.",
                toastLength: Toast.LENGTH_SHORT,
                timeInSecForIosWeb: 2,
                gravity: ToastGravity.CENTER,
                webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
              );
              return;
            }
          }
        }else if(arr){
          final elemento = _nombreElemento == "CRWL-D" ? "CRVL-D" : _nombreElemento;
          _movFinDir = "ver_aba";
          _movFinName = elemento;

          if(elemento != "CM"){
            //El último elemento puesto está abajo, por lo tanto se busca que haya 6 recuadros libres encima de este elemento
            final c1 = _properties[i]![j-1] == null ? true : _properties[i]![j-1]!["used"]; //Izquierda del original
            final c2 = _properties[i]![j+1] == null ? true : _properties[i]![j+1]!["used"]; //Derecha del original
            final c3 = _properties[i+1]![j-1] == null ? true : _properties[i+1]![j-1]!["used"]; //Esquina superior izquierda del original
            final c4 = _properties[i+1]![j] == null ? true : _properties[i+1]![j]!["used"]; //Arriba del original
            final c5 = _properties[i+1]![j+1] == null ? true : _properties[i+1]![j+1]!["used"]; //Esquina superior derecha del original


            //verificamos que todos los recuadros estén desocupados
            if(!c1 && !c2 && !c3 && !c4 && !c5){
              //Si se cumple entonces ponemos el elemento
              _properties[i]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_1_$_imgSize.png",
                "type" : "ver_aba",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_2_$_imgSize.png",
                "type" : "ver_aba",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j+1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_3_$_imgSize.png",
                "type" : "ver_aba",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i+1]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_4_$_imgSize.png",
                "type" : "ver_aba",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i+1]![j] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_5_$_imgSize.png",
                "type" : "ver_aba",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i+1]![j+1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_ver_6_$_imgSize.png",
                "type" : "ver_aba",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
            }else{
              //Si no, le notificamos al usuario que hay algún elemento estorbando o bien, su cuadricula es demasiado pequeña
              Fluttertoast.showToast(
                msg: "El elemento elegido no puede ser insertado en esta zona porque un elemento interfiere, o bien se sale de la cuadrícula.\n"
                    "Por favor libere una zona de 3x2 cuadros.",
                toastLength: Toast.LENGTH_SHORT,
                timeInSecForIosWeb: 2,
                gravity: ToastGravity.CENTER,
                webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
              );
              return;
            }
          }else{
            final c1 = _properties[i+1]![j-1] == null ? true : _properties[i]![j-1]!["used"]; //Izquierda del original
            final c2 = _properties[i]![j-1] == null ? true : _properties[i]![j+1]!["used"]; //Derecha del original
            final c3 = _properties[i-1]![j-1] == null ? true : _properties[i-1]![j-1]!["used"]; //Esquina superior izquierda del original
            final c4 = _properties[i+1]![j-2] == null ? true : _properties[i-1]![j]!["used"]; //Arriba del original
            final c5 = _properties[i]![j-2] == null ? true : _properties[i-1]![j+1]!["used"]; //Esquina superior derecha del original
            final c6 = _properties[i-1]![j-2] == null ? true : _properties[i-1]![j+1]!["used"]; //Esquina superior derecha del original

            if(!c1 && !c2 && !c3 && !c4 && !c5 && !c6){
              //Si se cumple entonces ponemos el elemento
              _properties[i]![j] = {
                "color" : Colors.transparent,
                "image" : "cont_$_imgSize.png",
                "type" : "izq",
                "data" : "codo",
                "enabled" : false,
                "used" : true
              };
              _properties[i+1]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_1_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_2_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i-1]![j-1] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_3_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i+1]![j-2] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_4_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i]![j-2] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_5_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
              _properties[i-1]![j-2] = {
                "color" : Colors.transparent,
                "image" : "${elemento}_hor_6_$_imgSize.png",
                "type" : "hor_izq",
                "data" : "final",
                "enabled" : true,
                "used" : true
              };
            }else{
              //Si no, le notificamos al usuario que hay algún elemento estorbando o bien, su cuadricula es demasiado pequeña
              Fluttertoast.showToast(
                msg: "El elemento elegido no puede ser insertado en esta zona porque un elemento interfiere, o bien se sale de la cuadrícula.\n"
                    "Por favor libere una zona de 3x2 cuadros.",
                toastLength: Toast.LENGTH_SHORT,
                timeInSecForIosWeb: 2,
                gravity: ToastGravity.CENTER,
                webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
              );
              return;
            }
          }
        }else if(der){
          //El último elemento puesto está abajo, por lo tanto se busca que haya 6 recuadros libres encima de este elemento
          final c1 = _properties[i+1]![j] == null ? true : _properties[i+1]![j]!["used"]; //Izquierda del original
          final c2 = _properties[i-1]![j] == null ? true : _properties[i-1]![j]!["used"]; //Derecha del original
          final c3 = _properties[i+1]![j-1] == null ? true : _properties[i+1]![j-1]!["used"]; //Esquina superior izquierda del original
          final c4 = _properties[i]![j-1] == null ? true : _properties[i]![j-1]!["used"]; //Arriba del original
          final c5 = _properties[i-1]![j-1] == null ? true : _properties[i-1]![j-1]!["used"]; //Esquina superior derecha del original
          final elemento = _nombreElemento == "CRVL-D" ? "CRWL-D" : _nombreElemento;
          _movFinDir = "hor_izq";
          _movFinName = elemento;

          //verificamos que todos los recuadros estén desocupados
          if(!c1 && !c2 && !c3 && !c4 && !c5){
            //Si se cumple entonces ponemos el elemento
            _properties[i+1]![j] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_1_$_imgSize.png",
              "type" : "hor_izq",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i]![j] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_2_$_imgSize.png",
              "type" : "hor_izq",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i-1]![j] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_3_$_imgSize.png",
              "type" : "hor_izq",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i+1]![j-1] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_4_$_imgSize.png",
              "type" : "hor_izq",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i]![j-1] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_5_$_imgSize.png",
              "type" : "hor_izq",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i-1]![j-1] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_6_$_imgSize.png",
              "type" : "hor_izq",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
          }else{
            //Si no, le notificamos al usuario que hay algún elemento estorbando o bien, su cuadricula es demasiado pequeña
            Fluttertoast.showToast(
              msg: "El elemento elegido no puede ser insertado en esta zona porque un elemento interfiere, o bien se sale de la cuadrícula.\n"
                  "Por favor libere una zona de 3x2 cuadros.",
              toastLength: Toast.LENGTH_SHORT,
              timeInSecForIosWeb: 2,
              gravity: ToastGravity.CENTER,
              webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
            );
            return;
          }
        }else{
          //El último elemento puesto está abajo, por lo tanto se busca que haya 6 recuadros libres encima de este elemento
          final c1 = _properties[i-1]![j] == null ? true : _properties[i-1]![j]!["used"]; //Izquierda del original
          final c2 = _properties[i+1]![j] == null ? true : _properties[i+1]![j]!["used"]; //Derecha del original
          final c3 = _properties[i-1]![j+1] == null ? true : _properties[i-1]![j+1]!["used"]; //Esquina superior izquierda del original
          final c4 = _properties[i]![j+1] == null ? true : _properties[i]![j+1]!["used"]; //Arriba del original
          final c5 = _properties[i+1]![j+1] == null ? true : _properties[i+1]![j+1]!["used"]; //Esquina superior derecha del original
          final elemento = _nombreElemento == "CRVL-D" ? "CRWL-D" : _nombreElemento;
          _movFinDir = "hor_der";
          _movFinName = elemento;

          //verificamos que todos los recuadros estén desocupados
          if(!c1 && !c2 && !c3 && !c4 && !c5){
            //Si se cumple entonces ponemos el elemento
            _properties[i-1]![j] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_3_$_imgSize.png",
              "type" : "hor_der",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i]![j] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_2_$_imgSize.png",
              "type" : "hor_der",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i+1]![j] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_1_$_imgSize.png",
              "type" : "hor_der",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i-1]![j+1] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_6_$_imgSize.png",
              "type" : "hor_der",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i]![j+1] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_5_$_imgSize.png",
              "type" : "hor_der",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
            _properties[i+1]![j+1] = {
              "color" : Colors.transparent,
              "image" : "${elemento}_hor_4_$_imgSize.png",
              "type" : "hor_der",
              "data" : "final",
              "enabled" : true,
              "used" : true
            };
          }else{
            //Si no, le notificamos al usuario que hay algún elemento estorbando o bien, su cuadricula es demasiado pequeña
            Fluttertoast.showToast(
              msg: "El elemento elegido no puede ser insertado en esta zona porque un elemento interfiere, o bien se sale de la cuadrícula.\n"
                  "Por favor libere una zona de 3x2 cuadros.",
              toastLength: Toast.LENGTH_SHORT,
              timeInSecForIosWeb: 2,
              gravity: ToastGravity.CENTER,
              webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
            );
            return;
          }
        }

        _finalizado = true;
      }

      _addHistorial(value, {
        "i": "$i",
        "j": "$j",
      });
      setState(() {});
    }else{
      Fluttertoast.showToast(
        msg: "Este cuadro no está disponible.",
        toastLength: Toast.LENGTH_SHORT,
        timeInSecForIosWeb: 2,
        gravity: ToastGravity.CENTER,
        webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
      );
      return;
    }
  }

  Widget _childCalc(){
    if(_historial.isEmpty){
      return Container(
        width: double.infinity,
        child: Text(
          "Aún no has realizado ningún movimiento, inserta algún elemento para empezar a calcular.",
          textAlign: TextAlign.center,
          style: GoogleFonts.roboto(
            color: _claro ? _colorIconoBarraC : _colorIconoBarraO,
            fontWeight: FontWeight.bold,
            fontSize: 16.0,
          ),
        ),
        alignment: Alignment.center,
      );
    }else{
      return _calcTable(_claro ? _colorIconoBarraC : _colorIconoBarraO, _campFiltGrasa == "Si");
    }
  }

  Future<Uint8List> _takeScreenshot() async{
    RenderRepaintBoundary? boundary = _scrKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    final image = await boundary.toImage();
    final byteData = await image.toByteData(format: ImageByteFormat.png);
    final pngBytes = byteData!.buffer.asUint8List();

    return pngBytes;
  }

  void _addHistorial(String value, Map<String, String> info){
    _historial.add({value: info});
    _historialRe.clear();
    _movHistRe = 0;
    _movHistorial++;
  }

  void _cambiarSalidas(int value, int salAnt){
    _numSalidasSelec = value;

    List<String> properties = [];

    _properties.forEach((key, value) {
      value.forEach((key0, value0) {
        value0.forEach((key1, value1) {
          String val = "";
          if(key1 == "color"){
            val = "${value1.value}";
          }else if(key1 == "enabled" || key1 == "used"){
            val = value1 ? "1" : "0";
          }else{
            val = value1;
          }
          properties.add("$key=>$key0=>$key1=>$val");
        });
      });
    });
    _properties = {};

    _addHistorial("properties", {
      "props" : jsonEncode(properties),
      "salAnt": "$salAnt"
    });
    setState(() {});
  }

  void _rehacerHistorial(int numCuadAnt, int numCuadDes, dynamic properties) => setState((){
    bool aumentoCuadricula = numCuadDes > numCuadAnt;
    bool disminuyoCuadricula = numCuadDes < numCuadAnt;

    int mitadDes = numCuadDes ~/ 2;
    int mitadAnt = numCuadAnt ~/ 2;

    if(aumentoCuadricula){
      int aumentoMitad = mitadDes - mitadAnt;
      int aumento = numCuadDes - numCuadAnt;

      for(int i = 0; i < numCuadDes; i++){
        if(_properties[i] == null) _properties[i] = {};
        for(int j = 0; j < numCuadDes; j++){
          if(_properties[i]![j] == null){
            _properties[i]![j] = {
              "color" : Colors.transparent,
              "image" : "no-image",
              "type" : "no-type",
              "data" : "no-data",
              "enabled" : false,
              "used" : false
            };
          }
        }
      }

      properties.forEach((key, value) {
        _properties[key] = {};
        value.forEach((key0, value0){
          if(value0["used"]){
            _properties[key + aumento]![key0 + aumentoMitad] = value0;
          }else{
            _properties[key]![key0] = {
              "color" : Colors.transparent,
              "image" : "no-image",
              "type" : "no-type",
              "data" : "no-data",
              "enabled" : false,
              "used" : false
            };
          }
        });
      });

      int index = 0;
      for (var element in _historial) {
        final key = element.keys.first;
        final coordI = int.parse(element[key]!["i"]!);
        final coordJ = int.parse(element[key]!["j"]!);

        _historial[index] = {
          key: {
            "i": "${coordI + aumento}",
            "j": "${coordJ + aumentoMitad}"
          }
        };
        index++;
      }
    }else if(disminuyoCuadricula){
      int disminMitad = mitadAnt - mitadDes;
      int dismin = numCuadAnt - numCuadDes;

      for(int i = 0; i < numCuadDes; i++){
        if(_properties[i] == null) _properties[i] = {};
        for(int j = 0; j < numCuadDes; j++){
          if(_properties[i]![j] == null){
            _properties[i]![j] = {
              "color" : Colors.transparent,
              "image" : "no-image",
              "type" : "no-type",
              "data" : "no-data",
              "enabled" : false,
              "used" : false
            };
          }
        }
      }

      properties.forEach((key, value) {
        _properties[key] = {};
        value.forEach((key0, value0){
          if(value0["used"]){
            _properties[key - dismin]![key0 - disminMitad] = value0;
          }else{
            _properties[key]![key0] = {
              "color" : Colors.transparent,
              "image" : "no-image",
              "type" : "no-type",
              "data" : "no-data",
              "enabled" : false,
              "used" : false
            };
          }
        });
      });

      int index = 0;
      for (var element in _historial) {
        final key = element.keys.first;
        final coordI = int.parse(element[key]!["i"]!);
        final coordJ = int.parse(element[key]!["j"]!);

        _historial[index] = {
          key: {
            "i": "${coordI - dismin}",
            "j": "${coordJ + disminMitad}"
          }
        };
        index++;
      }
    }else{
      properties.forEach((key, value) {
        _properties[key] = {};
        value.forEach((key0, value0){
          if(value0["used"]){
            _properties[key]![key0] = value0;
          }else{
            _properties[key]![key0] = {
              "color" : Colors.transparent,
              "image" : "no-image",
              "type" : "no-type",
              "data" : "no-data",
              "enabled" : false,
              "used" : false
            };
          }
        });
      });
    }
  });

  Table _calcTable(Color colorFuente, bool filInGrasa) {
    List<TableRow> rows = [];
    Map<String, dynamic> arrCalculos = {};

    int velocidad = int.parse(_velAire);
    double pd = math.pow((velocidad / 196.85), 2) / 16;
    double perdidaTotal = 0.0;
    arrCalculos["pd"] = pd;

    //se calcula la seccion circular a partir de la seccion cuadrada
    String unidadCaudal = _caudalEx.split(" ").last;
    int caudal = unidadCaudal == "CFM" ? int.parse(_caudalEx.split(" ").first) : (int.parse(_caudalEx.split(" ").first) / 1.7).round();
    double secCuad = math.sqrt((334.645 * caudal) / (3600 * velocidad)) * 100;
    double secCir = (1.265 * secCuad) / math.pow(2, 0.2);

    rows.add(TableRow(
      children: [
        Container(
          child: Text(
            "Velocidad:",
            style: GoogleFonts.roboto(
              fontWeight: FontWeight.bold,
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(bottom: 4.0),
        ),
        Container(
          child: Text(
            "$_velAire fpm",
            style: GoogleFonts.roboto(
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(
            bottom: 4.0,
            left: 8.0,
          ),
        ),
      ],
    ));
    rows.add(TableRow(
      children: [
        Container(
          child: Text(
            "Diámetro:",
            style: GoogleFonts.roboto(
              fontWeight: FontWeight.bold,
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(bottom: 4.0),
        ),
        Container(
          child: Text(
            _ductoCircularIN,
            style: GoogleFonts.roboto(
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(
            left: 8.0,
            bottom: 4.0,
          ),
        ),
      ],
    ));
    rows.add(TableRow(
      children: [
        Container(
          child: Text(
            "Pd:",
            style: GoogleFonts.roboto(
              fontWeight: FontWeight.bold,
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(bottom: 4.0),
        ),
        Container(
          child: Text(
            "${pd.toStringAsFixed(2)} mm c.d.a",
            style: GoogleFonts.roboto(
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(
            bottom: 4.0,
            left: 8.0,
          ),
        ),
      ],
    ));

    double coeficienteCampana = 0.62;
    double pt5 = pd * coeficienteCampana;
    double pe5 = pt5 / 25.4;

    perdidaTotal = perdidaTotal + pe5;
    arrCalculos["disCap"] = "Si";
    arrCalculos["pe5"] = pe5;

    rows.add(TableRow(
      children: [
        const SizedBox(height: 4.0),
        Container(),
      ],
    ));
    rows.add(TableRow(
      children: [
        Container(
          child: Text(
            "Pérdida por campana:",
            style: GoogleFonts.roboto(
              fontWeight: FontWeight.bold,
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(bottom: 4.0),
        ),
        Container(
          child: Text(
            "${pe5.toStringAsFixed(2)} in c.d.a.",
            style: GoogleFonts.roboto(
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(
            bottom: 4.0,
            left: 8.0,
          ),
        ),
      ],
    ));

    if(filInGrasa){
      arrCalculos["filInGrasa"] = "Si";
      arrCalculos["pe6"] = 0.5;
      perdidaTotal = perdidaTotal + 0.5;
      rows.add(TableRow(
        children: [
          Container(
            child: Text(
              "Pérdida por filtro inercial de grasa:",
              style: GoogleFonts.roboto(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(bottom: 4.0),
          ),
          Container(
            child: Text(
              "0.50 in c.d.a.",
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(
              bottom: 4.0,
              left: 8.0,
            ),
          ),
        ],
      ));
    }

    if(_tramosRectos.isNotEmpty){
      rows.add(TableRow(
        children: [
          const SizedBox(height: 4.0),
          Container(),
        ],
      ));
      double longitudTramosRectos = 0.0;

      _tramosRectos.forEach((key, value) {
        double longitudTramoRecto = double.parse(value["longitud"]!);
        longitudTramosRectos = longitudTramosRectos + longitudTramoRecto;
      });
      arrCalculos["lonTramRec"] = longitudTramosRectos;

      rows.add(TableRow(
        children: [
          Container(
            child: Text(
              "Longitud Tramos Rectos:",
              style: GoogleFonts.roboto(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(bottom: 4.0),
          ),
          Container(
            child: Text(
              "$longitudTramosRectos $_unidadLongitud",
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(
              left: 8.0,
              bottom: 4.0,
            ),
          ),
        ],
      ));

      double hf = 5.38 * (math.pow((velocidad / 196.85), 1.9) / math.pow(((secCir) * 10), 1.22));
      double pt1 = hf * longitudTramosRectos;
      double pe1 = pt1 / 25.4;

      perdidaTotal = perdidaTotal + pe1;
      arrCalculos["pe1"] = pe1;

      rows.add(TableRow(
        children: [
          Container(
            child: Text(
              "Pérdida en tramos rectos:",
              style: GoogleFonts.roboto(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(bottom: 4.0),
          ),
          Container(
            child: Text(
              "${pe1.toStringAsFixed(2)} in c.d.a.",
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(
              bottom: 4.0,
              left: 8.0,
            ),
          ),
        ],
      ));
    }

    if(_codosInstalados.isNotEmpty){
      int numCodosCont = 0;
      int numCodos3Pzs = 0;
      int numCodos4Pzs = 0;
      int numCodosCont45 = 0;
      int numCodos3Pzs45 = 0;
      int numCodos4Pzs45 = 0;
      int numTipoTCruz = 0;

      _codosInstalados.forEach((key, value) {
        if(value["tipo"] == "cCont"){
          numCodosCont++;
        }else if(value["tipo"] == "c3Pzs"){
          numCodos3Pzs++;
        }else if(value["tipo"] == "c4Pzs"){
          numCodos4Pzs++;
        }else if(value["tipo"] == "cCont45"){
          numCodosCont45++;
        }else if(value["tipo"] == "c3Pzs45"){
          numCodos3Pzs45++;
        }else if(value["tipo"] == "c4Pzs45"){
          numCodos4Pzs45++;
        }else if(value["tipo"] == "tipoT"){
          numTipoTCruz++;
        }else if(value["tipo"] == "cruz"){
          numTipoTCruz++;
        }
      });

      if(numCodosCont > 0){
        arrCalculos["numCodosCont"] = numCodosCont;
        rows.add(TableRow(
          children: [
            const SizedBox(height: 4.0),
            Container(),
          ],
        ));
        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "# Codos Continuos 90°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "$numCodosCont codo(s)",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));

        double coeficiente = 0.3;
        double pt2 = pd * coeficiente * numCodosCont;

        double pe2 = pt2 / 25.4;

        perdidaTotal = perdidaTotal + pe2;
        arrCalculos["pe2"] = pe2;

        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "Pérdida en codos continuos 90°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 8.0),
            ),
            Container(
              child: Text(
                "${pe2.toStringAsFixed(2)} in c.d.a.",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));
      }

      if(numCodos3Pzs > 0){
        arrCalculos["numCodos3Pzs"] = numCodos3Pzs;
        rows.add(TableRow(
          children: [
            const SizedBox(height: 4.0),
            Container(),
          ],
        ));
        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "# Codos 3 piezas 90°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "$numCodos3Pzs codo(s)",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                left: 8.0,
                bottom: 4.0,
              ),
            ),
          ],
        ));

        double coeficiente = 0.45;
        double pt3 = pd * coeficiente * numCodos3Pzs;
        double pe3 = pt3 / 25.4;

        perdidaTotal = perdidaTotal + pe3;
        arrCalculos["pe3"] = pe3;

        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "Pérdida en codos de 3 piezas 90°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4),
            ),
            Container(
              child: Text(
                "${pe3.toStringAsFixed(2)} in c.d.a.",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                left: 8.0,
                bottom: 4.0,
              ),
            ),
          ],
        ));
      }

      if(numCodos4Pzs > 0){
        arrCalculos["numCodos4Pzs"] = numCodos4Pzs;
        rows.add(TableRow(
          children: [
            const SizedBox(height: 4.0),
            Container(),
          ],
        ));
        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "# Codos 4 piezas 90°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "$numCodos4Pzs codo(s)",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));

        double coeficiente = 0.35;
        double pt4 = pd * coeficiente * numCodos4Pzs;
        double pe4 = pt4 / 25.4;

        perdidaTotal = perdidaTotal + pe4;
        arrCalculos["pe4"] = pe4;

        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "Pérdida en codos de 4 piezas 90°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "${pe4.toStringAsFixed(2)} in c.d.a.",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));
      }

      if(numCodosCont45 > 0){
        arrCalculos["numCodosCont45"] = numCodosCont45;
        rows.add(TableRow(
          children: [
            const SizedBox(height: 4.0),
            Container(),
          ],
        ));
        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "# Codos Continuos 45°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "$numCodosCont45 codo(s)",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));

        double coeficiente = 0.15;
        double pt10 = pd * coeficiente * numCodosCont45;

        double pe10 = pt10 / 25.4;

        perdidaTotal = perdidaTotal + pe10;
        arrCalculos["pe10"] = pe10;

        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "Pérdida en codos continuos 45°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 8.0),
            ),
            Container(
              child: Text(
                "${pe10.toStringAsFixed(2)} in c.d.a.",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));
      }

      if(numCodos3Pzs45 > 0){
        arrCalculos["numCodos3Pzs45"] = numCodos3Pzs45;
        rows.add(TableRow(
          children: [
            const SizedBox(height: 4.0,),
            Container(),
          ],
        ));
        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "# Codos 3 piezas 45°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "$numCodos3Pzs45 codo(s)",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                left: 8.0,
                bottom: 4.0,
              ),
            ),
          ],
        ));

        double coeficiente = 0.225;
        double pt11 = pd * coeficiente * numCodos3Pzs45;
        double pe11 = pt11 / 25.4;

        perdidaTotal = perdidaTotal + pe11;
        arrCalculos["pe11"] = pe11;

        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "Pérdida en codos de 3 piezas 45°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4),
            ),
            Container(
              child: Text(
                "${pe11.toStringAsFixed(2)} in c.d.a.",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                left: 8.0,
                bottom: 4.0,
              ),
            ),
          ],
        ));
      }

      if(numCodos4Pzs45 > 0){
        arrCalculos["numCodos4Pzs45"] = numCodos4Pzs45;
        rows.add(TableRow(
          children: [
            const SizedBox(height: 4.0),
            Container(),
          ],
        ));
        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "# Codos 4 piezas 45°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "$numCodos4Pzs45 codo(s)",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));

        double coeficiente = 0.175;
        double pt12 = pd * coeficiente * numCodos4Pzs45;
        double pe12 = pt12 / 25.4;

        perdidaTotal = perdidaTotal + pe12;
        arrCalculos["pe12"] = pe12;

        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "Pérdida en codos de 4 piezas 45°:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "${pe12.toStringAsFixed(2)} in c.d.a.",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));
      }

      if(numTipoTCruz > 0){
        arrCalculos["numTipoTCruz"] = numTipoTCruz;
        rows.add(TableRow(
          children: [
            const SizedBox(height: 4.0),
            Container(),
          ],
        ));
        rows.add(TableRow(
          children: [
            Container(
              child: Text(
                "# T y cruces:",
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(bottom: 4.0),
            ),
            Container(
              child: Text(
                "$numTipoTCruz codo(s)",
                style: GoogleFonts.roboto(
                  fontSize: 18.0,
                  color: colorFuente,
                ),
              ),
              padding: const EdgeInsets.only(
                bottom: 4.0,
                left: 8.0,
              ),
            ),
          ],
        ));

        double coeficiente = 1.4;
        double pt13 = pd * coeficiente * numTipoTCruz;

        double pe13 = pt13 / 25.4;

        perdidaTotal = perdidaTotal + pe13;
        arrCalculos["pe13"] = pe13;

        rows.add(TableRow(
            children: [
              Container(
                child: Text(
                  "Pérdida en T y cruces:",
                  style: GoogleFonts.roboto(
                    fontWeight: FontWeight.bold,
                    fontSize: 18.0,
                    color: colorFuente,
                  ),
                ),
                padding: const EdgeInsets.only(bottom: 8.0),
              ),
              Container(
                child: Text(
                  "${pe13.toStringAsFixed(2)} in c.d.a.",
                  style: GoogleFonts.roboto(
                    fontSize: 18.0,
                    color: colorFuente,
                  ),
                ),
                padding: const EdgeInsets.only(
                  bottom: 4.0,
                  left: 8.0,
                ),
              ),
            ]
        ));
      }
    }

    if(_perdidasAdicionales.isNotEmpty){
      rows.add(TableRow(
        children: [
          const SizedBox(height: 4.0),
          Container(),
        ],
      ));
      double perdidasAdicionales = 0.0;

      _perdidasAdicionales.forEach((key, value) {
        double perdida = double.parse(value["perdida"]!);
        perdidasAdicionales = perdidasAdicionales + perdida;
      });
      arrCalculos["pe7"] = perdidasAdicionales;

      rows.add(TableRow(
        children: [
          Container(
            child: Text(
              "Pérdidas Adicionales:",
              style: GoogleFonts.roboto(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(bottom: 4.0),
          ),
          Container(
            child: Text(
              "${perdidasAdicionales.toStringAsFixed(2)} in c.d.a.",
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(
              bottom: 4.0,
              left: 8.0,
            ),
          ),
        ],
      ));

      perdidaTotal = perdidaTotal + perdidasAdicionales;
    }

    if(_numAmp > 0){
      rows.add(TableRow(
        children: [
          const SizedBox(height: 4.0),
          Container(),
        ],
      ));
      double perdidaPorAmpliacion = 0.25;
      arrCalculos["pe8"] = perdidaPorAmpliacion;

      rows.add(TableRow(
        children: [
          Container(
            child: Text(
              "Pérdidas por Ampliación:",
              style: GoogleFonts.roboto(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(bottom: 4.0),
          ),
          Container(
            child: Text(
              "${perdidaPorAmpliacion.toStringAsFixed(2)} in c.d.a.",
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(
              bottom: 4.0,
              left: 8.0,
            ),
          ),
        ],
      ));

      perdidaTotal = perdidaTotal + perdidaPorAmpliacion;
    }

    if(_numRed > 0){
      rows.add(TableRow(
        children: [
          const SizedBox(height: 4.0),
          Container(),
        ],
      ));
      double perdidaPorReduccion = 0.25;
      arrCalculos["pe9"] = perdidaPorReduccion;

      rows.add(TableRow(
        children: [
          Container(
            child: Text(
              "Pérdidas por Ampliación:",
              style: GoogleFonts.roboto(
                fontWeight: FontWeight.bold,
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(bottom: 4.0),
          ),
          Container(
            child: Text(
              "${perdidaPorReduccion.toStringAsFixed(2)} in c.d.a.",
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                color: colorFuente,
              ),
            ),
            padding: const EdgeInsets.only(
              bottom: 4.0,
              left: 8.0,
            ),
          ),
        ],
      ));

      perdidaTotal = perdidaTotal + perdidaPorReduccion;
    }

    arrCalculos["perdidaTotal"] = perdidaTotal;
    rows.add(TableRow(
      children: [
        const SizedBox(height: 8.0),
        Container(),
      ],
    ));
    rows.add(TableRow(
      children: [
        Container(
          child: Text(
            "Presión Estática por Accesorios en el Sistema:",
            style: GoogleFonts.roboto(
              fontWeight: FontWeight.bold,
              fontSize: 18.0,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(bottom: 4.0),
        ),
        Container(
          child: Text(
            "${perdidaTotal.toStringAsFixed(2)} in c.d.a.",
            style: GoogleFonts.roboto(
              fontSize: 18.0,
              fontWeight: FontWeight.bold,
              color: colorFuente,
            ),
          ),
          padding: const EdgeInsets.only(
            bottom: 4.0,
            left: 8.0,
          ),
        ),
      ],
    ));

    _jsonCalculos = jsonEncode(arrCalculos);

    return Table(
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      children: rows,
    );
  }
}
