import { Component, OnInit, ElementRef } from "@angular/core";
import { CommonService } from "src/app/hmg-common/services/common/common.service";
import { TranslatorService } from "src/app/hmg-common/services/translator/translator.service";
import { WorkListBodyRequest } from "../models/NotificationBodyReq";
import { EITNotificatonBodyResponse } from "../models/EITNotificationBodyRes";
import { AbsenceNotificatonBodyResponse } from "../models/AbsenceNotificationBodyRes";
import { NotificatonButtonResponse } from "../models/NotificationButtonRes";
import { WorkListActionRequest } from "../models/NotificationActionReq";
import { WorkListButtonRequest } from "../models/NotificationButtonReq";
// import { isDate } from 'angular6-json-schema-form';
import { MenuResponse } from "src/app/hmg-common/services/menu/models/menu-response";
import { LoginRequest } from "src/app/hmg-common/services/authentication/models/login.request";
import { WorklistMainService } from "../service/work-list.main.service";
import { HomeComponent } from "src/app/notification/home/home.component";
import { TextInput } from 'src/app/uI-elements/text.input';
import { TextAreaInput } from 'src/app/uI-elements/text-area.input';
import { MenuService } from 'src/app/hmg-common/services/menu/menuservice.service';
import { Events, ModalController } from '@ionic/angular';
import { PONotificatonBodyResponse } from '../models/PONotificationBodyRes';
import { MONotificatonBodyResponse } from '../models/MONotificationBodyRes';
import { PRNotificatonBodyResponse } from '../models/PRNotificationBodyRes';
import { WorklistAttachService } from 'src/app/absence/service/work-list-attach.service';
import { NotificationGetAttachResponse } from 'src/app/eit/models/NotificationGetAttachRes';
import { PRNotificatonBodyList } from '../models/PRNotificationBodyList';
import { WorkListActionHistoryRequest } from '../models/ActionHistoryReq';
import { WorklistService } from '../service/worklist.service';
import { ViewNoteModalComponent } from '../view-note-modal/view-note-modal.component';
import { WorkListActionHistoryResponse } from '../models/ActionHistoryRes';
import { WorkListAttachViewComponent } from '../work-list-attach-view/work-list-attach-view.component';
import { ApplyActionModalComponent } from '../apply-action-modal/apply-action-modal.component';
import { POItemHistoryRes } from '../models/POItemHistoryRes';
import { POItemHistoryRequest } from '../models/POItemHistoryReq';
import { QuotationAnalysisResponse } from '../models/quotationAnalysisRes';
import { QuotationAnalysisRequest } from '../models/quotationAnalysisReq';
import { MoreActionModalComponent } from '../more-action-modal/more-action-modal.component'
import { WorkListReplacementRollComponent } from '../work-list-replacement-roll/work-list-replacement-roll.component';
import { WorkListRfcComponent } from '../work-list-rfc/work-list-rfc.component';
import { DashboredService } from 'src/app/hmg-common/services/dashbored/dashbored.service';
import { GetOpenNotificationsResponse } from 'src/app/hmg-common/services/dashbored/models/GetOpenNotificationsResponse';

@Component({
  selector: 'app-worklist-main-po',
  templateUrl: './worklist-main-po.component.html',
  styleUrls: ['./worklist-main-po.component.scss'],
})
export class WorklistMainPoComponent implements OnInit {
  private WorkListBodyObj: WorkListBodyRequest;
  private WorkListButtonsObj: WorkListButtonRequest;
  private WorkListActionObj: WorkListActionRequest;
  private WorkListActionHistoryObj: WorkListActionHistoryRequest;
  private WorkListAttachObj: WorkListButtonRequest;
  private PRList: PRNotificatonBodyList;

  public static PASS_NOTIFICATION_INFO = "passNotificationInfo";
  public static PASS_PO_INFO = "passPOInfo";
  public static PASS_PO_HEADER_ID = "passPOHeader";
  public static PASS_ACTION_MODE = "passActionMode";
  public static PASS_ACTION_MORE = "passActioMore";
  public isPostNoLoad = true;
  public worklistNotifications: any;
  public totalRequestCount = 0;
  getPassNotificationDetails: any;
  public static PASS_RES_ATTR = "passResAttr";
  TransactionID: number = -999;
  notificationBodyRes : any =[];
  actionHistoryRes: any =[];
  notificationButtonRes: any;
  actionMode: any;
  pInformation: string = "";
  pQuestion: string = "";
  RespondAttributesListRes: any;
  schemaNotific: any;
  NotRespondAttributeList: any;
  Resp2_val: any;
  notExampleJsonObject: any;
  hideForwordEmployee: any;
  exampleJsonObject: any;
  dataOfAttr: any;
  P_RESPOND_ATTRIBUTES_TBL: any;
  selEmployeeID: any;
  actionType: string = "";
  notificationArray: any;
  notificationDynamicAttributeArr: any;
  private textInput: TextInput;
  private textArea: TextAreaInput;
  notificationCount: any;
  attachmentRes: any;
  PRHeader: any;//change the tpye later
  PRLines: any;//change the tpye later
  IsReachEnd: boolean = true;
  P_PAGE_NUM: number = 1;
  P_PAGE_LIMIT: number = 100;
  headerTotal: any;
  totalH: any;
  valueH: any;
  taxH: any;
  taxvalueH: any;
  NotificationGetRespondAttributesList: any;
  confirmMsg: string;
  delMsg: string;
  closeMsg: string;
  POHeader: any;
  POLines: any;
  PO_NUMBER: any;
  itemHistoryRes: any;
  QutationAnalysisRes: any;
  activeSegment: any = "line_details";
  lines_note_limit: number = 24;
  notiActionBtnMore: any = [];
  demoeAttach: any = [];
  orgNote: any;
  truncating: boolean = true;
  hidden: boolean = true;
  selectedIndex = -1;
  showLessBtn: boolean;
  showMoreBtn: boolean = true;
  selectedAction: any = [];
  messageSuccess: boolean = false;
  approveDis: boolean = false;
  rejectDis: boolean = false;
  requestDis: boolean = false;
  moreDisabled: boolean = true;
  direction: string;
  defaultSegment = '';

