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 { ApproversList } from '../models/approvers';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';
import { WorkListButtonRequest } from 'src/app/eit/models/NotificationButtonReq';
import { ModalController } from '@ionic/angular';
import { NotificationGetAttachResponse } from 'src/app/eit/models/NotificationGetAttachRes';
import { AbsenceResponse } from '../models/absence.response';
import { SubmitAbConfirmService } from '../service/submit-absence-confirm.service';
import { WorklistAttachService } from '../service/work-list-attach.service';
import { ConfirmAddEitService } from '../service/confirm-add-eit-service';
import { AbsenceNotificatonBodyResponse } from '../models/AbsenceNotificationBodyRes';
import { AbsenceAttachmentComponent } from '../absence-attachment/absence-attachment.component';
import { WorkListAttachViewComponent } from 'src/app/notification/work-list-attach-view/work-list-attach-view.component';

@Component({
  selector: "app-absence-confirm",
  templateUrl: "./absence-confirm.component.html",
  styleUrls: ["./absence-confirm.component.scss"]
})
export class AbsenceConfirmComponent implements OnInit {
  P_TransactionID: number;
  approversList: ApproversList;
  selEmp: string = "";
  respID: number;
  absComments: string = "";
  selMenu: MenuResponse;
  attachItems: any;
  attachListDisplay: any;
  isTrue: any = 0;
  getPassNotificationDetails: any;
  menuType: string = "";
  attachmentRes: any;
  objIndex1: any;
  attachListOver: any = [];
  index: any = 0;
  attachReqObj: WorkListButtonRequest = new WorkListButtonRequest();
  private isResubmitAbs: boolean = false;
  private isSubmitBtnClicked: boolean;
  constructor(
    public common: CommonService,
    public ts: TranslatorService,
    public modalCtrl: ModalController,
    public ConfirmAddEitService: ConfirmAddEitService,
    public submitConService: SubmitAbConfirmService,
    public WorklistAttachService: WorklistAttachService
  ) {
    this.isSubmitBtnClicked = false;

    // this.isResubmitAbs = this.navParams.get("isResubmit");
    if (this.isResubmitAbs) {
      this.P_TransactionID = this.common.sharedService.getSharedData(
        AbsenceResponse.SHARED_DATA
      );
      this.getPassNotificationDetails =this.common.sharedService.getSharedData(
        AbsenceNotificatonBodyResponse.NOT_WORKLIST,
        true
      );
      this.selEmp = this.getPassNotificationDetails.SELECTED_EMPLOYEE_NUMBER;
      this.menuType = "E";
      this.respID = -999;
      // this.getApproversList();
      // console.log("this.getPassNotificationDetails.P_NOTIFICATION_ID :"+this.getPassNotificationDetails.NOTIFICATION_ID);
      this.getAttachment(this.getPassNotificationDetails.NOTIFICATION_ID);
    } else {
      this.selMenu = this.common.sharedService.getSharedData(
        MenuResponse.SHARED_DATA,
        true
      );
      this.selEmp = this.common.sharedService.getSharedData(
        MenuResponse.SHARED_SEL_EMP,
        true
      );
      this.respID = this.common.sharedService.getSharedData(
        MenuResponse.SHARED_SEL_RESP_ID,
        true
      );
      this.P_TransactionID = this.common.sharedService.getSharedData(
        AbsenceResponse.SHARED_DATA
      );
      this.menuType = this.selMenu.List_Menu.MENU_TYPE;
    }
    this.getApproversList();
  }

  ngOnInit() {}
  startAbApproval() {
    if (this.attachListOver) {
      //first call add attach inside success call submit
      let request = {
        AddAttachmentList: this.attachListOver
      };
      this.ConfirmAddEitService.addAttachment(request).subscribe(
        (result: any) => {
          this.handleAddAttachmentResults(result);
        }
      );
    } else {
      this.startAbsApprovalProcess();
    }
  } //end

  handleAddAttachmentResults(result) {
    if (this.common.validResponse(result)) {
      //this.isUpload=true;
      this.isTrue = 0;
      for (let i = 0; i < result.AddAttSuccessList.length; i++) {
        if (!result.AddAttSuccessList[i].AddSuccess) {
          this.attachListOver[i].isSuccess = false;
          // if false display cancel button with waring icon or design
        } // end if
        else {
          // if true remove cancel and set isSuccess = true
          this.attachListOver[i].isSuccess = true;
          this.isTrue = this.isTrue + 1; //count flag of attach status
        } //  end else
      } // end for

      if (this.isTrue == result.AddAttSuccessList.length) {
        this.startAbsApprovalProcess();
      } else {
        //stope
        let filtered = this.attachListOver.filter(function(el) {
          return el.isSuccess == true;
        });
        this.attachListOver = filtered;
        let msg: string = "";
       // msg = this.translate.translate("addAttach.errorMsg");
        //this.common.showAlert(msg);
      }
    }
  }

