import { ModalController } from '@ionic/angular';
import { WorklistService } from './../service/worklist.service';
import { Component, OnInit } from '@angular/core';
import { WorKListReplacmentEmployeeResponse } from '../models/ReplacmentEmployeeRes';
import { WorkListReplacmentEmployeeRequest } from '../models/ReplacmentEmployeeReq';
import { WorkListActionRequest } from '../models/NotificationActionReq';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { WorklistMainService } from '../service/work-list.main.service';
import { ViewReplacementModalComponent } from '../view-replacement-modal/view-replacement-modal.component';

@Component({
  selector: 'app-work-list-replacement-roll',
  templateUrl: './work-list-replacement-roll.component.html',
  styleUrls: ['./work-list-replacement-roll.component.scss'],
})
export class WorkListReplacementRollComponent implements OnInit {
  P_SEARCH_EMPLOYEE_DISPLAY_NAME: string = "";
  P_SEARCH_EMAIL_ADDRESS: string = "";
  getPassActionMode: any;
  selectedValue: any;
  inputSearch: any;
  selEmpName: any;
  selectedUserInf: any;
  userNote: any;
  getPassNotificationDetails: any;
  isAnswer: boolean = false;
  pQuestion: string = "";
  selEmp: any;
  P_PAGE_NUM: number;
  P_PAGE_LIMIT: number;
  ReplacementList: any = [];
  searchBy: string = "1";
  IsReachEnd: boolean = false;
  ReplacmentListRes: WorKListReplacmentEmployeeResponse;
  private WorkListReplacmentEmployeeObj: WorkListReplacmentEmployeeRequest = new WorkListReplacmentEmployeeRequest();
  private WorkListActionObj: WorkListActionRequest;
  getpassResAttr: any = [];
  active: any;
  demoeAttach: any = [];
  isSelect: boolean = false;
  searchKeyEnter: boolean = false;
  messageSuccess: boolean = false;
  public direction: string;
  P_RESPOND_ATTRIBUTES_TBL: any[];
  typingTimer: any;
  userSelected: boolean;
  actionHistory = [];
  arr = [];
  favoriteUserList: [] = [];
  isFilter = true;
  constructor(public worklistService: WorklistService, private cs: CommonService, public ts: TranslatorService, public workListMainService: WorklistMainService, public modalCtrl: ModalController) {
    this.P_PAGE_NUM = 1;
    this.P_PAGE_LIMIT = 50;
    this.getPassActionMode = this.cs.sharedService.getSharedData('passActionMode', false);
    // this.getFavruite();
    this.getPassNotificationDetails = this.cs.sharedService.getSharedData('passNotificationInfo', false);
    this.getpassResAttr = this.cs.sharedService.getSharedData('passResAttr', false);
    this.pQuestion = this.cs.sharedService.getSharedData('pQuestion', false);

    // tslint:disable-next-line: max-line-length
    this.arr = this.cs.sharedService.getSharedData('actionHistoryData', false) ? this.cs.sharedService.getSharedData('actionHistoryData', false) : [];
    var lookupObject = {};

    // tslint:disable-next-line: forin
    for (var i in this.arr) {
      lookupObject[this.arr[i]['USER_NAME']] = this.arr[i];
    }

    // tslint:disable-next-line: forin
    for (i in lookupObject) {
      this.actionHistory.push(lookupObject[i]);
    }



    if (this.getPassActionMode === 'ANSWER_INFO') {
      this.isAnswer = true;
    }

    this.WorkListReplacmentEmployeeObj.P_PAGE_NUM = this.P_PAGE_NUM;
    this.WorkListReplacmentEmployeeObj.P_PAGE_LIMIT = this.P_PAGE_LIMIT;

    this.WorkListActionObj = new WorkListActionRequest();
    this.WorkListActionObj.P_NOTIFICATION_ID = this.getPassNotificationDetails.NOTIFICATION_ID;//26919060;
    this.WorkListActionObj.P_FORWARD_TO_USER_NAME = "";
    this.WorkListActionObj.P_ACTION_MODE = "";
    this.WorkListActionObj.P_COMMENTS = "";
    this.WorkListActionObj.RespondAttributeList = [];// this.getpassResAttr;
    this.WorkListActionObj.P_APPROVER_INDEX = null;
    this.direction = TranslatorService.getCurrentLanguageName();
    var requestInfoDel = this.cs.sharedService.getSharedData('requestInfoDelUser');
    if (requestInfoDel != null) {
      this.userSelected = true;
      this.inputSearch = requestInfoDel.NAME;
      this.selEmp = requestInfoDel;
    }
  }

