//GLOBAL VARIABLES
let EMPID_TD="EMPID_TD";
let FORTNIGHT_TD="FORTNIGHT_TD";
let TRANSACTIONID_TD="TRANSACTIONID_TD";
let ADVANCE_AMOUNT_TD="ADVANCE_AMOUNT_TD";
let ADVANCE_DATE_TD="ADVANCE_DATE_TD";
let REMARKS_TD="REMARKS_TD";
let TABLE_ROW_ERROR_CLASS="TABLE_ROW_ERROR_CLASS";
let POST_CONTENT_OF_VERIFY_DUPLICATE_TRANSACTION_ID_REQUEST;
let TRANSACTION_IDS_ALREADY_EXIST_IN_SERVER_ARRAY;
let TRANSACTION_DETAILS_ALREADY_EXIST_ARRAY;
let EXPORTED_EXCEL_JSON;
let EMPLOYS_NOT_HAVE_FORTNIGHT;  
let FN_RESPONSE_MAP;


class AdvanceAmountTable{
    constructor(){
        this.CurrentSelectedFortNight=this.getCurrentSelectedFn();
        this.TableRowMap=new Map();
        this.transactionIdsArray=[];
        //error console varibales
        this.requiredFieldsMissingCount;
        this.invalidAdvanceAmountCount;
        this.advanceReleasedDateFnMismatchCount;
        this.invalidAdvanceReleasedDateCount;
        this.duplicateTransactionIdsCount;
        this.transactionIdExceedMaxLengthCount;
        this.remarksExceedMaxLengthCount;
        
    }
    
    
    getDynamicAdvanceAmountTable(excelJson){
            EXPORTED_EXCEL_JSON=excelJson;
            let tableBody="";
            let JsonLength=excelJson.length;
            if($.fn.DataTable.isDataTable('#empAdvanceExcelConvertedTable')){
                $('#empAdvanceExcelConvertedTable').DataTable().clear().destroy();
            }
            this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"");
            this.requiredFieldsMissingCount=0;
            this.invalidAdvanceAmountCount=0;
            this.advanceReleasedDateFnMismatchCount=0;
            this.invalidAdvanceReleasedDateCount=0;
            this.duplicateTransactionIdsCount=0;
            this.transactionIdExceedMaxLengthCount=0;
            this.remarksExceedMaxLengthCount=0;
            
