import { vacationTypeResponse } from './../model/vacationType.Respond';
import { notificationTypeResponse } from './../model/notification.Respond';
import { VacationTypeRequest } from './../model/VacationTypeRequest';
import { Component, OnInit, ElementRef } from '@angular/core';
import { VacationRuleServiceService } from '../service/vacation-rule-service.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { notificationTypeRequest } from '../model/notification.Request';
import * as moment from 'moment';
import { vacationRuleResponse } from '../model/vacationRule.Respond';
import { LoginRequest } from 'src/app/hmg-common/services/authentication/models/login.request';
import { ReplacementServiceRequest } from '../model/replacement-Service.request';
import { NumberInput } from 'src/app/uI-elements/number.input';
import { DateInput } from 'src/app/uI-elements/date.input';
import { SelectInput } from 'src/app/uI-elements/select.input';
import { TextInput } from 'src/app/uI-elements/text.input';
import { ModalController } from '@ionic/angular';
import { ReplacementListComponent } from '../replacement-list/replacement-list.component';
import { createVacationRequest } from '../model/createVacation.Request';
import { WorkListReplacementRollComponent } from 'src/app/notification/work-list-replacement-roll/work-list-replacement-roll.component';

@Component({
  selector: 'app-vacation-type',
  templateUrl: './vacation-type.component.html',
  styleUrls: ['./vacation-type.component.scss'],
})
export class VacationTypeComponent implements OnInit {
  ruleTypeList: any;
  index: any;
  vactionRuleSelected:any =-1;
  notificationTypeSelected: number;
  notification_list: any; ////
  notificationTypeShow:boolean=false;
  notificationSelected: any;
  createVacationRuleShow: boolean=false;
  createBtn: boolean;
  Sdate: any;
  isUpdate: any;
  SelAction: any;
  updateData: any;
  notificationType: { NOTIFICATION_NAME: any; NOTIFICATION_DISPLAY_NAME: any; NOTIFICATION_SUBJECT: any; FYI_FLAG: any; };
  P_ITEM_TYPE_TITLE: any;
  selEmployeeID: any;
  selEmployeeName: any;
  employeeSel: any;
  msgVal: any;
  notifTypeSel: any;
  itemType: any;
  Edate: string;
  Notification_Title: any;
  showForType_Y: boolean;
  isDeliver: boolean;
  REASSIGN_val: any =[];
  var_notification: any;
  exampleJsonObject: {};
  RespondAttributeList: any=[];
  GetRespondAttributeValueList: any;
  wFLookUpList: any;
  Resp2_val: any;
  dateInput: DateInput;
  numberInput: NumberInput;
  selectInput: any;
  textInput: TextInput;
  hideForwordEmployee: any;
  notifTypeSelP2: string;
  P_RESPOND_ATTRIBUTES_TBL: any=[];
  vacationRuleRequest: createVacationRequest;
  confirmMsg: string;
  direction: string;

  constructor(public vacationRuleService: VacationRuleServiceService,
    public ts: TranslatorService,
    public cs: CommonService,
    public modalController: ModalController,
    private elementRef: ElementRef) {
      this.direction = TranslatorService.getCurrentLanguageName();
   }

  ngOnInit() {
    this.isUpdate = this.cs.sharedService.getSharedData('isUpdate');
    if (this.isUpdate) {
      this.initCreateVaction();

    }
    else{
      this.getVacationType();
    }
  }