  constructor(
    public common: CommonService,
    public ts: TranslatorService,
    public worklistMainService: WorklistMainService,
    public elementRef: ElementRef,
    public menuService: MenuService,
    public events: Events,
    public worklistAttachService: WorklistAttachService,
    private modalCtrl: ModalController,
    public worklistService: WorklistService,
    public dashboredService: DashboredService,

  ) {
    this.direction = TranslatorService.getCurrentLanguageName()
    this.WorkListActionHistoryObj = new WorkListActionHistoryRequest();
    this.WorkListActionHistoryObj.P_PAGE_NUM = 1;
    this.WorkListActionHistoryObj.P_PAGE_LIMIT = this.P_PAGE_LIMIT;
  }

  ngOnInit() {

    this.WorkListAttachObj = new WorkListButtonRequest();

    this.intializeNotificationDetail();



  }//ngOn
  intializeNotificationDetail() {
    if (this.messageSuccess) {
      document.getElementById("notificationDynamicFieldsPO").innerHTML = "";
    }
    console.log("intializeNotificationDetail");
    this.getPassNotificationDetails = this.common.sharedService.getSharedData(
      HomeComponent.NOTIFICATION_DATA,
      false
    );
    console.log(this.getPassNotificationDetails.ROW_NUM);
    this.notificationArray = this.common.sharedService.getSharedData(
      HomeComponent.NOTIFICATION_ARR,
      false
    );
    this.WorkListBodyObj = new WorkListBodyRequest();
    this.WorkListButtonsObj = new WorkListButtonRequest();

    this.WorkListActionObj = new WorkListActionRequest();

    this.WorkListBodyObj.P_TRANSACTION_ID = this.TransactionID;
    this.WorkListBodyObj.P_NOTIFICATION_ID = this.getPassNotificationDetails.NOTIFICATION_ID;
    this.WorkListBodyObj.P_PAGE_NUM = 1;
    this.WorkListBodyObj.P_PAGE_LIMIT = this.P_PAGE_LIMIT;

    this.WorkListButtonsObj.P_NOTIFICATION_ID = this.getPassNotificationDetails.NOTIFICATION_ID;

    this.WorkListActionObj.P_NOTIFICATION_ID = this.getPassNotificationDetails.NOTIFICATION_ID;
    this.WorkListActionObj.P_FORWARD_TO_USER_NAME = "";
    this.WorkListActionObj.P_ACTION_MODE = "";
    this.WorkListActionObj.P_COMMENTS = "";
    this.WorkListActionObj.P_APPROVER_INDEX = null;

    this.WorkListActionHistoryObj.P_PAGE_NUM = 1;
    this.WorkListActionHistoryObj.P_PAGE_LIMIT = this.P_PAGE_LIMIT;
    this.WorkListActionHistoryObj.P_NOTIFICATION_ID = this.getPassNotificationDetails.NOTIFICATION_ID;

    this.WorkListAttachObj.P_NOTIFICATION_ID = this.getPassNotificationDetails.NOTIFICATION_ID;

    this.getNotificationButtons(this.WorkListButtonsObj);
    this.getNotificationResAttr(this.WorkListButtonsObj);
    this.getActionHistory(this.WorkListActionHistoryObj);
    this.getAttachmentNotification(this.WorkListAttachObj);


    if (this.getPassNotificationDetails.REQUEST_TYPE == "PO") {
      this.getPONotificationDetails(this.WorkListBodyObj);
    }
  }

  public segmentChanged(event: any) {
    this.activeSegment = event.detail.value;
    console.log(" event.detail.value: " + event.detail.value);
  }

  getPONotificationDetails(notificationBodyObj) {
    this.worklistMainService
      .getPONotificationBody(notificationBodyObj)
      .subscribe((result: PONotificatonBodyResponse) => {
        console.log(result.GetPoNotificationBodyList.POHeader[0].BUYER);
        this.handleWorkListBodyResult(result, "PO");
      });
  }

