import { createVacationRequest } from './../model/createVacation.Request';
import { ReplacementServiceRequest } from './../model/replacement-Service.request';
import { notificationTypeRequest } from './../model/notification.Request';
import { vacationTypeResponse } from './../model/vacationType.Respond';
import { vacationRuleResponse } from './../model/vacationRule.Respond';
import { Component, OnInit, ElementRef } from '@angular/core';
import * as moment from 'moment';
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 { LoginRequest } from 'src/app/hmg-common/services/authentication/models/login.request';
import { NavController, ModalController } from '@ionic/angular';
import { notificationTypeResponse } from '../model/notification.Respond';
import { Router, ActivatedRoute } from '@angular/router';
import { ReplacementListComponent } from '../replacement-list/replacement-list.component';

@Component({
  selector: 'app-create-vacation-rule',
  templateUrl: './create-vacation-rule.component.html',
  styleUrls: ['./create-vacation-rule.component.scss'],
})
export class CreateVacationRuleComponent implements OnInit {

  P_RESPOND_ATTRIBUTES_TBL: any;
  P_ITEM_TYPE_TITLE: any = "";
  Notification_Title: any = "";
  isDeliver: boolean = false;
  showForType_Y: boolean = false;
  Resp2_val: any;
  Sdate: any;
  // startTime: any;
  //endTime: any;
  Edate: any;
  msgVal: any;
  selEmployeeName: any;
  selEmployeeID: any;
  employeeSel: any;
  replacmentEmployeeInfo: any;
  itemType: any;
  notificationType: any;
  RespondAttributeList: any;
  vacationRuleRequest: createVacationRequest;
  REASSIGN_val: any;
  schemaNotific: any;
  notifTypeSel: any;
  // pAction: any;
  isUpdate: boolean = false;
  updateData: any;
  forwordAtt: any = "";
  SelAction: string = "";
  hideForwordEmployee: any;
  exampleJsonObject: any;

