var PENDING_INVOICE_ERROR_BUCKET_ARRAY;
class pendingInvoiceTable{
    getDynamicPendingInvoiceTable(excelJson){
        PENDING_INVOICE_ERROR_BUCKET_ARRAY=[];// on every time on creating obj of this class mkng array empty.
        let tableBodyUI='';
        let initialiseArrayValue=()=>{
            this.errorArray=[];
            this.errorArray["requiredFieldMissingCount"]=0;
            this.errorArray["invalidPONumber"]="NoErrorFound";
            this.errorArray["invalidReportDate"]="NoErrorFound";
            this.errorArray["reportRemarkExceedMaxLimit"]="NoErrorFound";
            this.errorArray["paymentRemarkExceedMaxLimit"]="NoErrorFound";
            this.errorArray["invalidInvoiceDate"]="NoErrorFound";
            this.errorArray["invalidInvoiceNo"]="NoErrorFound";
            this.errorArray["invalidInvoiceValue"]="NoErrorFound";
            this.errorArray["invalidPaymentDate"]="NoErrorFound";
            this.errorArray["invalidPaymentValue"]="NoErrorFound";
            this.errorArray["duplicateEntries"]="NoErrorFound";
            this.errorArray["invalidEntries"]="NoErrorFound";
        };
        let getInvoiceNameClass=(invoiceNumber)=>{
            invoiceNumber = (isNaN(invoiceNumber) ? (invoiceNumber).toUpperCase() : invoiceNumber); // if not a number convert to uppercase
            let className = invoiceNumber ? convertToClassNameFormate("invoiceNo_"+invoiceNumber+"_tr") : '';
            return className
        }
        // excelJson.forEach((val,index)=>{
        for(let index=0;index<excelJson.length; index++){
            initialiseArrayValue();
            let currentLoopVal=excelJson[index];
            let nextLoopVal=excelJson[index+1];
            let lastLoopIndex=excelJson.length-1;
            let uniqueId=convertToClassNameFormate(currentLoopVal['SiteId']+"_"+currentLoopVal['EmpId']+"_"+currentLoopVal['SiteVisit Date']);// in invoices_report .js
            let duplicateKeyword='';
            let inLineStyle='';
            this.checkDuplicateEntries(currentLoopVal, nextLoopVal,index, lastLoopIndex);
            this.checkInvalidEntries(currentLoopVal,uniqueId);
            if(currentLoopVal.duplicate){
                this.errorArray["duplicateEntries"]="Error";
                duplicateKeyword=`<span class="font-weight-bold text-danger d-block">Duplicate</span>`;
                inLineStyle=`style="background-color:var(--errorBgTableRow)"`;
            }
            if(currentLoopVal.invalidEntry){
                this.errorArray["invalidEntries"]="Error";
                duplicateKeyword=`<span class="font-weight-bold text-danger d-block" data-toggle="Abbrevation_tooltip" title="This details not present in downloaded excel">Invalid Entry</span>`;
                inLineStyle=`style="background-color:var(--errorBgTableRow)"`;
            }
            tableBodyUI+=`<tr class="${uniqueId} ${getInvoiceNameClass(currentLoopVal['InVoiceNo'])}" ${inLineStyle}>
                          <td>${index+1}</td>
                          <td>${currentLoopVal.SiteId}${duplicateKeyword}</td>
                          <td>${currentLoopVal.Project}</td>
                          <td>${currentLoopVal['StageOf Audit']}</td>
                          <td>${currentLoopVal['SiteVisit Date']}</td>
                          <td>${currentLoopVal.EmpId}</td>
                          <td>${currentLoopVal.EmpName}</td>
                          <td>${currentLoopVal['TL Id']}</td>
                          <td>${currentLoopVal['TL Name']}</td>
                          ${this.getValidPONumberTd(currentLoopVal.PONo, index)}
                          ${this.getReportSubmittedDateTd(currentLoopVal['Report Date(yyyy-mm-dd)'], currentLoopVal, index)}
                          ${this.getReportRemarksTd(currentLoopVal['Report Remarks'], index)}
                          ${this.getInvoiceRaisedDateTd(currentLoopVal['Invoice Date(yyyy-mm-dd)'], currentLoopVal, index)}
                          ${this.getInvoiceNumberTd(currentLoopVal['InVoiceNo'], currentLoopVal, index)}
                          ${this.getInvoiceValueTd(currentLoopVal['Invoice Value'], index)}
                          ${this.getPaymentDateTd(currentLoopVal['Payment Date(yyyy-mm-dd)'], currentLoopVal['Payment Value'], currentLoopVal, index)}
                          ${this.getPayentValueTd(currentLoopVal['Payment Value'], currentLoopVal, index)}
                          ${this.getPaymentRemarksTd(currentLoopVal['Payment Remarks'], index)}
                          ${this.getRemainingBalanceTd(Number(currentLoopVal['Invoice Value']), Number(currentLoopVal['Payment Value']), currentLoopVal, index)}
                          <td class="updateInvoiceBtn_Td">--</td>
                        </tr>`;
            PENDING_INVOICE_ERROR_BUCKET_ARRAY.push(this.errorArray);
        }
        // console.log("form pendingVoice.js");
        return tableBodyUI;    
    }
    getValidPONumberTd(poNo, currentLoopIndex){
        let poInputTag;
        if(poNo){
            if(!checkInvalidFormate(poNo)){                                  // return true if invalid, function In invoices_reports.js
                poInputTag=`<input type="text" value="${poNo}" class="form-control" readonly/>`;
            }else{
                this.errorArray["invalidPONumber"]="Error";
                poInputTag=`<input type="text" value="${poNo}" class="form-control border-danger" readonly/><span class="errorMsg invalidPONumber text-danger font-weight-bold">Required</span>`;
            }
        }else{ 
            this.errorArray["requiredFieldMissingCount"]++;
            poInputTag=`<input type="text" value="Not Available" class="form-control border-danger" error="true" readonly /><span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`;
        }
        return `<td class="poNo_Td" data-index="${currentLoopIndex}">${poInputTag}</td>`;
    }
    
