﻿import React from 'react';
import ReactDom from 'react-dom';
import SweetAlert from 'sweetalert2-react';
import TopBar from '../Common/TopBar';
import { ServiceRequest } from '../Request/service';
import Table from '../Common/Table';
import Session from '../Session';
import { SiteRoutes, baseUrl } from '../../../config';
import moment from 'moment';
import Filtro from '../Common/Filtro';
import Editar from '../Common/Editar';
import Lista from '../Common/Lista';
import LoginModal from '../Common/LoginModal';
import { play } from '../../../util';
import audio from 'simple-audio';
import BuscarArticulo from '../Common/BuscarArticulo';
import LocalStorage from '../LocalStorage';
import Swal from 'sweetalert2';

class ConteoMain extends React.Component {  
    constructor() {  
        super();
        this.state = {
            showFiltro: true,  
            showLista: false,
            showEditar: false,
            lstData: [],
            lstBodega: [],
            lstConteoDetail: [],
            lstConteoDetailFilter: [],
            bodega: 0,
            fechaInicio: moment(new Date()).format('01/MM/YYYY'),
            fechaFin: moment(new Date()).format("DD/MM/YYYY"),
            rowConteo: {},
            currentRowDetail: {},
            index: 0,
            disabledNext: '',
            disabledPrev: '',
            positions: [],
            digitarCantidad: false,
            sumaAutomatica: true,
            sumarCantidad: true,
            cambiarCantidad: false,
            articulo: '',
            cantidad: 0,
            filterContados: false,
            filterNoContados: false,
            //Seguridad de las acciones del menu
            showLoginModal: false,
            username: '',
            password: '',
            modulo:-1,
            menu: -1,
            opcion: -1,
            accion: undefined,
            opcionNombre: '',
            usuarioId: 0,
            showApplyOption: false,
            autorizado:true

        };
    }
  
    async componentWillMount() {

       
    }

      componentDidMount() {
        let _tienePermision =  ServiceRequest.Verificar_Permiso_Menu(this.props.data.Menu);
        if (parseInt(_tienePermision.data) == 0) {
            this.setState({ autorizado: false });
        }

        this.obtenerPosiciones();
        this.getBodegaList();
    }

    async getBodegaList() {
        let _response = await ServiceRequest.Bodega_Lista();
        if (_response.isError == false) {
            let lstBodega = _response.data;
            this.setState({ lstBodega })
        } else {
            toastr.error(_response.data)
        }

    }
    onChange(e) {
        let id = e.target.id;
        let value = e.target.value;
        let name = e.target.name;      
        let checked = e.target.checked;
        if (checked == undefined) {
            checked = false;
        }
        switch (id) {
            case 'select-bodega':
                this.setState({ [name]: value });
                break;
            case 'cantidad':
                this.updateCantidad(value);
                if (name =='boton'){
                    this.updateConteoCantidad(undefined, true);
                }            
                break; 
            case 'articulo':
                this.searchArticulo(value.trim());
                break; 
            case 'fecha-inicio':
                this.setState({ fechaInicio: value });
                break; 
            case 'fecha-fin':
                this.setState({ fechaFin: value });
                break; 
            case 'suma-automatica':
                this.setState({ sumaAutomatica: value, digitarCantidad: !value });
                break; 
            case 'cb-contados':
                this.state.filterContados = checked;
                this.doFilter();
                break;
            case 'cb-nocontados':
                this.state.filterNoContados = checked;
                this.doFilter();
                break;
        }    
    }
    onShowLista() {
        this.setState({ showApplyOption: false, showFiltro: false, showLista: true, showEditar: false, index: 0, currentRowDetail: {}, lstConteoDetailFilter: [], lstConteoDetail: [], articulo: '', filterNoContados: false, filterNoContados: false, sumaAutomatica: true, digitarCantidad: false, sumarCantidad: true, cambiarCantidad: false });             
    }
    onClick(e) {
        let id = e.currentTarget.id;
      
        switch (id) {
            case 'btn-filtrar':
                break;
            case 'btn-regresar':
                this.setState({ showFiltro: true, showLista: false, showEditar: false,  });
                break;
            case 'btn-editar':
                this.onEditar();
                break;
            case 'btn-regresar-editar':
                this.onShowLista();
                break;
            case 'btn-next':
                this.onNext();
                e.currentTarget.blur();
                break;
            case 'btn-prev':
                this.onPrev();
                e.currentTarget.blur();
                break;
            case 'rb-digitar-cantidad':
                this.setState({ digitarCantidad: !this.state.digitarCantidad, sumaAutomatica: !this.state.sumaAutomatica });
                break;
            case 'rb-suma-automatica':
                this.setState({ sumaAutomatica: !this.state.sumaAutomatica, digitarCantidad: !this.state.digitarCantidad });
                break;
            case 'rb-sumar-cantidad':
                this.setState({ sumarCantidad: !this.state.sumarCantidad, cambiarCantidad: !this.state.cambiarCantidad });
                break;
            case 'rb-cambiar-cantidad':
                this.setState({ cambiarCantidad: !this.state.cambiarCantidad, sumarCantidad: !this.state.sumarCantidad });
                break;
            case 'btn-aplicar':
                this.updateConteoCantidad();
                break;
            case 'btnCancel':
                this.setState({ showApplyOption: false });
                this.cancelarCantidad(); //Regresa la cantidad Actual a la cantidad original.
                break;
            case 'btnApply':
                this.updateConteoCantidadApply(undefined, true);
                break;
            case 'cantidad':
                this.setState({ showApplyOption: true });
                break;
            case 'btn-aplicar-orden':
                this.onAplicar();
                break;
            case 'btnEliminarDetalle':
                this.onBorrarDetalle()
                break;
            case 'btnBuscarArticulo':
                 this.buscarArticulo()
                break;
        }
    }

 