  initCreateVaction(){
    this.Sdate = moment().format('YYYY-MM-DDTHH:mm:ssZ');
    this.Edate="";

    // this.isUpdate = this.cs.sharedService.getSharedData('isUpdate');

    if (this.isUpdate) {
      this.updateData = this.cs.sharedService.getSharedData(vacationRuleResponse.SHARED_DATA, false);
      this.SelAction = this.updateData.ACTION;
      if (this.updateData.ACTION == "RESPOND" && this.updateData.FYI_FLAG == "Y") {
        this.SelAction = "Close"
      }
      this.notificationType = {
        NOTIFICATION_NAME: this.updateData.NOTIFICATION_NAME,
        NOTIFICATION_DISPLAY_NAME: this.updateData.NOTIFICATION_SUBJECT,
        NOTIFICATION_SUBJECT: this.updateData.NOTIFICATION_SUBJECT,
        FYI_FLAG: this.updateData.FYI_FLAG
      }
      /*************** */
      this.P_ITEM_TYPE_TITLE = this.updateData.ITEM_TYPE_DISPLAY_NAME;
      this.selEmployeeID = this.updateData.REPLACEMENT_USER_NAME;
      if (this.selEmployeeID) {
        this.selEmployeeName = this.updateData.RULE_NAME;
        this.employeeSel = this.updateData.RULE_NAME;
      }
      /************ */
      this.msgVal = this.updateData.MESSAGE;
      this.notifTypeSel = this.updateData.ACTION;
      this.itemType = this.updateData;
      this.notificationType = this.updateData;
      //this.Sdate = this.updateData.BEGIN_DATE;
      //this.Edate = this.updateData.END_DATE;
      let _Sdate = this.updateData.BEGIN_DATE ? this.updateData.BEGIN_DATE : "";
      let _Edate = this.updateData.END_DATE ? this.updateData.END_DATE : "";
      //let tzoffset = moment().utcOffset(); //offset in milliseconds
      if (_Sdate) {
        this.Sdate = moment(_Sdate).format('YYYY-MM-DDTHH:mm:ssZ');
        //this.Sdate = (new Date(myStartTime - tzoffset)).toISOString().slice(0, -1);
        //this.startTime = this.Sdate;
      }
      if (_Edate) {
        this.Edate = moment(_Edate).format('YYYY-MM-DDTHH:mm:ssZ');
        //this.Edate = (new Date(myEndTime - tzoffset)).toISOString().slice(0, -1);
        // this.endTime = this.Edate;
      }

      //this.schemaNotific =this.updateData.RespondAttributeList;

      //this.notifTypeSel=this.REASSIGN_val[0].RADIO_BUTTON_LABEL;
      //console.log(this.notifTypeSel);
      // this.getNotificationReassign();
    } else {
      this.msgVal="";
      this.isUpdate = false;
      this.SelAction = "";
      this.employeeSel = "";
      this.itemType = this.cs.sharedService.getSharedData(vacationTypeResponse.SHARED_DATA, false);
      this.notificationType = this.cs.sharedService.getSharedData(notificationTypeResponse.SHARED_DATA, false);
    }
    this.Notification_Title = this.notificationType.NOTIFICATION_DISPLAY_NAME;
    this.P_ITEM_TYPE_TITLE = this.itemType.ITEM_TYPE_DISPLAY_NAME;
    console.log("showForType_Y");
    if (this.notificationType.FYI_FLAG == 'Y') {
      this.showForType_Y = true;
    } else {
      this.showForType_Y = false;
    }
    if (this.itemType.ITEM_TYPE == "*") {
      this.isDeliver = false;
    } else {
      this.isDeliver = true;
    }

    this.getNotificationReassign();
    this.respondAttributes();


  }
  vacationRuleSel(event){
    this.vactionRuleSelected=event.detail.value;
    if(this.notificationTypeShow){
      //this.notificationTypeShow = false  
       this.notificationTypeShow = false 
       this.notifTypeSelP2 = "*";
      //this.part3show = false
    }
    if (this.createVacationRuleShow){
      this.createVacationRuleShow = false 
      this.createBtn=false; 



     }

   
    

   console.log("event: "+ event.detail.value);
  }
  notificationSel(event){

    this.notificationSelected=event.detail.value;
    if(this.createVacationRuleShow){
      //this.notificationTypeShow = false  
       this.createVacationRuleShow = false
       this.createBtn=false; 
      //this.part3show = false
    }

    
    // 
    console.log("notificationSel event: "+ event.detail.value);

  }

  notificationTypeSel(event){
   // notifTypeSelP2
   this.notificationTypeSelected=event.detail.value;
   if(this.createVacationRuleShow){
    //this.notificationTypeShow = false  
     this.createVacationRuleShow = false
     this.createBtn=false; 
    //this.part3show = false
  }

  }