            for(let index=0;index<JsonLength;index++){
                this.checkForDuplicateTransactionId(index,excelJson[index],excelJson[index+1],JsonLength);
                this.validateEmpId(excelJson[index]["EMP ID"]);
                this.getFortNight_ValidateReleaseDate(excelJson[index]["ADVANCE RELEASED DATE (YYYY-MM-DD)"], excelJson[index]);// according to excel template heading json
                this.validateTID(excelJson[index]["TRANSACTION-ID"],excelJson[index]);
                this.validateAdvanceAmount(excelJson[index]["ADVANCE AMOUNT"], excelJson[index]);
                this.validateRemarks(excelJson[index]["REMARKS"]);
                tableBody+=`<tr id="TrId${index+1}" class="${this.TableRowMap.get(TABLE_ROW_ERROR_CLASS)}  trEmpId${excelJson[index]["EMP ID"]}">
                            <td>${index+1}</td>
                            ${this.TableRowMap.get(EMPID_TD)}
                            <td class="tdEmpName">Employee Name</td>
                            ${this.TableRowMap.get(FORTNIGHT_TD)}
                            ${this.TableRowMap.get(TRANSACTIONID_TD)}
                            ${this.TableRowMap.get(ADVANCE_AMOUNT_TD)}
                            ${this.TableRowMap.get(ADVANCE_DATE_TD)}
                            ${this.TableRowMap.get(REMARKS_TD)}
                            </tr>`;
                  this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,""); 
                  excelJson[index]["tableRowId"]=`TrId${index+1}`;// adding unique id in ExcelJson.
            }
           
            $("#empAdvanceExcelConvertedTable tbody").append(tableBody);
            $("#empAdvanceExcelConvertedTable").DataTable({
                        dom: 'lBfrtip',
                        buttons:[],
                        aLengthMenu:[[10,50,100,500,-1],[10,50,100,500,"ALL"]],
                        pageLength:-1
                        
                });
                this.createErrorConsoleUI_requestServerForDuplicatTransactnId();
    }
    
    validateEmpId(empId){
        if(empId){
            this.TableRowMap.set(EMPID_TD,`<td class="empIdTd">${empId}</td>`);
        }else{
           this.TableRowMap.set(EMPID_TD,this.requiredTd());
        }
    }
    
    getFortNight_ValidateReleaseDate(advReleasedDate, currentLoopIndexJsonRow){
            if(advReleasedDate){
                let dateReg=/^\d{4}\/(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])$/;
                if(advReleasedDate.match(dateReg)){ // validate date with YYYY/MM/DD
                    let dateValuesArray=advReleasedDate.split('/');
                    let yearValue=dateValuesArray[0];
                    let monthName= getMonthName((dateValuesArray[1])-1); // this function in DashBoard/commom.js ("-1"  because array start from 0 to 11 indexs )
                    let fortNightType=getFortNightName(dateValuesArray[2]); //this function in DashBoard/commom.js
                    let fortNightValue=`${yearValue}-${monthName}-${fortNightType}`;// fortNight formate eg:"2021-April-1st FN"
                    if(fortNightValue!= this.CurrentSelectedFortNight){
                        this.TableRowMap.set(FORTNIGHT_TD,`<td class="border border-danger"><span>${fortNightValue}</span><p class="m-0 text-danger errorMsg">Invalid FortNight</p></td>`);
                        this.TableRowMap.set(ADVANCE_DATE_TD,`<td class="border border-danger"><span>${advReleasedDate}</span><p class="m-0 text-danger errorMsg advanceReleasedDateFnMismatchTd">This date not belongs to selected Fortnight</p></td>`);
                        this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"errorTableRow");
                        this.advanceReleasedDateFnMismatchCount++;
                    }else{
                        currentLoopIndexJsonRow.FORTNIGHT=fortNightValue;//updateing FortNight value Incurrent LoopIndex JsonRow
                        this.TableRowMap.set(FORTNIGHT_TD,`<td>${fortNightValue}</td>`);
                        this.TableRowMap.set(ADVANCE_DATE_TD,`<td>${advReleasedDate}</td>`);
                    }
                }else{
                     this.TableRowMap.set(FORTNIGHT_TD,`<td></td>`);
                     this.TableRowMap.set(ADVANCE_DATE_TD,`<td class="border border-danger"><span>${advReleasedDate}</span><p class="m-0 text-danger errorMsg invalidAdvanceReleasedDateTd">Invalid Date Format</p></td>`);
                     this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"errorTableRow");
                     this.invalidAdvanceReleasedDateCount++;
                }
            }else{
                 this.TableRowMap.set(FORTNIGHT_TD,`<td></td>`);
                 this.TableRowMap.set(ADVANCE_DATE_TD,this.requiredTd());
            }
            
    }
    
    validateTID(transactionId,currentLoopIndexJsonRow){
        if(transactionId){
            if(currentLoopIndexJsonRow.duplicateTId){
                 this.TableRowMap.set(TRANSACTIONID_TD,`<td class="border border-danger"><span>${transactionId}</span><p class="m-0 text-danger errorMsg duplicateTransactionIdsTd">Duplicate</p></td>`);
                 this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"errorTableRow");
                 this.duplicateTransactionIdsCount++;
            }else{
                if(transactionId.length<=100){ // t-id should not more than 100
                     this.TableRowMap.set(TRANSACTIONID_TD,`<td class="transactionTd"><span>${transactionId}</span></td>`);
                     this.transactionIdsArray.push(transactionId);
                }else{
                    this.TableRowMap.set(TRANSACTIONID_TD,`<td class="border border-danger"><span>${transactionId}</span><p class="m-0 text-danger errorMsg transactionIdExceedMaxLengthTd">Max 100 chars allowed</p></td>`);
                    this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"errorTableRow");
                    this.transactionIdExceedMaxLengthCount++;
                }
            }
        }else{
            this.TableRowMap.set(TRANSACTIONID_TD,this.requiredTd());
        }
    }
    
    validateAdvanceAmount(advanceAmnt, currentLoopIndexJsonRow){
        let reg=/^[0-9.]*$/;
        if(advanceAmnt){
            if(advanceAmnt.match(reg) && parseFloat(advanceAmnt)){
                 currentLoopIndexJsonRow["ADVANCE AMOUNT"]=parseFloat(advanceAmnt).toFixed(2);// update to integer value. up to 2decimals
                this.TableRowMap.set(ADVANCE_AMOUNT_TD,`<td>${advanceAmnt}</td>`);
            }else{
                this.TableRowMap.set(ADVANCE_AMOUNT_TD,`<td class="border border-danger"><span>${advanceAmnt}</span><p class="m-0 text-danger errorMsg invalidAdvanceAmountTd">Invalid Amount</p></td>`);
                this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"errorTableRow");
                this.invalidAdvanceAmountCount++;
            }
        }else{
            this.TableRowMap.set(ADVANCE_AMOUNT_TD,this.requiredTd());
        }
    }
    
    validateRemarks(remarks){
        if(remarks){
            if(remarks.length<=300){
                this.TableRowMap.set(REMARKS_TD,`<td><textarea rows="1" class="form-control" readonly >${remarks}</textarea></td>`);
            }else{
                this.TableRowMap.set(REMARKS_TD,`<td class="border border-danger"><textarea rows="1" class="form-control" readonly >${remarks}</textarea><p class="m-0 text-danger errorMsg remarksExceedMaxLengthTd">Max 300 chars allowed</p></td>`);
                this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"errorTableRow");
                this.remarksExceedMaxLengthCount++;
            }
        }
        else{
            this.TableRowMap.set(REMARKS_TD,`<td></td>`);
        }
        
    }
    

    
    checkForDuplicateTransactionId(loopIndex,currentLoopIndexJsonRow,nextLoopIndexJsonRow,excelJsonLength){
        if((loopIndex+1)<excelJsonLength){
            if(currentLoopIndexJsonRow!==null && nextLoopIndexJsonRow!==null){
                if(currentLoopIndexJsonRow["TRANSACTION-ID"]==nextLoopIndexJsonRow["TRANSACTION-ID"]){
                    currentLoopIndexJsonRow.duplicateTId=true;
                    nextLoopIndexJsonRow.duplicateTId=true;
                }
            }
            
        }
    }
    requiredTd(){
        this.requiredFieldsMissingCount++;
        this.TableRowMap.set(TABLE_ROW_ERROR_CLASS,"errorTableRow");
        return  `<td class="border border-danger text-danger errorMsg requiredFieldsMissingTd">Required</td>`;
    }
    
    createErrorConsoleUI_requestServerForDuplicatTransactnId(){
        let orderListUI='';
        let isErrorExist=this.requiredFieldsMissingCount!=0 || this.invalidAdvanceAmountCount!=0 || 
                        this.advanceReleasedDateFnMismatchCount!=0 || this.invalidAdvanceReleasedDateCount!=0 || 
                        this.duplicateTransactionIdsCount!=0 || this.transactionIdExceedMaxLengthCount!=0 ||
                        this.remarksExceedMaxLengthCount!=0;
        this.requiredFieldsMissingCount > 0 ?  //if
            orderListUI+=`<li><p class=" d-flex mb-0 text-danger">Required Fields Missing<span>(${this.requiredFieldsMissingCount}). </span><button class="btn btn-danger py-1 h-100 showErrorConsoleBtn" data-id="requiredFieldsMissingTd">show</button></p></li>`// true
            : orderListUI+=`<li><p class="mb-0 text-success">Required fields. <i class="fas fa-check"></i></p></li>`;// else false
            
        this.invalidAdvanceAmountCount > 0 ?
            orderListUI+=`<li><p class=" d-flex mb-0 text-danger">Invalid Advance Amount<span>(${this.invalidAdvanceAmountCount}). </span><button class="btn btn-danger py-1 h-100 showErrorConsoleBtn" data-id="invalidAdvanceAmountTd">show</button></p></li>`
            : orderListUI+=`<li><p class="mb-0 text-success">Advance amount format. <i class="fas fa-check"></i></p></li>`;
        
        this.advanceReleasedDateFnMismatchCount > 0 ?
            orderListUI+=`<li><p class=" d-flex mb-0 text-danger">Advance released date not belongs to ${this.CurrentSelectedFortNight}<span>(${this.advanceReleasedDateFnMismatchCount}). </span><button class="btn btn-danger py-1 h-100 showErrorConsoleBtn" data-id="advanceReleasedDateFnMismatchTd">show</button></p></li>`
            : orderListUI+=`<li><p class="mb-0 text-success">Advance released date. <i class="fas fa-check"></i></p></li>`;
        
        this.invalidAdvanceReleasedDateCount > 0 ?
            orderListUI+=`<li><p class=" d-flex mb-0  text-danger">Invalid advance released date format(YYYY-MM-DD)<span>(${this.invalidAdvanceReleasedDateCount}). </span><button class="btn btn-danger py-1 h-100 showErrorConsoleBtn" data-id="invalidAdvanceReleasedDateTd">show</button></p></li>`
            :orderListUI+=`<li><p class="mb-0 text-success">Advance released date format(YYYY-MM-DD). <i class="fas fa-check"></i></p></li>`;
        
        this.duplicateTransactionIdsCount > 0 ?
            orderListUI+=`<li><p class=" d-flex mb-0  text-danger">Duplicate transaction id's<span>(${this.duplicateTransactionIdsCount}). </span><button class="btn btn-danger py-1 h-100 showErrorConsoleBtn" data-id="duplicateTransactionIdsTd">show</button></p></li>`
            :orderListUI+=`<li><p class="mb-0 text-success">No duplicate transaction id found. <i class="fas fa-check"></i></p></li>`;
            
        this.transactionIdExceedMaxLengthCount > 0 ?
        orderListUI+=`<li><p class=" d-flex mb-0 text-danger">Transaction id exceed max length 100 char<span>(${this.transactionIdExceedMaxLengthCount}). </span><button class="btn btn-danger py-1 h-100 showErrorConsoleBtn" data-id="transactionIdExceedMaxLengthTd">show</button></p></li>`
        :orderListUI+=`<li><p class="mb-0 text-success">Transaction id length below 100 char. <i class="fas fa-check"></i></p></li>`;
        
        this.remarksExceedMaxLengthCount > 0 ?
         orderListUI+=`<li><p class=" d-flex mb-0 text-danger">Remarks exceed max length 300 char<span>(${this.remarksExceedMaxLengthCount}). </span><button class="btn btn-danger py-1 h-100 showErrorConsoleBtn" data-id="remarksExceedMaxLengthTd">show</button></p></li>`
        :orderListUI+=`<li><p class="mb-0 text-success">Remarks char length below 300. <i class="fas fa-check"></i></p></li>`;
        
        $("#empAdvanceAmntDetailsErrorConsole div ol").html(orderListUI);
        $(".loadingList_validatingExcelTemplate p.listItemData i").removeClass("spinner-border");
        
        if(isErrorExist){
            this.changesOnInvalidTemplateErrorWhileLoading();
            //background-color=yellow
        }else{
            this.changesOnValidTemplateWhileLoading();
            // console.log(this.transactionIdsArray);
            let obj={
                fortNight:this.CurrentSelectedFortNight,
                transactionIdsArray:this.transactionIdsArray
            }
            let postContent=JSON.stringify(obj);
            POST_CONTENT_OF_VERIFY_DUPLICATE_TRANSACTION_ID_REQUEST=postContent;
            this.request_employeeAdvanceInfo_andTransactionValidationArray(postContent);
            $("#loaderMainSection .loaderDiv .totalRecords").text(EXPORTED_EXCEL_JSON.length);
        }
    }
    
    
    
    request_employeeAdvanceInfo_andTransactionValidationArray(postContent){
        console.log(postContent);
        if(!checkWheatherLogoutOrNot_InternetConnection()){
            alertNoInternet_connection();
            this.changesOnErrorTransactionIdRequestWhileLoading();
        }else{
            $("#loaderMainSection .loaderDiv .retryBtn").removeClass("d-flex");
            $(".loadingList_validatingTransactionId p.listItemData i").removeClass("fas fa-redo");
            $(".loadingList_validatingTransactionId p.listItemData i").addClass("spinner-border");
            
            let responseData=postDataHttpRequest('DashBoard/php/verifyAdvAmtTransactionIdInServer_fortNightAdvDetails.php', postContent);
                responseData.then((result)=>{
                    console.log(result);
                    if(result.message=="SUCCESS"){
                        this.verifyTansactionIds_And_EmpIds_InExcelJsonFromResponseJson(result);
                    }else{
                        this.changesOnErrorTransactionIdRequestWhileLoading();
                        console.log("failure request unsuccess");
                    }
                })
                .catch((error)=>{
                    console.log(error);
                    this.changesOnErrorTransactionIdRequestWhileLoading();
                });
        }
    }
    
    verifyTansactionIds_And_EmpIds_InExcelJsonFromResponseJson(responseJson){
        let duplicateTransactionIdsArray=responseJson.TransactionID_responseDataArray;
        let latestFortNightDetailsJson=responseJson.fnAdvanceAmountDetails_responseDataArray;
        TRANSACTION_IDS_ALREADY_EXIST_IN_SERVER_ARRAY=responseJson.TransactionID_responseDataArray;// UPDATING IN GLOBAL VARIABLE
        let invalidEmpIdArray=this.validateEmployeeIdsInExcelJsonWithResponseJson(latestFortNightDetailsJson);
        let dupTranAryLenght_or_dupTrnsIdInExcelJsonCnt= this.checkDupTransnJsonResponseWithExcelJson_for_onlyTransnId_or_allTransnDetails_matching(duplicateTransactionIdsArray);
        if(invalidEmpIdArray.length === 0 && dupTranAryLenght_or_dupTrnsIdInExcelJsonCnt ===0){// if no invalid Empids and no duplicateTrsnIds in server
            this.changesOnNoInvalidEmpIdsAndDuplicateTransactionIdFoundWhileLoading();
            this.updateAdvanceAmountDetails();
        }
    }
    
    checkDupTransnJsonResponseWithExcelJson_for_onlyTransnId_or_allTransnDetails_matching(dupTranscAry){
        let collectTransactionDetailsAlReadyExistSameInServerArray=[];
        let returnValue;
        if(dupTranscAry.length > 0){
            let onlyDupTransactnIdCnt=0;
            let noOfElementsToDeleteInAry=1;
         
            const checkTransactionIdInExcelJson =(DpTransLoopObj, DpTransLoopIndex)=>{
            let transactionId=DpTransLoopObj.TRANSACTION_ID;
                for(let excelJsonLoopIndex=0; excelJsonLoopIndex < EXPORTED_EXCEL_JSON.length; excelJsonLoopIndex++){
                    if(EXPORTED_EXCEL_JSON[excelJsonLoopIndex]["TRANSACTION-ID"] === transactionId){
                        if(this.objectCompare(EXPORTED_EXCEL_JSON[excelJsonLoopIndex],DpTransLoopObj)){ // in excel Entire row details exiting in server
                        console.log(" #TrId"+(excelJsonLoopIndex+1));
                            $("#empAdvanceExcelConvertedTable #"+(EXPORTED_EXCEL_JSON[excelJsonLoopIndex]["tableRowId"])).addClass('text-success font-weight-bold');
                            collectTransactionDetailsAlReadyExistSameInServerArray.push(DpTransLoopObj);                                       // Array for collecting all matched TransactionDetails
                            EXPORTED_EXCEL_JSON.splice(excelJsonLoopIndex,noOfElementsToDeleteInAry);                           //deleting currentIndex obj from excelJson to update only requiredTransaction details not already exit one.
                            
                        }else{ // only transaction equal 
                            $("#empAdvanceExcelConvertedTable #TrId"+(excelJsonLoopIndex+1)).addClass('errorTableRow alreadyExitTransId');
                            $("#empAdvanceExcelConvertedTable #TrId"+(excelJsonLoopIndex+1)+" .transactionTd")
                                .append(`<p class="m-0 text-danger errorMsg">TransactionId already exist 
                                            <button class="btn btn-danger py-1 h-100 modalPopupBtn" data-index="${DpTransLoopIndex}" data-toggle="modal" data-target="#DuplicateTransactionIdsModalPopup">View</button>
                                        </p>`);
                            onlyDupTransactnIdCnt++;
                        }
                        break;// stop the loop becz only max one-transId match (unique transId) 
                    }
                }
            }
            // if transId exist in server
            for(let loopIndex=0; loopIndex < dupTranscAry.length; loopIndex++){
                checkTransactionIdInExcelJson(dupTranscAry[loopIndex],loopIndex);
            }
            
            
            if(onlyDupTransactnIdCnt > 0){
                 this.changesOnDuplicateTransactionIdFoundWhileLoading();
            }
            
            returnValue=onlyDupTransactnIdCnt;
        }else{
            returnValue=dupTranscAry.length;
        }
        
        TRANSACTION_DETAILS_ALREADY_EXIST_ARRAY=collectTransactionDetailsAlReadyExistSameInServerArray; //updating global Var
        return returnValue;
    }
    
    objectCompare(obj1, obj2){
        return obj1["EMP ID"]=== obj2.EMP_ID &&
                this.convertToDateFormate(obj1["ADVANCE RELEASED DATE (YYYY-MM-DD)"])=== this.convertToDateFormate(obj2.ADVANCE_RELEASE_DATE) &&
                obj1["ADVANCE AMOUNT"]==obj2.ADVANCE && 
                obj1["TRANSACTION-ID"]===obj2.TRANSACTION_ID;
    }
    convertToDateFormate(date){
        return new Date(date).toLocaleDateString('en-CA');
    }
    
    validateEmployeeIdsInExcelJsonWithResponseJson(fnJsonArray){
        let employsNotHaveFortNight={};
        FN_RESPONSE_MAP =new Map(); // global varable in assigned in contructor
        for(let indexLoop=0; indexLoop< fnJsonArray.length; indexLoop++){
            FN_RESPONSE_MAP.set(fnJsonArray[indexLoop].EMP_ID, fnJsonArray[indexLoop].EMP_NAME);
            FN_RESPONSE_MAP.set(fnJsonArray[indexLoop].EMP_ID+"_"+fnJsonArray[indexLoop].FORTNIGHT, fnJsonArray[indexLoop]);
            $(".trEmpId"+fnJsonArray[indexLoop].EMP_ID+" .tdEmpName").text(fnJsonArray[indexLoop].EMP_NAME);
        }
        const returnInvalidEmployeeIdsArray=()=>{
            let empIdArray=[];
            const checkEmpIdValidOrNot =(crntLoopObj)=>{
                if(!FN_RESPONSE_MAP.has(crntLoopObj["EMP ID"])){
                    empIdArray.push(crntLoopObj["EMP ID"]);                     // if the empid not exist in response fnJson ie: invalid empId
                }else{      // valid empIds
                    if(!FN_RESPONSE_MAP.has(crntLoopObj["EMP ID"]+"_"+crntLoopObj["FORTNIGHT"])){                      // if the empid_fortnight not exist in response fnJson ie: employee not have Fortnight
                       employsNotHaveFortNight[crntLoopObj["EMP ID"]]=this.getDetailsToCreateFortNightForEmployee(crntLoopObj); // appending to assoicate array if single employee multiple times will overrides
                    }
                }
            }
            for(let indexLoop=0;indexLoop<EXPORTED_EXCEL_JSON.length;indexLoop++){
                checkEmpIdValidOrNot(EXPORTED_EXCEL_JSON[indexLoop]);
            }
            return empIdArray;
        } 
        let invalidEmpIdArray=returnInvalidEmployeeIdsArray();
            if(invalidEmpIdArray.length>0){
                this.changesOnInvalidEmpIdsFoundWhileLoading();
                $.each(invalidEmpIdArray, function(index, invalidEmpId){
                $(".trEmpId"+invalidEmpId).addClass("errorTableRow invalidEmpId");
                $(".trEmpId"+invalidEmpId+" .empIdTd").append(`<p class="mb-0 text-danger errorMsg">Invalid EmpId</p>`);
                });
            } 
            
            EMPLOYS_NOT_HAVE_FORTNIGHT=Object.values(employsNotHaveFortNight); //assigning to global varables
            return invalidEmpIdArray;
    }
 
    getDetailsToCreateFortNightForEmployee(crntLoopObj){
        let empIdValue=crntLoopObj["EMP ID"];
        let empNameValue=FN_RESPONSE_MAP.get(empIdValue);
        let fortnightValue=crntLoopObj["FORTNIGHT"];
        let fromDateValue;
        let toDateValue;
        
        let dateArray=fortnightValue.split("-");// 2022-January-2nd FN;
        let year=dateArray[0];                  //2022
        let month=this.getMonthInNumber(dateArray[1]);  //January
        let fnType=dateArray[2];                //2nd FN
            // console.log("fnType",fnType);
        if(fnType=="1st FN"){
            fromDateValue=year+"-"+month+"-"+"01";
            toDateValue=year+"-"+month+"-"+"15";
            // console.log("fromDateValue",fromDateValue,"toDateValue",toDateValue);
        }else if(fnType=="2nd FN"){
            fromDateValue=year+"-"+month+"-"+"16";
            toDateValue=this.getLastDateOfThisMonth(year,month);
        }
        let obj={
            empId:empIdValue,
            empName:empNameValue,
            fortnight:fortnightValue,
            fromDate:fromDateValue,
            toDate:toDateValue,
            
        };
        
        return obj;
    }
    
    getLastDateOfThisMonth(year, month){
        return  new Date(year, month, 0).toLocaleDateString('en-CA');
    }
    getMonthInNumber(monthName){
        return new Date(Date.parse(monthName+" 1, 2022")).getMonth()+1;
    }
    
