import { WorkListAttachViewComponent } from './../../notification/work-list-attach-view/work-list-attach-view.component';
import { AddAttachComponent } from './../add-attach/add-attach.component';
import { NotificationGetAttachResponse } from './../models/NotificationGetAttachRes';
import { EITNotificatonBodyResponse } from './../models/EITNotificationBodyRes';
import { WorkListButtonRequest } from './../models/NotificationButtonReq';
import { ApproversList } from './../../absence/models/approvers';
import { EitRequest } from './../models/eit.request';
import { Component, OnInit } from '@angular/core';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';
import { ModalController } from '@ionic/angular';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { EitService } from '../services/eit.service';
import { AddEitResponse } from '../models/add.eit.response';

@Component({
  selector: 'app-confirm-add-eit',
  templateUrl: './confirm-add-eit.component.html',
  styleUrls: ['./confirm-add-eit.component.scss'],
})
export class ConfirmAddEitComponent implements OnInit {

  private P_TransactionID: number;
  private eitRequest: EitRequest;
  approversList: ApproversList;
  addrespList: any;//EitRespModel;
  eitComments: string = "";
  menuType: string = "";
  selEmp: string = "";
  respID: number;
  selMenu: MenuResponse;
  getAttachList: any;
  attachListDisplay: any = [];
  headerTitle: string = "";
  isTrue: any = 0;
  attachItems: any;
  private isResubmitEIT: boolean = false;
  private itemKey: string = "";
  private pActionMode: string = "SUBMIT";
  attachReqObj: WorkListButtonRequest = new WorkListButtonRequest();
  attachmentRes: any;
  objIndex1: any;
  attachListOver: any = [];
  index: any = 0;
  getPassNotificationDetails: any;
  isSubmitBtnClicked: boolean;
  isDelete: boolean = false;

  constructor(public modalController: ModalController, public cs: CommonService, private ts: TranslatorService, private eitService: EitService) {
    this.isSubmitBtnClicked = false;
    this.eitRequest = new EitRequest();
  }

  ngOnInit() {
    // console.log('ionViewDidLoad ConfirmAddEitPage');
    // let selMenu:MenuResponse=new MenuResponse();
    this.selMenu = this.cs.sharedService.getSharedData(MenuResponse.SHARED_DATA, false);
    this.selEmp = this.cs.sharedService.getSharedData(MenuResponse.SHARED_SEL_EMP, false);
    this.respID = this.cs.sharedService.getSharedData(MenuResponse.SHARED_SEL_RESP_ID, false);
    this.eitRequest = this.cs.sharedService.getSharedData(EitRequest.SHARED_DATA, false);
    this.isResubmitEIT = this.cs.sharedService.getSharedData('confirmAddEITData', false).isResubmit;
    if (this.isResubmitEIT) {
      this.getPassNotificationDetails = this.cs.sharedService.getSharedData(EITNotificatonBodyResponse.NOT_WORKLIST, true);
      // console.log("this.getPassNotificationDetails: " + this.getPassNotificationDetails);
      this.P_TransactionID = this.cs.sharedService.getSharedData("TransactionIDResubmit", true);
      let notification = this.cs.sharedService.getSharedData(EITNotificatonBodyResponse.NOT_WORKLIST, true);
      this.itemKey = notification.ITEM_KEY;
      this.pActionMode = "RESUBMIT";
      this.menuType = "E";
      this.respID = -999;
      this.selEmp = this.eitRequest.P_SELECTED_EMPLOYEE_NUMBER;
      this.getApproversList();
      this.getAttachment(this.getPassNotificationDetails.NOTIFICATION_ID);
      let msg: string = "";
      msg = this.ts.trPK("eit", "update-title");
      this.headerTitle = msg;
    } else {
      this.menuType = this.selMenu.List_Menu.MENU_TYPE;
      this.headerTitle = this.selMenu.GetMenuEntriesList.PROMPT;
      this.addrespList = this.cs.sharedService.getSharedData(AddEitResponse.SHARED_DATA);
      this.itemKey = this.addrespList.SubmitEITTransactionList.P_ITEM_KEY;
      this.P_TransactionID = this.addrespList.SubmitEITTransactionList.P_TRANSACTION_ID;
      this.isDelete = this.isResubmitEIT = this.cs.sharedService.getSharedData('confirmAddEITData', false).isDelete;


      this.getApproversList();
      //  this.confirmAddEit.submitEit(this.eitRequest).subscribe((result: AddEitResponse) => {
      //    this.handleSubmitEitResult(result);
      //    });
    }
  }

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