  handleWorkListBodyResult(result, Type) {
    this.notificationBodyRes = [];
    if (this.common.validResponse(result)) {
      this.pInformation = result.P_INFORMATION;
      this.pQuestion = result.P_QUESTION;
      if (Type == "EIT") {
        if (result.GetEITCollectionNotificationBodyList) {
          this.notificationBodyRes =
            result.GetEITCollectionNotificationBodyList;
        }
      } else if (Type == "ABSENCE") {
        console.log("ABSENCE");
        if (result.GetAbsenceCollectionNotificationBodyList) {
          this.notificationBodyRes =
            result.GetAbsenceCollectionNotificationBodyList;
        }
      } else if (Type == "PR") {
        if (result.GetPrNotificationBodyList) {
          console.log("PR");

          this.PRHeader = result.GetPrNotificationBodyList.PRHeader;
          this.PRLines = result.GetPrNotificationBodyList.PRLines;
          for (var i = 0; i < this.PRHeader.length; i++) {
            if (this.PRHeader[i].HDR_ATTRIBUTE_NAME === 'Requisition Total') {
              this.totalH = this.PRHeader[i].HDR_ATTRIBUTE_NAME;
              this.valueH = this.PRHeader[i].HDR_ATTRIBUTE_VALUE;

              //this. header.HDR_ATTRIBUTE_NAME != 'Non-Recoverable Tax'"
            }
            if (this.PRHeader[i].HDR_ATTRIBUTE_NAME === 'Non-Recoverable Tax') {
              this.taxH = this.PRHeader[i].HDR_ATTRIBUTE_NAME;
              this.taxvalueH = this.PRHeader[i].HDR_ATTRIBUTE_VALUE;

            }

            // HDR_ATTRIBUTE_VALUE
          }
          this.notificationBodyRes =
            result.GetPrNotificationBodyList;
        }

      } else if (Type == "PO") {
        if (result.GetPoNotificationBodyList) {
          console.log("PO");

          this.POHeader = result.GetPoNotificationBodyList.POHeader;
          this.POLines = result.GetPoNotificationBodyList.POLines;
          for (var i = 0; i < this.POHeader.length; i++) {
            this.PO_NUMBER = this.POHeader[i].PO_NUMBER;

            if (this.POHeader[i].HDR_ATTRIBUTE_NAME === 'Requisition Total') {
              this.totalH = this.POHeader[i].HDR_ATTRIBUTE_NAME;
              this.valueH = this.POHeader[i].HDR_ATTRIBUTE_VALUE;

              //this. header.HDR_ATTRIBUTE_NAME != 'Non-Recoverable Tax'"
            }
            if (this.POHeader[i].HDR_ATTRIBUTE_NAME === 'Non-Recoverable Tax') {
              this.taxH = this.POHeader[i].HDR_ATTRIBUTE_NAME;
              this.taxvalueH = this.POHeader[i].HDR_ATTRIBUTE_VALUE;

            }

            // HDR_ATTRIBUTE_VALUE
          }
          this.notificationBodyRes =
            result.GetPoNotificationBodyList;
        }
      }//
    }
  } //End handleWorkListBodyResult




  getNotificationButtons(notificationButtonsObj) {
    this.worklistMainService
      .getNotificationButtons(notificationButtonsObj)
      .subscribe((result: NotificatonButtonResponse) => {
        this.handleWorkListButtonsResult(result);
      });
  }

  handleWorkListButtonsResult(result) {
    if (this.common.validResponse(result)) {
      this.notiActionBtnMore = []
      // this.sharedData.setSharedData(result, WorKListResponse.SHARED_DATA);
      if (result.GetNotificationButtonsList != null) {
        this.notificationButtonRes = result.GetNotificationButtonsList;
        this.common.sharedService.setSharedData(this.notificationButtonRes, "passActionMore");
        console.log("test" + this.notificationButtonRes.length);
        for (let i = 0; i < this.notificationButtonRes.length; i++) {
          if (this.notificationButtonRes[i].BUTTON_ACTION == "APPROVE") {
            this.approveDis = true;
          } else
            if (this.notificationButtonRes[i].BUTTON_ACTION == "REJECT") {
              this.rejectDis = true;
            } else
              if (this.notificationButtonRes[i].BUTTON_ACTION == "REQUEST_INFO") {
                this.requestDis = true;
              } // if result == null
              else if (
                this.notificationButtonRes[i].BUTTON_ACTION != "APPROVE" && this.notificationButtonRes[i].BUTTON_ACTION != "REJECT" && this.notificationButtonRes[i].BUTTON_ACTION != "REQUEST_INFO")
          {
            this.moreDisabled = false;

          }
              
        } // valid it

      } // valid it
    } // End handleWorkListButtonsResult


  }
  applyAction(WorkListActionObj) {
    console.log("applyactio");
    this.worklistMainService
      .actionButton(WorkListActionObj)
      .subscribe((result: any) => {
        this.handleApplayActionResult(result);
      });
  }

  handleApplayActionResult(result) {
    if (this.common.validResponse(result)) {
      // tslint:disable-next-line: triple-equals
      if (result.MessageStatus == 1) {
        this.common.sharedService.setSharedData(true, 'loadWorkList');
        this.messageSuccess = true;
        setTimeout(() => {
          this.messageSuccess = false;
          // this.openNotificationsDashboard();
          this.nextNotfification();
        }, 5000);
      }
    } // valid it
  }