  getVacationType() {
    let request: VacationTypeRequest = new VacationTypeRequest();

    this.vacationRuleService.getVacationType(request, () => {
      this.getVacationType();
    }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      if (this.cs.validResponse(result)) {
        this.ruleTypeList = result.VrItemTypesList;
        console.log(this.ruleTypeList);
      } else {
        this.cs.presentAlert(result.ErrorEndUserMessage);
      }
    });
  }

  NextPage() {
    //notification_list
    
    if(this.vactionRuleSelected >= 0 ){
      //&& !this.notificationTypeShow && !this.notificationTypeShow){
      if(!this.notificationTypeShow){
    this.cs.sharedService.setSharedData(this.ruleTypeList[this.index], vacationTypeResponse.SHARED_DATA);

    if (this.ruleTypeList[this.index].ITEM_TYPE == "*") {
      let notificatioAtt: notificationTypeResponse = new notificationTypeResponse();
      notificatioAtt.FYI_FLAG = "";
      notificatioAtt.NOTIFICATION_DISPLAY_NAME = "All";
      notificatioAtt.NOTIFICATION_NAME = "*";
      notificatioAtt.NOTIFICATION_SUBJECT = "";
      this.cs.sharedService.setSharedData(notificatioAtt, notificationTypeResponse.SHARED_DATA);
           //part 3
      this.createVacationRuleShow = true
      this.createBtn=true; 
      //  if (this.notifTypeSelP2 == "*") {
      //   let notificatioAtt: notificationTypeResponse = new notificationTypeResponse();
      //   notificatioAtt.FYI_FLAG = "";
      //   notificatioAtt.NOTIFICATION_DISPLAY_NAME = "All";
      //   notificatioAtt.NOTIFICATION_NAME = "*";
      //   notificatioAtt.NOTIFICATION_SUBJECT = "";
      //   this.cs.sharedService.setSharedData(notificatioAtt, notificationTypeResponse.SHARED_DATA);
      // } else {
      //   this.cs.sharedService.setSharedData(this.notification_list[this.var_notification], notificationTypeResponse.SHARED_DATA);
      // }

      this.initCreateVaction();
    
      //this.cs.navigateForward('/vacation-rule/create-vacation-rule');

    } else {
            //part 2
      this.getNotificationType();

     // this.cs.navigateForward('/vacation-rule/notification-type');
    }

  }//end part not show
    else{
      // check if notifictype sele and part 3 not show
      //this.notificationSelected=event.detail.value;
    ///if(this.createVacationRuleShow
      if((this.notificationSelected >= 0 || this.notifTypeSelP2 == '*') && !this.createVacationRuleShow){
        //call part3
        this.createVacationRuleShow = false
        this.createBtn=false; 
        
  if (this.notifTypeSelP2 == "*") {
    let notificatioAtt: notificationTypeResponse = new notificationTypeResponse();
    notificatioAtt.FYI_FLAG = "";
    notificatioAtt.NOTIFICATION_DISPLAY_NAME = "All";
    notificatioAtt.NOTIFICATION_NAME = "*";
    notificatioAtt.NOTIFICATION_SUBJECT = "";
    this.cs.sharedService.setSharedData(notificatioAtt, notificationTypeResponse.SHARED_DATA);
  } else {
    this.cs.sharedService.setSharedData(this.notification_list[this.var_notification], notificationTypeResponse.SHARED_DATA);
  }

        this.initCreateVaction();       
      }

    }
  }
 
  
  else{
    let msg = this.ts.trPK('vacation-rule', 'fill-vacation-type');
    this.cs.presentAlert(msg);
  }

  }////////////////////////////////

  getNotificationType() {
    let request: notificationTypeRequest = new notificationTypeRequest();
    request.P_ITEM_TYPE = this.ruleTypeList[this.index].ITEM_TYPE; //;this.itemTypeObj.ITEM_TYPE;
    this.vacationRuleService.getNotificationType(request, () => {
      this.getNotificationType();
    }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      console.log(result);
      if (this.cs.validResponse(result)) {
        console.log(result.GetItemTypeNotificationsList);
        this.notification_list = result.GetItemTypeNotificationsList;
        //rest radio button of notifTypeSel (All , select) 
        this.notificationTypeShow=true;

      } else {
        this.cs.presentAlert(result.ErrorEndUserMessage);
      }
    });
  }

  getNotificationReassign() {
    let request: LoginRequest = new LoginRequest();

    this.vacationRuleService.notificationReassign(request, () => {
      this.getNotificationReassign();
    }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      console.log(result);
      if (this.cs.validResponse(result)) {
        console.log(result.GetNotificationReassignModeList);
        this.REASSIGN_val = result.GetNotificationReassignModeList;//[0].RADIO_BUTTON_ACTION;
        this.notifTypeSel = this.REASSIGN_val[0].RADIO_BUTTON_ACTION;
        this.reverseAction();
        this.createVacationRuleShow = true;
        this.createBtn=true; 
      } else {
        this.cs.presentAlert(result.ErrorEndUserMessage);
      }
    });
  }
  reverseAction() {
    if (this.updateData) {
      switch (this.SelAction) {
        case 'FORWARD': {
          this.notifTypeSel = "DELEGATE";
          break;
        }
        case 'RESPOND': {
          this.notifTypeSel = "RESPOND";
          break;
        }
        case 'CLOSE': {
          this.notifTypeSel = "CLOSE";
          break;
        }
        case 'NOOP': {
          this.notifTypeSel = "DELIVER";
          break;
        }
        case 'TRANSFER': {
          this.notifTypeSel = "TRANSFER";
          break;
        }
        default: {
          this.notifTypeSel = "";
          break;
        }
      }
    }
  }
