﻿import React from 'react';
import Switch from 'react-bootstrap-switch';
import InputNumber from '../InputNumber';
import AutoBind from 'react-autobind';
let $pContados = 0;
let $pNoContados = 0;
let chars = [];
class Editar extends React.Component {

    static defaultProps = {
        disabledNext: '',
        disabledPrev: '',
    }
    constructor() {
        super();
        this.state = {

        }
        AutoBind(this);
    }
    handleKeyPress(e) {
        let _this = this;
      
        if (e.keyCode !== 13) {
            if (!$("#cantidad").is(":focus") && !$("#txt-articulo").is(":focus")) {
                chars.push(e.key);
                _this.articuloInput.value = _this.articuloInput.value + e.key;
            }          
            } else
            if (e.keyCode === 13) {
                if (!$("#cantidad").is(":focus") && !$("#txt-articulo").is(":focus")) {
                    _this.props.onChange({ target: { id: 'articulo', value: chars.join('') } });
                    chars = [];
                    _this.articuloInput.value = "";
                }
                }        
    }

    windoListener() {
      
        window.addEventListener('keypress', this.handleKeyPress, false);

    }

    componentDidMount() {
        this.loadChart();
        let _switch = $('#suma-automatica');
        let _this = this;
        _switch.bootstrapSwitch({
            'onSwitchChange': function (event, state) {
                _this.props.onChange({ target: { id: 'suma-automatica', value: state } });
            },
        });
        this.validaCheckboxs();
        this.windoListener();
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (this.props.index != nextProps.index) {
            this.fadeIn();
            this.articuloInput.focus();
        }
        this.loadChart();

       if (nextProps.showApplyOption == false){
            this.articuloInput.focus();
        }
        

        return true;
    }