  // public nextNotfification() {
  //   //let itemExist = false;
  //   let itemNo = this.getPassNotificationDetails.ROW_NUM;
  //   itemNo += 1;
  //   if (itemNo > this.notificationArray.length) {
  //     this.common.openNotificationPage();
  //   } else {
  //     for (let i = 0; i < this.notificationArray.length; i++) {
  //       if (this.notificationArray[i].ROW_NUM == itemNo) {
  //         this.common.sharedService.setSharedData(this.notificationArray[i], HomeComponent.NOTIFICATION_DATA);
  //         // itemExist = true;
  //         this.intializeNotificationDetail();
  //         break;
  //       }
  //     }
  //     //     if(itemExist==false){
  //     // this.nextNotfification();
  //     //     }
  //   }
  // }

  public nextNotfification() {
    //let itemExist = false;
    if( document.getElementById("notificationDynamicFieldsPO") != null){
  
      document.getElementById("notificationDynamicFieldsPO").innerHTML = "";

       }
    let itemNo = this.getPassNotificationDetails.ROW_NUM;
    console.log(itemNo);
    let index = this.notificationArray.findIndex(x => x.ROW_NUM === itemNo);
    console.log(index);
    console.log(this.notificationArray);
    index += 1;
   
    if (index < this.notificationArray.length) {
      this.common.sharedService.setSharedData(this.notificationArray[index], HomeComponent.NOTIFICATION_DATA);
      if(this.notificationArray[index].REQUEST_TYPE == "PO" ){
        this.intializeNotificationDetail();
      }else
      if(this.notificationArray[index].REQUEST_TYPE == "PR" ){
        this.common.openWorklistMainPRPage() 
      }
      else
      if(this.notificationArray[index].REQUEST_TYPE == "MO" ){
        this.common.openWorklistMainMRPage() 
      }else{
        this.common.openWorklistMainPage();
      }

    }
    else{
      this.common.openNotificationPage();
    }
  }

