
let salesChart;
let salesChart1;
let salesChart2;
let salesChart3;
let salesChart4;
let salesChart5;
let salesChart6;
let salesChart7;

let colorArray = [ "#63b598", "#ce7d78", "#ea9e70", "#a48a9e", "#c6e1e8", "#648177" ,"#0d5ac1" , "#f205e6" ,"#1c0365" ,"#14a9ad" ,"#4ca2f9" ,"#a4e43f" ,"#d298e2" ,"#6119d0", "#d2737d" ,"#c0a43c" ,"#f2510e" ,"#651be6" ,"#79806e" ,"#61da5e" ,"#cd2f00" , "#9348af" ,"#01ac53" ,"#c5a4fb" ,"#996635","#b11573" ,"#4bb473" ,"#75d89e" , "#2f3f94" ,"#2f7b99" ,"#da967d" ,"#34891f" ,"#b0d87b" ,"#ca4751" ,"#7e50a8" , "#c4d647" ,"#e0eeb8" ,"#11dec1" ,"#289812" ,"#566ca0" ,"#ffdbe1" ,"#2f1179" , "#935b6d" ,"#916988" ,"#513d98" ,"#aead3a", "#9e6d71", "#4b5bdc", "#0cd36d", "#250662", "#cb5bea", "#228916", "#ac3e1b", "#df514a", "#539397", "#880977", "#f697c1", "#ba96ce", "#679c9d", "#c6c42c", "#5d2c52", "#48b41b", "#e1cf3b", "#5be4f0", "#57c4d8", "#a4d17a", "#225b8", "#be608b", "#96b00c", "#088baf", "#f158bf", "#e145ba", "#ee91e3", "#05d371", "#5426e0", "#4834d0", "#802234", "#6749e8", "#0971f0", "#8fb413", "#b2b4f0", "#c3c89d", "#c9a941", "#41d158", "#fb21a3", "#51aed9", "#5bb32d", "#807fb", "#21538e", "#89d534", "#d36647", "#7fb411", "#0023b8", "#3b8c2a", "#986b53", "#f50422", "#983f7a", "#ea24a3", "#79352c", "#521250", "#c79ed2", "#d6dd92", "#e33e52", "#b2be57", "#fa06ec", "#1bb699", "#6b2e5f", "#64820f", "#1c271", "#21538e", "#89d534", "#d36647", "#7fb411", "#0023b8", "#3b8c2a", "#986b53", "#f50422", "#983f7a", "#ea24a3", "#79352c", "#521250", "#c79ed2", "#d6dd92", "#e33e52", "#b2be57", "#fa06ec", "#1bb699", "#6b2e5f", "#64820f", "#1c271", "#9cb64a", "#996c48", "#9ab9b7", "#06e052", "#e3a481", "#0eb621", "#fc458e", "#b2db15", "#aa226d", "#792ed8", "#73872a", "#520d3a", "#cefcb8", "#a5b3d9", "#7d1d85", "#c4fd57", "#f1ae16", "#8fe22a", "#ef6e3c", "#243eeb", "#1dc18", "#dd93fd", "#3f8473", "#e7dbce", "#421f79", "#7a3d93", "#635f6d", "#93f2d7", "#9b5c2a", "#15b9ee", "#0f5997", "#409188", "#911e20", "#1350ce", "#10e5b1", "#fff4d7", "#cb2582", "#ce00be", "#32d5d6", "#17232", "#608572", "#c79bc2", "#00f87c", "#77772a", "#6995ba", "#fc6b57", "#f07815", "#8fd883", "#060e27", "#96e591", "#21d52e", "#d00043", "#b47162", "#1ec227", "#4f0f6f", "#1d1d58", "#947002", "#bde052", "#e08c56", "#28fcfd", "#bb09b", "#36486a", "#d02e29", "#1ae6db", "#3e464c", "#a84a8f", "#911e7e", "#3f16d9", "#0f525f", "#ac7c0a", "#b4c086", "#c9d730", "#30cc49", "#3d6751", "#fb4c03", "#640fc1", "#62c03e", "#d3493a", "#88aa0b", "#406df9", "#615af0", "#4be47", "#2a3434", "#4a543f", "#79bca0", "#a8b8d4", "#00efd4", "#7ad236", "#7260d8", "#1deaa7", "#06f43a", "#823c59", "#e3d94c", "#dc1c06", "#f53b2a", "#b46238", "#2dfff6", "#a82b89", "#1a8011", "#436a9f", "#1a806a", "#4cf09d", "#c188a2", "#67eb4b", "#b308d3", "#fc7e41", "#af3101", "#ff065", "#71b1f4", "#a2f8a5", "#e23dd0", "#d3486d", "#00f7f9", "#474893", "#3cec35", "#1c65cb", "#5d1d0c", "#2d7d2a", "#ff3420", "#5cdd87", "#a259a4", "#e4ac44", "#1bede6", "#8798a4", "#d7790f", "#b2c24f", "#de73c2", "#d70a9c", "#25b67", "#88e9b8", "#c2b0e2", "#86e98f", "#ae90e2", "#1a806b", "#436a9e", "#0ec0ff", "#f812b3", "#b17fc9", "#8d6c2f", "#d3277a", "#2ca1ae", "#9685eb", "#8a96c6", "#dba2e6", "#76fc1b", "#608fa4", "#20f6ba", "#07d7f6", "#dce77a", "#77ecca"];