  handleApproversResult(result) {
    if (this.cs.validResponse(result)) {
      this.approversList = result.GetApprovesList;
      // console.log("approvers List" + this.approversList);
    }
  }

  startEitApproval() {
    //first call add attach inside success call submit
    //   if(this.isResubmitEIT){
    // this.startEITApprovalProcess();
    //   }else{
    // let listToAdd:any=[];
    if (this.attachListOver) {
      // this.attachListOver.forEach(element => {
      //   if(element.toAdd==true)
      //   listToAdd.push(element);
      // });

      let request = {
        AddAttachmentList: this.attachListOver
      }

      this.eitService.addAttachment(
        request).
        subscribe((result: any) => {
          this.handleAddAttachmentResults(result);
        });
    } else {
      this.startEITApprovalProcess();
    }
    //  }
  }


  handleAddAttachmentResults(result) {

    if (this.cs.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;
          //this.attachItems[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.attachItems[i].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.startEITApprovalProcess();
      }
      else {
        //stope
        let filtered = this.attachListOver.filter(function (el) { return el.isSuccess == true; });
        this.attachListOver = filtered;
        let msg: string = "";
        msg = this.ts.trPK("eit", "attach-errorMsg");
        this.cs.presentAlert(msg);
        //  this.cs.presentAlert("fail to upload some attach file");
      }
    }
  }

  startEITApprovalProcess() {
    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_ITEM_KEY = this.itemKey;
    request.P_ACTION_MODE = this.pActionMode;
    request.P_COMMENTS = this.eitComments;
    this.eitService.startEitApprovalProcess(
      request).
      subscribe((result: any) => {
        this.handleResults(result);
      });
  }
  cancelEitProcess() {
    let body: any = {
      P_TRANSACTION_ID: this.P_TransactionID
    }
    this.eitService.cancelHRTransaction(
      body).
      subscribe((result: any) => {
        this.handleCancelResults(result);
      });

  }
  handleCancelResults(result) {
    if (this.cs.validResponse(result)) {
      this.isSubmitBtnClicked = false;
      // this.navCtrl.popToRoot();
    }
  }
  handleResults(result) {
    if (this.cs.validResponse(result)) {
      this.isSubmitBtnClicked = true;
      //if(this.isResubmitEIT==false){
      let msg: string = this.ts.trPK("eit", "approval-message-success");
      this.cs.presentAlert(msg);
      // }
      // this.navCtrl.popToRoot();

      // this.cs.openHome();
      this.cs.openNotificationPage();
    }
  }

  // addAttachment(){
  // this.navCtrl.push('AddAttachPage');


  // }

  async addAttachment(str: boolean, attachItems: any) {
    // console.log("inside attach modal");
    //open the modal with return data
    let attachDocID = attachItems.ATTACHED_DOCUMENT_ID;

    this.cs.sharedService.setSharedData( this.P_TransactionID, 'TransactionID');
    this.cs.sharedService.setSharedData(this.attachListOver.length, 'indexLastObj');

    const modal = await this.modalController.create({
      component: AddAttachComponent
    });

    modal.onDidDismiss()
      .then((data) => {
        if (data == "cancel" || data == "undefined") {
          return;
        } else {
          if (!str) {

            // this.attachItems =  data.map(function(el) {
            //   var o = Object.assign({}, el);
            //   o.isSuccess = false;
            //   return o;
            // })
            // this.objIndex1 =this.attachmentRes.findIndex(item => item == attachItems); //to use it in remove attach     
            //.ATTACHED_DOCUMENT_ID
            this.updateFile(data, attachDocID);
          } else {
            console.log(data);
            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;
            // this.attachListOver = this.attachListDisplay;
          }
          // this.attachListDisplay=data;

          //  this.attachItems =  this.attachListDisplay.map(function(el) {
          //   var o = Object.assign({}, el);
          //   o.isSuccess = false;
          //   return o;
          // })
        }
      });

    return await modal.present();
  }

  removeFile(objectitem) {


    // if (this.attachItems) {
    //   let index1 = this.attachItems.findIndex(item => item == objectitem);
    //   if (index1 > -1) {

    //     this.attachItems.splice(index1, 1);
    //   }
    //  this.attachListDisplay =this.attachListDisplay.filter(item => item.AttachmentID !== objectitem.AttachmentID); 
    // }
    if (this.attachListOver) {
      let index2 = this.attachListOver.findIndex(item => item == objectitem);
      if (index2 > -1) {
        this.attachListOver.splice(index2, 1);
      }
      //this.attachListOver =this.attachListOver.filter(item => item.AttachmentID !== objectitem.AttachmentID); 
    }
    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.eitService.getAttach(this.attachReqObj).
      subscribe((result: NotificationGetAttachResponse) => {
        this.handleWorkListAttachResult(result);
      });
  }

  handleWorkListAttachResult(result) {
    if (this.cs.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) {
    // let modal: Modal = this.modalCtrl.create('WorkListAttachViewPage', { displayData: value, TypeData: Type });
    // modal.present();

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

    modal.onDidDismiss()
      .then((data) => {
      });

    return await modal.present();
  }


  delelteFile(attach) {
    // let alert = this.cs.confirmAlertDialog(this.translate.translate('general.deletePerm'));

    this.cs.confirmAlertDialog((data) => {
      if (data == true) {
        this.continueDelete(attach);
      }
    }, this.ts.trPK('general', 'ok'), () => {

    }, this.ts.trPK('general', 'cancel'), this.ts.trPK('general', 'alert'), this.ts.trPK('eit', 'delete-perm'));

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


  }
  continueDelete(attach) {
    // console.log("trst" + attach.ATTACHED_DOCUMENT_ID);
    let req = {
      P_ATTACHED_DOCUMENT_ID: attach.ATTACHED_DOCUMENT_ID
    }
    this.eitService.deleteAttach(req).
      subscribe((result: any) => {
        if (this.cs.validResponse(result)) {
          if (result.DeleteAttachmentList.P_RETURN_STATUS === "S") {
            this.getAttachment(this.getPassNotificationDetails.NOTIFICATION_ID);
            let msg: string = "";
            msg = this.ts.trPK("eit", "deleteAttach");
            this.cs.presentAlert(msg);
            //this.cs.presentAlert("Success" );
          }
        }
      });
  }

  updateFile(attachList, attachDocID) {
    //console.log("updateFile" + attachDocID.ATTACHED_DOCUMENT_ID);
    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.eitService.updateAttach(req).
      subscribe((result: any) => {
        if (this.cs.validResponse(result)) {
          if (result.MessageStatus == 1) {
            let msg: string = "";
            msg = this.ts.trPK("eit", "attachUpdate");
            this.cs.presentAlert(msg);
            // this.cs.presentAlert("updated attach successfully" );

            //flag to disable update and enable remove
            //  this.removeFile(attachList);
            this.getAttachment(this.getPassNotificationDetails.NOTIFICATION_ID);
          }
        } // val
      });
  }


  ionViewWillLeave() {
    if (this.P_TransactionID && this.isSubmitBtnClicked == false)
      this.cancelEitProcess();
  }

}