  ngOnInit() {

  }

  getreplacmentemployee() {
    this.ReplacementList = [];
    this.IsReachEnd = false;
    this.P_PAGE_NUM = 1;
    if (this.inputSearch) {
      switch (this.searchBy) {
        case '1': {

          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME = this.inputSearch;
          this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME = "";
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS = "";

          break;
        }
        case '2': {
          this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME = this.inputSearch;
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS = "";
          break;
        }
        case '3': {
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS = this.inputSearch;
          this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME = "";
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
          break;
        }
        case '5': {

          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME = this.inputSearch;
          this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME = "";
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS = "";

          break;
        }
        default: {
          this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME = "";
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
          this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS = "";
          break;
        }
      }
    } else {
      this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME = "";
      this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME = "";
      this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS = "";
    }
    //  if(this.selectedValue =="1"){
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME=this.inputSearch;
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME="";
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS="";
    //   }
    //   else  if(this.selectedValue =="2"){
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME="";
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME=this.inputSearch;
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS="";
    //   }
    //   else  if(this.selectedValue =="3"){
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME="";
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME="";
    //     this.WorkListReplacmentEmployeeObj.P_SEARCH_EMAIL_ADDRESS=this.inputSearch;
    //   }

    this.worklistService.getReplacmentEmployeeList(this.WorkListReplacmentEmployeeObj).
      subscribe((result: WorKListReplacmentEmployeeResponse) => {
        this.handleWorkListReplacmentEmployeeResult(result);
      });

  }//End replacment Employee

  handleWorkListReplacmentEmployeeResult(result) {

    if (this.cs.validResponse(result)) {
      // this.sharedData.setSharedData(result, WorKListResponse.SHARED_DATA);
      if (this.cs.hasData(result.ReplacementList)) {
        //this.ReplacmentListRes =result.ReplacementList;
        this.ReplacementList = result.ReplacementList;
        this.P_PAGE_NUM++;
        let lastItemIndex = this.ReplacementList.length - 1;
        if (result.ReplacementList[lastItemIndex]) {
          let lastitem = result.ReplacementList[lastItemIndex];
          if (lastitem.NO_OF_ROWS == lastitem.ROW_NUM) {
            this.IsReachEnd = true;
          } else {
            this.IsReachEnd = false;
          }
        }
      } else {
        let msg: string = this.ts.trPK('general', 'noResult');
        this.cs.presentAlert(msg);
      }
      //  if(result.ReplacementList.length == 0){

      //   }

      //   else if(result.ReplacementList != null)
      //   { 
      //    this.ReplacmentListRes =result.ReplacementList;
      //    //open modal 
      //    this.openModale(this.ReplacmentListRes);


      //  } // if result == null

    } // valid it
  }

  getValueSelected(Value) {

    this.selectedValue = Value;
  }


  select(selectEmp, index) {
    this.selEmp = selectEmp
    this.active = index;
    this.userSelected = true;
    this.selEmp.EMPLOYEE_DISPLAY_NAME = this.selEmp.EMPLOYEE_DISPLAY_NAME ? this.selEmp.EMPLOYEE_DISPLAY_NAME : selectEmp.NAME;
    this.inputSearch = selectEmp.EMPLOYEE_DISPLAY_NAME ? selectEmp.EMPLOYEE_DISPLAY_NAME : selectEmp.NAME;
    //this.getreplacmentemployee();
  }
  clear() {
    this.selEmpName = "";
    this.selectedUserInf = null;

  }
  async openModale(ReplacmentListRes) {
    const modal = await this.modalCtrl.create({
      component: ViewReplacementModalComponent
    });

    modal.onDidDismiss()
      .then((data) => {
        if (data == "cancel" || data == "undefined") {
          //this.selEmpName="";
          return;
        } else {
          this.selectedUserInf = data;
          this.selEmpName = this.selectedUserInf.EMPLOYEE_DISPLAY_NAME;
        }
      });

    return await modal.present();
  }