document.addEventListener('DOMContentLoaded', function(){
    actualizarGrafico()
    actualizarGraficoVentasMes()


    initfechascomparacion4()
    initfechascomparacion5()    
    initfechascomparacion6()
    initfechascomparacion7()        

    actualizarGraficoVentasVendedor()
    actualizarGraficoVentasOperador()    
    actualizarGraficoVentasDepartamento()    
    actualizarGraficoVentasCategoria()        
})

function initfechascomparacion4()
{
    document.getElementById('fecha1_comporacion4').value=moment().startOf('month').format('YYYY-MM-DD');
    document.getElementById('fecha2_comporacion4').value=moment().endOf('month').format('YYYY-MM-DD');
   
}

function initfechascomparacion5()
{
    document.getElementById('fecha1_comporacion5').value=moment().startOf('month').format('YYYY-MM-DD');
    document.getElementById('fecha2_comporacion5').value=moment().endOf('month').format('YYYY-MM-DD');
   
}

function initfechascomparacion6()
{
    document.getElementById('fecha1_comporacion6').value=moment().startOf('month').format('YYYY-MM-DD');
    document.getElementById('fecha2_comporacion6').value=moment().endOf('month').format('YYYY-MM-DD');
   
}

function initfechascomparacion7()
{
    document.getElementById('fecha1_comporacion7').value=moment().startOf('month').format('YYYY-MM-DD');
    document.getElementById('fecha2_comporacion7').value=moment().endOf('month').format('YYYY-MM-DD');
   
}


// VENTAS POR VENDEDOR
function actualizarGraficoVentasVendedor() {

  //const anio = document.getElementById('year4').value;
  const anio=verifyDateRange('fecha1_comporacion4','fecha2_comporacion4');
  const sucursal = document.getElementById('sucursal4').value;

  if(salesChart4) { salesChart4.destroy(); }

  let salesChartCanvas = $('#comparacion4').get(0).getContext('2d')

  const url = base_url + 'admin/comparacionVentasVendedor/' + anio +'/'+sucursal;

  const http = new XMLHttpRequest();
  http.open("GET", url, true);
  http.send();
  http.onreadystatechange = function () {

      if (this.readyState == 4 && this.status == 200) {
          const res = JSON.parse(this.responseText);
        

          let misdatos=[];
          let labels=[];
          let midata=[];
          let midata2=[];
          let micolor=[];
          let cursor=0;

          res['ventas'].forEach((item) => {
              labels.push(`${item.codven}`)
              midata.push(item.total)
              midata2.push(item.meta)
              //micolor.push( colorArray[cursor] )
              cursor++
          });

          var salesChartData = {
              labels: labels,
              datasets: [
                {
                  label: "Venta",
                  backgroundColor: "#007bff",
                  data: midata
                },
                {
                  label: "Meta",
                  backgroundColor: "rgba(40,167,69,0.3)",
                  data: midata2
                },
              ]
            }
          
            var salesChartOptions = {
              maintainAspectRatio: false,
              responsive: true,
              plugins: {
                legend: {
                  display: false
                }
              },              
              scales: {
                xAxes: [{
                  gridLines: {
                    display: false
                  }
                }],
                yAxes: [{
                  gridLines: {
                    display: false
                  }
                }]
              }
            }
            // This will get the first returned node in the jQuery collection.
            // eslint-disable-next-line no-unused-vars
            salesChart4 = new Chart(salesChartCanvas, {
              type: 'bar',
              data: salesChartData,
              options: salesChartOptions
            })
      }
  }
}