    doFilter() {
        const { filterContados, filterNoContados, lstConteoDetail, lstConteoDetailFilter } = this.state;
        let _lstFiltered = [];
        lstConteoDetailFilter.map(item => {
            if (filterContados && item.Cantidad >0) {
                _lstFiltered.push(item);
            }
            if (filterNoContados && item.Cantidad == 0) {
                _lstFiltered.push(item);
            }
           
        });

        
        if (_lstFiltered.length > 0) {
            this.setState({ lstConteoDetail: _lstFiltered, index: 0, currentRowDetail: _lstFiltered[0] });
        } else {
            this.setState({ filterNoContados: false, filterContados: false, lstConteoDetail: lstConteoDetailFilter, index: 0, currentRowDetail: lstConteoDetailFilter[0] });
        }
          

    }
   async searchArticulo(pCodigo) {   
        let _index = 0;    
        let _rowFinded = {};
        const { lstConteoDetail, sumaAutomatica } = this.state;     
       
        let _equivalenteData = await ServiceRequest.Conteo_ValidarArticuloEquivalente(pCodigo);
        if (_equivalenteData.isError == false) {
            let _codigoArticulo = _equivalenteData.data;
        
            _rowFinded = lstConteoDetail.find(item => item.Id == _codigoArticulo.toString());
        
            if (_rowFinded != undefined) {  
              //Preguntamos si tiene un hijo  
        
                if (_rowFinded.Hijo =='' && _rowFinded.Padre =='')
                {
                    this.setState({ currentRowDetail: _rowFinded, articulo: _rowFinded.Id, index: _rowFinded.index, disabledNext: '', disabledPrev: '' });
                    if (sumaAutomatica) {
                        this.updateConteoCantidad(_rowFinded);
                    }
                }
                else{

                    Swal.fire({
                        title: 'Toma Física',
                        text: 'El Artículo '+_rowFinded.Id+' -'+_rowFinded.Nombre+' es un padre.¿Desea Facturar?',                   
                        showCancelButton: true,
                        confirmButtonColor: 'rgb(72, 196, 136)',                    
                        confirmButtonText: 'Hijo',
                        cancelButtonText:"Padre",
                       
                      }).then((result) => {
                            
                        if (result.value) {
                            //Validamos si existe el hijo en el conteo

                            if (_rowFinded.Hijo !='')
                            {
                                const _lstHijo = lstConteoDetail.filter(item => item.Id == _rowFinded.Hijo);                                
                                if (_lstHijo.length==0)
                                {
    
                                    toastr.error("Artículo hijo no encontrado");
                                }
    
                                this.setState({ currentRowDetail: _lstHijo[0], articulo: _lstHijo[0].Id, index: _lstHijo[0].index, disabledNext: '', disabledPrev: '' }, () => {
                              
                                    if (sumaAutomatica) {
                                        this.updateConteoCantidad( _lstHijo[0]);
                                    }
                                });
                                
                            }
                            else{
                                this.setState({ currentRowDetail: _rowFinded, articulo: _rowFinded.Id, index: _rowFinded.index, disabledNext: '', disabledPrev: '' });
                                if (sumaAutomatica) {
                                    this.updateConteoCantidad(_rowFinded);
                                }

                            }
                         
                        }
                        else{
                            if (result.dismiss=='cancel')
                            {    
                                  //Validamos si existe el padre en el conteo
                                  if (_rowFinded.Padre !='')
                                  {
                                    const _lstPadre = lstConteoDetail.filter(item => item.Id == _rowFinded.Padre);                                    
                                    if (_lstPadre.length==0)
                                    {
          
                                        toastr.error("Artículo Padre no se encuentra");
                                    }
        
                                    this.setState({ currentRowDetail: _lstPadre[0], articulo: _lstPadre[0].Id, index: _lstPadre[0].index, disabledNext: '', disabledPrev: '' }, () => {
                                  
                                        if (sumaAutomatica) {
                                            this.updateConteoCantidad( _lstPadre[0]);
                                        }
                                    });

                                  }
                                  else{ this.setState({ currentRowDetail: _rowFinded, articulo: _rowFinded.Id, index: _rowFinded.index, disabledNext: '', disabledPrev: '' });
                                  if (sumaAutomatica) {
                                      this.updateConteoCantidad(_rowFinded);
                                  }}
                           
                            }
                            else{                                  
                                //this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
                            }
                        }
                      })
        
        
                }
              


               
            } else {  
                this.playAudio('Error');
                toastr.error("Artículo no encontrado");
            }
        }
    }   
      