  submitAction() {

    if (this.selEmp && this.isAnswer == false) {
      // this.selectedUserInf = this.ReplacementList[this.selEmp];
      this.selectedUserInf = this.selEmp;
      if (this.selectedUserInf && this.selectedUserInf.USER_NAME) {
        if (this.userNote) {

          if (this.getPassActionMode == "APPROVE_AND_FORWARD" || this.getPassActionMode == "FORWARD") {

            let index_FORWARD = this.getpassResAttr.findIndex(x => x.ATTRIBUTE_NAME === "FORWARD_TO_USERNAME_RESPONSE");
            this.getpassResAttr[index_FORWARD].ATTRIBUTE_TEXT_VALUE = this.selectedUserInf.USER_NAME;
            // this.userNote;
            let index_Note = this.getpassResAttr.findIndex(x => x.ATTRIBUTE_NAME === "NOTE");
            this.getpassResAttr[index_Note].ATTRIBUTE_TEXT_VALUE = this.userNote;

            this.P_RESPOND_ATTRIBUTES_TBL = this.getpassResAttr;
            this.WorkListActionObj.P_FORWARD_TO_USER_NAME = this.selectedUserInf.USER_NAME;
            this.WorkListActionObj.P_ACTION_MODE = this.getPassActionMode;
            this.WorkListActionObj.P_COMMENTS = ""// response Attr
            this.WorkListActionObj.RespondAttributeList = this.P_RESPOND_ATTRIBUTES_TBL;

          } else {





            this.WorkListActionObj.P_FORWARD_TO_USER_NAME = this.selectedUserInf.USER_NAME;
            this.WorkListActionObj.P_ACTION_MODE = this.getPassActionMode;
            this.WorkListActionObj.P_COMMENTS = this.userNote;// response Attr
            // this.modalCtrl.dismiss();

          }



          this.workListMainService.actionButton(this.WorkListActionObj).
            subscribe((result: any) => {
              if (this.cs.validResponse(result)) {
                if (result.MessageStatus == 1) {

                  this.handleApplayActionResult(result);
                }
              }
            });

        } else {
          this.cs.redToastPK("replacementRoll", "enterNote");
          // let msg: string = this.ts.trPK("replacementRoll", "enterNote");
          // this.cs.showErrorMessageDialog(() => {
          // }, this.ts.trPK('general', 'ok'), msg);

        }
      } else {
        this.cs.redToastPK("replacementRoll", "msg");
        // let msg: string = this.ts.trPK("replacementRoll", "msg");
        // this.cs.showErrorMessageDialog(() => {
        // }, this.ts.trPK('general', 'ok'), msg);
      }
    } else if (this.isAnswer == true) {
      if (this.userNote) {
        this.WorkListActionObj.P_FORWARD_TO_USER_NAME = null;
        this.WorkListActionObj.P_ACTION_MODE = this.getPassActionMode;
        this.WorkListActionObj.P_COMMENTS = this.userNote;// response Attr
        // here must send response attr
        // this.modalCtrl.dismiss();

        this.workListMainService.actionButton(this.WorkListActionObj).
          subscribe((result: any) => {
            this.handleApplayActionResult(result);
          });
      } else {
        this.cs.redToastPK("replacementRoll", "enterNote");
        // let msg: string = this.ts.trPK("replacementRoll", "enterNote");
        // this.cs.showErrorMessageDialog(() => {
        // }, this.ts.trPK('general', 'ok'), msg);
      }
    } else {
      this.cs.redToastPK("replacementRoll", "msg");
      // let msg: string = this.ts.trPK("replacementRoll", "msg");
      // this.cs.showErrorMessageDialog(() => {
      // }, this.ts.trPK('general', 'ok'), msg);
    }
  }

  handleApplayActionResult(result) {
    if (this.cs.validResponse(result)) {
      if (result.MessageStatus == 1) {
        this.cs.sharedService.setSharedData(true, 'loadWorkList');



        this.messageSuccess = true;

        setTimeout(() => {
          this.messageSuccess = false;
          //this.modalCtrl.dismiss(succ);
          this.modalCtrl.dismiss({
            'dismissed': true,
            data: "Success"
          });
          if (this.selEmp && this.isAnswer == false) {
            this.setFavorite(this.selEmp);
          }
        }, 5000);

        this.cs.openNotificationPage();
        // this.messageSuccess = true;

        // setTimeout(() => {
        //   this.messageSuccess = false;
        //   //this.modalCtrl.dismiss(succ);
        //   this.modalCtrl.dismiss({
        //     'dismissed': true,
        //     data: "Success"
        //   });

        // }, 2000);

        // this.cs.openNotificationPage();
        this.modalCtrl.dismiss({
          'dismissed': true,
          data: "Success"
        });
      }

    } // not valid it

  }