    getReportSubmittedDateTd(reportDate, currentLoopJsonData, currentLoopIndex){
        let reportDateInputTag;
        if(reportDate){
            let returnVal=validateDateFormate(reportDate);                  //function In invoices_reports.js
            if(returnVal['validDate']){
                currentLoopJsonData['Report Date(yyyy-mm-dd)']=returnVal['dateValue']; // update json value after correcting
                reportDateInputTag=`<input type="date" value="${returnVal['dateValue']}" class="form-control"  min="2015-01-01"  error="false" readonly />`;
            }else{
                this.errorArray["invalidReportDate"]="Error";
                reportDateInputTag=`<input type="date"  class="form-control border-danger"  min="2015-01-01"  error="false" readonly/><span class="errorMsg invalidReportDate text-danger font-weight-bold">Invalid Date(${reportDate})</span>`;
            }
        }else{
            this.errorArray["requiredFieldMissingCount"]++;
            reportDateInputTag=`<input type="date" class="form-control border-danger"  min="2015-01-01"  error="true" readonly/><span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`;
        }
        return `<td class="reportSubmittedDate_Td" data-index="${currentLoopIndex}">${reportDateInputTag}</td>`;
    }
    
    getReportRemarksTd(reportRemarks, currentLoopIndex){
        let reportRemarkTextAreaTag;
        if(reportRemarks){
            if(reportRemarks.length<=300){
                reportRemarkTextAreaTag=`<textarea class="form-control" maxlength="300" readonly>${reportRemarks}</textarea>`;
            }else{
                this.errorArray["reportRemarkExceedMaxLimit"]="Error";
                reportRemarkTextAreaTag=`<textarea class="form-control  border-danger" maxlength="300" readonly>${reportRemarks}</textarea><span class="errorMsg reportRemarkExceedMaxLimit text-danger font-weight-bold">Max Limit 300</span>`;
            }
        }else{
            reportRemarkTextAreaTag=`<textarea class="form-control " maxlength="300" readonly></textarea>`;
        }
        return `<td class="reportRemarks_Td" data-index="${currentLoopIndex}">${reportRemarkTextAreaTag}</td>`;
    }
    