   /* updateConteoCantidad(pCurrentRow, pCambiar) {     
        
        const { currentRowDetail, digitarCantidad, sumarCantidad, sumaAutomatica, cambiarCantidad, showApplyOption} = this.state;
        let _efecto = '';
        let _cantidad = 0;
        var currentItem = pCurrentRow == undefined ? currentRowDetail : pCurrentRow;
        if (pCambiar) {
            if (digitarCantidad && sumarCantidad && showApplyOption) {
                _cantidad = parseInt(currentItem.Cantidad) + parseInt(currentItem.Conteo);
                if (_cantidad >= 9999999) {
                    toastr.error("La cantidad ingresada no está permitida");
                    this.playAudio('Error');
                    return;
                }
                currentItem.Conteo = _cantidad;
                currentItem.Cantidad = currentItem.Conteo;
                _efecto = 'Sumar';
            } else {
                _cantidad = currentItem.Cantidad;
                currentItem.Conteo = currentItem.Cantidad;
                _efecto = 'Cambiar';
            }
            
        } else {
            if (digitarCantidad && sumarCantidad) {
                _cantidad = parseInt(currentItem.Cantidad) + parseInt(currentItem.Conteo);
                if (_cantidad >= 9999999){
                    toastr.error("La cantidad ingresada no está permitida");
                    this.playAudio('Error');
                    return;
                }
                currentItem.Conteo = _cantidad;
                currentItem.Cantidad = currentItem.Conteo;
                _efecto = 'Sumar';
            } else
                if (digitarCantidad && cambiarCantidad) {
                    _cantidad = currentItem.Cantidad;
                    if (_cantidad >= 9999999) {
                        toastr.error("La cantidad ingresada no está permitida");
                        this.playAudio('Error');
                        return;
                    }
                    currentItem.Conteo = currentItem.Cantidad;
                    _efecto = 'Cambiar';
                } else
                    if (sumaAutomatica) {
                        _cantidad = 1;
                        if (parseInt(currentItem.Conteo) >= 9999999) {
                            toastr.error("No puede sumar a la cantidad ingresada.");
                            this.playAudio('Error');
                            return;
                        }
                        currentItem.Conteo = parseInt(currentItem.Conteo) + 1;
                        currentItem.Cantidad = parseInt(currentItem.Conteo);
                        _efecto = 'Sumar';
                    }
        }
        this.updateDetail(currentItem.Id, _cantidad, _efecto, currentItem);
        this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
    }*/


    cambiarDatos(currentItem,_cantidad,_efecto){
        //debugger;
        const {sumarCantidad,  showApplyOption} = this.state;
        if (sumarCantidad && showApplyOption) {  
            
            _cantidad = parseFloat(currentItem.Cantidad) + parseFloat(currentItem.Conteo);
            //
            if (_cantidad >= 9999999) {
                toastr.error("La cantidad ingresada no está permitida");
                this.playAudio('Error');
                return;
            }
            currentItem.Conteo = _cantidad;
            currentItem.Cantidad = currentItem.Conteo;
            _efecto = 'Sumar';
        } else {
            
            _cantidad = currentItem.Cantidad;
          
            currentItem.Conteo = currentItem.Cantidad;
            
            _efecto = 'Cambiar';
        }
        this.updateDetail(currentItem.Id, _cantidad, _efecto, currentItem);
        this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
    }
    cambiarDatosApply(currentItem, _cantidad, _efecto) {
        //debugger;
        const { sumarCantidad, showApplyOption } = this.state;
        if (sumarCantidad && showApplyOption) {

            _cantidad = parseFloat(currentItem.Cantidad) + parseFloat(currentItem.Conteo);
            //
            if (_cantidad >= 9999999) {
                toastr.error("La cantidad ingresada no está permitida");
                this.playAudio('Error');
                return;
            }
            currentItem.Conteo = _cantidad;
            currentItem.Cantidad = currentItem.Conteo;
            _efecto = 'Cambiar';
        } else {

            _cantidad = currentItem.Cantidad;

            currentItem.Conteo = currentItem.Cantidad;

            _efecto = 'Cambiar';
        }
        this.updateDetail(currentItem.Id, _cantidad, _efecto, currentItem);
        this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
    }
    
