import { Component, OnInit } 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 { HomeComponent } from '../home/home.component';
import { WorklistMainService } from '../service/work-list.main.service';
import { itgRequest } from '../models/itgFormDetailsRequest';
import { ModalController } from '@ionic/angular';
import { WorkListReplacementRollComponent } from '../work-list-replacement-roll/work-list-replacement-roll.component';
import { WorkListReplacementItgComponent } from '../work-list-replacement-itg/work-list-replacement-itg.component';


@Component({
  selector: 'app-work-list-main-itg',
  templateUrl: './work-list-main-itg.component.html',
  styleUrls: ['./work-list-main-itg.component.scss'],
})
export class WorkListMainItgComponent implements OnInit {

  public static APPROVAL = "Services/COCWS.svc/REST/ITGApproveRequest"
  public static REJECT = 'Services/COCWS.svc/REST/ITGRejectRequest'
  public static DELEGATE = 'Services/COCWS.svc/REST/ITGDelegateRequest';
  public static REQUEST_INFORMATION = 'Services/COCWS.svc/REST/ITGRequestInformation';
  public static ANSWER = 'Services/COCWS.svc/REST/ITGAnswer';
  public static GRANT = 'Services/COCWS.svc/REST/ITGGrantAccess';

  public request_info: any;
  public request_name: any;
  public all_request: any;
  public all_request_names: any;
  public is_all_items_sents: any;
  public request = new itgRequest();
  public activeSegment: any = "info";
  public request_details: any;
  public segmentsArray: { name: string, number: number }[] = [];
  public segmentData: { name: string, data: any }[] = [];
  public requestDetailsData: { name: string, data: any }[] = [];
  public dataLabelAndValue =[];
  public header: any = [];
  public rows: any = [];
  public workList: any;
  public commentText: string;
  public replcamentID: string;
  public actionSelected: any;
  public options: any;
  public index: number = 0;
  public grantDATA: any;
  public grantInfo: any;
  public grantFieldsConditionalValue: any = [];
  public filteredGrantFieldsConditionalValue: any = [];
  public grantFieldsLabel: any = [];
  public grantFieldsValue: any = [];
  public grantRequest: any = [];
  public ExchangeServerSelected: any;
  public ExchangeServerDBSelected: any;
  public actionBTN: { name: string, image: string, isAvailable: boolean }[] = [];
  index2: number;
  direction: string;
  defaultSegment = '';
  constructor(
    public common: CommonService,
    public ts: TranslatorService,
    public workListService: WorklistMainService,
    public modalCtrl: ModalController) { }

  ngOnInit() {
    this.direction = TranslatorService.getCurrentLanguageName()
    this.request_info = this.common.sharedService.getSharedData(HomeComponent.REQUSET_INFO);
    this.request_name = this.common.sharedService.getSharedData(HomeComponent.REQUSET_NAME);
    this.all_request = this.common.sharedService.getSharedData(HomeComponent.ALL_REQUEST);
    this.all_request_names = this.common.sharedService.getSharedData(HomeComponent.NAMES_ALL_iTEMS);
    this.is_all_items_sents = this.common.sharedService.getSharedData(HomeComponent.IS_ALL_NAME);
    this.all_request = this.all_request[0];
    this.changeITGForm(this.request_info, this.request_name);
  }



