$(document).ready(function () {

$("#excelfile").click(function(e){ 
  $('#excelfile').val(''); 
});

    var objData = new Map();
    $("#viewfile").click(function ExportToTable() {
        errorBucket=[];
        $("#resultMessage").empty();
        $("#exceltable").empty();
         var regex = /^([a-zA-Z0-9\s_\\.\-\\():])+(.xlsx)$/;
       // var regex = /^([a-zA-Z0-9\s_\\.\-\\():])+(.xlsx|.xls)$/;
        //var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
        /*Checks whether the file is a valid excel file*/
        if (regex.test($("#excelfile").val().toLowerCase())) {
            var xlsxflag = false; /*Flag for checking whether excel is .xls format or .xlsx format*/
            if ($("#excelfile").val().toLowerCase().indexOf(".xlsx") > 0) {
                xlsxflag = true;
            }
            /*Checks whether the browser supports HTML5*/
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var data = e.target.result;
                    /*Converts the excel data in to object*/
                    if (xlsxflag) {
                        var workbook = XLSX.read(data, {
                            type: 'binary'
                        });
                    } else {
                        var workbook = XLS.read(data, {
                            type: 'binary'
                        });
                    }
                    /*Gets all the sheetnames of excel in to a variable*/
                    var sheet_name_list = workbook.SheetNames;

                    var cnt = 0; /*This is used for restricting the script to consider only first sheet of excel*/
                    sheet_name_list.forEach(function (y) {
                        /*Iterate through all sheets*/
                        /*Convert the cell value to Json*/
                        if (xlsxflag) {
                            var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
                        } else {
                            var exceljson = XLS.utils.sheet_to_row_object_array(workbook.Sheets[y]);
                        }
                          var csv_string_data=XLSX.utils.sheet_to_csv(workbook.Sheets[y]);
                        //console.log(exceljson);
                        if (exceljson.length > 0 && cnt == 0) {
                            if(validateTemplateHeading(csv_string_data)){// heading part in template
                            //console.log(exceljson);
                                if(exceljson.length < 201){// max 200 records allowed
                                    $("button#submit").removeAttr("disabled");
                                    var exceljson=JSON.parse(JSON.stringify(exceljson).replace(/"\s+|\s+"/g,'"'))// remove empty spaces from string
                                    exceljson.sort(function (a, b) { // sorting excell raw data to find duplicateSiteId's.
                                    if (a.siteId) {
                                      var compairedValue = a.siteId.localeCompare(b.siteId);
                                      return compairedValue;
                                    }
                                    });
                                    //console.log(exceljson);
                                    var dynamicClassObj = new DynamicTabledata(); // class in DynamicTable.js
                                    var tableContent = dynamicClassObj.getDynamicTableContent(exceljson);
                                    objData.set("dataFromExcel", exceljson);
                                    //console.log(exceljson);
                                    $("#exceltable").append(tableContent);
                                    afterAppendRawDataToTableUi(exceljson);
                                    
                                }else{
                                    alert("Total site Details are "+exceljson.length+", Site-Details Max Limit 200");
                                }
                            }else{
                                alert("Invalid Template, please download the Template from below link & fill data and try again.");
                                }
                                cnt++;
                                
                        }else if(exceljson.length <= 0 && cnt == 0){
                              alert("Empty Excel uploaded");
                              cnt++;
                              
                        }


                    });

                }
                if (xlsxflag) {
                    /*If excel file is .xlsx extension than creates a Array Buffer from excel*/
                    reader.readAsArrayBuffer($("#excelfile")[0].files[0]);
                } else {
                    reader.readAsBinaryString($("#excelfile")[0].files[0]);
                }
            } else {
                alert("Sorry! Your browser does not support HTML5!");
            }
        } else {    
            alert("Please upload a valid Excel file! or Only file formate(.xlsx) supported");
             $("button#submit").attr("disabled","disabled");
        }
    });

    function afterAppendRawDataToTableUi(exceljson) {

        $(".customerNameDropDown").change(function () {

            var rowvalue = $(this).attr("data-rowIndex");
            $(this).siblings("span").remove();
            exceljson[rowvalue].customerName = $(this).val();
           
            errorBucket[rowvalue].set("cutomer", "noErrorFound");
            //removing error from errorBucket
            $("#tableRowIndex_" + rowvalue).css("background", "initial");

        });
        $(".circleDropDown").change(function () {
            var rowvalue = $(this).attr("data-rowIndex");
            $(this).siblings("span").remove();
            exceljson[rowvalue].circle = $(this).val();
            errorBucket[rowvalue].set("circle", "noErrorFound");
             $("#tableRowIndex_" + rowvalue).css("background", "initial");
        });
    }

    function errorValidation() {
        var returnValue = 'zeroErrors';
        for (var index = 0; index < errorBucket.length; index++) {
            if (errorBucket[index].get("siteId") == "Error" || errorBucket[index].get("siteName") == "Error" ||
                errorBucket[index].get("LatLong") == "Error" || errorBucket[index].get("cutomer") == "Error" ||
                errorBucket[index].get("circle") == "Error") {
                returnValue = errorBucket[index].get("rowIndex");
//                console.log("siteId"+errorBucket[index].get("siteId") +"siteName"+errorBucket[index].get("siteName") +"siteId"+errorBucket[index].get("LatLong") + "cutomer"+errorBucket[index].get("cutomer") +"circle"+errorBucket[index].get("circle") );
            }
        }
        //console.log("returnValue " + returnValue);
        return returnValue;

    }
    function validateTemplateHeading(csv_string_data){
        var stringcsvArray = csv_string_data.split(",");
                            
        if(stringcsvArray[0]=="sno" && stringcsvArray[1]=="siteId" && 
            stringcsvArray[2]=="siteName"&& stringcsvArray[3]=="latitude"&&
            stringcsvArray[4]=="longitude"&& stringcsvArray[5]=="customerName"&&
            stringcsvArray[6]=="circle"){
            return true;
        }else{
            return false;
        }
    
        
    }