    updateConteoCantidad(pCurrentRow, pCambiar) {   
        //debugger;  
        const { currentRowDetail, digitarCantidad, sumarCantidad, sumaAutomatica, cambiarCantidad, showApplyOption} = this.state;
        let _efecto = '';
        let _cantidad = 0;
        var currentItem = pCurrentRow == undefined ? currentRowDetail : pCurrentRow;
        
        if (pCambiar) {
            //Cuando es el boton de sumar
            //Validar Locacage    
        
            const localStorage = new LocalStorage();
            let Valida = localStorage.get('AccionDigitar');
            if (Valida==3 && showApplyOption)
            {
              
  
                  Swal.fire({
                    title: 'Elección al Digitar',
                    text: "Opciones",                    
                    showCancelButton: true,
                    confirmButtonColor: 'rgb(72, 196, 136)',                    
                    confirmButtonText: 'Sumar Cantidad',
                    cancelButtonText:"Reemplazar Cantidad",
                    cancelButtonColor: 'rgb(72, 196, 136)',

                  }).then((result) => {
                      
                    if (result.value) {
                        
                        this.setState({
                            sumarCantidad: true
                        }, () => {
                      
                            this.cambiarDatos(currentItem,_cantidad,_efecto);
                        });
                    }
                    else{
                        if (result.dismiss=='cancel')
                        {    
                            this.setState({
                                sumarCantidad: false
                            }, () => {
                                
                                this.cambiarDatos(currentItem,_cantidad,_efecto);
                            });
                        }
                        else{
                            this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
                        }
                    }
                  })
                
           
            }
            else
            { 
                this.cambiarDatos(currentItem,_cantidad,_efecto);}
        } else {
            if (digitarCantidad && sumarCantidad) {
                _cantidad = parseFloat(currentItem.Cantidad) + parseFloat(currentItem.Conteo);
                if (_cantidad >= 9999999){
                    toastr.error("La cantidad ingresada no está permitida");
                    this.playAudio('Error');
                    return;
                }
                currentItem.Conteo = _cantidad;
                currentItem.Cantidad = currentItem.Conteo;
                _efecto = 'Sumar';
            } else
                if (digitarCantidad && cambiarCantidad) {  
                    _cantidad = currentItem.Cantidad;
                    if (_cantidad >= 9999999) {
                        toastr.error("La cantidad ingresada no está permitida");
                        this.playAudio('Error');
                        return;
                    }
                    currentItem.Conteo = currentItem.Cantidad; 
                    _efecto = 'Cambiar';
                } else
                    if (sumaAutomatica) {
                        _cantidad = 1;
                        if (parseFloat(currentItem.Conteo) >= 9999999) {
                            toastr.error("No puede sumar a la cantidad ingresada.");
                            this.playAudio('Error');
                            return;
                        }
                        currentItem.Conteo = parseFloat(currentItem.Conteo) + 1;
                        currentItem.Cantidad = parseFloat(currentItem.Conteo);
                        _efecto = 'Sumar';
                       // _cantidad=  currentItem.Cantidad;
                    }
                    this.updateDetail(currentItem.Id, _cantidad, _efecto, currentItem);
                    this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
        }

        ///Antes enviar mensaje
      
        //console.log('Corre aqui');
        //btnApply 
        
       
       
       
    }
    updateConteoCantidadApply(pCurrentRow, pCambiar) {
        //debugger;
        const { currentRowDetail, digitarCantidad, sumarCantidad, sumaAutomatica, cambiarCantidad, showApplyOption } = this.state;
        let _efecto = '';
        let _cantidad = 0;
        var currentItem = pCurrentRow == undefined ? currentRowDetail : pCurrentRow;

        if (pCambiar) {
            //Cuando es el boton de sumar
            //Validar Locacage    

            const localStorage = new LocalStorage();
            let Valida = localStorage.get('AccionDigitar');
            if (Valida == 3 && showApplyOption) {


                Swal.fire({
                    title: 'Elección al Digitar',
                    text: "Opciones",
                    showCancelButton: true,
                    confirmButtonColor: 'rgb(72, 196, 136)',
                    confirmButtonText: 'Sumar Cantidad',
                    cancelButtonText: "Reemplazar Cantidad",

                }).then((result) => {

                    if (result.value) {

                        this.setState({
                            sumarCantidad: true
                        }, () => {

                            this.cambiarDatos(currentItem, _cantidad, _efecto);
                        });






                    }
                    else {
                        if (result.dismiss == 'cancel') {
                            this.setState({
                                sumarCantidad: false
                            }, () => {

                                this.cambiarDatos(currentItem, _cantidad, _efecto);
                            });
                        }
                        else {
                            this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
                        }
                    }
                })


            }
            else {
                this.cambiarDatosApply(currentItem, _cantidad, 'Cambiar');
            }




        } else {
            if (digitarCantidad && sumarCantidad) {
                _cantidad = parseFloat(currentItem.Cantidad) + parseFloat(currentItem.Conteo);
                if (_cantidad >= 9999999) {
                    toastr.error("La cantidad ingresada no está permitida");
                    this.playAudio('Error');
                    return;
                }
                currentItem.Conteo = _cantidad;
                currentItem.Cantidad = currentItem.Conteo;
                _efecto = 'Sumar';
            } else
                if (digitarCantidad && cambiarCantidad) {
                    _cantidad = currentItem.Cantidad;
                    if (_cantidad >= 9999999) {
                        toastr.error("La cantidad ingresada no está permitida");
                        this.playAudio('Error');
                        return;
                    }
                    currentItem.Conteo = currentItem.Cantidad;
                    _efecto = 'Cambiar';
                } else
                    if (sumaAutomatica) {
                        _cantidad = 1;
                        if (parseFloat(currentItem.Conteo) >= 9999999) {
                            toastr.error("No puede sumar a la cantidad ingresada.");
                            this.playAudio('Error');
                            return;
                        }
                        currentItem.Conteo = parseFloat(currentItem.Conteo) + 1;
                        currentItem.Cantidad = parseFloat(currentItem.Conteo);
                        _efecto = 'Sumar';
                        _cantidad = currentItem.Cantidad;
                    }
            this.updateDetail(currentItem.Id, _cantidad, _efecto, currentItem);
            this.setState({ articulo: "", currentRowDetail: currentItem, showApplyOption: false });
        }

        ///Antes enviar mensaje

        //console.log('Corre aqui');
        //btnApply 




    }
    async updateDetail(pArticulo, pCantidad, pEfecto, pRow) {
        console.log('updateDetail');
        let _response = {}
        if (this.props.data.tipo == 2) {
            _response = await ServiceRequest.SubConteo_Modificar_Detalle(this.state.rowConteo.Bodega_Id, this.state.rowConteo.Id, this.state.rowConteo.Conteo_Tipo, this.state.rowConteo.SubConteo_Id, pArticulo, this.state.currentRowDetail.Cantidad);
        } else {
            _response = await ServiceRequest.Conteo_WebUpdate(this.state.rowConteo.Id, pArticulo, this.state.rowConteo.Conteo_Tipo, pCantidad, pEfecto, this.state.rowConteo.Bodega_Id);
        }      
        
        if (_response.isError == false) {
            let _resp = _response.data;
            if (_resp == "") {   
                  
              
               toastr.success("Se ha actualizado correctamente.");
                this.playAudio('Exito');
            } else {
                if (_resp=="Cerrada")
                { const session = new Session();   
                    session.remove('Usuario');
                    console.log('modifica');
                    toastr.options.closeButton=true;
                    toastr.options.showDuration=2000;
                    //toastr.options.timeOut = 6000; // How long the toast will display without user interaction
                    //toastr.options.extendedTimeOut = 1000; // How long the toast will display after a user hovers over it
                    toastr.error("Su sesión ha caducado");
                    setTimeout(() => {  window.location.href = SiteRoutes.Login; }, 2000);
                    
                }
                else{
                toastr.error(_resp, "", options);
                this.playAudio('Error');}
            }
        } else {
            toastr.error(_response.data);
            this.playAudio('Error', "", options);
        }
    }
    