  changeITGForm(data, requestName) {
    this.request_info = data;
    this.request_name = requestName;
    this.request.RequestType = this.request_name;
    this.request.ItemID = this.request_info.ItemID;
    this.request.TaskID = this.request_info.ID;
    this.request.Comments = this.request_info.Comments;
    this.request.NewUserEMPId = this.request_info.NewUserEMPId;
    this.workListService.getITGFormDetails(this.request).subscribe((result: any) => {
      this.request_details = result.ITGRequest;
      this.grantInfo = result.ITGRequest.GrantFields;
      let count =0;
      for (let i = 0; i < result.ITGRequest.FieldGoups.length; i++) {
        this.segmentsArray[i] = { name: result.ITGRequest.FieldGoups[i].Title, number: i };
        this.segmentData[i] = { name: result.ITGRequest.FieldGoups[i].Title, data: result.ITGRequest.FieldGoups[i].Fields }
        for (let j = 0; j < this.segmentData[i].data.length; j++) {
         // console.log(this.segmentData[i].data[j])
          if(this.segmentData[i].data[j].Type ==="table"){
            // console.log(JSON.parse(this.segmentData[i].data[j].Value));
            this.dataLabelAndValue.push(JSON.parse(this.segmentData[i].data[j].Value))
            console.log(this.dataLabelAndValue);
          }
          // if (this.segmentData[i].data[j].TableValue){
          //   this.requestDetailsData[count] ={ name:this.segmentData[i].data[j].TableValue.Header, 
          //     data: this.segmentData[i].data[j].TableValue.Rows}
          //     count++;
          // }
        }
      }
      console.log(this.dataLabelAndValue)
      //console.log(this.requestDetailsData)
      this.segmentsArray[this.segmentsArray.length] = { name: 'Approval Level', number: this.segmentsArray.length }
      this.workList = this.request_details.WFHistory;
      this.options = this.request_details.AllowedActions;
      this.activeSegment = this.segmentsArray[0].name;
      for (let i = 0; i < this.options.length; i++) {
        this.imageURL(this.options[i].Action);
        this.actionBTN[i] = {
          name: this.options[i].Action, image: this.imageURL(this.options[i].Action), isAvailable: this.options[i].IsAvailable
        };
      }

      if (this.grantInfo) {
        let count = 0;
        this.grantFieldsConditionalValue = [];
        for (let i = 0; i < this.grantInfo.length; i++) {
          if (this.grantInfo[i].Value) {
            for (let j = 0; j < this.grantInfo[i].Value.length; j++) {
              this.grantFieldsValue[j] = this.grantInfo[i].Value[j];
            }
          }
          if (this.grantInfo[i].ConditionalValue) {
            for (let j = 0; j < this.grantInfo[i].ConditionalValue.length; j++) {
              this.grantFieldsConditionalValue[count] = this.grantInfo[i].ConditionalValue[j];
              count++;
            }
          }
        }
      }
      //result.ITGRequest.FieldGoups.Fields
    });
  }

  imageURL(actionName) {
    if (actionName == "Approve") {
      return "../assets/imgs/action-approve.png"
    }
    if (actionName == "Reject") {
      return "../assets/imgs/action-reject.png"
    }
    if (actionName == "RequestInformation") {
      return "../assets/imgs/action-info.png"
    }
    if (actionName == "Grant") {
      return "../assets/imgs/action-info.png"
    }
    if (actionName == "Delegate") {
      return "../assets/imgs/action-info.png"
    }
    if (actionName == "Answer") {
      return "../assets/imgs/action-info.png"
    }
  }

  public segmentChangedClick(event: any) {
    this.activeSegment = event.detail.value;
  }

  skip() {
    if (this.is_all_items_sents) {
      for (let i = 1; i < this.all_request_names.length; i++) {
        for (let j = 0; j < this.all_request_names[i].data.length; j++) {
          if (this.request_info.ID === this.all_request_names[i].data[j].ID
            && this.request_info.ItemID === this.all_request_names[i].data[j].ItemID) {
            this.index2 = j + 1;
            this.index = i + 1;
            if (this.all_request_names[i].data.length !== this.index2) {// if there is another request with same type
              this.clearDataArray();
              this.changeITGForm(this.all_request_names[i].data[this.index2], this.all_request_names[i].code);
              return false;
            } else if (this.index !== this.all_request_names.length) { // if there is another deffernet type.
              this.clearDataArray();
              this.changeITGForm(this.all_request_names[this.index].data[j], this.all_request_names[this.index].code);
              return false;
            }
          } else if (this.index === this.all_request_names.length) { //if its the end request redirecte to worklist home
            this.common.sharedService.setSharedData(true, 'loadWorkList');
            this.common.openNotificationPage();
            return false;
          }
        }
      }
    } else {
      for (let i = 0; i < this.all_request.length; i++) { // search for the request that clicked on all request
        if (this.request_info.ID == this.all_request[i].ID) { // check if the ID for the request is found.
          this.index = i + 1;
          if (this.index !== this.all_request.length) { // check if its last one to redirecte to home otherwise to next request.
            this.clearDataArray();
            this.changeITGForm(this.all_request[this.index], this.request_name);
            break;
          } else {
            this.common.sharedService.setSharedData(true, 'loadWorkList');
            this.common.openNotificationPage();
            break;
          }
        } else {
          this.common.sharedService.setSharedData(true, 'loadWorkList');
          this.common.openNotificationPage();
          break;
        }
      }
    }
  }