/////////////////////////////////////
respondAttributes() {
  let request: notificationTypeRequest = new notificationTypeRequest();
  request.P_NOTIFICATION_NAME = this.notificationType.NOTIFICATION_NAME;
  request.P_ITEM_TYPE = this.itemType.ITEM_TYPE;
  // this.vacationRuleService.respondAttributes(
  //   request).
  //   subscribe((result: Response) => {
  //     this.handlerespondAttributesResult(result);
  //   });
  this.vacationRuleService.respondAttributes(request, () => {
    this.respondAttributes();
  }, this.ts.trPK('general', 'retry')).subscribe((result) => {
    this.handlerespondAttributesResult(result);
  });


}
handlerespondAttributesResult(result) {
  if (this.cs.validResponse(result)) {
    this.RespondAttributeList = result.RespondAttributesList;
    if (result.RespondRolesList != "" && result.RespondRolesList[0].ATTRIBUTE_NAME != null && result.RespondRolesList[0].ATTRIBUTE_NAME != undefined) {
      this.Resp2_val = result.RespondRolesList[0].ATTRIBUTE_NAME;
      this.hideForwordEmployee = result.RespondRolesList[0];
    }

    if (result.RespondAttributesList) {
      //this.schemaNotific = JSON.parse(result.P_Schema);
      ////////************************************** */
      this.createVacationDynamicFields(result.RespondAttributesList);
    }
    this.reverseAction();
    if (this.isUpdate) {
      this.fillResposeAtrributes(result.RespondAttributesList);
    }
    // ATTRIBUTE_DISPLAY_NAME: "Note"
    // ATTRIBUTE_FORMAT: "4000"
    // ATTRIBUTE_NAME: "WF_NOTE"
    // ATTRIBUTE_TYPE: "VARCHAR2"
  }
}

createVacationDynamicFields(RespondAttributesList) {
  console.log("createVacationDynamicFields");
  const containerId = 'CVDynamicFields';
  for (let i = 0; i < RespondAttributesList.length; i++) {
    if (RespondAttributesList[i].ATTRIBUTE_TYPE == "VARCHAR2") {
      console.log("1");

      this.textInput = new TextInput(RespondAttributesList[i].ATTRIBUTE_DISPLAY_NAME, RespondAttributesList[i].ATTRIBUTE_NAME, "", containerId, "", "", "", "");
    } else if (RespondAttributesList[i].ATTRIBUTE_TYPE == "LOOKUP") {
      console.log("2");
      //call create WF_LOOKUP
      //call there or when the got response from responsedAtt
      this.selectInput = new SelectInput(RespondAttributesList[i].ATTRIBUTE_DISPLAY_NAME, RespondAttributesList[i].ATTRIBUTE_NAME, "", containerId, "", "", "");
      this.getWFLookUp(RespondAttributesList[i].ATTRIBUTE_FORMAT, RespondAttributesList[i].ATTRIBUTE_NAME);

    } else if (RespondAttributesList[i].ATTRIBUTE_TYPE == "DATE") {
      console.log("3");

      this.dateInput = new DateInput(RespondAttributesList[i].ATTRIBUTE_DISPLAY_NAME, RespondAttributesList[i].ATTRIBUTE_NAME, "", containerId, "", "", "", this.direction);
    } else if (RespondAttributesList[i].ATTRIBUTE_TYPE == "NUMBER") {
      console.log("4");

      this.numberInput = new NumberInput(RespondAttributesList[i].ATTRIBUTE_DISPLAY_NAME, RespondAttributesList[i].ATTRIBUTE_NAME, "", containerId, "", "", "");
    }
  }
}