  constructor(public vacationRuleService: VacationRuleServiceService, public ts: TranslatorService, public cs: CommonService,
    private elementRef: ElementRef, public navCtrl: NavController, public router: Router, public modalController: ModalController,
    private route: ActivatedRoute) {
    this.Sdate = moment().format('YYYY-MM-DDTHH:mm:ssZ');

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

    if (this.isUpdate) {
      this.updateData = this.cs.sharedService.getSharedData(vacationRuleResponse.SHARED_DATA, true);
      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.isUpdate = false;
      this.SelAction = "";
      this.itemType = this.cs.sharedService.getSharedData(vacationTypeResponse.SHARED_DATA, true);
      this.notificationType = this.cs.sharedService.getSharedData(notificationTypeResponse.SHARED_DATA, true);
    }
    this.Notification_Title = this.notificationType.NOTIFICATION_DISPLAY_NAME;
    this.P_ITEM_TYPE_TITLE = this.itemType.ITEM_TYPE_DISPLAY_NAME;
    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;
    }
  }

  ngOnInit() {
    this.getNotificationReassign();
    this.respondAttributes();
  }

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

    modal.onDidDismiss()
      .then((data) => {
        const user = data.data.empData;
        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');
      }
    });
    // console.log(this.msgVal)
    let msg: string = "";
    if (this.notifTypeSel == undefined) {
      msg = this.ts.trPK('vacation-rule', 'fillAction');
      // this.common.showAlert(msg);    
      this.cs.presentAlert(msg);
    } else if (this.msgVal == undefined) {
      msg = this.ts.trPK('vacation-rule', 'fillMsg');
      // this.common.showAlert(msg);
      this.cs.presentAlert(msg);
    } else if (this.Sdate == undefined) {
      msg = this.ts.trPK('vacation-rule', 'fillSDate');
      // this.common.showAlert(msg);
      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 if (isDate(responseAttrDic[key])) {
        //   obj.ATTRIBUTE_DATE_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 x: any; let y: any;
        //  x = moment(this.Sdate).format('YYYY/MM/DD');
        // if (this.startTime)
        //   y = moment(this.startTime).format('hh:mm:ss');
        //   else
        //   y='00:00:00'
        // jsonSDate = this.common.convertISODateToJsonDate(x + " " + y);
        let startDate = moment(this.Sdate).format('YYYY-MM-DDTHH:mm:ssZ');
        jsonSDate = this.cs.convertISODateToJsonDate(startDate);
      } else {
        jsonSDate = null;
      }
      if (this.Edate) {
        // let x: any; let y: any;
        // x = moment(this.Edate).format('YYYY/MM/DD');
        // if (this.endTime)
        //   y = this.endTime;
        //   else
        //   y='00:00:00'
        let endDate = moment(this.Edate).format('YYYY-MM-DDTHH:mm:ssZ');
        jsonEDate = this.cs.convertISODateToJsonDate(endDate);
        //jsonEDate = this.common.convertISODateToJsonDate(x + " " + y);
      } 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.ApplyFunc();
      }, 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.navCtrl.pop();
      this.cs.JustAlertDialog(this.ts.trPK('general', 'ok'), this.ts.trPK('vacation-rule', 'rule-success'))
      this.goToStart();
      // this.navCtrl.push("VacationRulePage");
      //  let index= this.navCtrl.indexOf('VacationRulePage');
      //   this.navCtrl.popTo('VacationRulePage');
    }
  }

  goToStart() {
    // let index: number;
    // let views: any[] = this.navCtrl()
    // let found: boolean = views.some((view, i) => {
    //   index = i
    //   return (view.id == 'VacationRulePage')
    // })
    // found ? this.navCtrl.popTo(views[index]) : this.navCtrl.push("HomePage")
    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.common.showAlert(msg);
    } else if (this.msgVal == undefined) {
      msg = this.ts.trPK('vacation-rule', 'fillMsg');
      // this.common.showAlert(msg);
    } else if (this.Sdate == undefined) {
      msg = this.ts.trPK('vacation-rule', 'fillSDate');
      //  this.common.showAlert(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 if (isDate(responseAttrDic[key])) {
        //   obj.ATTRIBUTE_DATE_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 x: any; let y: any;
      //   x = moment(this.Sdate).format('YYYY/MM/DD');
      //   if (this.startTime)
      //     y = moment(this.startTime).format('hh:mm:ss');
      //   jsonSDate = this.common.convertISODateToJsonDate(x + " " + y);
      // } else {
      //   jsonSDate = null;
      // }
      if (this.Sdate) {
        // let x: any; let y: any;
        // x = moment(this.Sdate).format('YYYY/MM/DD');
        // if (this.startTime)
        //   y = moment(this.startTime).format('hh:mm:ss');
        //   else
        //   y='00:00:00'
        // jsonSDate = this.common.convertISODateToJsonDate(x + " " + y);
        let startDate = moment(this.Sdate).format('YYYY-MM-DDTHH:mm:ssZ');

        jsonSDate = this.cs.convertISODateToJsonDate(startDate);
      } else {
        jsonSDate = null;
      }
      // if (this.Edate)
      //   jsonEDate = this.common.convertISODateToJsonDate(this.Edate + " " + this.endTime);
      // else
      //   jsonEDate = null;
      if (this.Edate) {
        // let x: any; let y: any;
        // x = moment(this.Edate).format('YYYY/MM/DD');
        // if (this.endTime)
        //   y = moment(this.endTime).format('hh:mm:ss');
        //   else
        //   y='00:00:00'
        // jsonEDate = this.common.convertISODateToJsonDate(x + " " + y);
        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
      }
      //let request = this.sharedData.getSharedData(vacationRuleResponse.SHARED_DATA);
      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();
      //this.navCtrl.popTo('VacationRulePage');
    }
  }




  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();
      } else {
        this.cs.presentAlert(result.ErrorEndUserMessage);
      }
    });
  }

  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.P_Schema)
        this.schemaNotific = JSON.parse(result.P_Schema);
      this.reverseAction();
      if (this.isUpdate) {
        this.fillResposeAtrributes(result.RespondAttributesList);
      }
      // ATTRIBUTE_DISPLAY_NAME: "Note"
      // ATTRIBUTE_FORMAT: "4000"
      // ATTRIBUTE_NAME: "WF_NOTE"
      // ATTRIBUTE_TYPE: "VARCHAR2"
    }
  }

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

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


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

}
