var PROJECT_AND_STAGE_OF_AUDIT_DD=getStageOfAuditdropDown();// function call in ../js/dynamicDropdown_of_project_&_stageOfAudit.js
var EMPLOYEES_NAME_ID_OBJ;
var DUPLICATE_SITE_PO_DETAILS_ARRAY;
var objData = new Map();

$("body").tooltip({
    selector:'[data-toggle="tooltip"]'
});


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

$("button#submit, button#validateExcelData").hide();
    
    $("#viewfile").click(function ExportToTable() {
        errorBucket=[];                                 // in globalVariable.js
        $("#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("before",exceljson);
                                if(exceljson.length < 201){// max 200 records allowed
                                    $("button#submit, button#validateExcelData").hide();
                                    $("button#validateExcelData").show();
                                    $("#errorConsole").addClass('d-none');
                                    $("#downloadTemplateLink").hide();
                                    var exceljson=JSON.parse(JSON.stringify(exceljson).replace(/"\s+|\s+"/g,'"'))// remove empty spaces from string
                                    sortExcelJsonAndCreateUiTable(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");
        }
    });

        $("#exceltable").on('change','.customerNameDropDown',function (){
            let exceljson=objData.get("dataFromExcel");
            var rowvalue = Number($(this).attr("data-rowIndex"));
            $(this).siblings("span").remove();
            exceljson[rowvalue].customerName = $(this).val();
            errorBucket[rowvalue].set("customer", "noErrorFound");
            //removing error from errorBucket
            // $("#tableRowIndex_" + rowvalue).css("background", "initial");
        });
        $("#exceltable").on('change','.circleDropDown',function () {
            let exceljson=objData.get("dataFromExcel");
            var rowvalue = Number($(this).attr("data-rowIndex"));
            $(this).siblings("span").remove();
            exceljson[rowvalue].circle = $(this).val();
            errorBucket[rowvalue].set("circle", "noErrorFound");
        });
        $("#exceltable").on('change','.empIdDropDown',function(){
            let exceljson=objData.get("dataFromExcel");
            var rowvalue = Number($(this).attr("data-rowIndex"));
            let empName=getEmpNameById($(this).val());
            $(this).siblings("span").remove();
            $(this).removeClass('bg-warning');
            exceljson[rowvalue].siteAssignedToEmpId = $(this).val();
            exceljson[rowvalue].siteAssignedToEmpName = empName;
            errorBucket[rowvalue].set("empId", "noErrorFound");
            checkRule("empId", rowvalue);
        });
        $("#exceltable").on('change','.projectDropDown', function(){
            let exceljson=objData.get("dataFromExcel");
            var rowvalue=Number($(this).attr("data-rowIndex"));
            let projectName=$(this).val();
            $(this).siblings("span").remove();
            $(this).removeClass('bg-warning');
            exceljson[rowvalue].project=projectName;
            errorBucket[rowvalue].set("project","noErrorFound");
            setStageOfAuditDropDown(projectName, rowvalue);
            checkRule("project",rowvalue);
        });
        $("#exceltable").on('change','.stageOfAuditDropDown',function(){
            let exceljson=objData.get("dataFromExcel");
            var rowvalue=Number($(this).attr("data-rowIndex"));
            $(this).siblings("span").remove();
            $(this).removeClass('bg-warning');
            exceljson[rowvalue].stageOfAudit=$(this).val();
            errorBucket[rowvalue].set("stageOfAudit","noErrorFound");
        });
        $("#exceltable").on('change','input.siteVisitDate',function(){
            let exceljson=objData.get("dataFromExcel");
            var rowvalue=Number($(this).attr("data-rowIndex"));
            $(this).siblings("span").remove();
            $(this).removeClass('bg-warning');
            exceljson[rowvalue]['siteVisitDate(yyyy-mm-dd)']=$(this).val();
            errorBucket[rowvalue].set("siteVisitDate","noErrorFound");
            checkRule("siteVisitDate",rowvalue);
        });
        $("#exceltable").on('change','input.poDropDownInputList', function(){
            $(this).removeClass('bg-warning');
            let exceljson=objData.get("dataFromExcel");
            let rowvalue=Number($(this).attr('data-rowIndex'));
            exceljson[rowvalue].poNumber=$(this).val();
        });
        
        $("#exceltable").on('click','.deleteCompleteRow', function(){
            let tooltipId=$(this).attr('aria-describedby');
            $(`.tooltip#${tooltipId}`).remove();
            let exceljson=objData.get("dataFromExcel");
            let rowvalue=Number($(this).attr('data-rowIndex'));
            onDeleteTableRow(exceljson, exceljson[rowvalue], rowvalue);
        });
        $("#exceltable").on('click','.clearEmployeeAllocations', function(){
            let exceljson=objData.get("dataFromExcel");
            let rowvalue=Number($(this).attr('data-rowIndex'));
            onClearEmployeeAllocations(exceljson[rowvalue], rowvalue);
        });
        $("#exceltable").on('click','.duplicateSiteDetailsRow', function(){
            let exceljson=objData.get("dataFromExcel");
            let currentDuplicateIcon=$(this);
            let rowvalue=Number(currentDuplicateIcon.attr('data-rowIndex'));
           onDuplicateTableRow(exceljson, exceljson[rowvalue], rowvalue, currentDuplicateIcon);
        });
        
    function onDeleteTableRow(exceljson,json, index, currentDeleteIcon){
            // delete from json
            let updateJsonOnDelete=()=>{
                let noOfElementsToDeleteFromArry=1;
                for(let loopIndex=0;loopIndex<exceljson.length;loopIndex++){
                    if(exceljson[loopIndex].deleteReferenceId==index){
                       exceljson.splice(loopIndex,noOfElementsToDeleteFromArry);
                        break;
                    }
                }
            }
            // delete from ui
            let updateTableOnDelete=()=>{
                $(`#tableRowIndex_${index}`).remove();
            }
            // delete from error bucket
            let updateErrorBucketOnDelete=()=>{
                let noOfElementsToDeleteFromArry=1;
                for(let loopIndex=0; loopIndex<errorBucket.length; loopIndex++){
                    if(errorBucket[loopIndex].get("rowIndex")==index){
                        errorBucket.splice(loopIndex,noOfElementsToDeleteFromArry);
                        break;
                    }
                }
            }
            updateJsonOnDelete();
            // updateErrorBucketOnDelete();
            updateTableOnDelete();
            
    }
    function onClearEmployeeAllocations(json, index){
         // clear in json
            let updateJsonOnClear=()=>{
                json.siteAssignedToEmpId=undefined,
                json.siteAssignedToEmpName=undefined,
                json["siteVisitDate(yyyy-mm-dd)"]=undefined,
                json.project=undefined,
                json.stageOfAudit=undefined,
                json.requiredCondition=false
            }
            // clear in ui
            let updateTableOnClear=()=>{
                $(`#empIdNameTd_${index} select.empIdDropDown`).val('');
                $(`#empIdNameTd_${index}`).children("span").remove();
                $(`#siteVisitDateTd_${index} input.siteVisitDate`).val('');
                $(`#siteVisitDateTd_${index}`).children("span").remove();
                $(`#projectTd_${index} select.projectDropDown`).val('');
                $(`#projectTd_${index}`).children("span").remove();
                $(`#stageOfAuditTd_${index} select.stageOfAuditDropDown`).val('');
                $(`#stageOfAuditTd_${index}`).children('span').remove();
            }
            // clear errors in error-bucket
            let updateErrorBucketOnClear=()=>{
            let keyArray=['empId','project','stageOfAudit','siteVisitDate'];
                keyArray.forEach(function(value){
                    errorBucket[index].set(value,"noErrorFound");
                });
            }
            updateJsonOnClear();
            updateErrorBucketOnClear();
            updateTableOnClear();
    }
    function onDuplicateTableRow(exceljson, json, index, currentDuplicateIcon){
        let beforeInsertExcelJsonLength=exceljson.length;
        let dynamicClassObj = new DynamicTabledata(); // class in DynamicTable.js
        // update in json
        let updateJsonOnDuplicate=()=>{
            let obj={
                deleteReferenceId:beforeInsertExcelJsonLength,
                siteId:json.siteId,
                siteName:json.siteName,
                latitude:json.latitude,
                longitude:json.longitude,
                customerName: json.customerName,
                circle: json.circle,
                district:json.district,
                poNumber:undefined,
                siteAssignedToEmpId:undefined,
                siteAssignedToEmpName:undefined,
                'siteVisitDate(yyyy-mm-dd)':undefined,
                project:undefined,
                stageOfAudit:undefined
                
            }
            exceljson.push(obj);
        }
        // update in ui
        let duplicateTableRow=(newlyInsertedObjIndex)=>{
             // only siteDetails need to duplicate
            let trUi=`<tr id="tableRowIndex_${newlyInsertedObjIndex}">
                        <td id="serialNumber${newlyInsertedObjIndex}">${index+1}</td>
                        <td class="siteId">${json.siteId}</td>
                        <td>${json.siteName}</td>
                        <td>${json.latitude},${json.longitude}</td>
                        ${dynamicClassObj.getCustomerDropDown(json.customerName, newlyInsertedObjIndex, json.cutomerNameMismatch, "LatLong")}
                        ${dynamicClassObj.getCircleDropDown(json.circle, newlyInsertedObjIndex, json.circleMismatch, "customer")}
                        <td>${json.district}</td>                                                                                           
                        ${dynamicClassObj.getPoNumber_Tds(exceljson[newlyInsertedObjIndex].poNumber,exceljson[newlyInsertedObjIndex],newlyInsertedObjIndex, "poNumber")}
                        ${dynamicClassObj.getEmpIdName_Tds(exceljson[newlyInsertedObjIndex], newlyInsertedObjIndex, "empId")}
                        <td id="siteVisitDateTd_${newlyInsertedObjIndex}"><input type="date" class="form-control siteVisitDate bg-warning" data-rowIndex="${newlyInsertedObjIndex}" /></td>
                        ${dynamicClassObj.getProject_stageOfAudit_Tds(exceljson[newlyInsertedObjIndex].project, exceljson[newlyInsertedObjIndex].stageOfAudit, exceljson[newlyInsertedObjIndex].requiredCondition, newlyInsertedObjIndex)}
                        ${dynamicClassObj.getOperationsTd(newlyInsertedObjIndex)}
                    </tr>`;
                    // <input class="form-control poNumberInputField bg-warning" data-rowIndex="${newlyInsertedObjIndex}" value="" placeholder="enter PO Number"/>
            $(trUi).insertAfter(currentDuplicateIcon.closest('tr'));
        }
        // update in error bucket with noErrorFound, insert at last index
        let updateErrorBucket=()=>{
            let errorValidationMapObjTemp=new Map();
            errorValidationMapObjTemp.set("rowIndex",beforeInsertExcelJsonLength);
            let keyArray=['siteId','siteName','LatLong','customer','circle', 'duplicateEntry',
                      'empId', 'siteVisitDate', 'project', 'stageOfAudit', 'siteNameMismatch',
                      'latitudeMismatch','longitudeMismatch','customerNameMismatch','circleMismatch','districtMismatch'];
            keyArray.forEach(function(value){
                errorValidationMapObjTemp.set(value,"noErrorFound");
            });
            errorBucket.push(errorValidationMapObjTemp);
        };
        updateJsonOnDuplicate();
        updateErrorBucket();
        duplicateTableRow(exceljson.length-1);
    }
    function setStageOfAuditDropDown(projectName, rowIndex){
        let optionTags=`<option value="" selected disabled>Select Of Audit</option>`;
        let stageOfAuditListArray=PROJECT_AND_STAGE_OF_AUDIT_DD[projectName];
        stageOfAuditListArray.forEach(function(value){
            optionTags+=`<option value="${value}">${value}</option>`;
        });
        $("#tableRowIndex_"+rowIndex+" .stageOfAuditDropDown").empty();
        $("#tableRowIndex_"+rowIndex+" .stageOfAuditDropDown").append(optionTags);
        $("#tableRowIndex_"+rowIndex+" .stageOfAuditDropDown").removeClass('bg-warning');
        if($("#stageOfAuditTd_"+rowIndex+" span.text-danger").length){ // check if exist
            $("#stageOfAuditTd_"+rowIndex+" span.text-danger").html("Please select stage of audit from dropdown list");
        }else{
            $("#stageOfAuditTd_"+rowIndex).append(`<span class="text-danger font-weight-bold">Please select stage of audit from dropdown list</span>`);
        }
        errorBucket[rowIndex].set("stageOfAudit","Error");// add error because this is required field.
        
    }
    
    function errorValidation() {
        var returnValue = 'zeroErrors';
        // console.log(errorBucket);
        var keyValue=['siteId','siteName','LatLong','customer','circle', 'duplicateEntry',
                      'empId', 'siteVisitDate', 'project', 'stageOfAudit', 'siteNameMismatch',
                      'latitudeMismatch','longitudeMismatch','customerNameMismatch','circleMismatch','districtMismatch'];
        for (var index = 0; index < errorBucket.length; index++) {
            keyValue.forEach(function(value){
                if(errorBucket[index].get(value)=="Error"){
                    // console.log(value);
                    returnValue = errorBucket[index].get("rowIndex");
                }
            });
            
            // if (errorBucket[index].get("siteId") == "Error" || errorBucket[index].get("siteName") == "Error" ||
            //     errorBucket[index].get("LatLong") == "Error" || errorBucket[index].get("customer") == "Error" ||
            //     errorBucket[index].get("circle") == "Error" || errorBucket[index].get("duplicateEntry")=="Error" ||
            //     errorBucket[index].get("empId") == "Error" || errorBucket[index].get("siteVisitDate")=="Error" ||
            //     errorBucket[index].get("project")== "Error" ||  errorBucket[index].get("stageOfAudit")=="Error" ||
            //     errorBucket[index].get("siteNameMismatch")=="Error" || errorBucket[index].get("latitudeMismatch")=="Error" ||
            //     errorBucket[index].get("longitudeMismatch")=="Error" || errorBucket[index].get("customerNameMismatch")=="Error" ||
            //     errorBucket[index].get("circleMismatch")=="Error" || errorBucket[index].get("districtMismatch")) {
            //     returnValue = errorBucket[index].get("rowIndex");
            // }
        }
        return returnValue;
    }
    
    function validateTemplateHeading(csv_string_data){
        // console.log(csv_string_data);
        var stringcsvArray = csv_string_data.split(",");
        let excelHeadingArray=['sno','siteId','siteName','latitude','longitude','customerName','circle','district','poNumber','siteAssignedToEmpId','siteAssignedToEmpName','siteVisitDate(yyyy-mm-dd)','project','stageOfAudit'];
        for(let loopIndex=0;loopIndex<excelHeadingArray.length;loopIndex++){
            if(stringcsvArray[loopIndex]!=excelHeadingArray[loopIndex]){
                return false;
            }
        }
        return true;
    }
 

    $("button#validateExcelData").click(function(){
        let spinnerIcon = $("#validateExcelData i");
        let excelJsondata = objData.get("dataFromExcel");
        sortExcelJsonAndCreateUiTable(excelJsondata);
        let checkError = errorValidation();
        $("#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>`);
            let errorNavigator =$("#triggerAnchr");
            errorNavigator.attr('href',"#serialNumber"+ checkError);
            errorNavigator[0].click();
            $("#tableRowIndex_"+ checkError).css('background', '#ff000024');
        }else{
            spinnerIcon.removeClass('d-none');
            $("#resultMessage").empty();
            let siteDetails=getSiteDetails_SitePODetails(excelJsondata);
            let postContent=siteDetails["sitePODetails"];
            let responseResult=postDataHttpRequest(ADD_SITE_BASE_URL + "getDuplicatePODetails", postContent);
            responseResult.then((result)=>{
                if(!result.error){
                    responseData=result.response;
                    let noOfRecordsAlreadyExisting=responseData.length;
                    if(noOfRecordsAlreadyExisting){
                        $("#highlightBtn").show();
                    }else{
                        $("#highlightBtn").hide();
                    }
                    let totalRecords=postContent.length;
                    $("#errorConsole").removeClass('d-none');
                    $("#totalRecordsValue").html(totalRecords);
                    $("#noOfSubmitRecords").html(totalRecords-noOfRecordsAlreadyExisting);
                    $("#noOfDuplicateRecords").html(noOfRecordsAlreadyExisting);
                    spinnerIcon.addClass('d-none');
                    $("#validateExcelData").hide();
                    $("#exceltable select, #exceltable input").attr("disabled",true);
                    $(".operationTh, .opertionsTd").remove();
                    $("button#submit").html(`Submit<i class="fa fa-spinner fa-spin ml-2 d-none"></i>`);
                    $("button#submit").show();
                    adjustJsonAsperRequirement(responseData);
                    DUPLICATE_SITE_PO_DETAILS_ARRAY=responseData;
                    // console.log(responseData);
                }
            })
            .catch((error)=>{
                console.log("error"+error);
            });
        }
    });
    
    $("#submit").click(function(){
        $("#submit").html(`Submit <i class="fa fa-spiner fa-spin"></i>`);
        let filterdExcelJson=removeDuplicateEntriesFromExcelJson();
        console.log(filterdExcelJson);
        if(filterdExcelJson.length>0){
            let postContent=getSiteDetails_SitePODetails(filterdExcelJson);
            let responseResult=postDataHttpRequest(ADD_SITE_BASE_URL+"addSiteAndPOBulk", postContent);
            responseResult.then((result)=>{
                $("#submit i").addClass('d-none');
                if(!result.error){
                    $("#resultMessage").html(`<div><h6 class="font-weight-bold mt-2 text-success">Succesfully Submitted : </h6><p class="mb-0"><span   style="font-size: 11px;"> No.Of Sites Added records: <span class="text-succcess">${result.noOfaddSiteDetailsInserted}</span></span></p>
                                                <p><span  style="font-size: 11px;"> No.Of Employee Allocations records: <span class="text-success">${result.noOfPODetailsInserted}</span></span></p>
                                             </div>`);
                    $("#submit").hide();
                }else{
                    $("#submit").html('Retry <i class="fa fa-undo ml-2 "></i>');
                    $("#resultMessage").html(`<b class="text-danger">Internal error unable to submit</b>`);
                }
            })
            .catch((erro)=>{
                console.log("error on submitting bulk siteDetails");
                $("#submit").html('Retry <i class="fa fa-undo ml-2 "></i>');
                $("#resultMessage").html(`<b class="text-danger">Internal error unable to submit</b>`);
            })
        }else{
            $("#resultMessage").html('<b class="text-success">Site Details & Employee Allocations Already Exist</b>');
        }
        
    });
    
    function removeDuplicateEntriesFromExcelJson(){
        let importedExcelJson = objData.get("dataFromExcel");
        let filterdExcelJson=importedExcelJson.filter(
            obj1 =>DUPLICATE_SITE_PO_DETAILS_ARRAY.every(
                obj2=>!(obj1.siteId === obj2.SITE_ID && obj1["siteVisitDate(yyyy-mm-dd)"] === obj2.SITE_ASSIGNED_DATE && obj1.siteAssignedToEmpId === obj2.SITE_ASSIGNED_TO_EMPID)
                )
                                                    );
        return filterdExcelJson;
    }
    
    $("#highlightBtn").click(function(){
        let referenceId;
        DUPLICATE_SITE_PO_DETAILS_ARRAY.forEach(function(value){
            let trUniqueClass=value.SITE_ID+"_"+value.SITE_ASSIGNED_DATE+"_"+value.SITE_ASSIGNED_TO_EMPID;
            $(`.${trUniqueClass}`).addClass("bg-light-success");
            referenceId=$(`.${trUniqueClass}`).attr('id');
        })
        //navigate to last highlighted rows
            $("#triggerAnchr").attr("href", "#" + referenceId);
            $("#triggerAnchr")[0].click();
    });

    EMPLOYEES_NAME_ID_OBJ=()=>{
        let empNameObj={}
        let empNameIdsAry=getLocalStorageValue("EMP_ID_NAME_ARRAY");
        empNameIdsAry.forEach(function(value, index){
            empNameObj[value.empId]=value.empName;
        });
        return empNameObj
    };
    
    function getLocalStorageValue(key){
        return JSON.parse(localStorage.getItem(key));           //  sessionStorage variable got set in addsite/index.js file
    }
    function getEmpNameById(empId){
        return EMPLOYEES_NAME_ID_OBJ()[empId];
    }
    
    
    //rule1
    function checkRule(onChangedValue, indexValue){
        let siteVisitDate=()=>{
            let value=$("#siteVisitDateTd_"+indexValue+" input.siteVisitDate").val(); 
            let isErrorAlreadyExist=$("#siteVisitDateTd_"+indexValue+" span.text-danger").length ? true : false;
            if(!value && !isErrorAlreadyExist){                                // if siteVisitDate not Assigned
                $("#siteVisitDateTd_"+indexValue).append(`<span class='text-danger font-weight-bold'>Required</span>`);
                $("#siteVisitDateTd_"+indexValue+" .siteVisitDate").removeClass('bg-warning');
                errorBucket[indexValue].set("siteVisitDate","Error");
            }
        }
        let project=()=>{
            let value=$("#projectTd_"+indexValue+" select.projectDropDown").val();
            let isErrorAlreadyExist=$("#projectTd_"+indexValue+" span.text-danger").length ? true : false;
            if(!value && !isErrorAlreadyExist){
                $("#projectTd_"+indexValue).append(`<span class="text-danger font-weight-bold">Please select project from dropdown list</span>`);
                $("#projectTd_"+indexValue+" .projectDropDown").removeClass("bg-warning");
                errorBucket[indexValue].set("project","Error");
            }
        }
        let empId=()=>{
            let value=$("#empIdNameTd_"+indexValue+" select.empIdDropDown").val(); 
            let isErrorAlreadyExist=$("#empIdNameTd_"+indexValue+" span.text-danger").length ? true : false;
            if(!value && !isErrorAlreadyExist){
                $("#empIdNameTd_"+indexValue).append(`<span class="text-danger font-weight-bold">Please select empId in dropdown list</span>`);
                $("#empIdNameTd_"+indexValue+" .empIdDropDown").removeClass("bg-warning");
                errorBucket[indexValue].set("stageOfAudit","Error");
            }
        }
        
        switch(onChangedValue){
            case "empId":
                    siteVisitDate(); //checkRemainingValues();
                    project();
                break;
            case "siteVisitDate":
                    empId();                       //checkRemainingValues();
                    project();
                break;
            case "project":
                    empId();                      //checkRemainingValues();
                    siteVisitDate();
                break;
        }
    }
    
    function getSiteDetails_SitePODetails(validExcelJson){
        let mainArrayObj={};
        let siteDetailsArray=[];
        let poDetailsArray=[];
        let jsonLength=validExcelJson.length;
             let addNewSiteDetails=(currentLoopObj)=>{
                    let tempObj={
                        siteId:currentLoopObj.siteId,
                        siteName: currentLoopObj.siteName,
                        latitude:currentLoopObj.latitude,
                        longitude:currentLoopObj.longitude,
                        customerName:currentLoopObj.customerName,
                        circle:currentLoopObj.circle,
                        district:currentLoopObj.district
                    } 
                    siteDetailsArray.push(JSON.stringify(tempObj));
            }
            let addPoDetails=(currentLoopObj)=>{
                let tempObj={
                    siteId:currentLoopObj.siteId,
                    poNumber:currentLoopObj.poNumber,
                    siteAssignedToEmpId:currentLoopObj.siteAssignedToEmpId,
                    siteAssignedToEmpName:currentLoopObj.siteAssignedToEmpName,
                    siteVisitDate:currentLoopObj["siteVisitDate(yyyy-mm-dd)"],
                    project:currentLoopObj.project,
                    stageOfAudit:currentLoopObj.stageOfAudit,
                    managerId:loggedUserId,             // in index.php file
                    managerName:loggedUserName          // in index.php file
                }
                poDetailsArray.push(JSON.stringify(tempObj)); 
            }
            for(let loopIndex=0; loopIndex<jsonLength;loopIndex++){
                let newSiteDetails=validExcelJson[loopIndex];
                let siteDetailsAlreadyExist=false;
                    siteDetailsArray.forEach(function(currentObject){
                        if(currentObject.siteId==newSiteDetails.siteId){
                            siteDetailsAlreadyExist=true;
                        }
                    });
                    if(!siteDetailsAlreadyExist){
                        addNewSiteDetails(newSiteDetails);
                    }
                    addPoDetails(newSiteDetails);
            }
        mainArrayObj["siteDetails"]=siteDetailsArray;
        mainArrayObj["sitePODetails"]=poDetailsArray;
        // console.log(mainArrayObj);
        return mainArrayObj;
    }
    
 
    
    function sortExcelJsonAndCreateUiTable(exceljson){
        errorBucket=[];
        var sortJsonClassObj= new sortRawJsonData();
            sortJsonClassObj.sortDataBySiteId_empId_siteVisitDate(exceljson);
        var dynamicClassObj = new DynamicTabledata(); // class in DynamicTable.js
        var tableContent = dynamicClassObj.getDynamicTableContent(exceljson);
            objData.set("dataFromExcel", exceljson);
        $("#exceltable").empty().append(tableContent);
        // afterAppendRawDataToTableUi(exceljson);
    }
    
    function adjustJsonAsperRequirement(json){
        let loopIndex=0;
        while(loopIndex<json.length){
            if(json[loopIndex].SITE_ASSIGNED_DATE=="0000-00-00"){// while remove duplicate rowvalues from excel json requirement is not be ('' or '0000-00-00') only need undefined
                json[loopIndex].SITE_ASSIGNED_DATE=undefined;
            }
            if(json[loopIndex].SITE_ASSIGNED_TO_EMPID==""){
                json[loopIndex].SITE_ASSIGNED_TO_EMPID=undefined;
            }
           loopIndex++; 
        }
    }
    
    
    
//  rules
/*
rule1
1) In PO Details: -   If only PO number given allow to submit.
2) In PO Details: -   If no PO Details allow to submit.
3) In PO Details: - (empIdName, SitevisitDate, Project, stateOfAudit) If any one of these fields present all remaining fields need to insert.
    i.e (add only if all 4 fields values there)


rule2
1) only one entry should me be  there with (siteId+empId+siviteDate) combination, if not print duplicate entry.
*/