fillResposeAtrributes(respList) {
  let body = {
    P_RULE_ID: this.updateData.RULE_ID,
    GetRespondAttributeValueTBL: respList
  }
  this.vacationRuleService.getRespondAttributeValues(
    body).
    subscribe((result: Response) => {
      this.handleFillResponseAttr(result);
    });
}

handleFillResponseAttr(result) {
  if (this.cs.validResponse(result)) {
    if (result.GetRespondAttributeValueList && result.GetRespondAttributeValueList.length > 0) {
      this.GetRespondAttributeValueList=result.GetRespondAttributeValueList;
      let resp_val: any = result.GetRespondAttributeValueList[0].P_ATTRIBUTE_NAME;
      let Emp_ID: any = result.GetRespondAttributeValueList[0].P_ATTRIBUTE_TEXT_VALUE;
      let valueList = result.GetRespondAttributeValueList;
      var obj = {};
      if (resp_val == this.Resp2_val) {
        let request: ReplacementServiceRequest = new ReplacementServiceRequest();

        request.P_SEARCH_USER_NAME = Emp_ID;
        request.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
        request.P_SEARCH_EMAIL_ADDRESS = "";
        request.P_PAGE_NUM = 1;
        request.P_PAGE_LIMIT = 1000

        this.vacationRuleService.getReplacementList(request).
          subscribe((result: Response) => {
            this.handleFillRole(result);
          });
      }
      for (let i = 0; i < valueList.length; i++) {
        obj[valueList[i].P_ATTRIBUTE_NAME] = valueList[i].P_ATTRIBUTE_TEXT_VALUE;
      }
      this.exampleJsonObject = obj;
      //Call set value of  responsed attribute
     // this.createVacationDynamicFields(this.exampleJsonObject);//ashwaq
      this.setRespondAttributeValue();
      // this.exampleJsonObject = new Map(valueList.map(obj => [ obj., obj.P_ATTRIBUTE_TEXT_VALUE ]));
    }
  }
}
handleFillRole(result) {
  if (this.cs.validResponse(result)) {
    this.selEmployeeName = result.ReplacementList[0].EMPLOYEE_DISPLAY_NAME;
    this.selEmployeeID = result.ReplacementList[0].USER_NAME;
  }
}
setRespondAttributeValue(){

  for (let i = 0; i < this.RespondAttributeList.length; i++) {
   if(this.RespondAttributeList[i].ATTRIBUTE_NAME == this.GetRespondAttributeValueList[i].P_ATTRIBUTE_NAME){
    if (this.RespondAttributeList[i].ATTRIBUTE_TYPE == "VARCHAR2") {
      console.log("1");
      let x = (document.getElementById(this.RespondAttributeList[i].ATTRIBUTE_NAME)) as HTMLInputElement;
      x.value=this.GetRespondAttributeValueList[i].P_ATTRIBUTE_NUMBER_VALUE;
    } else if (this.RespondAttributeList[i].ATTRIBUTE_TYPE == "LOOKUP") {
      console.log("2");
      //call create WF_LOOKUPP_ATTRIBUTE_NAME
      //call there or when the got response from responsedAtt

    let x = (document.getElementById(this.RespondAttributeList[i].ATTRIBUTE_NAME)) as HTMLSelectElement;
    if(this.wFLookUpList){
    let index= this.wFLookUpList.findIndex(x => x.LOOKUP_CODE == this.GetRespondAttributeValueList[i].P_ATTRIBUTE_TEXT_VALUE);
    console.log("Hel: "+ index);
    x.options[index+1].selected=true;
    
    }

    } else if (this.RespondAttributeList[i].ATTRIBUTE_TYPE == "DATE") {
      console.log("3");

    } else if (this.RespondAttributeList[i].ATTRIBUTE_TYPE == "NUMBER") {
      console.log("4");
      let x = (document.getElementById(this.RespondAttributeList[i].ATTRIBUTE_NAME)) as HTMLInputElement;
      x.value=this.GetRespondAttributeValueList[i].P_ATTRIBUTE_NUMBER_VALUE;
     
    }
  }//end if
  }

}