  // cancel() {
  //   this.navCtrl.pop();
  // }


  doInfinite(infiniteScroll) {
    if (!this.IsReachEnd) {
      //const request =new WorkListActionRequest();
      // request.WorkListReplacmentEmployeeObj.P_SEARCH_USER_NAME=this.P_SEARCH_USER_NAME;
      // request.WorkListReplacmentEmployeeObj.P_SEARCH_EMPLOYEE_DISPLAY_NAME=this.P_SEARCH_EMPLOYEE_DISPLAY_NAME;
      // request.P_SEARCH_EMAIL_ADDRESS=this.P_SEARCH_EMAIL_ADDRESS;
      this.WorkListReplacmentEmployeeObj.P_PAGE_NUM = this.P_PAGE_NUM;
      this.WorkListReplacmentEmployeeObj.P_PAGE_LIMIT = this.P_PAGE_LIMIT;
      //  request.P_SELECTED_EMPLOYEE_NUMBER=this.selEmp;

      this.worklistService.getReplacmentEmployeeList(this.WorkListReplacmentEmployeeObj).
        subscribe((result: any) => {
          if (this.cs.validResponse(result)) {
            if (this.cs.hasData(result.ReplacementList)) {
              this.P_PAGE_NUM++;
              result.ReplacementList.forEach(vr => {
                if (vr.ROW_NUM == vr.NO_OF_ROWS) {
                  this.IsReachEnd = true;
                }
                else {
                  this.IsReachEnd = false;
                }
                this.ReplacementList.push(vr);
                // this.pro.GetVacationRulesList.push(vr);   
              });
            } else {
              this.IsReachEnd = true;
            }
          }
          //this.P_PAGE_NUM++;
          if (infiniteScroll) {
            infiniteScroll.target.complete();
          }


        }, (Error) => console.log(Error), () => infiniteScroll.target.complete());
    } else {
      if (infiniteScroll) {
        infiniteScroll.target.complete();
      }
    }
  }

  public col() {
    alert("test");
  }

  closeModal() {
    this.modalCtrl.dismiss();
  }

  selectedType;
  onChangeSelect(select) {
    let selectValue = select.detail.value;

    if (selectValue == '1') {
      this.isSelect = true;
      this.isFilter = true;
      this.selectedType = 1;
      this.listOfRealted = this.actionHistory;
    } else if (selectValue === '4') {
      if (this.favoriteUserList.length === 0 || this.favoriteUserList === undefined) {
        this.getFavruite();
      }
      this.isFilter = true;
      this.selectedType = 4;
    } else if (selectValue === '2' || selectValue === '3' || selectValue === '5') {
      this.isSelect = true;
      this.isFilter = false;
      this.selectedType = 0;
    }
    else {
      this.isSelect = false;
      this.selectedType = 0;
    }
  }

  onChangeInput() {
    this.ReplacementList = [];
    clearTimeout(this.typingTimer);
    this.typingTimer = setTimeout(() => {
      if (this.inputSearch.length > 2) {
        this.getreplacmentemployee();
      }
    }, 3000);


    // if (this.inputSearch.length > 0) {
    //   this.searchKeyEnter = true;
    //   this.getreplacmentemployee();
    // } else {
    //   this.searchKeyEnter = false;

    // }
  }
  getPlaceHolder() {
    return this.searchBy == '1' ? this.ts.trPK('replacementRoll', 'searchbyname') : this.searchBy == '2' ? this.ts.trPK('replacementRoll', 'searchbyusername') : this.ts.trPK('replacementRoll', 'searchbyemail');
  }
  getFavruite() {
    this.cs.startLoading();
    this.worklistService.getFavorite({}, () => {

    }).subscribe((result) => {
      if (this.cs.validResponse(result)) {
        this.cs.stopLoading();
        this.favoriteUserList = result['Mohemm_GetFavoriteReplacementsList'];
        this.listOfFav = this.favoriteUserList;

        /**** THIS CODE TO CHECK STAR OF EMPLOYEE IF THE IT IS IN FAVOORIT LIST AND SHOW IN WORKFLOW LIST****/
        // this.actionHistory.forEach((obj, i) => {
        //   if(this.favoriteUserList.some(x => x['USER_NAME'] === obj.USER_NAME)) {
        //     this.actionHistory[i].isInFavorite = true;
        //   } else {
        //     this.actionHistory[i].isInFavorite = false;
        //   }
        // });
        // console.log(this.actionHistory);
        /**** END ****/

      }
    });
  }
  saveUserFavruiteList(request) {
    this.worklistService.saveFavoriteList(request, () => {
    }).subscribe((result) => {
      if (this.cs.validResponse(result)) {
        this.cs.toastPK("replacementRoll", "favorite-saved");

      }
    })
  }

