
/*
    Sidebar menu--------------------------------------------------------------------
*/


function MenuLinkA(props){
  return <a className='item' href={'/'+props.data.path} key={props.data.slug}>{props.data.title}</a>;
}

function SimpleAccordionSubMenu(props){
  let a = [];
  for(var b in props.data){
    a.push(<MenuLinkA data={props.data[b]} key={'SA'+b}/>);
  }
  return (
    <div className='menu' >
      {a}
    </div>
  )
}

function SimpleAccordionMenuItem(props){
  return(
    <div className="item">
      <div className='title'>
          <i className={props.data.icon+" icon"}></i>
          <i className="dropdown icon"></i>
          {props.data.title}
      </div>
      <div className='active content'>
        <SimpleAccordionSubMenu data={props.data.submenu} />
      </div>
    </div>
  )
}

function SimpleAccordionMenu(props){
  let a = [];

  for(var b in props.data){
    a.push( <SimpleAccordionMenuItem data={props.data[b]} key={'SA'+b}/> );
  }

  return(
    <div className="accordion massive menu" >
      {a}
    </div>
  )
}

function AccordionMenuItem(props){
  return(
    <div className="item">
      <div className="active title accordion-title">
        <i className="dropdown icon"></i>
        {props.data.title}
      </div>
      <div className="active content">
        <SimpleAccordionMenu data={props.data.submenu} />
      </div>
    </div>
  )
}

function AccordionMenu(props){
  return(
    <div className="ui inverted vertical accordion massive menu">
      <AccordionMenuItem data={props.data}/>
    </div> 
  )
}

function SidebarItem(props){
  return(
    <div className='item'>
      <AccordionMenu data={props.data}/>
    </div>
  )
}


class LeftMainMenu extends React.Component{
  constructor(props){
    super(props);
    
  }

  createData = (data) => {
    let o = [] ;
    for( var a in data){
      o.push( <SidebarItem data={data[a]} key={a}/> );
    }
    return o;
  }

  componentDidMount = () =>{
    $('.ui.accordion').accordion({
      exclusive:false
    });
  }
  
  render(){
    return[
      <a className='item' href='/' key='logo'>
            <img className='ui very padded centered align  small image' src='https://insightcargo.com.br/images/logo_insightcargo.png'/>
        </a>,
        this.createData( this.props.data )
    ]
    
  }
}