  actionButton(action) {

    console.log("actionButton" + action);
   // alert("don't forget");
    //let ButtonAction: string = this.actionType;
    let ButtonAction: string = action;

    var responseAttrDic = this.notExampleJsonObject;
    this.P_RESPOND_ATTRIBUTES_TBL = [];
    for (let i = 0; i < this.notificationDynamicAttributeArr.length; i++) {
      let obj: any = {};
      obj.ATTRIBUTE_NAME = this.notificationDynamicAttributeArr[i].ATTRIBUTE_NAME;
      if (this.notificationDynamicAttributeArr[i].ATTRIBUTE_TYPE === "number") {
        obj.ATTRIBUTE_NUMBER_VALUE = (document.getElementById(this.notificationDynamicAttributeArr[i].ATTRIBUTE_NAME) as HTMLInputElement).value;
      }
      //  else if (isDate(responseAttrDic[key])) {
      //   obj.ATTRIBUTE_DATE_VALUE = responseAttrDic[key];
      // }
      else if (this.notificationDynamicAttributeArr[i].ATTRIBUTE_TYPE == "VARCHAR2") {
        obj.ATTRIBUTE_TEXT_VALUE = (document.getElementById(this.notificationDynamicAttributeArr[i].ATTRIBUTE_NAME) as HTMLInputElement).value;
      }
      this.P_RESPOND_ATTRIBUTES_TBL.push(obj);
    }
    console.log("a"+ this.P_RESPOND_ATTRIBUTES_TBL);

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

    if (
      ButtonAction == "APPROVE" ||
      ButtonAction == "REJECT" ||
      ButtonAction == "DEL" ||
      ButtonAction == "CLOSE"
    ) {
      this.WorkListActionObj.P_FORWARD_TO_USER_NAME = "";
      this.WorkListActionObj.P_ACTION_MODE = ButtonAction;
      this.WorkListActionObj.P_COMMENTS = "";
      this.WorkListActionObj.RespondAttributeList = this.P_RESPOND_ATTRIBUTES_TBL;

      //sheardData

      // this.common.sharedService.setSharedData(
      //   this.WorkListActionObj,
      //   WorklistMainPRComponent.PASS_NOTIFICATION_INFO
      // );
      if (ButtonAction == "APPROVE") {
        this.confirmMsg = this.ts.trPK('worklistMain', 'approveMsg')
      }
      else if (ButtonAction == "REJECT") {
        this.confirmMsg = this.ts.trPK('worklistMain', 'rejectMsg')

      }
      else if (ButtonAction == "DEL") {
        this.confirmMsg = this.ts.trPK('worklistMain', 'delMsg')

      }
      else if (ButtonAction == "CLOSE") {
        this.confirmMsg = this.ts.trPK('worklistMain', 'closeMsg')

      }

      this.common.confirmAlertDialogAction(
        () => {
          this.applyAction(this.WorkListActionObj);
        }, this.ts.trPK('general', 'ok'),
        () => { }, this.ts.trPK('general', 'cancel'),
        this.ts.trPK('vacation-rule', 'confirmation'),
        this.confirmMsg);





      // alert.onDidDismiss((data) => {
      //   if (data == true) {
      //     this.continueDelete(attach);
      //   }
      // });

      //this.openApplyModal(this.WorkListActionObj);



      ////////////this.applyAction(this.WorkListActionObj);
    }

    if (ButtonAction == "RFC") {
      // alert("Return For Correction");
      this.WorkListActionObj.P_ACTION_MODE = ButtonAction;
      // this.navCtrl.push("WorkListRfcPage", {
      //   passNotificationInfo: this.getPassNotificationDetails,
      //   passActionMode: ButtonAction,
      //   passResAttr: this.P_RESPOND_ATTRIBUTES_TBL
      // });
      this.common.sharedService.setSharedData(
        this.getPassNotificationDetails,
        WorklistMainPoComponent.PASS_NOTIFICATION_INFO
      );
      this.common.sharedService.setSharedData(
        ButtonAction,
        WorklistMainPoComponent.PASS_ACTION_MODE
      );
      this.common.sharedService.setSharedData(
        this.P_RESPOND_ATTRIBUTES_TBL,
        WorklistMainPoComponent.PASS_RES_ATTR
      );
      //this.common.openWorklistRFCPage();
      this.openRFCModal();
    } else if (ButtonAction == "ANSWER_INFO") {
      // this.navCtrl.push("WorkListReplacmentRollPage", {
      //   pQuestion: this.pQuestion,
      //   passNotificationInfo: this.getPassNotificationDetails,
      //   passActionMode: ButtonAction,
      //   passResAttr: this.P_RESPOND_ATTRIBUTES_TBL
      // });
      this.common.sharedService.setSharedData(this.pQuestion, "pQuestion");
      this.common.sharedService.setSharedData(
        this.getPassNotificationDetails,
        WorklistMainPoComponent.PASS_NOTIFICATION_INFO
      );
      this.common.sharedService.setSharedData(
        ButtonAction,
        WorklistMainPoComponent.PASS_ACTION_MODE
      );
      this.common.sharedService.setSharedData(
        this.P_RESPOND_ATTRIBUTES_TBL,
        WorklistMainPoComponent.PASS_RES_ATTR
      );
      console.log("c"+ this.P_RESPOND_ATTRIBUTES_TBL);

      // this.common.openWorklistRollReplacement();
      this.openRepRolModal();
    } else if (
      ButtonAction == "DELEGATE" ||
      ButtonAction == "REQUEST_INFO" ||
      ButtonAction == "TRANSFER" ||
      ButtonAction == "TRANSFER_INFO" ||
      ButtonAction == "APPROVE_AND_FORWARD" ||
      ButtonAction == "FORWARD"


    ) {
      //   alert("multi option: "+ ButtonAction);
      this.WorkListActionObj.P_ACTION_MODE = ButtonAction;
      // this.navCtrl.push("WorkListReplacmentRollPage", {
      //   passNotificationInfo: this.getPassNotificationDetails,
      //   passActionMode: ButtonAction,
      //   passResAttr: this.P_RESPOND_ATTRIBUTES_TBL
      // });
      this.common.sharedService.setSharedData(
        this.getPassNotificationDetails,
        WorklistMainPoComponent.PASS_NOTIFICATION_INFO
      );
      this.common.sharedService.setSharedData(
        ButtonAction,
        WorklistMainPoComponent.PASS_ACTION_MODE
      );
      this.common.sharedService.setSharedData(
        this.P_RESPOND_ATTRIBUTES_TBL,
        WorklistMainPoComponent.PASS_RES_ATTR
      );
      // this.common.openWorklistRollReplacement();
      this.openRepRolModal();
    } else if (
      ButtonAction == "UPDATE_ACTION" ||
      ButtonAction == "CONTINUE_ACTION"
    ) {
      if (this.getPassNotificationDetails.REQUEST_TYPE == "EIT") {
        this.common.sharedService.setSharedData(
          this.notificationBodyRes,
          EITNotificatonBodyResponse.SHARED_DATA
        );
        this.common.sharedService.setSharedData(
          this.getPassNotificationDetails,
          EITNotificatonBodyResponse.NOT_WORKLIST
        );
        // this.navCtrl.push("EitUpdateListPage");
      } else if (this.getPassNotificationDetails.REQUEST_TYPE == "ABSENCE") {
        this.common.sharedService.setSharedData(
          this.notificationBodyRes,
          AbsenceNotificatonBodyResponse.SHARED_DATA
        );
        this.common.sharedService.setSharedData(
          this.getPassNotificationDetails,
          AbsenceNotificatonBodyResponse.NOT_WORKLIST
        );
        // this.navCtrl.push("SubmitAbsencePage", {
        //   dirfromNotificationPage: true,
        //   submitAbsObjList: this.notificationBodyRes[0].Collection_Notification
        // });
        this.common.openConfirmAbsece();
      }
    }
    else if (this.notificationButtonRes.length > 0 && !ButtonAction) {
      (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");
        }
      });
      this.common.presentAlert(
        this.ts.trPK("worklistMain", "actionRequird")
      );
    }
  }

  openActionHistory() {
    // this.navCtrl.push("WorkListActionHistoryPage", {
    //   passNotificationInfo: this.getPassNotificationDetails
    // });
    this.common.sharedService.setSharedData(
      this.getPassNotificationDetails,
      WorklistMainPoComponent.PASS_NOTIFICATION_INFO
    );
    this.common.openWorklistHistoryPage();
  }



  openSupportDocuments() {
    // this.navCtrl.push("WorkListAttachPage", {
    //   passNotificationInfo: this.getPassNotificationDetails
    // });
    this.common.sharedService.setSharedData(
      this.getPassNotificationDetails,
      WorklistMainPoComponent.PASS_NOTIFICATION_INFO
    );
    this.common.openWorklistAttachPage();
  }

  getNotificationResAttr(notificationButtonsObj) {
    console.log("getNotificationResAttr");
    this.NotRespondAttributeList = [];

    this.worklistMainService
      .notificationResponseAttr(notificationButtonsObj)
      .subscribe((result: NotificatonButtonResponse) => {
        this.handleNotificationResAttrResult(result);
      });
  }

  handleNotificationResAttrResult(result) {
    if (this.common.validResponse(result)) {
      // this.sharedData.setSharedData(result, WorKListResponse.SHARED_DATA);
      this.NotRespondAttributeList =
        result.NotificationGetRespondAttributesList;
      if (
        result.NotificationRespondRolesList != "" &&
        result.NotificationRespondRolesList[0].ATTRIBUTE_NAME != null &&
        result.NotificationRespondRolesList[0].ATTRIBUTE_NAME != undefined
      ) {
        this.Resp2_val = result.NotificationRespondRolesList[0].ATTRIBUTE_NAME;
        this.hideForwordEmployee = result.NotificationRespondRolesList[0];
      }
      this.notificationDynamicFields(result.NotificationGetRespondAttributesList);
      this.NotificationGetRespondAttributesList = result.NotificationGetRespondAttributesList;

      this.common.sharedService.setSharedData(
        this.NotificationGetRespondAttributesList,
        WorklistMainPoComponent.PASS_RES_ATTR
      );

      this.notificationDynamicAttributeArr = result.NotificationGetRespondAttributesList;
      if (result.P_Schema) this.schemaNotific = JSON.parse(result.P_Schema);
    } // valid it
  } // End handleWorkListButtonsResult

  notificationDynamicFields(notificationAttr) {
    const containerId = 'notificationDynamicFieldsPO';
    for (let i = 0; i < notificationAttr.length; i++) {
      if (notificationAttr[i].ATTRIBUTE_TYPE == "VARCHAR2") {
        this.textArea = new TextAreaInput(notificationAttr[i].ATTRIBUTE_DISPLAY_NAME, notificationAttr[i].ATTRIBUTE_NAME, "", containerId, "", "", "");
        console.log(this.textArea );

      } else if (notificationAttr[i].ATTRIBUTE_TYPE == "ROLE") {

      } else if (notificationAttr[i].ATTRIBUTE_TYPE == "DATE") {

      } else if (notificationAttr[i].ATTRIBUTE_TYPE == "NUMBER") {

      }
    }
  }

  openNotificationBody() {
    if (this.getPassNotificationDetails.REQUEST_TYPE == "EIT") {
      this.common.sharedService.setSharedData(
        this.notificationBodyRes,
        EITNotificatonBodyResponse.SHARED_DATA
      );
      this.common.sharedService.setSharedData(
        this.getPassNotificationDetails,
        EITNotificatonBodyResponse.NOT_WORKLIST
      );
      // this.navCtrl.push("WorkListDetailsPage", { NotBodyType: "EIT" });
      this.common.sharedService.setSharedData("EIT", "NotBodyType");
      this.common.openNotificationDetailsPage();
    } else if (this.getPassNotificationDetails.REQUEST_TYPE == "ABSENCE") {
      this.common.sharedService.setSharedData(
        this.notificationBodyRes,
        AbsenceNotificatonBodyResponse.SHARED_DATA
      );
      this.common.sharedService.setSharedData(
        this.getPassNotificationDetails,
        AbsenceNotificatonBodyResponse.NOT_WORKLIST
      );
      this.common.sharedService.setSharedData("ABSENCE", "NotBodyType");
      //this.navCtrl.push("WorkListDetailsPage", { NotBodyType: "ABSENCE" });
      this.common.openNotificationDetailsPage();
    }
  }

  // getNotificationCountAfterSubmit() {
  //   const req: any = {};
  //   this.menuService.getNotificationCount(req).subscribe((result: any) => {
  //     if (this.common.validResponse(result)) {
  //       this.notificationCount =
  //         result.GetOpenNotificationsNumList.P_OPEN_NOTIFICATIONS_NUM;
  //       if (this.notificationCount <= 0) {
  //         this.notificationCount = null;
  //       }
  //       this.events.publish("getNotCount", this.notificationCount);
  //     }
  //   });
  // }




  getAttachmentNotification(WorkListAttachObj) {
    this.attachmentRes =[];
    this.worklistAttachService.getAttach(WorkListAttachObj).
      subscribe((result: NotificationGetAttachResponse) => {
        this.handleWorkListAttachResult(result);
      });
  }

  handleWorkListAttachResult(result) {
    if (this.common.validResponse(result)) {
      // this.sharedData.setSharedData(result, WorKListResponse.SHARED_DATA);
      if (result.GetAttachementList != null) {
        this.attachmentRes = result.GetAttachementList;
      } // if result == null
    } // valid it
  }

  getActionHistory(WorkListActionHistoryObj) {
    this.IsReachEnd = true;
    this.actionHistoryRes=[];
    this.worklistService.getActionHistory(WorkListActionHistoryObj).
      subscribe((result: WorkListActionHistoryResponse) => {
        this.handleWorkListActionHistoryResult(result);
      });


  }
  handleWorkListActionHistoryResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.GetActionHistoryList)) {
        this.actionHistoryRes = result.GetActionHistoryList;

        this.P_PAGE_NUM++;
        this.WorkListActionHistoryObj.P_PAGE_NUM = this.P_PAGE_NUM;
        let lastItemIndex = this.actionHistoryRes.length - 1;
        if (result.GetActionHistoryList[lastItemIndex]) {
          let lastitem = result.GetActionHistoryList[lastItemIndex];
          if (lastitem.NO_OF_ROWS == lastitem.ROW_NUM) {
            this.IsReachEnd = true;
          } else {
            this.IsReachEnd = false;
          }
        }
      }
      this.turnCateFun(this.actionHistoryRes);

    }
  }

  async openNoteDetail(note, sender) {
    // let modalPage = this.modalCtrl.create('ViewNoteModalPage', { textNote: note });
    // modalPage.present();
    console.log("note" + note);

    this.common.sharedService.setSharedData(note, 'ViewNoteModalPage')
    this.common.sharedService.setSharedData(sender, 'ViewNoteModalPageSender')

    const modal = await this.modalCtrl.create({
      component: ViewNoteModalComponent,
      backdropDismiss: false,

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

    return await modal.present();
  }

  doInfinite(infiniteScroll) {
    console.log("doInfinite action history");
    if (!this.IsReachEnd) {
      this.worklistService.getActionHistory(this.WorkListActionHistoryObj).
        subscribe((result: any) => {
          if (this.common.validResponse(result)) {
            if (result.GetActionHistoryList != undefined) {
              this.P_PAGE_NUM++;
              this.WorkListActionHistoryObj.P_PAGE_NUM = this.P_PAGE_NUM;

              (result.GetActionHistoryList).forEach(element => {
                if (element.ROW_NUM == element.NO_OF_ROWS) {
                  this.IsReachEnd = true;
                } else {
                  this.IsReachEnd = false;
                }
                this.actionHistoryRes.push(element);
              }, (Error) => console.log(Error), () => infiniteScroll.target.complete());
            }// if list length >0
            else {
              this.IsReachEnd = true;
            }
          }// if response == 1
          //this.pageNum++;
          infiniteScroll.target.complete();

        });
    } else {
      if (infiniteScroll)
        infiniteScroll.target.complete();
    }
  }//end infiniteScroll

  //**********Attachment *****************//


  async OpenAttachFiles(value, Type) {
    // let modal: Modal = this.modalCtrl.create('WorkListAttachViewPage', { displayData: value, TypeData: Type });
    // modal.present();

    this.common.sharedService.setSharedData({ displayData: value, TypeData: Type }, 'WorkListAttachViewPage')
    const modal = await this.modalCtrl.create({
      component: WorkListAttachViewComponent
    });

    return await modal.present();
  }

  getItemHistory(itemID) {
    console.log(itemID);
    this.IsReachEnd = false;
    const request = new POItemHistoryRequest();
    request.P_ITEM_ID = parseInt(itemID);
    request.P_PAGE_LIMIT = 100;
    request.P_PAGE_NUM = 1;
    this.worklistMainService.getPOItemHistory(request).
      subscribe((result: POItemHistoryRes) => {
        // this.common.sharedService.setSharedData(
        //   result.GetItemHistoryList,
        //   WorklistMainPoComponent.ItemHistoryList
        // );
        this.common.sharedService.setSharedData(
          itemID,
          WorklistMainPoComponent.PASS_PO_INFO
        );
        //open page 
        // this.common.openItemHistoryPage();
        this.handleItemHistoryResult(result);
      });
  }


  handleItemHistoryResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.GetPoItemHistoryList)) {
        this.common.openItemHistoryPage();

      }
    }
    else {
      this.common.presentAlert(
        this.ts.trPK("general", "empty")
      );
    }

  }

  getQutationAnalysis(headerID, itemID) {
    console.log(itemID + headerID);
    this.IsReachEnd = false;
    const request = new QuotationAnalysisRequest();
    request.P_ITEM_ID = parseInt(itemID);
    request.P_PO_HEADER_ID = headerID;
    request.P_PAGE_LIMIT = 100;
    request.P_PAGE_NUM = 1;
    this.worklistMainService.getQutationAnalysis(request).
      subscribe((result: QuotationAnalysisResponse) => {
        this.common.sharedService.setSharedData(
          itemID,
          WorklistMainPoComponent.PASS_PO_INFO
        );
        this.common.sharedService.setSharedData(
          headerID,
          WorklistMainPoComponent.PASS_PO_HEADER_ID
        );
        //open page

        this.handleQutationAnalysisResult(result);
      });


  }
  handleQutationAnalysisResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.GetQuotationAnalysisList)) {

        //open page
        //set sheard data
        //

        this.common.openQutationAnalysisPage();


        // this.QutationAnalysisRes = result.GetQutationAnalysisList;
        // this.P_PAGE_NUM++;
        // let lastItemIndex = this.QutationAnalysisRes.length - 1;
        // if (result.GetQutationAnalysisList[lastItemIndex]) {
        //   let lastitem = result.GetQutationAnalysisList[lastItemIndex];
        //   if (lastitem.NO_OF_ROWS == lastitem.ROW_NUM) {
        //     this.IsReachEnd = true;
        //   } else {
        //     this.IsReachEnd = false;
        //   }
        // }
      }//hasData
      else {
        this.common.presentAlert(
          this.ts.trPK("general", "empty")
        );
      }

    }
  }

  loadMoreNotificationBody() {
    console.log("loadMoreNotificationBody PO");
    if (!this.IsReachEnd) {
      console.log("this.IsReachEnd" + this.IsReachEnd);

      this.worklistMainService.getPONotificationBody(this.WorkListBodyObj).
        subscribe((result: any) => {
          if (this.common.validResponse(result)) {
            if (result.GetPoNotificationBodyList != undefined) {
              this.P_PAGE_NUM++;
              this.WorkListBodyObj.P_PAGE_NUM = this.P_PAGE_NUM;
              (result.GetPoNotificationBodyList).forEach(element => {
                if (element.ROW_NUM == element.NO_OF_ROWS) {
                  this.IsReachEnd = true;
                } else {
                  this.IsReachEnd = false;
                }
                this.notificationBodyRes.push(element);
              }, (Error) => console.log(Error), () =>
                //infiniteScroll.target.complete()
                console.log("test")
              );
            }// if list length >0
            else {
              this.IsReachEnd = true;
            }
          }// if response == 1
          //this.pageNum++;
          // infiniteScroll.target.complete();

        });
    } else {
      // if (infiniteScroll)
      //   infiniteScroll.target.complete();
    }
  }//end infiniteScroll

  loadMoreActionHistory() {
    console.log("doInfinite action history MR");

    if (!this.IsReachEnd) {
      this.worklistService.getActionHistory(this.WorkListActionHistoryObj).
        subscribe((result: any) => {
          if (this.common.validResponse(result)) {
            if (result.GetActionHistoryList != undefined) {
              this.P_PAGE_NUM++;
              this.WorkListActionHistoryObj.P_PAGE_NUM = this.P_PAGE_NUM;
              (result.GetActionHistoryList).forEach(element => {
                if (element.ROW_NUM == element.NO_OF_ROWS) {
                  this.IsReachEnd = true;
                } else {
                  this.IsReachEnd = false;
                }
                this.actionHistoryRes.push(element);
              }, (Error) => console.log(Error), () =>
                //infiniteScroll.target.complete()
                console.log("TEST"));
            }// if list length >0
            else {
              this.IsReachEnd = true;
            }
          }// if response == 1
          //this.pageNum++;
          //  infiniteScroll.target.complete();

        });
    } else {
      //if (infiniteScroll)
      //infiniteScroll.target.complete();
    }
  }//end infiniteScroll

  async openMoreActions() {




    const modal = await this.modalCtrl.create({
      component: MoreActionModalComponent,
      backdropDismiss: false,

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

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

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

          // this.selectedAction = data.data;
          this.actionType = data.data.BUTTON_ACTION;
          console.log(this.actionType);
          ///call  Action button
          this.actionButton(this.actionType);
        }
      });

    return await modal.present();




  }

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

  public checkLines(note) {
    console.log(note.split("\n").length);
    console.log(note.length);

    if (note && note != null) {


      return (note.length > this.lines_note_limit) ? true : false;



    }



    return false;
  };


  public turnCateFun(actionHis) {
    for (let i = 0; i < actionHis.length; i++) {
      actionHis[i].visible = false;

    }
    // actionHis.map((obj) => {
    //   obj.visible = false;
    //   // or via brackets
    //   // obj['total'] = 2;
    //   return obj;
    // })
    this.actionHistoryRes = actionHis;
    console.log("test");
  }

  async openRepRolModal() {




    const modal = await this.modalCtrl.create({
      component: WorkListReplacementRollComponent,
      backdropDismiss: false,

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

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

        if (data.data == "cancel" || data.data == undefined) {
          return;
        }  else if (data.data == "Success") {
          // this.openNotificationsDashboard();
          this.nextNotfification();

        }
      });

    return await modal.present();




  }

  async openRFCModal() {




    const modal = await this.modalCtrl.create({
      component: WorkListRfcComponent,
      backdropDismiss: false,

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

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

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


        }
      });

    return await modal.present();




  }

  openNotificationsDashboard() {
    this.dashboredService.getOpenNotifications('', '', this.isPostNoLoad).subscribe((result: GetOpenNotificationsResponse) => {
      if (this.common.validResponse(result)) {
        this.worklistNotifications = result;
        this.totalRequestCount = this.worklistNotifications.P_OPEN_NTF_NUMBER;
        this.common.sharedService.setSharedData(result, 'worklistNotifications');
      }
    });
  }


}
