import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';
import 'package:path_provider/path_provider.dart';
import 'package:quiosco_soler_2/clientes/providers/movimientos_provider.dart';
import 'package:quiosco_soler_2/clientes/widgets/lateral_menu_cliente.dart';
import 'package:shimmer/shimmer.dart';

import '../../src/pages/pdf_viewer.dart';
import '../models/cuentas_bancarias.dart';
import '../models/movimientos_comprobantes.dart';
import '../models/movimientos_contacto.dart';
import '../models/saldos_cartera.dart';
import '../models/saldos_contacto.dart';
import '../providers/cuentas_bancarias_provider.dart';
import '../providers/saldos_provider.dart';
import '../widgets/deslizar.dart';

class InicioClientes extends StatefulWidget {
  const InicioClientes({Key? key}) : super(key: key);

  @override
  State<InicioClientes> createState() => _InicioClientesState();
}

class _InicioClientesState extends State<InicioClientes> {
  final _scaffoldKey = GlobalKey<ScaffoldState>();
  final _scrollController = ScrollController();
  final _saldosProvider = SaldosProvider();
  final _movimientosProvider = MovimientosProvider();
  final _cuentasBancariasProvider = CuentasBancariasProvider();
  final _meses = {
    DateTime.january : 'Enero', DateTime.february : 'Febrero', DateTime.march : 'Marzo',
    DateTime.april : 'Abril', DateTime.may : 'Mayo', DateTime.june : 'Junio',
    DateTime.july : 'Julio', DateTime.august : 'Agosto', DateTime.september : 'Septiembre',
    DateTime.october : 'octubre', DateTime.november : 'Noviembre', DateTime.december : 'Diciembre'
  };
  final db = Localstore.instance;

  late SaldosContacto _saldosContacto;
  late SaldosCartera _saldosCartera;
  late MovimientosContacto _movimientosContacto;
  late MovimientosComprobantes _movimientosComprobantes;
  late CuentasBancarias _cuentasBancarias;
  late int _facturas;
  late int _notasCargo;
  late int _notasCredito;
  late int _pago;
  late String _mes;

  int _selectedTab = 0;
  int _selector = 0;
  int _anio = DateTime.now().year;
  bool _isLoading = true;
  bool _empleado = false;
  bool _showRegistros = false;
  bool _mostrarRegistros = true;
  bool _showFiles = false;
  bool _changingDate = false;
  bool _isVencida = false;
  bool _isTotal = false;
  bool _deslizo = false;
  String _registroTitle = '';
  String _filesTitle = '';
  String _totalMod = '';
  String _moneda = 'MXP';
  String _loginKey = '';
  dynamic _loginData = {};

  @override
  void initState() {
    super.initState();
    _mes = _meses[DateTime.now().month]!;
    refresh();
  }

  void refresh() async{
    final dbItems = await db.collection('clientes').get();
    final key = dbItems!.keys.last;

    final item = dbItems[key];
    _loginKey = key.replaceAll('/clientes/', '');
    _empleado = item.containsKey('dinumAfter');
    _loginData = item;

    final saldosContacto = await _saldosProvider.fetchSaldosContacto(item['accesToken']);
    final saldosCartera = await _saldosProvider.fetchSaldosCartera(item['accesToken'], item['dinum'], item['user']);
    final movimientosContacto = await _movimientosProvider.fetchMovimientosContacto(item['accesToken']);
    final movimientosComprobantes = await _movimientosProvider.fetchMovimientosComprobantes(
      item['accesToken'],
      item['dinum'],
      item['user'],
      _buildFec('first', DateTime.now().month, DateTime.now().year),
      _buildFec('last', DateTime.now().month, DateTime.now().year),
    );
    final cuentas = await _cuentasBancariasProvider.fetchCuentasBancarias(item['accesToken'], item['dinum']);

    _saldosCartera = saldosCartera;
    _saldosContacto = saldosContacto;
    _movimientosContacto = movimientosContacto;
    _cuentasBancarias = cuentas;
    _movimientosComprobantes = movimientosComprobantes;
    _facturas = movimientosComprobantes.result!.datosGenerales!.factura!.total!;
    _notasCargo = movimientosComprobantes.result!.datosGenerales!.notadecargo!.total!;
    _notasCredito = movimientosComprobantes.result!.datosGenerales!.notadecredito!.total!;
    _pago = movimientosComprobantes.result!.datosGenerales!.pago!.total!;

    setState(() => _isLoading = false);
  }

  String _buildFec(String select, int month, int year){
    final lastDay = DateUtils.getDaysInMonth(year, month);
    final monthStr = month < 10 ? '0$month' : '$month';

    if(select == 'last'){
      return '$year-$monthStr-$lastDay';
    }

    return '$year-$monthStr-01';
  }