/*    function validateTemplate_dataRows(JsonData){
        console.log(JsonData.length);
        // let key=Object.keys(JsonData);
        // if(key[0]=="sno" && key[1]=="siteId" && 
        //     key[2]=="siteName"&&key[3]=="latitude"&&
        //     key[4]=="longitude"&&key[5]=="customerName"&&
        //     key[6]=="circle"){
        //         for(let key in JsonData){
        //           // console.log(key);
        //         }
        //     return true;
        // }else{
        //     return false;
        // }
    }*/



    $("#submit").click(function () {
        errorBucket=[];
        $("#resultMessage").empty();
        $("#exceltable").empty();
        let dynamicClassObj = new DynamicTabledata();
        console.log("array of object"+ objData.get("dataFromExcel"));
        let tableContent = dynamicClassObj.getDynamicTableContent(objData.get("dataFromExcel"));
        $("#exceltable").append(tableContent);
        afterAppendRawDataToTableUi(objData.get("dataFromExcel"));
        
        var spinnerIcon = $("#submit i");
        var checkError = errorValidation();
        //alert(checkError);
           $("#resultMessage").removeClass("text-danger");
        if (checkError != 'zeroErrors') { // if any error found.
              $("#resultMessage").addClass("text-danger");
              $("#resultMessage").html("<b>Fill all required fields and submit</b>");
            var errorNavigator = $("#triggerAnchr");
            errorNavigator.attr("href", "#serialNumber" + checkError);
            errorNavigator[0].click();
            $("#tableRowIndex_" + checkError).css("background", "#ff000024");
        } else { // if no error found.
            spinnerIcon.removeClass("d-none");
               $("#resultMessage").empty();
            //console.log(errorBucket);
            var data = objData.get("dataFromExcel");
           // console.log(data);
            var excelRowDataArray = [];
            for (var index = 0; index < data.length; index++) {
                console.log(JSON.stringify(data[index]));
                excelRowDataArray.push(JSON.stringify(data[index])); // making stringyfy of each SiteDetails.
            }
            //console.log(excelRowDataArray);
            var content = excelRowDataArray; // getting required Data from map
            $.ajax({
                type: "POST",
                url: ADD_SITE_BASE_URL + "addSiteBulk",
                data: {
                    valueArray: content,
                    empid: '<?php echo $_SESSION["userId"];?>',
                    empName: '<?php echo $_SESSION["userName"];?>',
                },
                success: function (response) {
                    spinnerIcon.addClass("d-none");
                        if(response.error){
                            $("#resultMessage").addClass("text-danger");
                           }
                    $("#resultMessage").html(response.message);
                   // console.log(response.message);
                },
                error: function (error) {
                    console.log("error on getting response from API");
                    spinnerIcon.addClass("d-none");

                }

            });
        }
    });
});