    updateCantidad(newCant) {
        var currentItem = this.state.currentRowDetail;      
        if (newCant == "") {
            newCant = 0;
        }
        currentItem.Cantidad = newCant;
        this.setState({ currentRowDetail: currentItem });
    }
    cancelarCantidad() {
        var currentItem = this.state.currentRowDetail;
        if (currentItem.Conteo != currentItem.Cantidad){
            currentItem.Cantidad = currentItem.Conteo;  
            this.setState({ currentRowDetail: currentItem });
        }
    }
    async recargarEditar() {
        let { rowConteo, index } = this.state;
        if (rowConteo.Estado != 'Guardado') {
            toastr.warning("El Conteo no se encuentra en estado Guardado. No se puede Editar.");
            return;
        }
        let _lstConteoDetail = [];
        let _response = {};
        const localStorage = new LocalStorage();
        let Empresa = localStorage.get('Empresa');
        let Sucursal = localStorage.get('Sucursal');  
        _response = await ServiceRequest.ConteoProductos_ScaneaArticulosWeb(rowConteo.Id, this.props.data.tipo, rowConteo.Bodega_Id,Empresa,Sucursal);
        
        if (_response.isError == false) {
            _lstConteoDetail = _response.data;
        } else {
            toastr.error(_response.data);
            this.playAudio("Error");
            return;
        }

        let lstConteoDetail = this.mapConteoDetail(_lstConteoDetail);

        let _newIndex = parseInt(index + 1) >= lstConteoDetail.length ? 0 : parseInt(index) + 1;
        let _disablePrev = '';
        let _disableNext = ''; 
        if (_newIndex == 0) {
            _disablePrev = 'disabled';
        } else {
            _disablePrev = '';
        }
        if (_newIndex == lstConteoDetail.length) {
            _disableNext = 'disabled';
        } else { 
            _disableNext = '';
        }

        if (_lstConteoDetail.length > 0){
            this.setState({ rowConteo: rowConteo, showFiltro: false, showLista: false, showEditar: true, lstConteoDetailFilter: lstConteoDetail, lstConteoDetail: lstConteoDetail, currentRowDetail: lstConteoDetail[_newIndex], disabledPrev: _disablePrev, disabledNext: _disableNext, index: _newIndex });
        } else {
            this.setState({ showApplyOption: false, showFiltro: false, showLista: true, showEditar: false, index: 0, currentRowDetail: {}, lstConteoDetailFilter: [], lstConteoDetail: [], articulo: '', filterNoContados: false, filterNoContados: false, sumaAutomatica: true, digitarCantidad: false, sumarCantidad: true, cambiarCantidad: false });
        }
       


    }

    async editarConteo() {
        let { rowConteo } = this.state;
        let _lstConteoDetail = [];
        let _response = {};
        const localStorage = new LocalStorage();
        let Empresa = localStorage.get('Empresa');
        let Sucursal = localStorage.get('Sucursal');  
        
        if (this.props.data.tipo == 2) { //Es Distribuida?
            _response = await ServiceRequest.SubConteo_Cargar(rowConteo.Bodega_Id, rowConteo.Id, rowConteo.Conteo_Tipo, Empresa, Sucursal);
            
            if (_response.isError == false) {
                if (_response.data.SubConteo[0].SubConteo_id == undefined) {
                    toastr.error(_response.data.Mensaje);
                    return;
                } else {
                    if (_response.data.SubConteo[0].SubConteo_Estado == "AP") {
                        toastr.error("El subconteo ya ha sido aplicado, no puede editarse");
                        this.playAudio("Error");
                        return;
                    } else {
                        _lstConteoDetail = _response.data.Detalle;
                        
                        rowConteo.SubConteo_Id = _response.data.SubConteo[0].SubConteo_id;
                    }
                }
                  
            } else {
                toastr.error(_response.data);
                this.playAudio("Error");
                return;
            }

        } else {
            _response = await ServiceRequest.ConteoProductos_ScaneaArticulosWeb(rowConteo.Id, this.props.data.tipo, rowConteo.Bodega_Id, Empresa, Sucursal);
            
            if (_response.isError == false) {
                _lstConteoDetail = _response.data;
            } else {
                toastr.error(_response.data);
                this.playAudio("Error");  
                return;
            }
        }

        let lstConteoDetail = this.mapConteoDetail(_lstConteoDetail);
        
        if (_lstConteoDetail.length > 0) {
            this.setState({ rowConteo: rowConteo, showFiltro: false, showLista: false, showEditar: true, lstConteoDetailFilter: lstConteoDetail, lstConteoDetail: lstConteoDetail, currentRowDetail: lstConteoDetail[0], disabledPrev: 'disabled', disabledNext: '' });

        } else {
            toastr.error("El Conteo no tiene detalles.")
        }

       

    }
    async  onEditar() {
        const { rowConteo } = this.state;
        const localStorage = new LocalStorage();
        this.setState({sumarCantidad :  localStorage.get('AccionDigitar')==1,cambiarCantidad :localStorage.get('AccionDigitar')==2, sumaAutomatica: localStorage.get('AccionScanear')==1 });
        if (rowConteo.Estado != 'Guardado') {
            toastr.warning("El Conteo no se encuentra en estado Guardado. No se puede aplicar.");
            return;
        }
        this.validarMenuOpcion(this.props.data.Menu, 'Editar', () => { this.editarConteo(); })
           }

