$(document).ready(function () {
    $("a").removeClass("active");
    $(".Report2,.Report_class").addClass("active");
    setTimeout(function () {
        $(".Report_class").click();
    }, 500);

    $("#activity").keypress(function () {
        Activity_Suggestions();
    });

//                                $('#activity').on('input', function (e) {
//                                    Activity_Suggestions();
//                                });

    $('.select2bs4').select2({
        theme: 'bootstrap4'
    });
});


var keycount = 0;
function addKeywords() {
    var keyword = $("#activity").val().trim();
    if (keyword === "" || keyword === null) {
        return false;
    } else {
        var hiddenInput = "<input type='text' id='keycount_" + keycount + "' name='activityArr[]' value='" + keyword + "'>";
        var span = "<span style='font-size: 87%;margin-right: 8px;' id='span_" + keycount + "' class='right badge badge-info'>" + keyword + " &nbsp;&nbsp;<i style='cursor: pointer'  onclick='removeKeyWord(\"" + keycount + "\")' class='fas fa-window-close'></i></span>"
        $("#hidden_inputs").append(hiddenInput);
        $("#span_list").append(span);
        keycount++;
        $("#activity").val("")
    }
}
function removeKeyWord(id) {
    keycount--;
    $("#keycount_" + id).remove();
    $("#span_" + id).remove();

}

function Activity_Suggestions() {
    var keyword = $("#activity").val().trim();
    if (keyword.length < 1) {
        return true;
    }
    if (keyword === "" || keyword === null) {
        return false;
    }
    $.ajax({
        url: base_urlJs+"Public_Controller/Activity_Suggestions",
        type: "post",
        data: {Key: keyword},
        success: function (data) {
            var activityList = [];
            var arr = JSON.parse(data);
            for (i = 0; i < arr.length; i++) {
                if (arr[i]['activity'] != "") {
                    activityList.push(arr[i]['activity']);
                }
            }
            $("#activity").autocomplete({
                source: activityList
            });
        },
        error: function (jqXhr) {
            if (jqXhr.status == 400) { //Validation error or other reason for Bad Request 400
                var json = $.parseJSON(jqXhr.responseText);
                console.log(json);
            }
        }
    });
}

function loadSatisfaction(arr) {
    for (i = 0; i < arr.length; i++) {
        $("#Satisfaction_body").append("<tr><td>" + arr[i]['satisfaction'] + "</td><td>" + arr[i]['count'] + "</td></tr>");
    }
}

function loadData() {
    $("#chart1").empty();
    $("#chart2").empty();
    $("#Satisfaction_body").empty();
    if (keycount > 0) {
        var activityarr = $("input[name='activityArr[]']").map(function () {
            return $(this).val().trim();
        }).get();
        var sup = $("#sup").val();
        var dep = $("#dep").val();
        $.ajax({
            url: base_urlJs+"Report_Controller/activityReportLoad",
            type: "get",
            data: {activityArr: activityarr, sup: sup, dep: dep},
            success: function (data) {
                var arr = JSON.parse(data);
                console.log(arr['array1']);
                if (arr['array1'].length > 0) {
                    chart1(arr['array1']);

                }
                if (arr['array2'].length > 0) {
                    chart2(arr['array2']);
                }

                if (arr['array3'].length > 0) {
                    loadSatisfaction(arr['array3']);
                }
				$(".highcharts-credits").hide()
            },
            error: function (jqXhr) {
                if (jqXhr.status == 400) { //Validation error or other reason for Bad Request 400
                    var json = $.parseJSON(jqXhr.responseText);
                    console.log(json);
                }
            }
        });


    } else {
        Swal.fire(
                'Error!',
                'Please add activities first!',
                'error'
                );
    }

}

function chart2(arr) {
    var categoriesList = [];
    var dataList = [];
    for (i = 0; i < arr.length; i++) {
        categoriesList.push((arr[i]['hours']));
        dataList.push(Number(arr[i]['count']));
    }

    Highcharts.chart('chart2', {
		chart: {
			type: 'spline',
			// inverted: true
		},
        title: {
            text: 'Hours vs Employees'
        },
        xAxis: {
            categories: categoriesList,
            tickmarkPlacement: 'on',
            title: {
                enabled: true
            }

        },
        yAxis: {
            title: {
                text: 'Employees Count'
            },
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        tooltip: {
            split: true,
            valueSuffix: ' Employees'
        },
        plotOptions: {
            series: {
                cursor: 'pointer',
                point: {
                    events: {
                        click: function () {
//                                                        $("#model1").modal();
//                                                        alert('Category: ' + this.category + ', value: ' + this.y);
                            loadModel1(this.category);
                        }
                    }
                }
            }
        },
        series: [{
                name: 'Hours',
                data: dataList
            }]
    });
}

function chart1(arr) {

    var categoriesList = [];
    var dataList = [];
    for (i = 0; i < arr.length; i++) {
        categoriesList.push(Number(arr[i]['emp_id']));
        dataList.push(parseFloat(arr[i]['hours'].replace(":",".")));
    }
                               // console.log(categoriesList)
                               // console.log(dataList)
    Highcharts.chart('chart1', {
        chart: {
            type: 'column'
        },
        title: {
            text: 'Distribution'
        },
//                                    subtitle: {
//                                        text: 'Source: WorldClimate.com'
//                                    },
        xAxis: {
            categories: categoriesList
            , labels: {
                rotation: 60
            },
            crosshair: true
        },
        yAxis: {
            min: 0,
            title: {
                text: 'Time (Hours)'
            }
        },
        tooltip: {
            headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
            pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                    '<td style="padding:0"><b>{point.y:.1f} Hours</b></td></tr>',
            footerFormat: '</table>',
            shared: true,
            useHTML: true
        },
        plotOptions: {
            column: {
                pointPadding: 0.3,
                borderWidth: 0
            }
        },
        series: [{
                name: 'Employee',
                data: dataList

            }]
    });
}

function loadModel1(hr) {
    $("#model1").modal();
    var activityarr = $("input[name='activityArr[]']").map(function () {
        return $(this).val().trim();
    }).get();
    var sup = $("#sup").val();
    var dep = $("#dep").val();
    $.ajax({
        url: base_urlJs+"Report_Controller/activityReporEmpList",
        type: "get",
        data: {activityArr: activityarr, sup: sup, dep: dep, hour: hr},
        success: function (data) {

            var arr = JSON.parse(data);
            var empList = arr['array'];
            $("#model1").modal();
            $("#model1_body").empty();
            for (i = 0; empList.length > i; i++) {
                $("#model1_body").append("<p>" + empList[i]['empName'] + "-" + empList[i]['empId'] + "</p>")
            }

        },
        error: function (jqXhr) {
            if (jqXhr.status == 400) { //Validation error or other reason for Bad Request 400
                var json = $.parseJSON(jqXhr.responseText);
                console.log(json);
            }
        }
    });
}