// VENTAS POR DEPARTAMENTO
function actualizarGraficoVentasDepartamento() {

  //const anio = document.getElementById('year4').value;
  const anio=verifyDateRange('fecha1_comporacion5','fecha2_comporacion5');
  const sucursal = document.getElementById('sucursal5').value;

  if(salesChart6) salesChart6.destroy();
  
  let salesChartCanvas = $('#comparacion5').get(0).getContext('2d')

  const url = base_url + 'admin/comparacionVentasDepartamento/' + anio+'/'+sucursal;

  const http = new XMLHttpRequest();
  http.open("GET", url, true);
  http.send();
  http.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
          const res = JSON.parse(this.responseText);
        

          let misdatos=[];
          let labels=[];
          let midata=[];
          let micolor=[];
          let cursor=0;

          res['ventas'].forEach((item) => {
              labels.push(`${item.departamento}`)
              midata.push(item.total)
              //micolor.push( colorArray[Math.floor(Math.random() * (colorArray.length-1))] )
              micolor.push( colorArray[cursor] )
              cursor++
          });

          misdatos.push({
            backgroundColor: micolor,
            borderColor: micolor,
            pointColor: micolor,
            pointRadius: false,
            data: midata
          })

          
          var salesChartData = {
              labels: labels,
              datasets: misdatos             
            }
          
            var salesChartOptions = {
              maintainAspectRatio: false,
              responsive: true,
              plugins: {
                legend: {
                  display: false
                }
              },              
              scales: {
                xAxes: [{
                  gridLines: {
                    display: false
                  }
                }],
                yAxes: [{
                  gridLines: {
                    display: false
                  }
                }]
              }
            }
          
            // This will get the first returned node in the jQuery collection.
            // eslint-disable-next-line no-unused-vars
            salesChart6 = new Chart(salesChartCanvas, {
              type: 'bar',
              data: salesChartData,
              options: salesChartOptions
            }
            )
      }
  }
}



// VENTAS POR DEPARTAMENTO
function actualizarGraficoVentasCategoria() {

  //const anio = document.getElementById('year4').value;
  const anio=verifyDateRange('fecha1_comporacion7','fecha2_comporacion7');
  const sucursal = document.getElementById('sucursal7').value;

  if(salesChart7) salesChart7.destroy();
  
  let salesChartCanvas = $('#comparacion7').get(0).getContext('2d')

  const url = base_url + 'admin/comparacionVentasCategoria/' + anio +'/'+sucursal;
  const http = new XMLHttpRequest();
  http.open("GET", url, true);
  http.send();
  http.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
          const res = JSON.parse(this.responseText);

          let misdatos=[];
          let labels=[];
          let midata=[];
          let micolor=[];
          let cursor=0;

          res['ventas'].forEach((item) => {
              labels.push(`${item.cod_linea}`)
              midata.push(item.totalventa)
              //micolor.push( colorArray[Math.floor(Math.random() * (colorArray.length-1))] )
              micolor.push( colorArray[cursor] )
              cursor++
          });

          misdatos.push({
            backgroundColor: micolor,
            borderColor: micolor,
            pointColor: micolor,
            pointRadius: false,
            data: midata
          })
         
          var salesChartData = {
              labels: labels,
              datasets: misdatos          
            }
          
            var salesChartOptions = {
              maintainAspectRatio: false,
              responsive: true,
              plugins: {
                legend: {
                  display: false
                }
              },              
              scales: {
                xAxes: [{
                  gridLines: {
                    display: false
                  }
                }],
                yAxes: [{
                  gridLines: {
                    display: false
                  }
                }]
              }
            }
          
            // This will get the first returned node in the jQuery collection.
            // eslint-disable-next-line no-unused-vars
            salesChart7 = new Chart(salesChartCanvas, {
              type: 'bar',
              data: salesChartData,
              options: salesChartOptions
            }
            )
      }
  }
}