/*
    Head info grids--------------------------------------------------------------------
*/
function HeadInfoItem(props){
    return(
      <div className='column'>
        <div className='ui blue segment'>
          <div className='ui titleKpi small header'>{props.data.t.toUpperCase()}</div>
            <span className='valueBoxKpi'>{props.data.v}</span>
        </div>
      </div>
    )
  }

  function HeadInfo(props){
    let itens     = [];
    const titles  = [];

    for( var d in props.data ){
      var dados = {t:d,v:props.data[d]};
      itens.push(<HeadInfoItem  data={dados} key={d} />);}
    return(
      <div className='ui equal width grid item contentBox'>
        <div className='row'>
            {itens}
        </div>
    </div>
    )
  }

  /*
    Individual Dropdowns------------------------------------------------------------------
  */

  /* Dropdown de Agrupamento de data */
  function DropdownGroupDate(props){
    return(
              <select id='groupDate' className="ui selection item dropdown" placeholder='Visão' defaultValue={nOpts.groupDate}>
                <option value=''>Visão</option>
                <option value='day'>Diário</option>
                <option value='month'>Mensal</option>
                <option value='year'>Anual</option>
              </select>
    )
  }

  /* Dropdown de meses */
  function DropdownMonths(props){
    let opts = [];

    for(var m in fOpts[props.year]){
      opts.push(<option value={m} key={m}>{fOpts[props.year][m]}</option>);
    }

    return(
            <select id='month' className='ui selection item dropdown' placeholder='Mês' defaultValue={nOpts.month}>
                <option value=''>Mês</option>
                {opts}
            </select>
    )
  }

  /* Dropdown de anos */
  function DropdownYears(props){
    let options = [];
    for(var o in fOpts){
      options.push(<option value={o} key={o}>{o}</option>);
    }
    return(
            <select id='year' className='ui selection item dropdown' placeholder='Mês' defaultValue={nOpts.year} key='year'>
                <option value=''>Ano</option>
                {options}
            </select> )
  }


  /*
    Group of Dropdowns------------------------------------------------------------------
  */

  function renderGroupedFilters(v){
    switch(v){
      case 'day'  : tabFilter.render(<GroupDayTabFilters />) ; break ;
      case 'month': tabFilter.render(<GroupMonthTabFilters />) ; break ;
      case 'year' : tabFilter.render(<GroupYearTabFilters />) ; break ;
    }
  }

  function GroupButtonsTabFilters(props){
    
    function handleSubmit() {
      downloadCSV(`${props.titleExport}`,convertToCSV(dataTableData));
    }

    function copyToClip(){
      copyHTMLElementToClipboard(document.querySelector('.ui.groupedData'));
    }

      return([
        <div className='ui big compact icon button' onClick={handleSubmit} title='Exportar .csv' key='excel'>
          <i className="file excel outline icon"></i>
        </div>,
        <div className='ui big compact icon button' onClick={copyToClip} title='Copiar tabela' key='copy'>
          <i className="copy outline icon"></i>
        </div> 
        ]  
      )
  }

  class GroupDayTabFilters extends React.Component{
  
    componentDidMount(){
      $('#groupDate').dropdown({
        onChange: function(v){
          nOpts.groupDate = v;
          renderGroupedFilters(v);
          initCharts();
        }
      });
      $('#year').dropdown({
        onChange:function(v){
          nOpts.year = v;
          // adicionar options dos meses correspondentes ao ano no elemento #month
          renderGroupedFilters(v);
          initCharts();
        }
      });
      $('#month').dropdown({
        onChange:function(v){
          nOpts.month = v;
          renderGroupedFilters(v);
          initCharts();
        }
      });      
      
    }


    render(){
      return(
              <div className='ui compact menu'>
                <DropdownMonths select={nOpts.month} year={nOpts.year} key='month'/>
                <DropdownYears select={nOpts.year} key='years'/>
                <DropdownGroupDate select={nOpts.groupDate} key='group'/>
              </div>
      );
    }

  }

  class GroupMonthTabFilters extends React.Component{

    componentDidMount(){
      $('#groupDate').dropdown({
        onChange: function(v){
          nOpts.groupDate = v;
          renderGroupedFilters(v);
          initCharts();
        }
      });
      $('#year').dropdown({
        onChange:function(v){
          nOpts.year = v;
          renderGroupedFilters(v);
          initCharts();
        }
      });
      
    }

    render(){
      return(
              <div className='ui navy compact menu'>
                <DropdownYears key='year'/>
                <DropdownGroupDate select={nOpts.groupDate} key='group'/>
              </div>
      );
    }

  }

  class GroupYearTabFilters extends React.Component{

    componentDidMount(){
      $('#groupDate').dropdown({
        onChange: function(v){
          nOpts.groupDate = v;
          renderGroupedFilters(v);
          initCharts();
        }
      });
    }

    render(){
      return(
        <div className='ui two column equal width grid'>
            
            <div className='wide column'>

            </div>

            <div className='right aligned column'>
              <div className='ui navy compact menu'>
                <DropdownGroupDate select={nOpts.groupDate} />
              </div>
            </div>

        </div>
      );
    }

  }





/*
 * FILTERS --------------------------------------------
*/


  class BranchFilterNoBg extends React.Component{
    constructor(props){
        super(props);
        this.inputSelect = React.createRef(); // Criando a referência
        this.filial = props.default ;
    }

    componentDidMount(){
        const selectElement = this.inputSelect.current;
        const propa = this.props;
        $(selectElement).dropdown();
        $(selectElement).on('change', function(){
            var selectedValue = $(this).find('input[name="floption"]').val();
            if (propa.callback) {
              propa.callback(); // Invoca a função passada como prop
            }
        });
    }

    render(){
        const opts = [
          React.createElement(
            'div',
            {key:'default','data-value': '',className:'item'},
            'Todas as unidades'
          )
        ];
        for(var a in this.props.data){
            opts.push(React.createElement(
                'div',
                { key: a, 'data-value': this.props.data[a].wms, className:'item'},
                this.props.data[a].titulo
            ));
        }
        return React.createElement(
            'div',
            {className:'ui scrolling dropdown',ref: this.inputSelect,id:'selectFilial'},
            [
                React.createElement(
                    'input',
                    {key:0,type:'hidden',name:'filial',id:'filial',value:this.filial}),
                React.createElement(
                    'div',
                    {key:1,className:'default text'},
                    "Selecionar filial"),
                React.createElement(
                    'div',
                    {key:2,className:'menu'},
                    opts),
                    React.createElement(
                      'i',
              {key:3,className:'dropdown icon'}),
            ]
        );
    }
  }