  clearDataArray() {
    this.commentText = '';
    this.actionSelected = '';
    this.segmentsArray = [];
    this.segmentData = [];
    this.workList = [];
    this.actionBTN = [];
  }



  actionService(action, comments?, grantRequests?) {

    let url: string;
    let request = new itgRequest();
    request.RequestType = this.request_name;
    request.ItemID = this.request_info.ItemID;
    request.TaskID = this.request_info.ID;
    request.Comments = this.commentText;
    // request.Comments = this.request_info.Comments;
    request.EmployeeNumber = this.request_info.EmployeeNumber;
    request.NewUserEMPId = this.replcamentID;
    this.common.confirmAlertDialogAction(
      () => {
        if (action == 1) { //approved
          url = WorkListMainItgComponent.APPROVAL;
          this.workListService.getITGActionRequest(request, url)
            .subscribe((result: any) => {
              if (result.MessageStatus != 1) {
                this.common.presentAlert(this.ts.trPK('general', 'error-itg'));

            } else if (result.MessageStatus == 1) {
              console.log("hello action 1");
              this.common.presentAlert(this.ts.trPK('worklistMain', 'Tran_Succ'));

            
              this.confirmMsg(1)
              // this.common.openNotificationPage();
              this.skip();
            }
            });
        } else if (action == 2) {//reject
          url = WorkListMainItgComponent.REJECT;
          this.workListService.getITGActionRequest(request, url)
            .subscribe((result: any) => {
              console.log("hello action 2");

              if (result.MessageStatus != 1) {
                this.common.presentAlert(this.ts.trPK('general', 'error-itg'));

            } else if (result.MessageStatus == 1) {
              this.common.presentAlert(this.ts.trPK('worklistMain', 'Tran_Succ'));

              this.confirmMsg(2)
              // this.common.openNotificationPage();
              this.skip();
            }
            });
        } else if (action == 3) {//request more info
          request.NewUserEMPId = this.replcamentID;
          url = WorkListMainItgComponent.REQUEST_INFORMATION;
          if (!comments) {
            this.common.presentAlert(this.ts.trPK('worklist', 'empty-comment'));
          } else {
            request.Comments = comments;
            this.workListService.getITGActionRequest(request, url)
              .subscribe((result: any) => {
                console.log("hello action 3");

                if (result.MessageStatus != 1) {
                  //this.common.presentAlert(result.Message);
                  this.common.presentAlert(this.ts.trPK('general', 'error-itg'));
                }

                  if (result.MessageStatus == 1) {
                    this.common.presentAlert(this.ts.trPK('worklistMain', 'Tran_Succ'));

                    this.confirmMsg(3)
                //  this.common.openNotificationPage();
                this.skip();
              }
              });
          }
        } else if (action == 4) {//delegate
          request.NewUserEMPId = this.replcamentID;
          url = WorkListMainItgComponent.DELEGATE;
          this.workListService.getITGActionRequest(request, url)
            .subscribe((result: any) => {
              console.log("hello action 4");

              if (result.MessageStatus != 1) {
                this.common.presentAlert(this.ts.trPK('general', 'error-itg'));

            } else if (result.MessageStatus == 1) {
              this.common.presentAlert(this.ts.trPK('worklistMain', 'Tran_Succ'));

              this.confirmMsg(4)
              // this.common.openNotificationPage();
              this.skip();
            }
            });
        } else if (action == 5) { //answer
          url = WorkListMainItgComponent.ANSWER;
          if (!comments) {
            this.common.presentAlert(this.ts.trPK('worklist', 'empty-comment'));
          } else {
            this.workListService.getITGActionRequest(request, url)
              .subscribe((result: any) => {
                console.log("hello action 5");

                if (result.MessageStatus != 1) {
                  this.common.presentAlert(this.ts.trPK('general', 'error-itg'));

              } else if (result.MessageStatus == 1) {
                this.common.presentAlert(this.ts.trPK('worklistMain', 'Tran_Succ'));

                this.confirmMsg(5)
                // this.common.openNotificationPage();
                this.skip();
              }
              });
          }
        } else if (action == 6) { //grant
          url = WorkListMainItgComponent.GRANT;
          if (!comments) {
            this.common.presentAlert(this.ts.trPK('worklist', 'empty-comment'));
          }
          else {
            if (this.grantRequest) {
              request.AdditionalFields = this.grantRequest;
              this.workListService.getITGActionRequest(request, url)
                .subscribe((result: any) => {
                  console.log("hello action 6");
                  if (result.MessageStatus != 1) {
                    this.common.presentAlert(this.ts.trPK('general', 'error-itg'));

                } else if (result.MessageStatus == 1) {
                  this.common.presentAlert(this.ts.trPK('worklistMain', 'Tran_Succ'));

                  this.confirmMsg(6)
                  // this.common.openNotificationPage();
                  this.skip();
                }
                });
            } else {
              this.common.presentAlert(this.ts.trPK('worklist', 'empty-comment'));
            }
          }

        }
      }, this.ts.trPK('general', 'ok'),
      () => {
        this.actionSelected = '';
        this.common.sharedService.setSharedData(true, 'loadWorkList');
      }, this.ts.trPK('general', 'cancel'),
      this.ts.trPK('vacation-rule', 'confirmation'),
      this.confirmMsg(action));


  }