  startAbsApprovalProcess() {
    let request: any = {};
    request.P_SELECTED_EMPLOYEE_NUMBER = this.selEmp;
    request.P_MENU_TYPE = this.menuType;
    request.P_SELECTED_RESP_ID = this.respID;
    request.P_TRANSACTION_ID = this.P_TransactionID;
    request.P_COMMENTS = this.absComments;
    this.submitConService
      .startAbApprovalProcess(request)
      .subscribe((result: any) => {
        this.handleResults(result);
      });
  }
  cancelAbProcess() {
    let body: any = {
      P_TRANSACTION_ID: this.P_TransactionID
    };
    this.submitConService.cancelHRTransaction(body).subscribe((result: any) => {
      this.handleCancelResults(result);
    });
  }
  handleCancelResults(result) {
    if (this.common.validResponse(result)) {
      this.isSubmitBtnClicked = false;
      // this.navCtrl.popToRoot();
    }
  }
  handleResults(result) {
    if (this.common.validResponse(result)) {
      this.isSubmitBtnClicked = true;
      //if(this.isResubmitAbs==false){
     let msg: string = this.ts.trPK("general", "messageSuccess");
     this.common.presentAlert(msg);
    
      // }
      // this.navCtrl.popToRoot();
      this.common.openNotificationPage();
    }
  }

  getApproversList() {
    let body: any = {
      P_TRANSACTION_ID: this.P_TransactionID,
      P_AME_TRANSACTION_TYPE: "SSHRMS",
      P_PAGE_NUM: 1,
      P_PAGE_LIMIT: 1000
    };
    this.submitConService.getApproversList(body).subscribe((result: any) => {
      this.handleApproversResult(result);
    });
  }

  handleApproversResult(result) {
    if (this.common.validResponse(result)) {
      this.approversList = result.GetApprovesList;
    }
  }

  async addAttachment(str: boolean, attachItems: any) {
    let attachDocID = attachItems.ATTACHED_DOCUMENT_ID;
    // var modalPage = this.modalCtrl.create("AddAttachPage", {
    //   indexLastObj: this.attachListOver.length,
    //   TransactionID: this.P_TransactionID,
    //   enableBackdropDismiss: false
    // });
    const modal = await this.modalCtrl.create({
      component: AbsenceAttachmentComponent,
      componentProps:{  indexLastObj: this.attachListOver.length, TransactionID: this.P_TransactionID},
      keyboardClose: true,
      animated: false
    }); 
    modal.onDidDismiss()
    .then((data) => {
      if (data == "cancel" || data == "undefined") {
        return;
      } else {
        if (!str) {
          this.updateFile(data, attachDocID);
        } else {
          this.attachListDisplay = data.data;
          this.attachItems = this.attachListDisplay.map(function (el) {
            var o = Object.assign({}, el);
            o.isSuccess = false;
            return o;
          });
          this.attachListOver = this.attachListOver ? this.attachListOver.concat(this.attachItems) : this.attachItems;
        }
      }
    });
    return await modal.present();

  }

  removeFile(objectitem) {
   
    if (this.attachListOver) {
      let index2 = this.attachListOver.findIndex(item => item == objectitem);
      if (index2 > -1) {
        this.attachListOver.splice(index2, 1);
      }
    }
    if (this.attachmentRes) {
      let index3 = this.attachmentRes.findIndex(item => item == objectitem);
      if (index3 > -1) {
        this.attachmentRes.splice(index3, 1);
      }
    }
  }

  getAttachment(NotificationID) {
    this.attachReqObj.P_NOTIFICATION_ID = NotificationID;

    this.WorklistAttachService.getAttach(this.attachReqObj).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
  }

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

    return await modal.present();
  }

  updateFile(attachList, attachDocID) {
  
    let req = {
      P_ATTACHED_DOCUMENT_ID: attachDocID,
      P_FILE_DATA: attachList[0].P_FILE_DATA,
      P_FILE_NAME: attachList[0].P_FILE_NAME,
      P_FILE_CONTENT_TYPE: attachList[0].P_FILE_CONTENT_TYPE
    };
    this.submitConService.updateAttach(req).subscribe((result: any) => {
      if (this.common.validResponse(result)) {
        if (result.MessageStatus == 1) {
          let msg: string = "";
          // msg = this.translate.translate("addAttach.attachUpdate");
          // this.common.showAlert(msg);
        
          this.getAttachment(this.getPassNotificationDetails.NOTIFICATION_ID);
        }
      } // val
    });
  }

  delelteFile(attach) {
    // let alert = this.common.showConfirmMsg(
    //   this.translate.translate("general.deletePerm")
    // );
    // alert.onDidDismiss(data => {
    //   if (data == true) {
    //     this.continueDelete(attach);
    //   }
    // });
  }
  continueDelete(attach) {
   
    let req = {
      P_ATTACHED_DOCUMENT_ID: attach.ATTACHED_DOCUMENT_ID
    };
    this.submitConService.delteAttach(req).subscribe((result: any) => {
      if (this.common.validResponse(result)) {
        if (result.DeleteAttachmentList.P_RETURN_STATUS === "S") {
          this.getAttachment(this.getPassNotificationDetails.NOTIFICATION_ID);
          // let msg: string = "";
          // msg = this.translate.translate("addAttach.deleteAttach");
          // this.common.showAlert(msg);
        }
      }
    });
  }
  ionViewWillLeave() {
    if (this.P_TransactionID && this.isSubmitBtnClicked == false)
      this.cancelAbProcess();
  }
}