getWFLookUp(resAttrFormat: any, ATTRIBUTE_NAME) {

  const request = {
    P_LOOKUP_TYPE: resAttrFormat,
  }

  this.vacationRuleService.getLookup(request, () => { }, this.ts.trPK('general', 'retry')).subscribe(
    (result: any) => {
      if (this.cs.validResponse(result)) {
        //   console.log("Lookup result "+ result);

        this.wFLookUpList=result.WFLookUpList
        this.fillDropdownList(result.WFLookUpList, ATTRIBUTE_NAME);
      } else {
        this.cs.presentAlert(result.ErrorEndUserMessage);
      }
    });

}

fillDropdownList(optionList: any = [],attributeID) {
  let elemID: any = attributeID;
  let eitObj: any;

  if (optionList.length > 0) {
    
    let select = document.getElementById(elemID) as HTMLSelectElement;
    document.getElementById(elemID).innerHTML = "";

 
    var firstoption = document.createElement("option");
    firstoption.text = this.ts.trPK("general", "choose");
    firstoption.value = "";
    select.add(firstoption);
    for (let i = 0; i < optionList.length; i++) {

      var option = document.createElement("option");
      option.text = optionList[i].LOOKUP_MEANING;
      option.value = optionList[i].LOOKUP_CODE;
      select.add(option);

    }
   
    select.disabled = false;
  }

}

async SearchReplacment() {
  const modal = await this.modalController.create({
    component: ReplacementListComponent
  });
  modal.cssClass = 'replaceRoll-modal';


  modal.onDidDismiss()
    .then((data) => {
      const user = data.data;
      console.log(data)
      console.log(user);
      if (data) {
        this.selEmployeeName = user.EMPLOYEE_DISPLAY_NAME;
        this.selEmployeeID = user.USER_NAME;
        this.employeeSel = this.selEmployeeName + "," + this.selEmployeeID
      }




    
    });

  return await modal.present();
}

clearEmployee() {
  this.selEmployeeName = "";
  this.selEmployeeID = "";
}

/////////////////////////////////////////////