  confirmMsg(action) {
    console.log("confirmMsg");
    if (action === 1) {
      return this.ts.trPK('worklist', 'approveMsg');
    }
    if (action === 2) {
      return this.ts.trPK('worklist', 'rejectMsg');
    }
    if (action === 3) {
      return this.ts.trPK('worklist', 'requestInformationMsg');
    }
    if (action === 4) {
      return this.ts.trPK('worklist', 'delegateMsg');
    }
    if (action === 5) {
      return this.ts.trPK('worklist', 'answerMsg');
    }
    if (action === 6) {
      return this.ts.trPK('worklist', 'grantMsg');
    }

  }

  selectAtion(actionSelected) {
    this.actionSelected = actionSelected;
    if (this.actionSelected == "Answer") {
      this.actionService(5, this.commentText)
    }
    if (this.actionSelected == "Approve") {
      this.actionService(1, this.commentText);
    }
    if (this.actionSelected == "Delegate") {
      // this.actionService(4, this.commentText)
      // this.common.openWorklistRollReplacement();
      this.presentModal(4);
    }
    if (this.actionSelected === 'Doable') {
    }
    if (this.actionSelected === 'Grant') {
      this.actionService(6, this.commentText, this.grantRequest);
    }
    if (this.actionSelected === 'NotDoable') {
    }
    if (this.actionSelected === 'Question') {
    }
    if (this.actionSelected === 'Reject') {
      this.actionService(2, this.commentText);
    }
    if (this.actionSelected === 'RequestInformation') {
      this.presentModal(3);
    }

  }



  async presentModal(actionNumber) {
    const modal = await this.modalCtrl.create({
      component: WorkListReplacementItgComponent,
      backdropDismiss: false,
    });
    modal.cssClass = 'replaceRoll-modal';
    modal.onDidDismiss()
      .then((data) => {
        this.replcamentID = data.data.empData.USER_NAME;

        if (actionNumber == 3) {
          this.actionService(3, this.commentText);
        } else if (actionNumber == 4) {
          this.actionService(4);
        }

      });
    return await modal.present();
  }

  filterGrantDB(valueSelected, object, selectedOption?) {
    let count = 0;
    this.filteredGrantFieldsConditionalValue = [];
    this.grantRequest.push({ Key: object.FieldName, Value: valueSelected });
    for (let i = 0; i < this.grantInfo.length; i++) {
      if (selectedOption === this.grantInfo[i].ConditionalFieldName) {
        for (let j = 0; j < this.grantFieldsConditionalValue.length; j++) {
          if (valueSelected === this.grantFieldsConditionalValue[j].Key) {
            this.filteredGrantFieldsConditionalValue[count] = this.grantInfo[i].ConditionalValue[j].Value[0];
            count++;
          }
        }
      }
    }
  }


}