    getInvoiceRaisedDateTd(invoiceDate, currentLoopJsonData, currentLoopIndex){
        let invoiceDateInputTag;
        if(invoiceDate){
            let returnVal=validateDateFormate(invoiceDate);                     //function In invoices_reports.js
                if(returnVal['validDate']){
                    currentLoopJsonData['Invoice Date(yyyy-mm-dd)']=returnVal['dateValue'];
                    invoiceDateInputTag=`<input type="date" class="form-control" value="${returnVal['dateValue']}" error="false" min="2015-01-01" />`;
                }else{
                    this.errorArray["invalidInvoiceDate"]="Error";
                    invoiceDateInputTag=`<input type="date" class="form-control border-danger" error="false" min="2015-01-01" /><span class="errorMsg invalidInvoiceDate text-danger">Invalid Date(${invoiceDate})</span>`;
                }
        }else{
            this.errorArray["requiredFieldMissingCount"]++;
            invoiceDateInputTag=`<input type="date" class="form-control border-danger" error="true" min="2015-01-01" /><span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`;
        }
        return `<td class="invoiceDate_Td" data-index="${currentLoopIndex}">${invoiceDateInputTag}</td>`;
    }
    
    getInvoiceNumberTd(invoiceNo, currentLoopJsonData, currentLoopIndex){
        let invoiceNoInputTag;
        if(invoiceNo){
            if(!checkInvalidFormate(invoiceNo)){ // return true if invalid , function In invoices_reports.js
                let invoiceNumber = (isNaN(invoiceNo) ?  invoiceNo.toUpperCase() : invoiceNo);
                invoiceNumber=invoiceNumber.replaceAll(' ','_');
                currentLoopJsonData["InVoiceNo"]=invoiceNumber;// update json
                invoiceNoInputTag=`<input type="text" class="form-control" value="${invoiceNumber}" error="false"/>`;
            }else{
                this.errorArray["invalidInvoiceNo"]="Error";
                invoiceNoInputTag=`<input type="text" class="form-control border-danger" value="${invoiceNo}" error="false"/><span class="errorMsg invalidInvoiceNo text-danger font-weight-bold">Required</span>`;
            }
        }else{
            this.errorArray["requiredFieldMissingCount"]++;
            invoiceNoInputTag=`<input type="text" class="form-control border-danger" error="true"/><span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`;
        }
        return `<td class="invoiceNo_Td" data-index="${currentLoopIndex}">${invoiceNoInputTag}</td>`;
    }
    
    getInvoiceValueTd(invoiceValue, currentLoopIndex){
        let invoiceValueInputTag;
        if(invoiceValue && invoiceValue!=0){
            if(!isNaN(invoiceValue)){ // is number
                invoiceValueInputTag=`<input type="number" value="${invoiceValue}" class="form-control" error="false"/>`;
            }else{
                this.errorArray["invalidInvoiceValue"]="Error";
                invoiceValueInputTag=`<input type="number"  class="form-control border-danger" error="false"/><span class="errorMsg invalidInvoiceValue text-danger font-weight-bold">Invalid Value(${invoiceValue})</span>`;
            }
            
        }else{
            this.errorArray["requiredFieldMissingCount"]++;
            invoiceValueInputTag=`<input type="number"  class="form-control border-danger" error="true"/><span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`;
        }
        return `<td class="invoiceValue_Td" data-index="${currentLoopIndex}">${invoiceValueInputTag}</td>`;    
    }
    
    getPaymentDateTd(paymentDate, paymentValue, currentJsonData, currentLoopIndex){
        console.log("paymentDate",paymentDate);
        let paymentDateInputTag;
        if(!isNaN(paymentValue) && paymentValue!=0){ // if payemnt value is number & not =0;    ie: if paymnt-value their then paymnt-date required
            if(paymentDate){
                let returnVal=validateDateFormate(paymentDate);                 //function In invoices_reports.js
                if(returnVal['validDate']){
                    paymentDateInputTag=`<input type="date" value="${returnVal['dateValue']}"  class="form-control" error="false"/>`;
                    currentJsonData['Payment Date(yyyy-mm-dd)']=returnVal['dateValue'];
                }else{
                    this.errorArray["invalidPaymentDate"]="Error";;
                    paymentDateInputTag=`<input type="date"  class="form-control border-danger"  error="false"/><span class="errorMsg invalidPaymentDate text-danger font-weight-bold">Invalid Date(${paymentDate})</span>`;
                }
            }else{
                this.errorArray["requiredFieldMissingCount"]++;
                paymentDateInputTag=`<input type="date" class="form-control border-danger" error="true"/><span class="errorMsg requiredFieldMissingCount text-danger font-weight-bold">Required</span>`;
            }    
        }else{
            paymentDateInputTag=`<input type="date" class="form-control" error="false"/>`;
            currentJsonData['Payment Date(yyyy-mm-dd)']='0000-00-00';
        }
        return `<td class="paymentDate_Td" data-index="${currentLoopIndex}">${paymentDateInputTag}</td>`;
    }
    