    mapConteoDetail(pConteoDetail) {
        const session = new Session();
        const urlFile = session.get('WSAdminFiles');
        let _index = -1;
        return pConteoDetail.map(item => {
            _index++;
           
            return {
                index: _index,
                Id: item.Articulo_id,
                Nombre: item.Articulo_Nombre,
                Decimales:item.Articulo_Decimales,  
                Conteo: item.Detalle_Existencia_Conteo,
                PosicionA1: item.PosicionA1 == null ? '' : item.PosicionA1,
                PosicionA2: item.PosicionA2 == null ? '' : item.PosicionA2,
                PosicionA3: item.PosicionA3 == null ? '' : item.PosicionA3,
                Cantidad: item.Detalle_Existencia_Conteo,
                Hijo: item.Hijo == null ? '' : item.Hijo,
                Padre: item.Padre == null ? '' : item.Padre,
                Imagen_Url: item.Imagen_Url == '' ? baseUrl + 'Public/img/not-image.png' : urlFile + 'Archivos/Imagenes/Articulos_PEQ/' + item.Imagen_Url
            }
        });
    }

    onSelectRowConteo(pRow) {
        this.setState({rowConteo:pRow});
    }

    onSeleccionar() {  
        this.loadData();
    }
    onAplicar() {
        const { rowConteo } = this.state;
        if (rowConteo.Estado !='Guardado'){
            toastr.warning("El Conteo no se encuentra en estado Guardado. No se puede aplicar.");
            return;
        }
        ReactDom.render(<SweetAlert show={true}
            title="Confirmar"
            text={"¿Desea aplicar el conteo  #" + rowConteo.Id + "?"}
            confirmButtonColor={'rgb(72, 196, 136)'}
            showCancelButton onConfirm={() => this.validarMenuOpcion(this.props.data.Menu, 'Aplicar', () => { this.aplicarConteo(); })} />,
            document.getElementById('confirm-container'));
    }

    onBorrarDetalle() {
        const { rowConteo, currentRowDetail } = this.state;
        if (rowConteo.Estado != 'Guardado') {
            toastr.warning("El Conteo no se encuentra en estado Guardado. No se puede borrar el detalle.");
            return;
        }
        ReactDom.render(<SweetAlert show={true}
            title="Confirmar"
            text={"¿Desea eliminar el articulo  " + currentRowDetail.Id + " " + currentRowDetail.Nombre +"  de la Toma Física?"}
            confirmButtonColor={'rgb(72, 196, 136)'}
            showCancelButton onConfirm={() => this.validarMenuOpcion(this.props.data.Menu, 'Eliminar Artículo Actual', () => { this.borrarDetalle(currentRowDetail); })} />,
            document.getElementById('confirm-container'));
    }

    

   async borrarDetalle(pDetalle) {
        const { rowConteo } = this.state;

        let _response = await ServiceRequest.Conteo_BorrarDetalle(rowConteo.Id, pDetalle.Id, rowConteo.Conteo_Tipo, rowConteo.Bodega_Id);
        console.log(_response,'_response');
                if (_response.isError == false) {
                    let _resp = _response.data;
                    if (_resp == "") {
                        toastr.success("Se ha eliminado correctamente.");
                        this.playAudio('Exito');
                        this.recargarEditar();
                    } else {
                        console.log(_resp,'_resp ce');
                        if (_resp=="Cerrada")
                        { const session = new Session();   
                            session.remove('Usuario');
                            
                            toastr.error("Su sesión ha caducado");
                            setTimeout(() => {  window.location.href = SiteRoutes.Login; }, 2000);
                            
                        }
                        else{
                        toastr.error(_resp);
                        this.playAudio('Error');
                        }
                    }
                } else {
                    toastr.error(_response.data);
                    this.playAudio('Error');
                }
        
    }

 async aplicarConteo() {
      const { rowConteo } = this.state;
      //TODO: validar opcion y pedir validacion
      let _response = {};

      if (this.props.data.tipo==2){ // Es Distribuida
          _response = await ServiceRequest.SubConteo_Aplicar(rowConteo.Bodega_Id, rowConteo.Id, rowConteo.Conteo_Tipo);
        
          if (_response.isError == false) {
              if (_response.data == "") {
                  $('#mas-opciones').modal('hide');
                  toastr.success("El Subconteo ha sido aplicado correctamente.");
                  this.loadData();
              } else {
                  toastr.error(_response.data);  
                  this.playAudio("Error");
              }
          } else {
              toastr.error(_response.data);
              this.playAudio("Error");
          }
      } else {  
          _response = await ServiceRequest.ConteoProductos_Aplicar_Web(rowConteo.Bodega_Id, this.props.data.tipo, rowConteo.Id, this.state.usuarioId);
          console.log(_response,'_response');
          if (_response.isError == false) {
              let _resp = _response.data;
              console.log(_resp,'resp');

              if (_resp.indexOf("OK=") != -1) {
                  let _mensajeArr = _resp.split('=');
                  $('#mas-opciones').modal('hide');
                  toastr.success(_mensajeArr[1]);
                  this.loadData();
              } else {
                  toastr.error(_response.data);
                  this.playAudio("Error");
              }
          } else {
              toastr.error(_response.data);
              this.playAudio("Error");
          }

      }
           
  }
  onEliminar() {
      const { rowConteo } = this.state;
      if (rowConteo.Estado != 'Guardado') {
          toastr.warning("El Conteo no se encuentra en estado Guardado. No se puede eliminar.");
          return;
      }   
      ReactDom.render(<SweetAlert show={true}
             title="Confirmar"
             text={"¿Desea eliminar el conteo  #" + rowConteo.Id +"?"}
            confirmButtonColor={'rgb(72, 196, 136)'}
            showCancelButton onConfirm={() => this.validarMenuOpcion(this.props.data.Menu, 'Eliminar', () => { this.eliminarConteo(); })} />,
            document.getElementById('confirm-container'));
  }

