$(document).ready(function () {

    $(function () {
      $('[data-toggle="tooltip"]').tooltip()
    })

    mapTags();
    get_stats();
    
    update_dates();
    function update_dates()
    {
        chData = $('#visits_chart').data('data');
        if (chData.length < 2)
            return;
        chLabels = JSON.parse($('#visits_chart').data('labels').replaceAll('\'', '\"'));
        area_Labels = JSON.parse($('#visits_chart').data('areas').replaceAll('\'', '\"'));
        console.log(chLabels);
        var canvas = document.createElement('canvas');
        canvas.setAttribute('id', 'canvas_vc');
        $('#visits_chart').empty();
        $('#visits_chart').append(canvas);
        colors = [
                        'rgba(250, 100, 100, 1)',
                        'rgba(100, 250, 100, 1)',
                        'rgba(100, 100, 250, 1)',
                        'rgba(100, 250, 250, 1)',
            ]
        datasets = []
        for(i in chData)
        {
            datasets.push({
              label: area_Labels[i],
              data: chData[i],
              backgroundColor: colors[i],
              lineTension: 0.4
            })
        }
        var chartData = {
          labels: chLabels,
          datasets: datasets
        };
        if (canvas) {
          var chart = new Chart(canvas, {
          type: 'line',
          data: chartData,
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
             datalabels: {
                textAlign: 'center',
                maintainAspectRatio: false,
                font: {
                    lineHeight: 1.6
                }
              },
              legend: {
                display: false,
              },
              title: {
                display: false,
              }
            },
            tooltips: {
                enabled: false
            }
          }
          });
        }
    }

    $('.nav-link').click(function(){
        $('.select_div').hide();
        $('#select_div'+$(this).data('profarea_id')).show();
        get_stats();
    });

    $('.show_visits').click(function(){
        getVisits($(this).data('visit_ids'));
    });


    function mapTags(){
        var lang = getUrlParameter('lang');
        $.each($('.diagnoses_select'), function(e) {

            var profarea_id = $(this).data('profarea_id');
            console.log(profarea_id);
            if(lang == 'en')
                $(this).append('<option value=0 selected style="color: #888;">Diagnos</option>');
            else
                $(this).append('<option value=0 selected style="color: #888;">Диагноз</option>');
            $.ajax({
                type:'GET',
                url: '/get_diagnos_tags/'+profarea_id+'?lang='+lang,
                async: false,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success: (data) => {
                    for(tag_num in data)
                    {
                        var tag = data[tag_num]
                        if(tag['category_id'] == null && tag['diagnos'] == true)
                        {
                            var icd = ''
                            if (tag['icd'])
                            {
                                icd = tag['icd'] + ' '
                            }
                            $(this).append('<option value="'+tag['id']+'">'+icd+tag['standart_name']+'</option>');
                            console.log('appended');
                        }
                    }
                },
                error:function (jqXHR, exception) {
                }
            });
        });
    }

    $('.diagnoses_select').on('change', function() {get_stats(null)});
    $('#pirogov_confirmed').on('change', function() {get_stats(null)});
    $('#doctor_select').on('change', function() {get_stats(null)});
    $('#start_date').on('change', function() {get_stats(null)});
    $('#end_date').on('change', function() {get_stats(null)});
    $('#med_visit').on('change', function() {get_stats(null)});
    $('#med_exam').on('change', function() {get_stats(null)});
    $('#dest_direct').on('change', function() {get_stats(null)});
    $('#source_direct').on('change', function() {get_stats(null)});


    $('#today').on('click', function() {get_stats('today')});
    $('#7days').on('click', function() {get_stats('7days')});
    $('#30days').on('click', function() {get_stats('30days')});



    function get_stats(time_param)
    {
        lang = getUrlParameter('lang');
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        var user_id = $('#doctor_select').val();
        var pirogov_confirmed = $('#pirogov_confirmed').is(':checked');
        var med_exam = $('#med_exam').is(':checked');
        var med_visit = $('#med_visit').is(':checked');
        var dest_direct = $('#dest_direct').is(':checked');
        var source_direct = $('#source_direct').is(':checked');
        var profarea_id = $('.tab-pane.active').data('profarea_id');
        var diagnos_id = $('#diagnos'+profarea_id).val();
        var clinic_id = $('#clinic_id').val();
            var url = '/get_stats?lang='+lang+'&start_date='+start_date+'&time_param='+time_param+'&dest_direct='+dest_direct+'&source_direct='+source_direct+'&med_exam='+med_exam+'&med_visit='+med_visit+'&end_date='+end_date+'&user_id='+user_id+'&pirogov_confirmed='+pirogov_confirmed+'&diagnos_id='+diagnos_id+'&profarea_id='+profarea_id+'&clinic_id='+clinic_id;
        $.ajax({
            type:'GET',
            url: url,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                $('#num_surgical'+profarea_id).html(data['surgical']);
                $('#num_surgical'+profarea_id).parent().data('visit_ids', data['visits']['surgical']);
                $('#num_therapeutic'+profarea_id).html(data['therapeutic']);
                $('#num_therapeutic'+profarea_id).parent().data('visit_ids', data['visits']['therapeutic']);
                $('#num_waiting'+profarea_id).html(data['waiting']);
                $('#num_norma'+profarea_id).html(data['norma']);
                $('#num_waiting'+profarea_id).parent().data('visit_ids', data['visits']['waiting']);
                $('#num_unsatisfactory'+profarea_id).html(data['unsatisfactory']);
                $('#num_unsatisfactory'+profarea_id).parent().data('visit_ids', data['visits']['unsatisfactory']);
                var chLabels = [data['translate']['surgical'],data['translate']['therapeutic'],data['translate']['norma'],data['translate']['waiting'],data['translate']['unsatisfactory']];
                var chNames = ['surgical','therapeutic','norma','waiting','unsatisfactory'];
                var chData = [data['surgical'], data['therapeutic'], data['norma'], data['waiting'], data['unsatisfactory']];
                var canvas = document.createElement('canvas');
                canvas.setAttribute('id', 'canvas'+profarea_id);
                $('#chart'+profarea_id).empty();
                $('#chart'+profarea_id).append(canvas);
                var chartData = {
                  labels: chLabels,
                  datasets: [{
                      data: chData,
                      backgroundColor: [
                        'rgba(250, 100, 100, 1)',
                        'rgba(100, 190, 100, 1)',
                        'rgba(0, 250, 0, 1)',
                        'rgba(200, 200, 200, 1)',
                        'rgba(100, 100, 200, 1)',
                      ]
                  }]
                };
                if (canvas) {
                  var chart = new Chart(canvas, {
                  type: 'doughnut',
                  data: chartData,
                  options: {
                    responsive: true,
                    plugins: {
                     datalabels: {
                        color: '#111',
                        textAlign: 'center',
                        font: {
                            lineHeight: 1.6
                        },
                        formatter: function(value, ctx) {
                            return ctx.chart.data.labels[ctx.dataIndex] + '\n' + value + '%';
                        }
                      },
                      legend: {
                        position: 'top',
                      },
                      title: {
                        display: true,
                      }
                    },
                    tooltips: {
                        enabled: false
                    },
                    onClick: (evt, activeEls, chart) => {
                      if (activeEls.length === 0 || chart.getElementsAtEventForMode(evt, 'nearest', {
                          intersect: true
                        }, true).length === 0) {
                        return;
                      }
                      console.log('Function param: ', activeEls[0].index);
                      getVisits(data['visits'][chNames[activeEls[0].index]])
//                      console.log('lookup with the event: ', chart.getElementsAtEventForMode(evt, 'nearest', {
//                        intersect: true
//                      }, true)[0].index);

//                      activeEls.forEach(point => {
//                        console.log('val: ', chart.data.datasets[point.datasetIndex].data[point.index])
//                      })
                    }
                  }
                  });
                }
            },
            error:function (jqXHR, exception) {
                after_error();
            }
        });

    }

    $('.excl_dwnld').on('click', function() {getExcel()});

    $('.excl_dwnld2_0').on('click', function() {getExcel2_0()});

    function getExcel2_0(){
        lang = getUrlParameter('lang');
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        var clinic_id = $('#clinic_id').val();
        var url = '/routing/report/'+clinic_id+'?lang='+lang+'&start_date='+start_date+'&end_date='+end_date+'&reload='+$('#reload').is(':checked');
        $.ajax({
            type:'GET',
            url: url,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                var a = document.createElement('a');
                a.href = '/excel/'+ data['file'];
                filename = $('#clinic_name').val()+'_report'
                a.download = filename + '.xlsx';
                document.body.append(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL('/excel/'+ data['file']);
            },
            error:function (jqXHR, exception) {
                after_error();
            }
        });
    }

    function getExcel(){
        lang = getUrlParameter('lang');
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        var user_id = $('#doctor_select').val();
        var pirogov_confirmed = $('#pirogov_confirmed').is(':checked');
        var med_exam = $('#med_exam').is(':checked');
        var med_visit = $('#med_visit').is(':checked');
        var dest_direct = $('#dest_direct').is(':checked');
        var source_direct = $('#source_direct').is(':checked');
        var profarea_id = $('.tab-pane.active').data('profarea_id');
        var diagnos_id = $('#diagnos'+profarea_id).val();
        var clinic_id = $('#clinic_id').val();
        var url = '/get_excel_stats?lang='+lang+'&start_date='+start_date+'&dest_direct='+dest_direct+'&source_direct='+source_direct+'&med_exam='+med_exam+'&med_visit='+med_visit+'&end_date='+end_date+'&user_id='+user_id+'&pirogov_confirmed='+pirogov_confirmed+'&diagnos_id='+diagnos_id+'&profarea_id='+profarea_id+'&clinic_id='+clinic_id;
        $.ajax({
            type:'GET',
            url: url,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                var a = document.createElement('a');
                a.href = '/excel/'+ data['file'];
                filename = $('#clinic_name').val()+'_report'
                a.download = filename + '.xlsx';
                document.body.append(a);
                a.click();
                a.remove();
                window.URL.revokeObjectURL('/excel/'+ data['file']);
            },
            error:function (jqXHR, exception) {
                after_error();
            }
        });
    }

    function getVisits(ids){
        var message = {
                visit_ids: ids,
                clinic_id: $('#clinic_id').val()
        }
        $.ajax({
            type:'POST',
            url: '/prepare_stats_visits',
            async: !1,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            data: JSON.stringify(message),
            success: (data) => {
                $('#visits_table').empty();
                $('#visits_modal').modal('toggle');
                $('#datatable').DataTable().clear().destroy();
                for (visit_num in data)
                {
                    visit = data[visit_num]
                    if($('#language').val() == 'ru')
                        $('#visits_table').append('<tr '+getTooltip(visit['confirmed_tags'])+'><td><a href="/medical_report/'+visit['id']+'">'+visit['patient']+'</a></td><td><a href="/medical_report/'+visit['id']+'">'+visit['date']+'</a></td><td><a href="/medical_report/'+visit['id']+'">'+visit['telephone']+'</a></td><td><a href="/medical_report/'+visit['id']+'">'+visit['doctor']+'</a></td><td style="display: none;">'+visit['department']+'</td><td><a href="/medical_report/'+visit['id']+'">'+getDiagnosesText(visit['confirmed_tags'])+'</a></td></tr>');
                    else
                        $('#visits_table').append('<tr '+getTooltip(visit['confirmed_tags'])+'><td><a href="/medical_report/'+visit['id']+'?lang=en">'+visit['patient']+'</a></td><td><a href="/medical_report/'+visit['id']+'">'+visit['date']+'</a></td><td><a href="/medical_report/'+visit['id']+'">'+visit['telephone']+'</a></td><td><a href="/medical_report/'+visit['id']+'">'+visit['doctor']+'</a></td><td style="display: none;">'+visit['department']+'</td><td><a href="/medical_report/'+visit['id']+'">'+getDiagnosesText(visit['confirmed_tags'])+'</a></td></tr>');
                }
                $('tr[data-bs-toggle="tooltip"]').tooltip({
                    html: true,
                });
                var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-toggle="tooltip"]'))
                var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
                  return new bootstrap.Tooltip(tooltipTriggerEl)
                })
//                $('#datatable').DataTable({
//                    "scrollX": true
//                });
            }
        });
    }
    function getDiagnosesText(tags)
    {
        var diagnoses = '';
        for(tag in tags)
            diagnoses += tags[tag] + '<br>'
        return diagnoses
    }
    function getTooltip(tags)
    {
        var diagnoses = '';
        for(tag in tags)
            diagnoses += tags[tag] + '<br>'
        return ''
//        return 'data-bs-toggle="tooltip" data-bs-placement="bottom" title="'+diagnoses+'"'
    }

    $('#visits_modal').on('shown.bs.modal', function () {
//       $('#datatable_wrapper').hide();
       $('#datatable').DataTable( {
            "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.10.19/i18n/Russian.json"
            },
            "scrollX": true
       });
    });

    function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    };

    function getRandomInt(max) {
        return Math.floor(Math.random() * Math.floor(max));
    }

});