// ---------------------ui changes functions--------------------------------------------
    changesOnInvalidTemplateErrorWhileLoading(){
        $(".loadingList_validatingExcelTemplate p.listItemData").removeClass("text-success");// if exist
        $(".loadingList_validatingExcelTemplate p.listItemData i").addClass('fas fa-times text-danger');
        $(".loadingList_validatingExcelTemplate .error").show();
        $("#empAdvanceAmntDetailsErrorConsole div.section").addClass("errorDivBg");
        
    }
    changesOnValidTemplateWhileLoading(){
         $(".loadingList_validatingExcelTemplate p.listItemData").addClass("text-success");
         $(".loadingList_validatingExcelTemplate p.listItemData i").removeClass('fas fa-times text-danger');
        $(".loadingList_validatingExcelTemplate p.listItemData i").addClass('fas fa-check');
        $(".loadingList_validatingExcelTemplate .error").hide();
        $(".loadingList_validatingTransactionId p.listItemData").addClass('onloading');
        $(".loadingList_validatingTransactionId p.listItemData i").removeClass("fa-check fa-times text-danger");
        $("#empAdvanceAmntDetailsErrorConsole div.section").removeClass("errorDivBg highLight");
    }
    
    changesOnDuplicateTransactionIdFoundWhileLoading(){
        $(".loadingList_validatingTransactionId p.listItemData").removeClass("text-success");// if already got success on previous template
        $(".loadingList_validatingTransactionId p.listItemData i").addClass('fas fa-times text-danger');
        $(".loadingList_validatingTransactionId p.listItemData i").removeClass("spinner-border");
        $(".loadingList_validatingTransactionId .error.duplicateTransactionId").show();
    }
    changesOnNoInvalidEmpIdsAndDuplicateTransactionIdFoundWhileLoading(){
        $(".loadingList_validatingTransactionId p.listItemData").addClass("text-success");// if already got success on previous template
        $(".loadingList_validatingTransactionId p.listItemData i").removeClass('fas fa-times text-danger spinner-border');
        $(".loadingList_validatingTransactionId p.listItemData i").addClass("fas fa-check");
        $(".loadingList_validatingTransactionId .error").hide();
        $(".loadingList_updatingAdvAmtDetails p.listItemData").addClass("onloading");
        $(".loadingList_updatingAdvAmtDetails .uploadingRecordsDetails_li").show();
        $(".loadingList_updatingAdvAmtDetails .uploadingRecordsDetails_li").addClass("onloading");
    }
    changesOnErrorTransactionIdRequestWhileLoading(){
            $("#loaderMainSection .loaderDiv .retryBtn").addClass("d-flex");
            $('#loaderMainSection .loaderDiv .retryBtn').attr('data-retry-at','varifyDuplicateTransactionIdsRequest');
            $(".loadingList_validatingTransactionId p.listItemData i").addClass("fas fa-redo text-danger");
            $(".loadingList_validatingTransactionId p.listItemData i").removeClass("spinner-border fa-times");
            $(".loadingList_validatingTransactionId .error").hide();
    }
    changesOnErrorInsertFnAndAdvncRequestWhileLoading(){
            $("#loaderMainSection .loaderDiv .retryBtn").addClass("d-flex");
            $('#loaderMainSection .loaderDiv .retryBtn').attr('data-retry-at','insertFnAdvanceAmtRequest');
            $(".loadingList_updatingAdvAmtDetails p.listItemData i").addClass("fas fa-redo text-danger");
            $(".loadingList_updatingAdvAmtDetails p.listItemData i").removeClass("spinner-border fa-times");
            $(".loadingList_updatingAdvAmtDetails .error").hide();
    }
    changesOnSuccessfullyInsertFnAndAdvncRequestWhileLoading(){
            $(".loadingList_updatingAdvAmtDetails p.listItemData").addClass("text-success");
            $(".loadingList_updatingAdvAmtDetails p.listItemData i").addClass("fas fa-check");
            $(".loadingList_updatingAdvAmtDetails p.listItemData i").removeClass("spinner-border fa-times text-danger");
            $("#loaderMainSection .resultMessage").html('<h1 class="text-success m-0"><i class="fas fa-check"></i></h1><p class="text-success m-0">Succesfully submited</p>');
    }
    changesOnErrorRecordsAlreadyExistWhileLoading(){
            $(".loadingList_updatingAdvAmtDetails p.listItemData i").addClass("fas fa-times text-danger");
            $(".loadingList_updatingAdvAmtDetails p.listItemData i").removeClass("spinner-border fa-check");
            $("#loaderMainSection .resultMessage").html('<h6 class="text-success">The exported template records already exist</h6>');
    }
    changesOnInvalidEmpIdsFoundWhileLoading(){
        $(".loadingList_validatingTransactionId p.listItemData").removeClass("text-success");// if already got success on previous template
        $(".loadingList_validatingTransactionId p.listItemData i").addClass('fas fa-times text-danger');
        $(".loadingList_validatingTransactionId p.listItemData i").removeClass("spinner-border");
        $(".loadingList_validatingTransactionId .error.invalidEmpId").show();
    }
    // -------------------------------end-----------------------------------------------------
    
    
    
    
    // ------------------------submit Fortnight advance Amount  details of Employee------------------
    updateAdvanceAmountDetails(){
        let transAlrdyExstLngth=TRANSACTION_DETAILS_ALREADY_EXIST_ARRAY.length;
        $("#loaderMainSection .loaderDiv .exitingRecords").text(transAlrdyExstLngth);
        $("#loaderMainSection .uploadingRecordsDetails_li .submitedRecords").text(0);
        if(transAlrdyExstLngth>0){
            $("#loaderMainSection .loaderDiv .exitingRecordsBtn").show();
        }else{
            $("#loaderMainSection .loaderDiv .exitingRecordsBtn").hide();
        }
//   console.log("EMPLOYS_NOT_HAVE_FORTNIGHT",EMPLOYS_NOT_HAVE_FORTNIGHT);
//   console.log("EXPORTED_EXCEL_JSON",EXPORTED_EXCEL_JSON);
 
    let obj={
        InsertFn:EMPLOYS_NOT_HAVE_FORTNIGHT,
        advanceAmntDetails:EXPORTED_EXCEL_JSON
    }
    console.log(obj);
    let postContent=JSON.stringify(obj);
    
        if(EXPORTED_EXCEL_JSON.length>0){
            this.request_insertFnForEmployeesWhoDntHave_andInsertAdncDetails(postContent);
        }else{
            this.changesOnErrorRecordsAlreadyExistWhileLoading();
        }
    }
    
    
    request_insertFnForEmployeesWhoDntHave_andInsertAdncDetails(postContent){
        // console.log(postContent);
        if(!checkWheatherLogoutOrNot_InternetConnection()){
            alertNoInternet_connection();
            this.changesOnErrorInsertFnAndAdvncRequestWhileLoading();
        }else{
            let responseData=postDataHttpRequest('DashBoard/php/InserFortNightAdvanceAmountDetails.php',postContent);
            responseData.then((result)=>{
                console.log(result);
                if(result.message="SUCCESS"){
                    $("#loaderMainSection .uploadingRecordsDetails_li .submitedRecords").text(EXPORTED_EXCEL_JSON.length);
                    this.changesOnSuccessfullyInsertFnAndAdvncRequestWhileLoading();
                }else{
                    this.changesOnErrorInsertFnAndAdvncRequestWhileLoading();
                }
            })
            .catch((error)=>{
                console.log(error);
                this.changesOnErrorInsertFnAndAdvncRequestWhileLoading();
            })
            
            
        }
    }
    
    
    //--------------------------end-------------------------------------------------
    
    
    //------------------------------------------common function----------------------------------
    getCurrentSelectedFn(){
            let yearValue=$("#formRequest_employeeAdvanceInfo .year").val();
            let monthValue=$("#formRequest_employeeAdvanceInfo .month").val();
            let FnType=$("#formRequest_employeeAdvanceInfo .fn").val();
        return `${yearValue}-${monthValue}-${FnType}`;
    }
    //--------------------------------------------end------------------------------------------

}


// ;;