 async eliminarConteo() {
      const { rowConteo } = this.state;
      let _response = await ServiceRequest.ConteoProductos_Remove(rowConteo.Bodega_Id, this.props.data.tipo, rowConteo.Id);
      if (_response.isError == false) {
          if (_response.data == "") {
              toastr.success("Se ha eliminado correctamente.");
          } else {
              toastr.error(_response.data);
          }
      } else {
          toastr.error(_response.data);
      }
      this.loadData();
  }

    onNext() {
        let _DetailList = this.state.lstConteoDetail;
        var index = this.state.index;
        if (_DetailList.length > 0) {
            let nextIndex = index + 1;
            if (nextIndex < _DetailList.length) {
                this.cancelarCantidad(); //Regresa la cantidad Actual a la cantidad original, si no ha actualizado.
                let RowCurrent = _DetailList[nextIndex];
                if (_DetailList.length == nextIndex + 1) {
                    jQuery("#container-view").hide();
                    this.setState({ currentRowDetail: RowCurrent, articulo: '', index: nextIndex, disabledNext: 'disabled', disabledPrev: '', showApplyOption:false });
                } else {
                    jQuery("#container-view").hide();
                    this.setState({ currentRowDetail: RowCurrent, articulo: '', index: nextIndex, disabledNext: '', disabledPrev: '', showApplyOption: false });

                }

            }
        }
    }

    onPrev() {
        let _DetailList = this.state.lstConteoDetail;
        var index = this.state.index;
        if (_DetailList.length > 0) {
            let prevIndex = index - 1;
            if (prevIndex >= 0) {
                this.cancelarCantidad(); //Regresa la cantidad Actual a la cantidad original, si no ha actualizado.
                let RowCurrent = _DetailList[prevIndex];
                if (prevIndex == 0) {
                    jQuery("#container-view").hide();
                    this.setState({ currentRowDetail: RowCurrent, articulo: '', index: prevIndex, disabledPrev: 'disabled', disabledNext: '', showApplyOption: false });
                } else {
                    jQuery("#container-view").hide();
                    this.setState({ currentRowDetail: RowCurrent, articulo: '', index: prevIndex, disabledPrev: '', disabledNext: '', showApplyOption: false });
                }

            } else {
              //  this.setState({ showLista: true, showFiltro:false, showEditar:false });
            }
        }  
    }

    buscarArticulo() {     
        ReactDom.render(<BuscarArticulo Id="BuscarArticulo" data={this.state.lstConteoDetail} Title="Buscar Art&iacute;culo"  onRowSelected={this.onRowSelected.bind(this)} />, document.getElementById('modal-container'));
        $('#BuscarModal').modal('show');
        $('#BuscarModal').on('show.bs.modal', function (event) {
            $('#BuscarModal').addClass("z-index-9999");
        });
    }

    onRowSelected(rowSelected) {
        var Nombre = rowSelected.Name;
        switch (Nombre) {
            case "BuscarArticulo":
                this.searchArticulo(rowSelected.row.Id);
                break;
        }
    }

    async obtenerPosiciones() {
        let Response = await ServiceRequest.Obtener_Posiciones();
        if (Response.isError == false) {
            this.setState({ positions: Response.data });
        }
    }

    async  loadData() {
        const { bodega, fechaInicio, fechaFin } = this.state;
        const localStorage = new LocalStorage();
        let Empresa = localStorage.get('Empresa');
        let Sucursal = localStorage.get('Sucursal');
      
        let _response = await ServiceRequest.Conteo_Lista(this.props.data.tipo, 'GU', bodega, fechaInicio, fechaFin,Empresa,Sucursal);
        if (_response.isError == false) {
            let lstData = _response.data;  
            if (lstData.length > 0) {
                this.setState({ lstData: lstData, showFiltro: false, showLista: true, showEditar: false, rowConteo: {}, currentRowDetail: {}, index: 0 });
              
            } else {
                toastr.warning("No se ha encontrado resultado para el rango de fechas seleccionado.");
               // this.setState({ lstData: lstData, showFiltro: false, showLista: true, showEditar: false, rowConteo: {}, currentRowDetail: {}, index: 0 });
                this.setState({ showFiltro: true, showLista: false, showEditar: false, lstData:[] });
            }
           
        } else {
            toastr.error(_response.data);
        }
    }

    //Seguridad del Menu
    onChangeLoginModal(e) {
        const id = e.target.id;
        const name = e.target.name;
        const value = e.target.value;
        this.setState({ [name]: value })
    }