// VENTAS POR OPERADOR
function actualizarGraficoVentasOperador() {

  //const anio = document.getElementById('year4').value;
  const anio=verifyDateRange('fecha1_comporacion6','fecha2_comporacion6');
  const sucursal = document.getElementById('sucursal6').value;

  if(salesChart5) salesChart5.destroy();
  
  let salesChartCanvas = $('#comparacion6').get(0).getContext('2d')

  const url = base_url + 'admin/comparacionVentasOperador/' + anio +'/'+sucursal;

  const http = new XMLHttpRequest();
  http.open("GET", url, true);
  http.send();
  http.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
          const res = JSON.parse(this.responseText);
        

          let misdatos=[];
          let labels=[];
          let midata=[];
          let midata2=[];
          let micolor=[];
          let cursor=0;

          res['ventas'].forEach((item) => {
              labels.push(`${item.codven}`)
              midata.push(item.total)
              midata2.push(item.meta)
              cursor++
          });

          /*misdatos.push({
            backgroundColor: micolor,
            borderColor: micolor,
            pointColor: micolor,
            pointRadius: false,
            data: midata
          })*/

          
          var salesChartData = {
              labels: labels,
              datasets: [
                {
                  label: "Venta",
                  backgroundColor: "#007bff",
                  data: midata
                },
                {
                  label: "Meta",
                  backgroundColor: "rgba(40,167,69,0.3)",
                  data: midata2
                },
              ]            
            }
          
            var salesChartOptions = {
              maintainAspectRatio: false,
              responsive: true,
              plugins: {
                legend: {
                  display: false
                }
              },              
              scales: {
                xAxes: [{
                  gridLines: {
                    display: false
                  }
                }],
                yAxes: [{
                  gridLines: {
                    display: false
                  }
                }]
              }
            }
          
            // This will get the first returned node in the jQuery collection.
            // eslint-disable-next-line no-unused-vars
            salesChart5 = new Chart(salesChartCanvas, {
              type: 'bar',
              data: salesChartData,
              options: salesChartOptions
            }
            )
      }
  }
}



function verifyDateRange(date1,date2)
{
    const fecha1 = document.getElementById(date1);
    const fecha2 = document.getElementById(date2);

    const mdate1 = moment(fecha1.value, "YYYY-MM-DD");
    const mdate2 = moment(fecha2.value, "YYYY-MM-DD");    

    const isValidDate1 = mdate1.isValid();
    const isValidDate2 = mdate2.isValid();

    if(isValidDate1===false && isValidDate2===false)
    {
      initfechascomparacion3()
    } else if(isValidDate1===true && isValidDate2===false) {
      fecha2.value=fecha1.value
    } else if(isValidDate1===false && isValidDate2===true) {
      fecha1.value=fecha2.value
    }

    const esMenor = mdate1.isBefore(mdate2);

    if(esMenor===false) {
        [fecha1.value, fecha2.value] = [fecha2.value, fecha1.value];
    }
    return fecha1.value+'_'+fecha2.value;
}



