
 //////////////////////////////////////////////////-----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;
}