ApplyFunc() {
  (this.elementRef.nativeElement.querySelectorAll('ion-item') as HTMLElement[]).forEach((x) => {
    if (x.classList.contains('requiredItem')) {
      x.classList.add('ng-touched');
      x.classList.remove('ng-untouched');
    }
  });
  let msg: string = "";
  if (this.notifTypeSel == undefined ) {
    msg = this.ts.trPK('vacation-rule', 'fillAction');
    this.cs.presentAlert(msg);
  } else if (this.msgVal == undefined ) {
    msg = this.ts.trPK('vacation-rule', 'fillMsg');
    this.cs.presentAlert(msg);
  } else if (this.Sdate == undefined || this.Sdate == '') {
    msg = this.ts.trPK('vacation-rule', 'fillSDate');
    this.cs.presentAlert(msg);
   }else if (this.Edate == undefined || this.Edate =='') {
    msg = this.ts.trPK('vacation-rule', 'fillEDate');
    this.cs.presentAlert(msg);
   }

  // else if (this.selEmployeeID == undefined) {
  //   msg = this.ts.trPK('vacation-rule', 'fillReplacement');
  //   this.cs.presentAlert(msg);
  // }
   else {
   // var responseAttrDic = this.exampleJsonObject;//haroon
    var responseAttrDic =this.RespondAttributeList; // Ashwaq
    this.P_RESPOND_ATTRIBUTES_TBL = [];
    for (let key in responseAttrDic) {
      let obj: any = {};
      obj.ATTRIBUTE_NAME =responseAttrDic[key].ATTRIBUTE_NAME;//ashwaq to get ATTRIBUTE_NAME

      if (typeof responseAttrDic[key] === "number") {
        obj.ATTRIBUTE_NUMBER_VALUE = (document.getElementById(responseAttrDic[key].ATTRIBUTE_NAME) as HTMLInputElement).value;

      }
    
      else {
        obj.ATTRIBUTE_TEXT_VALUE =(document.getElementById(responseAttrDic[key].ATTRIBUTE_NAME) as HTMLInputElement).value;

      }
      this.P_RESPOND_ATTRIBUTES_TBL.push(obj);
    }


   
    let repUserName = this.selEmployeeID;
    if(repUserName == null || repUserName ==""){

    }
    if (this.hideForwordEmployee && this.hideForwordEmployee.ATTRIBUTE_NAME) {
      let obj: any = {};
      repUserName = "";
      obj.ATTRIBUTE_NAME = this.hideForwordEmployee.ATTRIBUTE_NAME;
      obj.ATTRIBUTE_TEXT_VALUE = this.selEmployeeID;
      this.P_RESPOND_ATTRIBUTES_TBL.push(obj);
    }
    let pAction = "";
    pAction = this.getActionValue();
    let jsonSDate = "";
    let jsonEDate = "";
    if (this.Sdate) {
      let startDate = moment(this.Sdate).format('YYYY-MM-DDTHH:mm:ssZ');
      jsonSDate = this.cs.convertISODateToJsonDate(startDate);
    } else {
      jsonSDate = null;
    }
    if (this.Edate) {
     
      let endDate = moment(this.Edate).format('YYYY-MM-DDTHH:mm:ssZ');
      jsonEDate = this.cs.convertISODateToJsonDate(endDate);
    } else {
      jsonEDate = null;
    }
    let request: createVacationRequest = new createVacationRequest();
    request.P_BEGIN_DATE = jsonSDate;
    request.P_END_DATE = jsonEDate;
    request.P_MESSAGE = this.msgVal;
    request.P_REPLACEMENT_USER_NAME = repUserName;
    request.P_ITEM_TYPE = this.itemType.ITEM_TYPE;
    request.P_NOTIFICATION_NAME = this.notificationType.NOTIFICATION_NAME;
    request.P_ACTION = pAction;
    request.RespondAttributeList = this.P_RESPOND_ATTRIBUTES_TBL;
    this.vacationRuleRequest = request;

  




    this.vacationRuleService.createVacationRule(request, () => {
    }, this.ts.trPK('general', 'retry')).subscribe((result) => {
      if (this.cs.validResponse(result)) {
        console.log(result);
        this.handlecreateVacationResult(result);
      } else {
        this.cs.presentAlert(result.ErrorEndUserMessage);
      }
    });

  }
}
handlecreateVacationResult(result) {
  if (this.cs.validResponse(result)) {
    this.cs.JustAlertDialog(this.ts.trPK('general', 'ok'), this.ts.trPK('vacation-rule', 'rule-success'))
    this.goToStart();
 
  }
}

goToStart() {

  this.cs.navigateRoot('/home')
}