// VENTAS POR MES
function actualizarGraficoVentasMes() {

  const anio = document.getElementById('year1').value;
  
  if(salesChart1) salesChart1.destroy();

  // Get context with jQuery - using jQuery's .get() method.
  let salesChartCanvas = $('#comparacion1').get(0).getContext('2d')

  const url = base_url + 'admin/comparacionVentasMes/' + anio;

  const http = new XMLHttpRequest();
  http.open("GET", url, true);
  http.send();
  http.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
          const res = JSON.parse(this.responseText);
          var salesChartData = {
              labels: ['Enero', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
              datasets: [
                {
                  label: 'Venta del Mes',
                  backgroundColor: 'rgba(247,222,97,0.9)',
                  borderColor: 'rgba(247,222,97,0.8)',
                  pointRadius: false,
                  pointColor: '#3b8bba',
                  pointStrokeColor: 'rgba(247,222,97,1)',
                  pointHighlightFill: '#fff',
                  pointHighlightStroke: 'rgba(247,222,97,1)',
                  data: [res.ventas.ene, res.ventas.feb, res.ventas.mar, res.ventas.abr, res.ventas.may, res.ventas.jun, res.ventas.jul, res.ventas.ago, res.ventas.sep, res.ventas.oct, res.ventas.nov, res.ventas.dic],
                }
              ]
            }
          
            var salesChartOptions = {
              maintainAspectRatio: false,
              responsive: true,
              legend: {
                display: false
              },
              scales: {
                xAxes: [{
                  gridLines: {
                    display: false
                  }
                }],
                yAxes: [{
                  gridLines: {
                    display: false
                  }
                }]
              }
            }
          
            // This will get the first returned node in the jQuery collection.
            // eslint-disable-next-line no-unused-vars
            salesChart1 = new Chart(salesChartCanvas, {
              type: 'bar',
              data: salesChartData,
              options: salesChartOptions
            }
            )
      }
  }
}


function actualizarGrafico() {

    const anio = document.getElementById('year5').value;
    
    if(salesChart) salesChart.destroy();

    // Get context with jQuery - using jQuery's .get() method.
    let salesChartCanvas = $('#comparacion').get(0).getContext('2d')

    const url = base_url + 'admin/comparacionAbonosVentasMes/' + anio;
    const http = new XMLHttpRequest();
    http.open("GET", url, true);
    http.send();
    http.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            const res = JSON.parse(this.responseText);
            var salesChartData = {
                labels: ['Enero', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
                datasets: [
                  {
                    label: 'Pagos',
                    backgroundColor: 'rgba(220,53,69, 1)',
                    borderColor: 'rgba(220,53,69, 1)',
                    pointRadius: false,
                    pointColor: 'rgba(220,53,69, 1)',
                    pointStrokeColor: '#c1c7d1',
                    pointHighlightFill: '#fff',
                    pointHighlightStroke: 'rgba(220,220,220,1)',
                    data: [res.abonos.ene, res.abonos.feb, res.abonos.mar, res.abonos.abr, res.abonos.may, res.abonos.jun, res.abonos.jul, res.abonos.ago, res.abonos.sep, res.abonos.oct, res.abonos.nov, res.abonos.dic]
                  },
                  {
                    label: 'Ventas',
                    backgroundColor: 'rgba(40,167,69,0.9)',
                    borderColor: 'rgba(40,167,69,0.8)',
                    pointRadius: false,
                    pointColor: '#3b8bba',
                    pointStrokeColor: 'rgba(40,167,69,1)',
                    pointHighlightFill: '#fff',
                    pointHighlightStroke: 'rgba(40,167,69,1)',                    
                    data: [res.ventas.ene, res.ventas.feb, res.ventas.mar, res.ventas.abr, res.ventas.may, res.ventas.jun, res.ventas.jul, res.ventas.ago, res.ventas.sep, res.ventas.oct, res.ventas.nov, res.ventas.dic],
                  }
                ]
              }
            
              var salesChartOptions = {
                maintainAspectRatio: false,
                responsive: true,
                legend: {
                  display: false
                },
                scales: {
                  xAxes: [{
                    gridLines: {
                      display: false
                    }
                  }],
                  yAxes: [{
                    gridLines: {
                      display: false
                    }
                  }]
                }
              }
            
              // This will get the first returned node in the jQuery collection.
              // eslint-disable-next-line no-unused-vars
              salesChart = new Chart(salesChartCanvas, {
                type: 'line',
                data: salesChartData,
                options: salesChartOptions
              }
              )
        }
    }
}

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
  color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
  }