  setFavorite(selEmp) {
    selEmp.EMPLOYEE_DISPLAY_NAME = selEmp.EMPLOYEE_DISPLAY_NAME ? selEmp.EMPLOYEE_DISPLAY_NAME : selEmp.NAME;
    selEmp.EMPLOYEE_IMAGE = selEmp.EMPLOYEE_IMAGE ? selEmp.EMPLOYEE_IMAGE : '';
    selEmp.EMAIL_ADDRESS = selEmp.EMAIL_ADDRESS ? selEmp.EMAIL_ADDRESS : '';
    if (this.favoriteUserList.some(x => x['USER_NAME'] === selEmp.USER_NAME)) {
      let confirmBoxhtml = `<div>
      <h4>Do you want to add ` + selEmp.EMPLOYEE_DISPLAY_NAME + ` in your favorite list </h4>
      <br/>
      <br/>
      <div class="fav-profileImageDiv"><ion-row>`;
      if (selEmp.EMPLOYEE_IMAGE) {
        confirmBoxhtml += '<div class="img-box"><img class="empImgeRep" src="data:image/png;base64,' + selEmp.EMPLOYEE_IMAGE + '"></div>';
      }
      if (!selEmp.EMPLOYEE_IMAGE) {
        confirmBoxhtml += '<div class="img-box"><img class="empImgeRep" src="../assets/imgs/profile.png"></div>';
      }

      confirmBoxhtml += ` <div class="name-box"><ion-label class="fav-employee-details">
      <span>` + selEmp.EMPLOYEE_DISPLAY_NAME + `</span>
     </ion-label>
     </div></ion-row> </div>
     </div>`;
      const userIndex = this.favoriteUserList.findIndex(x => x['USER_NAME'] === selEmp.USER_NAME)
      if (userIndex === -1) {
        this.cs.presentConfirmDialog(
          confirmBoxhtml
          , () => {
            const request =
              [
                {
                  'USER_NAME': selEmp['USER_NAME'],
                  'EMPLOYEE_DISPLAY_NAME': selEmp['EMPLOYEE_DISPLAY_NAME'],
                  'EMAIL_ADDRESS': selEmp.EMAIL_ADDRESS,
                  'EMPLOYEE_IMAGE': selEmp.EMPLOYEE_IMAGE,
                  'IsFavorite': true
                }
              ];

            this.saveUserFavruiteList(request);
          }, () => { });
      }
    } else {
      const request =
        [
          {
            'USER_NAME': selEmp['USER_NAME'],
            'EMPLOYEE_DISPLAY_NAME': selEmp['EMPLOYEE_DISPLAY_NAME'],
            'EMAIL_ADDRESS': selEmp.EMAIL_ADDRESS,
            'EMPLOYEE_IMAGE': selEmp.EMPLOYEE_IMAGE,
            'IsFavorite': false
          }
        ];
        this.saveUserFavruiteList(request);
    }
  }

  listOfRealted: any = [];
  listOfFav: any = [];

  filterList(event) {
    const val = event.target.value;
    if (this.selectedType === 1) {
      if (val === '') {
        this.actionHistory = this.listOfRealted;
      } else {
        this.actionHistory = this.listOfRealted.filter((item) => {
          return (item.NAME.toLowerCase().indexOf(val.toLowerCase()) > -1);
        });
      }
    } else if (this.selectedType === 4) {
      if (val === '') {
        this.favoriteUserList = this.listOfFav;
      } else {
        this.favoriteUserList = this.listOfFav.filter((item) => {
          return (item.EMPLOYEE_DISPLAY_NAME.toLowerCase().indexOf(val.toLowerCase()) > -1);
        });
      }
    } else {
      return;
    }
  }
}