class DateCalendarNoBg extends React.Component {
    constructor(props) {
        super(props);
        this.inputRef = React.createRef(); // Criando a referência
    }

    componentDidMount(){
        const inputElement = this.inputRef.current;
        if( inputElement ){
            let nowDate = new Date();
            const propa = this.props;
            $('#selectDate').calendar({
                type: 'date',
                text: ptBRCalendar,
                initialDate:nowDate,
                // onShow: function () {
                //     const input = $('#date');
                //     input.data('previous-value', input.val());},
                // onHide: function () {
                //     const input = $(this).find('input');
                //     if (!input.val()) {input.val(input.data('previous-value'));}},
                onChange:function(){
                    if (propa.callback) {
                      propa.callback(); // Invoca a função passada como prop
                    }
                },
                formatter: {date: 'DD/MM/YYYY'}
            });
        }
    }
    
    render(){
        return React.createElement(
                'div',
                { className:'ui transparent calendar', id:'selectDate'},
                React.createElement(
                    'div',
                    { className:'ui input left icon'},
                    [   React.createElement(
                            'i',
                            {key:0,className:'calendar icon'}),
                        React.createElement(
                            'input',
                            {key:1,ref: this.inputRef, type:'text', placeholder:'dd/mm/aaaa', name:'date', id:'date'})
                    ]
                )
        )
    }
}



class MonthFilterNoBg extends React.Component{
    constructor(props){
        super(props);
        this.inputSelect = React.createRef(); // Criando a referência
        this.month = props.default ; 
    }

    componentDidMount(){
        const selectElement = this.inputSelect.current;
        const propa = this.props;
        $(selectElement).dropdown();
        $(selectElement).on('change', function() {
            var selectedValue = $(this).find('input[name="mes"]').val();
            if (propa.callback) {
              propa.callback(); // Invoca a função passada como prop
            }
        });
    
    }

    render(){
        const opts = [];
        const m=['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
        const date = new Date();
        const month = this.month ? parseInt(this.month) : (date.getMonth()+1) ;
        

        for(var i=0;i<12;i++){
            let classT = 'item';
            if(i==(month-1)){ classT += " active selected"; }
            opts.push(React.createElement(
                'div',
                { key: i, 'data-value': (i+1), className:classT},
                m[i]
            ));
        }

        return React.createElement(
            'div',
            {className:'ui scrolling dropdown', id:'selectMonth',ref: this.inputSelect},
            [
                React.createElement(
                    'input',
                    {key:0,type:'hidden',name:'mes',defaultValue:month,id:'mes'}),
                React.createElement(
                    'div',
                    {key:1,className:'default text'},
                    "Selecionar"),
                React.createElement(
                    'div',
                    {key:2,className:'menu'},
                    opts),
                React.createElement(
                    'i',
                    {key:3,className:'dropdown icon'}),
            ]
        );
    }
}



// class YearFilterNoBg extends React.Component{
  
//   constructor(props){
//       super(props);
//       this.inputSelect = React.createRef(); // Criando a referência
//   }

//   getValue(){
//     if (this.inputSelect.current) {
//         return this.inputSelect.current.value; }
//     return null; }

//   componentDidMount(){
//       const selectElement = this.inputSelect.current;
//       const propa = this.props;
//       $(selectElement).dropdown();
//       $(selectElement).on('change',function(){
//           var selectedValue = $(this).find('input[name="ano"]').val();
//           if( propa.callback ){
//             propa.callback();
//           }
//       });
//   }

//   render(){
//       const opts = [];
//       const yearIni = 2024;
//       const date = new Date();
      
//       for(var i=yearIni;i<=parseInt(date.getFullYear());i++){
//         let classT = 'item';
//         if( i == parseInt(date.getFullYear()) ){
//           opts.push(React.createElement(
//             'div',
//             { key: i, 'data-value': i, className:"item active selected"},
//             i
//           ));
//         }else{
//           opts.push(React.createElement(
//               'div',
//               { key: i, 'data-value': i, className:"item"},
//               i
//           ));
//         }
//       }
//       return React.createElement(
//           'div',
//           {className:'ui scrolling dropdown', id:'selectYear',ref: this.inputSelect},
//           [
//             React.createElement(
//               'input',
//               {key:0,type:'hidden',name:'ano',value:parseInt(date.getFullYear()),id:'ano'}
//             ),
//             React.createElement(
//               'div',
//               {key:1,className:'default text'},
//               "Selecionar"
//             ),
//             React.createElement(
//               'div',
//               {key:2,className:'menu'},
//               opts
//             ),
//             React.createElement(
//               'i',
//               {key:3,className:'dropdown icon'}
//             ),
//           ]
//       );
//   }
  
// }



class YearFilterNoBg extends React.Component{
  