    onShowLogingModal(accion) {
        this.setState({
            showLoginModal: true,
            accion: accion
        })
    }
    onCloseLoginModal() {
        this.setState({
            showLoginModal: false,
            accion: undefined,
            username: '',
            password: '',
            menu: -1,
            modulo:-1,
            opcion: -1,
            opcionNombre:''

        })
    }

    async  onValidarLoginModal() {
        const { modulo, menu, opcion, username, opcionNombre, password, accion, rowConteo } = this.state;
        let _tipoDoc = this.props.data.tipo;
      let Response = await ServiceRequest.Menu_Validar_Opcion(menu, opcion, username, password, opcionNombre, _tipoDoc, rowConteo.Id, this.props.data.Menu );
        if (Response.isError == false) {
            let _Usuario = Response.data.Usuario_Id;
            let _Mensaje = Response.data.Mensaje;
            this.setState({ usuarioId: _Usuario});
            if (_Usuario != undefined) {
                if (_Mensaje == "") {
                    accion();
                } else {
                    toastr.error(_Mensaje)
                }

            } else {
                toastr.error("No est&aacute; autorizado para realizar esta acci&oacute;n.")
            }
        } else {
            toastr.error("Ha ocurrido un error al procesar la acci&oacute;n.")
            
        }
    }



    async  validarMenuOpcion(pMenuNombre, pOpcionNombre, accion) {
        let Response = await ServiceRequest.Obtener_Menu_Opcion(pMenuNombre, pOpcionNombre);
        if (Response.isError == false) {
            let _Opcion = Response.data[0];
            if (_Opcion.Menu_Id != undefined) {
                this.setState({ modulo: _Opcion.Modulo_Id, opcionNombre: pOpcionNombre, menu: _Opcion.Menu_Id, opcion: _Opcion.Opcion_Id });
                if (_Opcion.Opcion_Validar) {
                    this.onShowLogingModal(accion);
                } else {
                    accion();
                }
            } else {
                toastr.error("No est&aacute; autorizado para realizar esta acci&oacute;n.")
            }
        } else {
            toastr.error("Ha ocurrido un error al procesar la acci&oacute;n.")
            
        }
    }
    playAudio(pTipo) {
        if (pTipo == 'Exito') {
            audio.playSound('ExitoAudio');
        }

        if (pTipo == 'Error') {
            audio.playSound('ErrorAudio');
        }
    }
    render() {
        const {
            showEditar,
            showFiltro,
            showLista,
            lstData,
            lstBodega,
            bodega,
            fechaFin,
            fechaInicio,
            rowConteo,
            currentRowDetail,
            positions,
            lstConteoDetail,
            lstConteoDetailFilter,
            disabledNext,
            disabledPrev,
            index,
            digitarCantidad,
            sumaAutomatica,
            sumarCantidad,
            cambiarCantidad,
            articulo,
            cantidad,
            showApplyOption,
            filterContados,
            filterNoContados,
            autorizado
            } = this.state;

        const { data } = this.props;

        let d = new Date();
        let time = d.getTime();
        return (
            <div>
                <TopBar />
                {autorizado ? <div>
                    {showFiltro ? <Filtro
                        onChange={this.onChange.bind(this)}
                        bodega={bodega}
                        fechaInicio={fechaInicio}
                        fechaFin={fechaFin}
                        onSeleccionar={this.onSeleccionar.bind(this)}
                        onClick={this.onClick.bind(this)}
                        title={data.titleFiltro}
                        lstBodega={lstBodega}
                    /> : ''}
                    {showEditar ? <Editar
                        showApplyOption={showApplyOption}
                        onClick={this.onClick.bind(this)}
                        data={rowConteo}
                        currentRowDetail={currentRowDetail}
                        lstConteoDetail={lstConteoDetail}
                        lstConteoDetailFilter={lstConteoDetailFilter}
                        positions={positions}
                        onChange={this.onChange.bind(this)}
                        disabledPrev={disabledPrev}
                        disabledNext={disabledNext}
                        index={index}
                        digitarCantidad={digitarCantidad}
                        sumaAutomatica={sumaAutomatica}
                        sumarCantidad={sumarCantidad}
                        cambiarCantidad={cambiarCantidad}
                        articulo={articulo}
                        cantidad={cantidad}
                        filterContados={filterContados}
                        filterNoContados={filterNoContados}
                        tipo={this.props.data.tipo}
                    /> : ''}
                    {showLista ? <Lista
                        onAplicar={this.onAplicar.bind(this)}
                        onEliminar={this.onEliminar.bind(this)}
                        data={lstData}
                        onClick={this.onClick.bind(this)}
                        title={data.titleLista}
                        onSelectRowConteo={this.onSelectRowConteo.bind(this)}
                    /> : ''}
                </div> : <p className="text-danger" style={{padding:'50px', textAlign:'center'}}>No está autorizado para utilizar este módulo. Comuníquese con el administrador.</p>}
                {/*Login Modal */}
                {this.state.showLoginModal ? (
                    <LoginModal
                        onClose={this.onCloseLoginModal.bind(this)}
                        onValidar={this.onValidarLoginModal.bind(this)}
                        username={this.state.username}
                        password={this.state.password}
                        onChange={this.onChangeLoginModal.bind(this)}
                    />) : null}

               
              
                {/*Container SweetAlert */}
                <div id="confirm-container"></div>             
            </div>
        )
    }
};
export default ConteoMain; 