    getPayentValueTd(paymentValue, currentJsonData, currentLoopIndex){
        let paymentValueInputTag;
        if(paymentValue && paymentValue!="null"){
            if(!isNaN(paymentValue) && paymentValue>=0){// in number formate
                paymentValueInputTag=`<input type="number" class="form-control" value="${paymentValue}"/>`;
            }else{
                this.errorArray["invalidPaymentValue"]="Error";
                paymentValueInputTag=`<input type="number" class="form-control border-danger" /><span class="errorMsg invalidPaymentValue text-danger font-weight-bold">Invalid Data(${paymentValue})</span>`
            }
        }else{
            paymentValueInputTag=`<input type="number" class="form-control" value="0"/>`;
            currentJsonData['Payment Value']="0";
        }
        return `<td class="paymentValue_Td" data-index="${currentLoopIndex}">${paymentValueInputTag}</td>`; 
    }
    
    getPaymentRemarksTd(paymentRemarks, currentLoopIndex){
        let paymentRemarksTextareaTag;
        if(paymentRemarks){
            if(paymentRemarks.length <=300){
                paymentRemarksTextareaTag=`<textarea class="form-control" placeholder="Enter Payment Remarks" maxlength="300">${paymentRemarks}</textarea>`;
            }else{
                this.errorArray["paymentRemarkExceedMaxLimit"]="Error"
                paymentRemarksTextareaTag=`<textarea class="form-control border-danger" placeholder="Enter Payment Remarks" maxlength="300">${paymentRemarks}</textarea><span class="errorMsg paymentRemarkExceedMaxLimit text-danger font-weight-bold">Max Limit 300</span>`;
            }
        }else{
            paymentRemarksTextareaTag=`<textarea class="form-control" placeholder="Enter Payment Remarks" maxlength="300"></textarea>`;
        }
        return `<td class="paymentRemarks_Td" data-index="${currentLoopIndex}">${paymentRemarksTextareaTag}</td>`;
    }
    
    getRemainingBalanceTd(invoiceValue, paymentValue, currentJsonData, currentLoopIndex){
        let updatedInvoiceValue=(invoiceValue)? invoiceValue:0;
        let updatedPaymentValue=(paymentValue)? paymentValue:0;
        let balanceAmount=updatedInvoiceValue-updatedPaymentValue;
        currentJsonData['Balance']=balanceAmount;
        return `<td class="remainingBalance_Td" data-index="${currentLoopIndex}"><input type="number" class="form-control" value="${balanceAmount}" readonly/></td>`;
    }
    checkDuplicateEntries(currentLoopObj, nextLoopObj, currentLoopIndex, lastLoopIndex){
        let keys=["SiteId","EmpId", "SiteVisit Date"]
        let checkCurrentLoopDuplicateEntries=()=>{
            for(let i=0;i<keys.length; i++){
                let keyValue=keys[i];
                // console.log("currentLoopObj[keyValue]",currentLoopObj[keyValue]);
                // console.log("nextLoopObj[keyValue]", nextLoopObj[keyValue]);
                if(currentLoopObj[keyValue]!=nextLoopObj[keyValue]){
                    return false;
                }
            }
            return true;
        }
        if(currentLoopIndex!=lastLoopIndex){
            if(checkCurrentLoopDuplicateEntries()){
            currentLoopObj.duplicate=true;
            nextLoopObj.duplicate=true;
            }
        }
    }
    checkInvalidEntries(currentLoopVal,uniqueId){
        let objExist=PENDING_INVOICES_REPORTS_RESPONSE_JSON_IN_OBJECT[uniqueId] // in invoices_report.js
        if(!objExist){
            currentLoopVal.invalidEntry=true;
        }
    }
    
    
}




// ;;