updateVacationRule() {
  (this.elementRef.nativeElement.querySelectorAll('ion-item') as HTMLElement[]).forEach((x) => {
    if (x.classList.contains('requiredItem')) {
      x.classList.add('ng-touched');
      x.classList.remove('ng-untouched');
    }
  });
  let msg: string = "";
  if (this.notifTypeSel == undefined ) {
    msg = this.ts.trPK('vacation-rule', 'fillAction');
    this.cs.presentAlert(msg);

  } else if (this.msgVal == undefined) {
    msg = this.ts.trPK('vacation-rule', 'fillMsg');
    this.cs.presentAlert(msg);

  } else if (this.Sdate == undefined || this.Sdate == '') {
    msg = this.ts.trPK('vacation-rule', 'fillSDate');
    this.cs.presentAlert(msg);

  }else if (this.Edate == undefined || this.Edate =='') {
    msg = this.ts.trPK('vacation-rule', 'fillEDate');
    this.cs.presentAlert(msg);
   }
  else {
    var responseAttrDic = this.exampleJsonObject;
    this.P_RESPOND_ATTRIBUTES_TBL = [];
    for (let key in responseAttrDic) {
      let obj: any = {};
      obj.ATTRIBUTE_NAME = key;
      if (typeof responseAttrDic[key] === "number") {
        obj.ATTRIBUTE_NUMBER_VALUE = responseAttrDic[key];
      }
 
      else {
        obj.ATTRIBUTE_TEXT_VALUE = responseAttrDic[key];
      }
      this.P_RESPOND_ATTRIBUTES_TBL.push(obj);
    }
    let repUserName = this.selEmployeeID;
    if (this.hideForwordEmployee && this.hideForwordEmployee.ATTRIBUTE_NAME) {
      let obj: any = {};
      repUserName = "";
      obj.ATTRIBUTE_NAME = this.hideForwordEmployee.ATTRIBUTE_NAME;
      obj.ATTRIBUTE_TEXT_VALUE = this.selEmployeeID;
      this.P_RESPOND_ATTRIBUTES_TBL.push(obj);
    }
    let pAction = "";
    pAction = this.getActionValue();
    let jsonSDate = "";
    let jsonEDate = "";

    if (this.Sdate) {

      let startDate = moment(this.Sdate).format('YYYY-MM-DDTHH:mm:ssZ');

      jsonSDate = this.cs.convertISODateToJsonDate(startDate);
    } else {
      jsonSDate = null;
    }

    if (this.Edate) {
     
      let endDate = moment(this.Edate).format('YYYY-MM-DDTHH:mm:ssZ');
      jsonEDate = this.cs.convertISODateToJsonDate(endDate);
    } else {
      jsonEDate = null;
    }
    let body: any = {

      P_RULE_ID: this.updateData.RULE_ID,
      P_BEGIN_DATE: jsonSDate,
      P_END_DATE: jsonEDate,
      P_MESSAGE: this.msgVal,
      P_REPLACEMENT_USER_NAME: repUserName,
      P_ACTION: pAction,
      RespondAttributeList: this.P_RESPOND_ATTRIBUTES_TBL
    }
    this.vacationRuleService.updateVacationRule(
      body).
      subscribe((result: Response) => {
        this.handleupdateVacationResult(result);
      });
  }
}

handleupdateVacationResult(result) {
  if (this.cs.validResponse(result)) {
    this.cs.JustAlertDialog(this.ts.trPK('general', 'ok'), this.ts.trPK('vacation-rule', 'rule-update-success'))
    this.goToStart();
  }
}


getActionValue(): string {
  let pAction = "";
  //this.pAction = this.notifTypeSel;
  //console.log(this.pAction);
  if (this.notifTypeSel) {
    switch (this.notifTypeSel) {
      case 'DELEGATE': {
        pAction = "FORWARD";
        break;
      }
      case 'RESPOND': {
        pAction = "RESPOND";
        break;
      }
      case 'CLOSE': {
        pAction = "RESPOND";
        break;
      }
      case 'DELIVER': {
        pAction = "NOOP";
        break;
      }
      case 'TRANSFER': {
        pAction = "TRANSFER";
        break;
      }
      default: {
        pAction = "";
        break;
      }
    }
    return pAction;
  }
}

async openReplacementRoll() {

  const modal = await this.modalController.create({
    component: ReplacementListComponent,
    backdropDismiss: false,

  });
  modal.cssClass = 'replaceRoll-modal';

  modal.onDidDismiss().then((data) => {
    console.log(data.data);

    if (data.data == "cancel" || data.data == undefined) {
      return;
    } else {

      this.selEmployeeName = data.data.EMPLOYEE_DISPLAY_NAME;
      this.selEmployeeID = data.data.USER_NAME;
      this.employeeSel = this.selEmployeeName + "," + this.selEmployeeID
    }
  });

  return await modal.present();




}

//////
openConfirmAlertDialogAction(flag){
  if(flag==true){
  
  this.confirmMsg = this.ts.trPK('vacation-rule', 'confirm-msg-success')

  }
  else{
    this.confirmMsg=  this.ts.trPK('vacation-rule', 'update-msg-success')

  }
this.cs.confirmAlertDialogAction(
  () => {
    if(flag==true){
    this.ApplyFunc();
    }
    else{
     this.updateVacationRule();
    }
  }, this.ts.trPK('general', 'ok'),
  () => { }, this.ts.trPK('general', 'cancel'),
  this.ts.trPK('vacation-rule', 'confirmation'),
  this.confirmMsg
  )
}


//////
}