  void showViewer(File document) {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => PDFViewer(
        localFile: true,
        file: document,
      ),
    ));
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        final shouldClose = await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => AlertDialog(
            title: const Text('Advertencia'),
            content: const Text('¿Seguro que desea salir del portal de clientes?'),
            actions: [
              TextButton(
                child: const Text('Cancelar'),
                onPressed: () => Navigator.pop(context, false),
              ),
              TextButton(
                child: const Text('Aceptar'),
                onPressed: () => Navigator.pop(context, true),
              ),
            ],
          ),
        );

        return shouldClose;
      },
      child: _isLoading ? Scaffold(
        body: _buildLoadingPage(context),
      ) : DefaultTabController(
        length: 2,
        child: Scaffold(
          key: _scaffoldKey,
          drawer: _isLoading ? null : LateralMenuCliente(
            cuentasBancarias: _cuentasBancarias,
            shouldRefresh: (val){
              if(val){
                setState(() => _isLoading = true);
                refresh();
              }
            },
          ),
          appBar: _isLoading ? null : _buildAppBar(),
          body: _buildMainPage(),
        ),
      ),
    );
  }

  Widget _buildLoadingPage(BuildContext context){
    final _screenSize = MediaQuery.of(context).size;
    return Container(
      width: _screenSize.width,
      height: _screenSize.height,
      color: const Color(0xFF636363),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Shimmer.fromColors(
              baseColor: const Color(0xFFCCCCCC),
              highlightColor: const Color(0xFFFF0000),
              child: Text(
                'Cargando...',
                textAlign: TextAlign.center,
                style: GoogleFonts.robotoSlab(
                  fontSize: 36.0,
                ),
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Text(
              'Este proceso puede tardar unos minutos, por favor espere',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                fontSize: 22.0,
                color: const Color(0xFF888888),
              ),
            ),
          )
        ],
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() => AppBar(
    automaticallyImplyLeading: false,
    backgroundColor: Colors.white,
    centerTitle: true,
    title: Row(
      children: [
        Image.asset(
          'assets/logo.png',
          width: 32.0,
        ),
        const SizedBox(width: 8.0),
        TextButton(
          style: TextButton.styleFrom(
            padding: EdgeInsets.zero,
            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
            minimumSize: const Size(0.0, 0.0),
          ),
          child: const Icon(
            Icons.menu,
            color: Color(0xFFFF0000),
          ),
          onPressed: () => _scaffoldKey.currentState?.openDrawer(),
        ),
        const Expanded(
          child: Text(
            'CLIENTE',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.red,
              fontFamily: 'Helvetica Neue Black Cond',
            ),
          ),
        ),
        TextButton(
          style: TextButton.styleFrom(
            padding: EdgeInsets.zero,
            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
            minimumSize: const Size(0.0, 0.0),
          ),
          child: const Icon(
            Icons.menu,
            color: Colors.white,
          ),
          onPressed: null,
        ),
        const SizedBox(width: 16.0),
        TextButton(
          style: TextButton.styleFrom(
            padding: EdgeInsets.zero,
            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
            minimumSize: const Size(0.0, 0.0),
          ),
          child: Icon(
            _empleado ? Icons.close : Icons.logout,
            color: const Color(0xFFFF0000),
          ),
          onPressed: () async{
            if(_empleado){
              final Map<String, dynamic> item = {};
              item['accesToken'] = _loginData['accesToken'];
              item['dinum'] = _loginData['dinumAfter'];
              item['user'] = _loginData['userAfter'];

              await db.collection('clientes').doc(_loginKey).set(item);
            }

            Navigator.pop(_scaffoldKey.currentContext!);
          },
        ),
      ],
    ),
    bottom: TabBar(
      indicatorColor: const Color(0xFFB40404),
      onTap: (index) => setState(() => _selectedTab = index),
      tabs: [
        Tab(
          child: Text(
            'Saldos',
            style: GoogleFonts.roboto(
              fontWeight: FontWeight.w500,
              color: _selectedTab == 0 ? const Color.fromRGBO(180, 4, 4, 1) : const Color.fromRGBO(103, 97, 107, 1),
            ),
          ),
        ),
        Tab(
          child: Text(
            'Movimientos',
            style: GoogleFonts.roboto(
              fontWeight: FontWeight.w500,
              color: _selectedTab == 1 ? const Color.fromRGBO(180, 4, 4, 1) : const Color.fromRGBO(103, 97, 107, 1),
            ),
          ),
        )
      ],
    ),
  );

  Widget _buildMainPage(){
    return TabBarView(
      children: [
        AnimatedCrossFade(
          firstChild: _buildSaldos(),
          secondChild: _buildRegistros(_registroTitle, _totalMod, _isVencida, _isTotal, _moneda),
          crossFadeState: !_showRegistros ? CrossFadeState.showFirst : CrossFadeState.showSecond,
          duration: const Duration(milliseconds: 750),
        ),
        AnimatedCrossFade(
          firstChild: _buildMovimientos(),
          secondChild: _buildFiles(_filesTitle, _selector),
          crossFadeState: !_showFiles ? CrossFadeState.showFirst : CrossFadeState.showSecond,
          duration: const Duration(milliseconds: 750),
        )
      ],
    );
  }

  Widget _buildMovimientos(){
    return SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 0.0),
              alignment: Alignment.center,
              child: TextButton(
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Text(
                      '$_mes $_anio',
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w900,
                        fontSize: 24.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(width: 4.0),
                    const Icon(
                      Icons.arrow_drop_down,
                      size: 32.0,
                      color: Color(0xFF333333),
                    )
                  ],
                ),
                onPressed: () => _changeDateOfInvoices(),
              ),
            ),
            _buildSingleCard('','assets/facturas.png', 'FACTURAS', _isLoading
                ? '' : '$_facturas CFDIs', false, false, 0, false, false),
            _buildSingleCard('','assets/notasCargo.png', 'NOTAS DE CARGO', _isLoading
                ? '' : '$_notasCargo CFDIs', false, false, 3, false, false),
            _buildSingleCard('','assets/notasCredito.png', 'NOTAS DE CRÉDITO', _isLoading
                ? '' : '$_notasCredito CFDIs', false, false, 1, false, false),
            _buildSingleCard('','assets/complementos_Pago.png', 'COMPLEMENTOS DE PAGO', _isLoading
                ? '' : '$_pago CFDIs', false, false, 2, false, false),
            _buildContactCard(
                _isLoading ? '' : _movimientosContacto.result.depa,
                _isLoading ? '1234567' : _movimientosContacto.result.tele,
                _isLoading ? '' : _movimientosContacto.result.corr,
                _isLoading ? '' : _movimientosContacto.result.exte
            )
          ],
        ),
      ),
    );
  }

  Widget _buildSaldos(){
    return SafeArea(
      child: SingleChildScrollView(
        child: Column(
          children: [
            if(_saldosCartera.result!.datosGenerales.usd.total == 'NA')
              _buildSingleCard(
                _isLoading ? 'no-data'
                    : _saldosCartera.result!.datosGenerales.mxp.totalCartera,
                'assets/totalCartera.png',
                'TOTAL DE CARTERA',
                _isLoading ? ''
                    : '\$ ${_saldosCartera.result!.datosGenerales.mxp.totalCartera} MXN',
                true,
                true,
                0,
                false,
                true,
              ),
            if(_saldosCartera.result!.datosGenerales.usd.total != 'NA')
              _buildSingleCardDobleMoneda(
                [
                  _isLoading ? 'no-data'
                      : _saldosCartera.result == null ? ''
                      : _saldosCartera.result!.datosGenerales.usd.totalCartera,
                  _isLoading ? 'no-data'
                      : _saldosCartera.result == null ? ''
                      : _saldosCartera.result!.datosGenerales.mxp.totalCartera
                ],
                'assets/totalCartera.png',
                'TOTAL DE CARTERA',
                [
                  _isLoading ? ''
                      : _saldosCartera.result == null ? ''
                      : '\$ ${_saldosCartera.result!.datosGenerales.usd.totalCartera} USD',
                  _isLoading ? ''
                      : _saldosCartera.result == null ? ''
                      : '\$ ${_saldosCartera.result!.datosGenerales.mxp.totalCartera} MXN'
                ],
                false,
                true,
              ),
            if(_saldosCartera.result!.datosGenerales.usd.total == 'NA')
              _buildSingleCard(
                _isLoading ? 'no-data'
                    : _saldosCartera.result == null ? ''
                    : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencer!,
                'assets/carteraVencer.png',
                'CARTERA POR VENCER',
                _isLoading ? ''
                    : _saldosCartera.result == null ? ''
                    : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencer == null ? ""
                    : '\$ ${_saldosCartera.result!.datosGenerales.mxp.totalCarteraVencer} MXN',
                true,
                _isLoading ? false
                    : _saldosCartera.result == null ? false
                    : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencer != '0.00',
                0,
                false,
                false,
              ),
            if(_saldosCartera.result!.datosGenerales.usd.total != 'NA')
              _buildSingleCardDobleMoneda(
                [
                  _isLoading ? 'no-data'
                      : _saldosCartera.result == null ? ''
                      : _saldosCartera.result!.datosGenerales.usd.totalCarteraVencer!,
                  _isLoading ? 'no-data'
                      : _saldosCartera.result == null ? ''
                      : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencer!
                ],
                'assets/carteraVencer.png',
                'CARTERA POR VENCER',
                [
                  _isLoading ? ''
                      : _saldosCartera.result == null ? ''
                      : '\$ ${_saldosCartera.result!.datosGenerales.usd.totalCarteraVencer} USD',
                  _isLoading ? ''
                      : _saldosCartera.result == null ? ''
                      : '\$ ${_saldosCartera.result!.datosGenerales.mxp.totalCarteraVencer} MXN'
                ],
                false,
                false,
              ),
            _buildCarteraVencidaCard(
              _saldosCartera.result!.datosGenerales.usd.total == "NA"
                  ? [
                _isLoading ? 'no-data'
                    : _saldosCartera.result == null ? ''
                    : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencida!
              ] : [
                _isLoading ? 'no-data'
                    : _saldosCartera.result == null ? ''
                    : _saldosCartera.result!.datosGenerales.usd.totalCarteraVencida!,
                _isLoading ? 'no-data'
                    : _saldosCartera.result == null ? ''
                    : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencida!
              ],
              'CARTERA VENCIDA',
              _saldosCartera.result!.datosGenerales.usd.total == "NA"
                  ? [
                _isLoading ? ''
                    : _saldosCartera.result == null ? ''
                    : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencida == null ? ""
                    : '\$ ${_saldosCartera.result!.datosGenerales.mxp.totalCarteraVencida} MXN'
              ] : [
                _isLoading ? ''
                    : _saldosCartera.result == null ? ''
                    : '\$ ${_saldosCartera.result!.datosGenerales.usd.totalCarteraVencida} USD',
                _isLoading ? ''
                    : _saldosCartera.result == null ? ''
                    : '\$ ${_saldosCartera.result!.datosGenerales.mxp.totalCarteraVencida} MXN'
              ],
              _isLoading ? {'no-data' : CarteraVencer()}
                  : _saldosCartera.result == null ? {'no-data' : CarteraVencer()}
                  : _saldosCartera.result!.carteraVencer,
              _isLoading ? false
                  : _saldosCartera.result == null ? false
                  : _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencida != '0.00',
              _saldosCartera.result!.datosGenerales.usd.total == 'NA'
                  ? [
                _saldosCartera.result!.datosGenerales.mxp.pendientePorAplicar!
              ] : [
                _saldosCartera.result!.datosGenerales.usd.pendientePorAplicar!,
                _saldosCartera.result!.datosGenerales.mxp.pendientePorAplicar!
              ],
              _saldosCartera.result!.datosGenerales.usd.total != "NA",
            ),
            _buildContactCard(
              _isLoading ? '' : _saldosContacto.result.depa,
              _isLoading ? '1234567' : _saldosContacto.result.tele,
              _isLoading ? '' : _saldosContacto.result.corr,
              _isLoading ? '' : _saldosContacto.result.exte,
            ),
            const SizedBox(height: 16.0)
          ],
        ),
      ),
    );
  }

  Widget _buildRegistros(String title, String totalMod, bool isVencida, bool isTotal, String moneda){
    List<TableRow> _rows = [];

    _rows.add(TableRow(
      decoration: const BoxDecoration(color: Color.fromRGBO(230, 230, 230, 0.5)),
      children: [
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Doc',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Folio',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Fecha Emisión',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Fecha Vencimiento',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Pedido',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Total',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Días Vencimiento',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
          child: Text(
            'Importe Pendiente',
            textAlign: TextAlign.center,
            style: GoogleFonts.roboto(
              color: const Color(0xFF67616B),
              fontWeight: FontWeight.w700,
              fontSize: 18.0,
            ),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        )
      ],
    ));

    String? porAplicar = _moneda == 'MXP'
        ? _saldosCartera.result!.datosGenerales.mxp.pendientePorAplicar
        : _saldosCartera.result!.datosGenerales.usd.pendientePorAplicar;
    porAplicar == null ? porAplicar = "0.00" : porAplicar = porAplicar;
    double fltPorApli = double.parse(porAplicar.replaceAll(",", ""));
    fltPorApli = double.parse(fltPorApli.toStringAsFixed(2));

    String strTot = _moneda == 'MXP'
        ? _saldosCartera.result!.datosGenerales.mxp.total
        : _saldosCartera.result!.datosGenerales.usd.total;
    double fltTot = double.parse(strTot.replaceAll(',', ''));
    fltTot = double.parse(fltTot.toStringAsFixed(2));

    String? strVen = _moneda == 'MXP'
        ? _saldosCartera.result!.datosGenerales.mxp.totalCarteraVencida
        : _saldosCartera.result!.datosGenerales.usd.totalCarteraVencida;
    strVen == null ? strVen = "0.00" : strVen = strVen;
    double fltVen = double.parse(strVen.replaceAll(',', ''));
    fltVen = double.parse(fltVen.toStringAsFixed(2));

    double fltImpTot = isVencida ? fltVen : isTotal ? fltTot : fltTot - fltVen - fltPorApli;
    fltImpTot = double.parse(fltImpTot.toStringAsFixed(2));

    final arrImpTot = fltImpTot.toString().split(".");
    final arrImpTotInt = arrImpTot[0].toString().split("").reversed.toList();
    String strImpTot = "";

    for(int a = arrImpTotInt.length - 1; a >= 0; a--){
      strImpTot = "$strImpTot${arrImpTotInt[a]}";
      if(a % 3 == 0){
        strImpTot = "$strImpTot,";
      }
    }

    strImpTot = strImpTot.substring(0, strImpTot.length-1);
    strImpTot = "$strImpTot.${arrImpTot[1]}";
    if(!_isLoading){
      int i = 0;
      int j = 0;
      if(_mostrarRegistros){
        if(_saldosCartera.result != null){
          if(_saldosCartera.result!.registros.isNotEmpty){
            do{
              if(isVencida && _saldosCartera.result!.registros[i].moneda == moneda){
                if(_saldosCartera.result!.registros[i].diasdevencimiento > 0){
                  _rows.add(TableRow(
                    decoration: BoxDecoration(
                      color: j%2 != 0 ? const Color.fromRGBO(250, 250, 250, 0.5) : const Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].doc,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].folio,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].fechaEmision,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].fechaVencimiento,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].pedido,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].total,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].diasdevencimiento.toString(),
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].importePendiente,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      )
                    ],
                  ));
                  j++;
                }
              }else if(isTotal && _saldosCartera.result!.registros[i].moneda == moneda){
                _rows.add(TableRow(
                  decoration: BoxDecoration(
                    color: j%2 != 0 ? const Color.fromRGBO(250, 250, 250, 0.5) : const Color.fromRGBO(255, 255, 255, 0.5),
                  ),
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].doc,
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].folio,
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].fechaEmision,
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].fechaVencimiento,
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].pedido,
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].total,
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].diasdevencimiento.toString(),
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                      child: Text(
                        _saldosCartera.result!.registros[i].importePendiente,
                        textAlign: TextAlign.center,
                        style: GoogleFonts.roboto(fontSize: 16.0),
                      ),
                    )
                  ],
                ));
                j++;
              }else if(_saldosCartera.result!.registros[i].moneda == moneda){
                if(_saldosCartera.result!.registros[i].diasdevencimiento == 0 && _saldosCartera.result!.registros[i].tipo != "PENDIENTE"){
                  _rows.add(TableRow(
                    decoration: BoxDecoration(
                      color: j%2 != 0 ? const Color.fromRGBO(250, 250, 250, 0.5) : const Color.fromRGBO(255, 255, 255, 0.5),
                    ),
                    children: [
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].doc,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].folio,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].fechaEmision,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].fechaVencimiento,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].pedido,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].total,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].diasdevencimiento.toString(),
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                        child: Text(
                          _saldosCartera.result!.registros[i].importePendiente,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(fontSize: 16.0),
                        ),
                      )
                    ],
                  ));
                  j++;
                }
              }
              i++;
            }while(i < _saldosCartera.result!.registros.length);
          }
        }
      }
      return SafeArea(
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: SingleChildScrollView(
            child: Column(
              children: [
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.fromLTRB(32.0, 32.0, 32.0, 8.0),
                  child: Text(
                    title,
                    textAlign: TextAlign.center,
                    style: GoogleFonts.roboto(
                      color: const Color(0xFF67616B),
                      fontWeight: FontWeight.w700,
                      fontSize: 18.0,
                    ),
                  ),
                ),
                ElevatedButton(
                  onPressed: () => setState((){
                    _showRegistros = false;
                    _deslizo = false;
                    _scrollController.jumpTo(0.0);
                  }),
                  child: Text(
                    'Regresar',
                    style: GoogleFonts.roboto(
                      color: const Color.fromRGBO(255, 0, 0, 1),
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  style: ElevatedButton.styleFrom(
                    primary: const Color(0xFF4285F4).withOpacity(0.1),
                    elevation: 0.0,
                  ),
                ),
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.fromLTRB(8.0, 8.0, 16.0, 4.0),
                  child: Text(
                    'Cantidades Expresadas en ${_moneda == 'USD' ? _saldosCartera.result!.datosGenerales.usd.moneda : _saldosCartera.result!.datosGenerales.mxp.moneda}',
                    textAlign: TextAlign.start,
                    style: GoogleFonts.roboto(
                      fontSize: 16.0,
                      fontWeight: FontWeight.w700,
                      color: const Color(0xFF67616B),
                      fontStyle: FontStyle.italic,
                    ),
                  ),
                ),
                Stack(
                  children: [
                    NotificationListener<ScrollNotification>(
                      onNotification: (scrollNotification){
                        if(scrollNotification is ScrollStartNotification){
                          _onStartScroll(scrollNotification.metrics);
                        }
                        return true;
                      },
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        controller: _scrollController,
                        child: SizedBox(
                          width: 1024,
                          child: Table(
                            children: _rows,
                            defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                          ),
                        ),
                      ),
                    ),
                    if(!_deslizo)
                      Positioned(
                        top: 16.0,
                        right: 16.0,
                        child: Deslizar(),
                      )
                  ],
                ),
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.all(16.0),
                  child: Text(
                    _mostrarRegistros ? 'Importe Total: \$$strImpTot'
                        '\n Importe Pendiente: \$$totalMod'
                        : 'No se encontraron registros',
                    textAlign: _mostrarRegistros ? TextAlign.end : TextAlign.center,
                    style: GoogleFonts.roboto(
                      fontSize: 18.0,
                      fontWeight: FontWeight.w700,
                      color: const Color(0xFF67616B),
                    ),
                  ),
                ),
                const SizedBox(height: 16.0),
                ElevatedButton(
                  onPressed: () => setState((){
                    _showRegistros = false;
                    _deslizo = false;
                    _scrollController.jumpTo(0.0);
                  }),
                  child: Text(
                    'Regresar',
                    style: GoogleFonts.roboto(
                      color: const Color.fromRGBO(255, 0, 0, 1),
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  style: ElevatedButton.styleFrom(
                    primary: const Color(0xFF4285F4).withOpacity(0.1),
                    elevation: 0.0,
                  ),
                )
              ],
            ),
          ),
        ),
      );
    }
    return Container();
  }

  Widget _buildFiles(String title, int selector){
    List<TableRow> _rows;
    if(!_isLoading){
      _rows = _movimientosComprobantes.result!.registros!.map((registro){
        if(!_actualMonth(registro.fechaEmision!)){
          return TableRow(
            children: [
              Container(),
              Container(),
              Container(),
              Container(),
              Container(),
              Container()
            ],
          );
        }
        if(registro.tipocomprobante!.index == selector){
          return TableRow(
            decoration: const BoxDecoration(color: Color.fromRGBO(255, 255, 255, 0.5)),
            children: [
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                child: Text(
                  registro.folio!,
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(fontSize: 16.0),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                child: Text(
                  _correctDate(registro.fechaEmision!),
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(fontSize: 16.0),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                child: Text(
                  registro.pedido!,
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(fontSize: 16.0),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                child: Text(
                  registro.total!,
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(fontSize: 16.0),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                child: Text(
                  registro.moneda!,
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(fontSize: 16.0),
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
                child: IconButton(
                  icon: const Icon(
                    Icons.remove_red_eye,
                    color: Colors.black,
                  ),
                  onPressed: () {
                    final mesesNum = {
                      'Enero'   : DateTime.january, 'Febrero' : DateTime.february,   'Marzo' : DateTime.march,
                      'Abril'   : DateTime.april,   'Mayo' : DateTime.may,           'Junio' : DateTime.june,
                      'Julio'   : DateTime.july,    'Agosto' : DateTime.august,      'Septiembre' : DateTime.september,
                      'octubre' : DateTime.october, 'Noviembre' : DateTime.november, 'Diciembre' : DateTime.december
                    };
                    Fluttertoast.showToast(
                      msg: 'Abriendo PDF...',
                      toastLength: Toast.LENGTH_LONG,
                      gravity: ToastGravity.CENTER,
                      timeInSecForIosWeb: 1,
                    );
                    _movimientosProvider.fetchComprobantePDF(
                      _loginData['accesToken'],
                      registro.acciones!,
                      _anio.toString(),
                      mesesNum[_mes]! < 10 ? '0${mesesNum[_mes]}' : '${mesesNum[_mes]}',
                    ).then((comprobantePDF){
                      _createFileFromString(comprobantePDF.result!.data!, comprobantePDF.result!.name!).then((name){
                        showViewer(name);
                      });
                    });
                  },
                ),
              )
            ],
          );
        }
        return TableRow(
          children: [
            Container(),
            Container(),
            Container(),
            Container(),
            Container(),
            Container()
          ],
        );
      }).toList();
      _rows.insert(0, TableRow(
        decoration: const BoxDecoration(color: Color.fromRGBO(230, 230, 230, 0.5)),
        children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
            child: Text(
              'Folio',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                color: const Color(0xFF67616B),
                fontWeight: FontWeight.w700,
                fontSize: 18.0,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
            child: Text(
              'Fecha Emisión',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                color: const Color.fromRGBO(255, 0, 0, 0.5),
                fontWeight: FontWeight.w700,
                fontSize: 18.0,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
            child: Text(
              'Pedido',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                color: const Color(0xFF67616B),
                fontWeight: FontWeight.w700,
                fontSize: 18.0,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
            child: Text(
              'Total',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                color: const Color(0xFF67616B),
                fontWeight: FontWeight.w700,
                fontSize: 18.0,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
            child: Text(
              'Moneda',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                color: const Color(0xFF67616B),
                fontWeight: FontWeight.w700,
                fontSize: 18.0,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8.0),
            child: Text(
              'Acciones',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                color: const Color(0xFF67616B),
                fontWeight: FontWeight.w700,
                fontSize: 18.0,
              ),
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
            ),
          )
        ],
      ));
      return SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              Container(
                width: double.infinity,
                child: Text(
                  title,
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(
                    color: const Color(0xFF67616B),
                    fontWeight: FontWeight.w700,
                    fontSize: 18.0,
                  ),
                ),
                margin: const EdgeInsets.fromLTRB(32.0, 32.0, 32.0, 0.0),
              ),
              ElevatedButton(
                onPressed: () => setState(() => _showFiles = false),
                child: Text(
                  'Regresar',
                  style: GoogleFonts.roboto(
                    color: const Color.fromRGBO(255, 0, 0, 1),
                    fontSize: 18.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  primary: const Color(0xFF4285F4).withOpacity(0.1),
                  elevation: 0.0,
                ),
              ),
              Stack(
                children: [
                  NotificationListener<ScrollNotification>(
                    onNotification: (scrollNotification){
                      if(scrollNotification is ScrollStartNotification){
                        _onStartScroll(scrollNotification.metrics);
                      }
                      return true;
                    },
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: SizedBox(
                        width: 1024,
                        child: Table(
                          children: _rows,
                          defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                        ),
                      ),
                    ),
                  ),
                  if(!_deslizo)
                    Positioned(
                      top: 16.0,
                      right: 16.0,
                      child: Deslizar(),
                    )
                ],
              ),
              if(_movimientosComprobantes.result!.registros!.isEmpty)
                Container(
                  width: double.infinity,
                  margin: const EdgeInsets.all(16.0),
                  child: Text(
                    'No se encontraron registros',
                    textAlign: TextAlign.center,
                    style: GoogleFonts.roboto(
                      fontSize: 16.0,
                    ),
                  ),
                ),
              const SizedBox(height: 16.0),
              ElevatedButton(
                onPressed: () => setState(() => _showFiles = false),
                child: Text(
                  'Regresar',
                  style: GoogleFonts.roboto(
                    color: const Color.fromRGBO(255, 0, 0, 1),
                    fontSize: 18.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  primary: const Color(0xFF4285F4).withOpacity(0.1),
                  elevation: 0.0,
                ),
              )
            ],
          ),
        ),
      );
    }
    return Container();
  }

  Future<void> _changeDateOfInvoices() async{
    setState(() => _changingDate = true);
    final actualYear = DateTime.now().year;
    const initialYear = 2000;
    final List<int> years = [];

    for(int i = initialYear; i <= actualYear; i++){
      years.add(i);
    }

    final yearResponse = await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text("Selecciona el año"),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: years.reversed.map((e) => TextButton(
              child: Text("$e"),
              onPressed: () => Navigator.pop(context, e),
            )).toList(),
          ),
        ),
        actions: [
          TextButton(
            child: const Text('Cancelar'),
            onPressed: () => Navigator.pop(context, 0),
          )
        ],
      ),
    );

    if(yearResponse == 0 || yearResponse == null) return;

    const Map<int, String> months = {
      1: 'Enero', 2: 'Febrero', 3: 'Marzo', 4: 'Abril', 5: 'Mayo', 6: 'Junio', 7: 'Julio',
      8: 'Agosto', 9: 'Septiembre', 10: 'Octubre', 11: 'Noviembre', 12: 'Diciembre',
    };
    final actualMonth = DateTime.now().month;
    final List<int> displayedMonths = [];

    for(int j = 1; j <= 12; j++){
      if(actualYear == yearResponse){
        if(j <= actualMonth){
          displayedMonths.add(j);
        }
      }else{
        displayedMonths.add(j);
      }
    }

    final monthResponse = await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: const Text("Selecciona el mes"),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: displayedMonths.map((e) => TextButton(
              child: Text(months[e]!),
              onPressed: () => Navigator.pop(context, e),
            )).toList(),
          ),
        ),
        actions: [
          TextButton(
            child: const Text('Cancelar'),
            onPressed: () => Navigator.pop(context, 0),
          )
        ],
      ),
    );

    if(monthResponse == 0 || monthResponse == null) return;

    setState(() {
      _anio = yearResponse;
      _mes = _meses[monthResponse]!;
    });

    final dateUtil = DateUtils.getDaysInMonth(_anio, monthResponse);
    final strMonth = monthResponse < 10 ? '0$monthResponse' : '$monthResponse';
    final fecIni = '$_anio-$strMonth-01';
    final fecFin = '$_anio-$strMonth-$dateUtil';

    Fluttertoast.showToast(
      msg: 'Obteniendo datos...',
      toastLength: Toast.LENGTH_LONG,
      timeInSecForIosWeb: 3,
      gravity: ToastGravity.CENTER,
    );

    final movimientosComprobantes = await _movimientosProvider.fetchMovimientosComprobantes(
      _loginData['accesToken'],
      _loginData['dinum'],
      _loginData['user'],
      fecIni,
      fecFin,
    );

    setState(() {
      _facturas = movimientosComprobantes.result!.datosGenerales!.factura!.total!;
      _notasCargo = movimientosComprobantes.result!.datosGenerales!.notadecargo!.total!;
      _notasCredito = movimientosComprobantes.result!.datosGenerales!.notadecredito!.total!;
      _pago = movimientosComprobantes.result!.datosGenerales!.pago!.total!;
      _changingDate = false;
    });
  }

  Widget _buildSingleCard(String totalMod, String imgBack, String title, String desc, bool saldos, bool mostrarRegistros, int selector, bool isVencida, bool isTotal){
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
      margin: const EdgeInsets.all(16.0),
      elevation: 10,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: SizedBox(
          height: 152.0,
          child: Stack(
            children: [
              Positioned(
                bottom: 0.0,
                right: 0.0,
                child: Image.asset(
                  imgBack,
                  width: 128.0,
                ),
              ),
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                    margin: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      title,
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w700,
                        fontSize: 18.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    margin: const EdgeInsets.only(bottom: 4.0),
                    child: _changingDate ? const Center(
                        child: CircularProgressIndicator()
                    ) : Text(
                      desc,
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w900,
                        fontSize: 22.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  ElevatedButton(
                    child: Text(
                      'Ver Detalles',
                      style: GoogleFonts.roboto(
                        color: const Color.fromRGBO(255, 0, 0, 1),
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    onPressed: saldos ? () => setState((){
                      _showRegistros = true;
                      _mostrarRegistros = mostrarRegistros;
                      _registroTitle = title;
                      _totalMod = totalMod;
                      _isVencida = isVencida;
                      _isTotal = isTotal;
                      _moneda = 'MXP';
                    }) : () => setState((){
                      _showFiles = true;
                      _filesTitle = title;
                      _selector = selector;
                    }),
                    style: ElevatedButton.styleFrom(
                      primary: const Color(0xFF4285F4).withOpacity(0.1),
                      elevation: 0.0,
                    ),
                  )
                ],
              ),
              const SizedBox(height: 16.0)
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildContactCard(String depto, String num, String cor, String ext){
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
      margin: const EdgeInsets.all(16.0),
      elevation: 10,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: SizedBox(
          height: 412.0,
          child: Stack(
            children: [
              Positioned(
                bottom: 0.0,
                right: 0.0,
                child: Image.asset(
                  'assets/contacto.png',
                  width: 224.0,
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                bottom: 0.0,
                child: Container(
                  width: 3000,
                  height: 16.0,
                  color: const Color.fromRGBO(255, 0, 0, 1),
                ),
              ),
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                    margin: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      'CONTACTO',
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w700,
                        fontSize: 18.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    //margin: EdgeInsets.only(bottom: 4.0),
                    child: Text(
                      'Para cualquier duda o aclaración favor de comunicarse al:',
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w900,
                        fontSize: 16.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    margin: const EdgeInsets.only(bottom: 4.0),
                    child: Text(
                      'Depto. $depto\n\n'
                          'Tel: (${num.substring(0, 3)}) ${num.substring(3)} ext. $ext \n\n'
                          '$cor',
                      style: GoogleFonts.roboto(
                        fontSize: 16.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16.0)
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildSingleCardDobleMoneda(List<String> totalesMod, String imgBack, String title, List<String> desc, bool isVencida, bool isTotal){
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
      margin: const EdgeInsets.all(16.0),
      elevation: 10,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.0),
        child: SizedBox(
          height: 248.0,
          child: Stack(
            children: [
              Positioned(
                bottom: 0.0,
                right: 0.0,
                child: Image.asset(
                  imgBack,
                  width: 128.0,
                ),
              ),
              Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                    margin: const EdgeInsets.only(top: 8.0),
                    child: Text(
                      title,
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w700,
                        fontSize: 18.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    margin: const EdgeInsets.only(bottom: 4.0),
                    child: _changingDate ? const Center(
                      child: CircularProgressIndicator(),
                    ) : Text(
                      desc[0],
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w900,
                        fontSize: 22.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  ElevatedButton(
                    child: Text(
                      'Ver Detalles',
                      style: GoogleFonts.roboto(
                        color: const Color.fromRGBO(255, 0, 0, 1),
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold
                      ),
                    ),
                    onPressed: () => setState((){
                      _showRegistros = true;
                      _mostrarRegistros = true;
                      _registroTitle = title;
                      _totalMod = totalesMod[0];
                      _isVencida = isVencida;
                      _isTotal = isTotal;
                      _moneda = 'USD';
                    }),
                    style: ElevatedButton.styleFrom(
                      primary: const Color(0xFF4285F4).withOpacity(0.1),
                      elevation: 0.0,
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    margin: const EdgeInsets.only(bottom: 4.0),
                    child: _changingDate ? const Center(
                      child: CircularProgressIndicator(),
                    ) : Text(
                      desc[1],
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w900,
                        fontSize: 22.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                  ElevatedButton(
                    child: Text(
                      'Ver Detalles',
                      style: GoogleFonts.roboto(
                        color: const Color.fromRGBO(255, 0, 0, 1),
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    onPressed: () => setState((){
                      _showRegistros = true;
                      _mostrarRegistros = true;
                      _registroTitle = title;
                      _totalMod = totalesMod[1];
                      _isVencida = isVencida;
                      _isTotal = isTotal;
                      _moneda = 'MXP';
                    }),
                    style: ElevatedButton.styleFrom(
                      primary: const Color(0xFF4285F4).withOpacity(0.1),
                      elevation: 0.0,
                    ),
                  )
                ],
              ),
              const SizedBox(height: 16.0)
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildCarteraVencidaCard(List<String> totalMod, String title, List<String> desc, Map<String, CarteraVencer> carteraVencer, bool mostrarRegistros, List<String> porAplicar, bool isDoble){
    return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
      margin: const EdgeInsets.all(16.0),
      elevation: 10,
      child: ClipRRect(
          borderRadius: BorderRadius.circular(8.0),
          child: SizedBox(
            height: isDoble ? 848.0 : 460.0,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 16.0),
                  margin: const EdgeInsets.only(top: 8.0),
                  child: Text(
                    title,
                    style: GoogleFonts.roboto(
                      fontWeight: FontWeight.w700,
                      fontSize: 18.0,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
                if(isDoble)
                  Container(
                    width: double.infinity,
                    padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                    margin: const EdgeInsets.only(bottom: 4.0),
                    child: Text(
                      desc[0],
                      style: GoogleFonts.roboto(
                        fontWeight: FontWeight.w900,
                        fontSize: 22.0,
                      ),
                      textAlign: TextAlign.center,
                    ),
                  ),
                if(isDoble)
                  ElevatedButton(
                    child: Text(
                      'Ver Detalles',
                      style: GoogleFonts.roboto(
                        color: const Color.fromRGBO(255, 0, 0, 1),
                        fontSize: 18.0,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    onPressed: () => setState((){
                      _mostrarRegistros = mostrarRegistros;
                      _totalMod = totalMod[0];
                      _showRegistros = true;
                      _registroTitle = title;
                      _isVencida = true;
                      _isTotal = false;
                      _moneda = 'USD';
                    }),
                    style: ElevatedButton.styleFrom(
                      primary: const Color(0xFF4285F4).withOpacity(0.1),
                      elevation: 0.0,
                    ),
                  ),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
                  margin: const EdgeInsets.only(bottom: 4.0),
                  child: Text(
                    isDoble ? desc[1] : desc[0],
                    style: GoogleFonts.roboto(
                      fontWeight: FontWeight.w900,
                      fontSize: 22.0,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
                ElevatedButton(
                  child: Text(
                    'Ver Detalles',
                    style: GoogleFonts.roboto(
                      color: const Color.fromRGBO(255, 0, 0, 1),
                      fontSize: 18.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  onPressed: () => setState((){
                    _mostrarRegistros = mostrarRegistros;
                    _totalMod = isDoble ? totalMod[1] : totalMod[0];
                    _showRegistros = true;
                    _registroTitle = title;
                    _isVencida = true;
                    _isTotal = false;
                    _moneda = 'MXP';
                  }),
                  style: ElevatedButton.styleFrom(
                    primary: const Color(0xFF4285F4).withOpacity(0.1),
                    elevation: 0.0
                  ),
                ),
                const SizedBox(height: 16.0),
                if(isDoble)
                  Container(
                    width: double.infinity,
                    height: 40.0,
                    color: const Color(0xFFEEEEEE),
                    child: Row(
                      children: [
                        Expanded(
                          flex: 1,
                          child: SizedBox(
                            child: Text(
                              'Moneda: ',
                              textAlign: TextAlign.right,
                              style: GoogleFonts.roboto(
                                fontWeight: FontWeight.bold,
                                color: const Color(0xFF777777),
                                fontSize: 18.0,
                              ),
                            ),
                          ),
                        ),
                        Expanded(
                          flex: 1,
                          child: SizedBox(
                            child: Text(
                              ' USD',
                              textAlign: TextAlign.left,
                              style: GoogleFonts.roboto(
                                fontWeight: FontWeight.w300,
                                color: const Color(0xFF777777),
                                fontSize: 18.0,
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                if(isDoble)
                  Table(
                    children: [
                      _buildTableRow(false, '1-15', _isLoading ? '' : carteraVencer['USD'] != null ? carteraVencer['USD']!.the015! : '', false, false, false),
                      _buildTableRow(true, '16-30', _isLoading ? '' : carteraVencer['USD'] != null ? carteraVencer['USD']!.the1630! : '', false, false, false),
                      _buildTableRow(false, '31-45', _isLoading ? '' : carteraVencer['USD'] != null ? carteraVencer['USD']!.the3145! : '', false, false, false),
                      _buildTableRow(true, '+45', _isLoading ? '' : carteraVencer['USD'] != null ? carteraVencer['USD']!.the45! : '', true, false, false),
                      _buildTableRow(false, '  ', _isLoading ? '  ' : '  ', false, true, false),
                      _buildTableRow(true, 'Pagos y Créditos por Aplicar',
                          _isLoading ? '' : porAplicar[0], false, false, true),
                    ],
                  ),
                if(isDoble)
                  const SizedBox(height: 16.0),
                Container(
                  width: double.infinity,
                  height: 40.0,
                  color: const Color(0xFFEEEEEE),
                  child: Row(
                    children: [
                      Expanded(
                        flex: 1,
                        child: SizedBox(
                          child: Text(
                            'Moneda: ',
                            textAlign: TextAlign.right,
                            style: GoogleFonts.roboto(
                                fontWeight: FontWeight.bold,
                                color: const Color(0xFF777777),
                                fontSize: 18.0
                            ),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: SizedBox(
                          child: Text(
                            ' MXN',
                            textAlign: TextAlign.left,
                            style: GoogleFonts.roboto(
                                fontWeight: FontWeight.w300,
                                color: const Color(0xFF777777),
                                fontSize: 18.0
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Table(
                  children: [
                    _buildTableRow(false, '1-15', _isLoading ? '' : carteraVencer['MXP'] != null ? carteraVencer['MXP']!.the015! : '', false, false, false),
                    _buildTableRow(true, '16-30', _isLoading ? '' : carteraVencer['MXP'] != null ? carteraVencer['MXP']!.the1630! : '', false, false, false),
                    _buildTableRow(false, '31-45', _isLoading ? '' : carteraVencer['MXP'] != null ? carteraVencer['MXP']!.the3145! : '', false, false, false),
                    _buildTableRow(true, '+45', _isLoading ? '' : carteraVencer['MXP'] != null ? carteraVencer['MXP']!.the45! : '', true, false, false),
                    _buildTableRow(false, '  ', _isLoading ? '  ' : '  ', false, true, false),
                    _buildTableRow(true, 'Pagos y Créditos por Aplicar',
                        _isLoading ? '' : isDoble ? porAplicar[1] : porAplicar[0], false, false, true),
                  ],
                )
              ],
            ),
          )
      ),
    );
  }

  TableRow _buildTableRow(bool gray, String range, String carteraVencer, bool last, bool empty, bool porAplicar){
    return TableRow(
        decoration: BoxDecoration(
          color: gray ? const Color(0xFFEEEEEE) : const Color.fromRGBO(0, 0, 0, 0),
        ),
        children: [
          Container(
            child: Text(
              empty ? range : porAplicar ? range : '$range días',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                fontWeight: FontWeight.w600,
                color: const Color(0xFF67616b),
              ),
            ),
            padding: const EdgeInsets.all(8.0),
          ),
          Container(
            child: Text(
              empty ? carteraVencer : '\$$carteraVencer',
              textAlign: TextAlign.center,
              style: GoogleFonts.roboto(
                fontSize: 18.0,
                color: last ? const Color(0xFFFF0000) : const Color(0xFF67616b),
                decoration: last ? TextDecoration.underline : TextDecoration.none
              ),
            ),
            padding: const EdgeInsets.all(8.0),
          )
        ]
    );
  }

  _onStartScroll(ScrollMetrics metrics) => setState(() => _deslizo = true);

  bool _actualMonth(String date){
    final Map<String, String> months = {
      'JAN' : 'ENERO', 'FEB' : 'FEBRERO', 'MAR' : 'MARZO', 'APR' : 'ABRIL', 'MAY' : 'MAYO', 'JUN' : 'JUNIO',
      'JUL' : 'JULIO', 'AUG' : 'AGOSTO', 'SEP' : 'SEPTIEMBRE', 'OCT' : 'OCTUBRE', 'NOV' : 'NOVIEMBRE', 'DEC' : 'DICIEMBRE'
    };
    final arrDate = date.split('/');
    final month = months[arrDate[1]];
    final year = int.parse('20${arrDate[0]}');

    if(_anio == year && month == _mes.toUpperCase()){
      return true;
    }

    return false;
  }

  String _correctDate(String date){
    final arrDate = date.split('/');
    return '${arrDate[2]}/${arrDate[1]}/20${arrDate[0]}';
  }

  Future<File> _createFileFromString(String encoded, String name) async{
    Uint8List bytes = base64Decode(encoded);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = File(
        "$dir/$name"
    );
    await file.writeAsBytes(bytes);
    return file;
  }
}
