import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { FileUploader } from 'ng2-file-upload';
import { AddAttachComponent } from 'src/app/eit/add-attach/add-attach.component';
import { AddEitResponse } from 'src/app/eit/models/add.eit.response';
import { BasicRequest } from "../models/basic.request";
import { NotificationGetAttachResponse } from 'src/app/eit/models/NotificationGetAttachRes';
import { EitService } from 'src/app/eit/services/eit.service';
import { SubmitEitModalComponent } from 'src/app/eit/submit-eit-modal/submit-eit-modal.component';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { EITNotificatonBodyResponse } from 'src/app/notification/models/EITNotificationBodyRes';
import { WorkListButtonRequest } from 'src/app/notification/models/NotificationButtonReq';
import { WorkListAttachViewComponent } from 'src/app/notification/work-list-attach-view/work-list-attach-view.component';
import { ProfileService } from '../service/profile.service';
import { SubmitAddressModalComponent } from '../submit-eit-modal/submit-address-modal.component';

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

  private P_TransactionID: number;
  private basicRequest: BasicRequest;
  approversList = [];
  basicResponseList: any;
  eitComments: string = "";
  menuType: string = "";
  selEmp: string = "";
  respID: number;
  selMenu: MenuResponse;
  getAttachList: any;
  attachListDisplay: any = [];
  headerTitle: string = "";
  isTrue: any = 0;
  attachItems: any;
  public 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;

  /***Add Attchment Vars */
  isUpload: boolean = false;
  inQueue: boolean = false;
  addAttachmentListReq: any;
  attachmentID: number = 0;
  addAttachRequest: any = [];
  fileData: any;
  fileType: any;
  dirPage: any;
  TransactionID: any;
  indexLastObj: any = 0;
  filterAllowedType: any = ['application/pdf', 'image/jpeg', 'image/png', 'text/plain', 'image/jpg', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  direction: string;


  constructor(public modalController: ModalController, public cs: CommonService, private ts: TranslatorService, private eitService: EitService, public profileService: ProfileService) {
    this.direction = TranslatorService.getCurrentLanguageName()
    this.isSubmitBtnClicked = false;
    this.basicRequest = new BasicRequest();
  }

  ngOnInit() {
    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.basicRequest = this.cs.sharedService.getSharedData(BasicRequest.SHARED_DATA, false);

    this.selEmp = this.basicRequest.P_SELECTED_EMPLOYEE_NUMBER;
    
    this.menuType = this.selMenu.List_Menu.MENU_TYPE;
    this.headerTitle = this.selMenu.GetMenuEntriesList.PROMPT;
    this.basicResponseList = this.cs.sharedService.getSharedData('basic-details-response', false);
    console.log(this.basicResponseList);
    this.itemKey = this.basicResponseList.P_ITEM_KEY;
    this.P_TransactionID = this.basicResponseList.P_TRANSACTION_ID;
    // this.isDelete = this.isResubmitEIT = this.cs.sharedService.getSharedData('confirmAddEITData', false).isDelete;

    this.getApproversList();
    
  }

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

  startEitApproval() {
    if (this.attachListOver) {
      let request = {
        AddAttachmentList: this.attachListOver
      }

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


  handleAddAttachmentResults(result) {

    if (this.cs.validResponse(result)) {
      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.startBasicDetailsApprovalProcess();
      }
      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);
      }
    }
  }

  startBasicDetailsApprovalProcess() {
    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.profileService.startBasicDetailsApprovalProcess(
      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;
    }
  }
  handleResults(result) {
    if (this.cs.validResponse(result)) {
      this.isSubmitBtnClicked = true;
      let msg: string = this.ts.trPK("eit", "approval-message-success");
      this.cs.presentAlert(msg);
      this.cs.openNotificationPage();
    }
  }

  async addAttachment(str: boolean, attachItems: any) {
    //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.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;
          }
        }
      });

    return await modal.present();
  }

  /*****submit modal********/
  async openSubmitModal() {
    this.cs.sharedService.setSharedData(this.attachListOver, 'submitAttachmentList');
    this.cs.sharedService.setSharedData(this.eitComments, 'eitComments');
    const modal = await this.modalController.create({
      component: SubmitAddressModalComponent,
      backdropDismiss: false,

    });
    modal.cssClass = 'note-modal';

    modal.onDidDismiss()
      .then((data) => {
        console.log(data.data);

        if (data.data == "cancel" || data.data == undefined) {
          return;
        } else {
          this.startEitApproval();
        }
      });

    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.eitService.getAttach(this.attachReqObj).
      subscribe((result: NotificationGetAttachResponse) => {
        this.handleWorkListAttachResult(result);
      });
  }

  handleWorkListAttachResult(result) {
    if (this.cs.validResponse(result)) {
      if (result.GetAttachementList != null) {
        this.attachmentRes = result.GetAttachementList;
      } // if result == null
    } // valid it

  }

  async OpenAttachFiles(value, Type) {
    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) {
    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'));
  }

  continueDelete(attach) {
    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);
          }
        }
      });
  }

  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.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.getAttachment(this.getPassNotificationDetails.NOTIFICATION_ID);
          }
        }
      });
  }


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

  /*******************Add attchement Functions*************/

  public uploader: FileUploader = new FileUploader({
    allowedMimeType: ['application/pdf', 'image/jpeg', 'image/png', 'text/plain', 'image/jpg', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'],
    maxFileSize: 10 * 1024 * 1024,
    formatDataFunctionIsAsync: true,
    formatDataFunction: async (item) => {
      return new Promise((resolve, reject) => {
        resolve({
          name: item._file.name,
          length: item._file.size,
          contentType: item._file.type,
          date: new Date()
        });
      });
    }
  });


  onFileSelectedclick(event) {
    event.target.value = '';
  }



  onFileSelected(input) {

    if (!(this.filterAllowedType.indexOf(input.target.files[0].type) > -1)) {
      let msg: string = "";
      msg = this.ts.trPK("general", "notSupport");
      this.cs.presentAlert(msg);
      return
    }    // todo: show alert that you tried uploading wrong files

    else {
      const file = input.target.files[0];
      this.getBase64(file).then(
        data => this.pushObject(data, file.name, file.type)
      );
    }
  }


  getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }


  pushObject(fileData, name, type) {

    console.log("before push: " + this.index);
    try {
      let array = name.split('.');
      let attachType: string = array[array.length - 1];
      this.attachListOver.push(
        {
          AttachmentID: this.attachListOver.length,
          P_FILE_CONTENT_TYPE: attachType,//type.split('/')[1],
          P_FILE_DATA: fileData.split(',')[1],
          P_FILE_NAME: name,//.split('.')[0],
          P_TRANSACTION_ID: this.P_TransactionID
        })

    } catch (e) {
    }
  }
  
}