  constructor(props){
      super(props);
      this.inputSelect = React.createRef(); // Criando a referência
      this.year = props.default ;  
  }

  getValue(){
    if (this.inputSelect.current) {
        return this.inputSelect.current.value; }
    return null; }

  componentDidMount(){
      if( this.props.callback ) {
        const selectElement = this.inputSelect.current;
        const propa = this.props;
        $(selectElement).dropdown();
        $(selectElement).on('change',function(){
            var selectedValue = $(this).val();
            if( propa.callback ){
              propa.callback();
            }
        });
      }
  }

  render(){
      const opts = [];
      const yearIni = 2024;
      const date = new Date();
      const year = this.year ? parseInt(this.year) : parseInt(date.getFullYear()) ;
      for(var i=yearIni;i<=parseInt(date.getFullYear());i++){
        let classT = 'item';
        opts.push(React.createElement(
          'option',
          { key: i, 'value': i, className:"item"},
          i
        ));

      }
      return React.createElement(
          'select',
          {className:'ui scrolling basic padded dropdown', id:'ano',ref: this.inputSelect,defaultValue:year},
          opts
      );
  }
  
}


// class StatisticsInfo extends React.Component{
//   constructor(props){
//     super(props);
//   }

//   render(){
//     let items = [];
//     for(var a in this.props.data){
//       items.push(React.createElement(
//         'div',
//         {key:a,className:'statistic'},
//         [
//           React.createElement(
//             'div',
//             {key:a+'-value',className:'value'},
//             this.props.data[a]),
//           React.createElement(
//             'div',
//             {key:a+'-label',className:'label'},
//             a
//           )
//         ]
//       ))
//     }

//     return React.createElement(
//       'div',
//       {key:0,className:'ui mini micro statistics'},
//       items
//     );

//   }

// }



class StatisticsInfo extends React.Component{
  constructor(props){
    super(props);
  }

  render(){
    let items = [];
    for(var a in this.props.data){
      items.push(React.createElement(
        'div',
        {key:a,className:'column'},
        [
          React.createElement(
            'div',
            {key:a+'-value',className:'value'},
            this.props.data[a]),
          React.createElement(
            'div',
            {key:a+'-label',className:'label'},
            a
          )
        ]
      ))
    }

    return React.createElement(
      'div',
      {key:0,className:'ui mini micro equal width grid'},
      items
    );

  }

}
  

class UnidadeSelect extends React.Component{
  constructor(props){
    super(props);
  }

  componentDidMount(){
    $("a.item",this.select).on('click',function(e){
      e.preventDefault();
      $(this).parent().find('.active').removeClass('active');
      $(this).addClass('active');
    });
  }

  render(){
    const opts = [
      {k:'pedido',v:'Pedidos'},
      {k:'item',v:'Itens'},
      {k:'unidade',v:'Unidades'},
      {k:'valor',v:'Valor'},
      {k:'volume',v:'Volumes'}
    ];
    let options = [];
    $('.active.item').removeClass('active');
    for(var a in opts){
      options.push(React.createElement(
        'a',
        {href:opts[a].k,className:`${this.props.default && this.props.default == opts[a].k ? 'active' : ''} item`,key:opts[a].v},
        opts[a].v
      ))
    }
    return <div className="ui mini compact vertically fitted menu unitSelect" ref={(el)=>{this.select = el;}}>
             {options}
          </div>;
  }
  
}