    fadeIn() {
        jQuery("#container-view").fadeIn(500);
    }
    componentWillReceiveProps() {
       /* if (!this.props.showApplyOption) {
            this.articuloInput.focus();
        }*/
    }
    obtenerPosicion(pNombre) {
        if (this.props.positions != null && this.props.positions != undefined) {
            if (this.props.positions.length > 0) {
                let _position = this.props.positions.find(item => item.Parametro_Nombre == pNombre);
                if (_position != undefined) {
                    return _position.Parametro_Valor;
                }
            }
        }
        return "";
    }
    loadChart() {
        this.Chart = Highcharts.chart('container', {
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false,
                type: 'pie'
            },
            title: {
                text: ''
            },
            colors: ['#ddae27', '#ea0000', '#37c480'],

            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                        style: {
                            fontSize: '8px',
                            color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                        }
                    }
                }
            },
            series: this.dataChart(),
            navigation: {
                buttonOptions: {
                    enabled: false
                }
            }

        });
    }
    onClick(e) {
        e.target.select();
    }

   
    dataChart() {
        let _Detail = this.props.lstConteoDetailFilter;
        let _Contados = _Detail.filter(item =>  item.Cantidad > 0 );
        let _NoContados = _Detail.filter(item =>  item.Cantidad == 0 );

        $pContados = _Contados.length;
        $pNoContados = _NoContados.length; 
        return [{
            name: 'Items',
            colorByPoint: true,
            data: [
               
                {
                    name: 'Contados',
                    y: $pContados,
                    sliced: true,
                    selected: true
                }, {
                    name: 'No Contados',
                    y: $pNoContados,
                }]
        }];
    }

    componentWillUnmount() {
        if (this.Chart) {
            this.Chart.destroy();
        }
        window.removeEventListener('keypress', this.handleKeyPress, false);
    }

    changeCheckbox(id, value) {
        let _checkbox = document.getElementById(id);
        _checkbox.checked = value;
    }

    validaCheckboxs() {
        this.changeCheckbox("cb-contados", this.props.filterContados)
        this.changeCheckbox("cb-nocontados", this.props.filterNoContados)     
    }


    render() {
        const { onClick, data, positions, currentRowDetail, onChange, lstConteoDetail, disabledNext, disabledPrev, index,
            digitarCantidad,
            sumaAutomatica,
            sumarCantidad,
            cambiarCantidad,
            articulo,
            cantidad,
            showApplyOption,
            filterNoContados,
            filterContados,
            tipo
        } = this.props;
        let _readOnlyInput = { readonly: 'true' };
        let _disabledInput = { disabled: 'disabled' };
        return (
            <div>
            <div className="editar">
                <div className="row">
                    <div className="col-xs-12 col-md-8 col-md-offset-2">
                        <div className="editar-conteo">
                            <div className="header">
                                <div className="row">
                                    <div className="col-xs-8">
                                            <div className="row"  style={{ marginLeft: '10px'}}> <a href="#" className="back" onClick={onClick} id='btn-regresar-editar'><i className="fa fa-angle-left" />Conteo #{data.Id}</a></div>
                                        <div className="row"> <p className="fecha">{data.Fecha}</p></div>
                                    </div>
                                    <div className="col-xs-4 text-right">
                                        <p className="estado">{data.Estado}</p>
                                    </div>
                                </div>
                            </div>
                            <div id='container-view'>
                              
                                    <div className="row" style={{marginTop:'10px'}}>
                                <div className="col-xs-12">
                                    <div className="search">
                                        <div className="row"> 
                                            <div className="col-xs-6">
                                                <label>Artículos</label>
                                            </div>
                                            <div className="col-xs-6">
                                                <span>{parseInt(index) + 1}/{lstConteoDetail.length}</span>
                                            </div>
                                        </div>
                                        <div className="row">
                                                    <div className="col-xs-8">
                                        <div className="form-group"> 
                                                    <input ref={(input) => { this.articuloInput = input; }} type="text" name="articulo" id="articulo" {..._readOnlyInput}   {..._disabledInput} onChange={onChange} value={articulo}/>
                                                    <p>{currentRowDetail.Id}</p>  <p>{currentRowDetail.Nombre}</p>
                                        </div>
                                                    </div>
                                                    <div className="col-xs-4">
                                                        <img className="img-producto" src={currentRowDetail.Imagen_Url} />
                                                    </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="row">
                                <div className="col-xs-12">
                                    <table className="table table-bordered" id='table-locations'>
                                        <thead>
                                            <tr>
                                                <th scope="col">{this.obtenerPosicion("PosicionX")}</th>
                                                <td>{currentRowDetail.PosicionA1}</td>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <th scope="col">{this.obtenerPosicion("PosicionY")}</th>
                                                <td>{currentRowDetail.PosicionA2}</td>
                                            </tr>
                                            <tr>
                                                <th scope="col">{this.obtenerPosicion("PosicionZ")}</th>
                                                <td>{currentRowDetail.PosicionA3}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                                <div className="row">
                                    <div className="col-xs-12 text-center">
                                                <InputNumber showApplyOption={showApplyOption} decimales={currentRowDetail.Decimales} title='' value={currentRowDetail.Cantidad} onChange={onChange} onClick={onClick} />
                                    </div>
                                </div>
                            </div>
                          

                            {digitarCantidad ? <div className="row" style={{ marginTop: '10px' }}>
                                <div className="col-xs-12">
                                    <ul className="radio-buttons">
                                                <li onClick={() => { onClick({ target: { id: 'rb-sumar-cantidad' }, currentTarget: { id: 'rb-sumar-cantidad' } }) }}>
                                            <input type="radio" id="sumarCantidad" checked={sumarCantidad} onChange={onChange} />
                                            <label htmlFor="a-option">Sumar Cantidad</label>
                                            <div className="check" />
                                        </li>
                                                <li onClick={() => { onClick({ target: { id: 'rb-cambiar-cantidad' }, currentTarget: { id: 'rb-cambiar-cantidad' }}) }}>
                                            <input type="radio" id="cambiarCantidad" checked={cambiarCantidad} onChange={onChange} />
                                            <label htmlFor="c-option">Cambiar Cantidad</label>
                                            <div className="check"><div className="inside" /></div>
                                        </li>
                                    </ul>
                                </div>
                            </div> : ''}
                            
                            </div>
                          </div>
                    </div>
                </div>
                <div className="footer-buttons">
                    <button id='btn-prev' className={disabledPrev} {...disabledPrev} onClick={onClick}>Anterior</button>
                    <label data-toggle="modal" data-target="#mas-opciones" ><i className="fa fa-check"/> Más Opciones</label>
                    <button id='btn-next' {...disabledNext} onClick={onClick} className={'last ' + disabledNext }>Siguiente</button>
                </div>
            </div>

            <div className="modal fade opciones" id="mas-opciones" tabIndex={-1} role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div className="modal-dialog" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                                <span aria-hidden="true">×</span>
                            </button>
                            <h5 className="modal-title" id="exampleModalLabel">Opciones</h5>
                        </div>
                        <div className="modal-body">
                            <div className="row">
                                    <div className="col-sm-12 col-xs-12 col-md-8 ">
                                    <div id="container" style={{ minWidth: 250, height: 120, maxWidth: 500, margin: '0 auto' }} />
                                </div>
                                <div className="col-xs-4 container-filtro-chart">
                                    <p>Filtrar</p>
                                    <div className="form-check">
                                            <input type="checkbox" className="form-check-input" id="cb-contados" onChange={onChange}/>
                                            <label className="form-check-label" htmlFor="cb-contados">Contados</label>
                                    </div>
                                    <div className="form-check">
                                            <input type="checkbox" className="form-check-input" id="cb-nocontados" onChange={onChange}/>
                                            <label className="form-check-label" htmlFor="cb-nocontados">No Contados</label>
                                    </div>
                                </div>
                            </div>
                            <div className="row">
                                    <div className="col-xs-12">
                                        <div className="make-switch col-xs-12" onClick={onChange}>
                                            <label htmlFor="switchSumar" className="hop">¿Sumar Automáticamente al Escanear?</label>
                                            <input name="switchSumar" type="checkbox" data-off-text="No" data-on-color="success" data-on-text="Sí" checked={sumaAutomatica} className="BSswitch switch-small" id='suma-automatica' onChange={onChange} />
                                        </div>
                                    </div>
                            </div>
                            {tipo == 0 ?
                                <div>
                                    <hr />
                                    <div className="row">
                                            <div className="col-xs-6 fullwidth">
                                                <button id='btnEliminarDetalle' className="btn btn-primary" onClick={onClick} data-dismiss="modal">Eliminar Artículo Actual</button>
                                        </div>
                                            <div className="col-xs-6">
                                                <button id='btnBuscarArticulo' className="btn btn-primary" onClick={onClick} data-dismiss="modal">Buscar Artículo</button>
                                            </div>
                                    </div>
                                </div>
                                    : <div>
                                        <hr />
                                        <div className="row">
                                            <div className="col-md-6">
                                                <button id='btnBuscarArticulo' className="btn btn-primary" onClick={onClick} data-dismiss="modal">Buscar Artículo</button>
                                            </div>
                                            <div className="col-md-6">
                                                
                                            </div>
                                        </div>
                                    </div>}
                        </div>
                        <div className="modal-footer">
                            <button type="button"  data-dismiss="modal"><i className="fa fa-close" />Cancelar</button>
                            <button type="button" id="btn-aplicar-orden" className="last" onClick={onClick} ><i className="fa fa-check" />Aplicar Conteo</button>
                        </div>
                    </div>
                </div>
            </div>
           
                </div>
        )
    }
};
export default Editar; 
