import { AddEitComponent } from './../add-eit/add-eit.component';
import { ModalController } from '@ionic/angular';
import { CommonService } from 'src/app/hmg-common/services/common/common.service';
import { EitRequest } from './../models/eit.request';
import { EITTransactionsRequest } from './../models/EITTransactionsReq';
import { MenuResponse } from 'src/app/hmg-common/services/menu/models/menu-response';
import { Component, OnInit } from '@angular/core';
import { EitService } from '../services/eit.service';
import { EIT_ACTION } from '../models/submit.eit.action';
import { TranslatorService } from 'src/app/hmg-common/services/translator/translator.service';
import { AddEitResponse } from '../models/add.eit.response';

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

  P_PAGE_NUM: number;
  P_PAGE_LIMIT: number;
  IsReachEnd: boolean = false;
  userName: any;
  isDelete: boolean = false;
  getResEITTransactionList: any = [];
  eitAddedList: any = [];
  getPassMnuEntryObj: any;
  selMenu: MenuResponse = new MenuResponse();
  //getMenuResponse :MenuResponse=new MenuResponse
  EITTransactionsListObj: EITTransactionsRequest = new EITTransactionsRequest();
  selEmp: string;
  respID: number;
  transactionNo: number = 0;
  menuType: string = "";
  private functionName: string = "";
  private eitRequest: EitRequest;
  private eitTransactionTbl: any = [];
  private validEitTransactionTbl: any = [];
  private desxFlexCode: string = "";
  private selectedIndex: number;
  private pAction: number = 0;
  public headerTitle: string = "";
  data: any;
  accrualNetInfants: any;
  accrualUNetChild: any;
  accrualNetAdult: any;

  public options = {
    cutoutPercentage: 80,
    tooltips: { enabled: false },
    legend: { display: false }};
    gaugeType = "full";
  accrualBalancesList: any;
  common: any;
  direction: string;
    // gaugeValue = 11.200;
    // gaugeLabel = "";

  constructor(private cs: CommonService, private EITService: EitService, private ts: TranslatorService, private modalCtrl: ModalController) {
    this.direction = TranslatorService.getCurrentLanguageName()
    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.getPassMnuEntryObj = this.selMenu.GetMenuEntriesList;
    this.menuType = this.selMenu.List_Menu.MENU_TYPE;
    this.transactionNo = 0;
    this.functionName = this.getPassMnuEntryObj.FUNCTION_NAME;
    console.log("fN>>>>>>>>>>>>>>>>>"+this.functionName);
    this.headerTitle = this.selMenu.GetMenuEntriesList.PROMPT;
    this.validEitTransactionTbl = [];
    this.P_PAGE_NUM = 1;
    this.P_PAGE_LIMIT = 50;
  }

  ngOnInit() { 
    this.getEITTransactions();

    this.accrualBalancesList = this.cs.sharedService.getSharedData('tickitsbalance', false);
      // accrualNetInfants
      // accrualUNetChild
      // accrualNetAdult
      this.accrualNetAdult = this.accrualBalancesList[1].ACCRUAL_NET_ENTITLEMENT;
      this.accrualUNetChild = this.accrualBalancesList[2].ACCRUAL_NET_ENTITLEMENT;
      this. accrualNetInfants= this.accrualBalancesList[3].ACCRUAL_NET_ENTITLEMENT;
     
    this.data = {
      // labels: ['earingTotal', 'deductionTotal'],
      datasets: [
          {  data: [this.accrualNetInfants, this.accrualUNetChild, this.accrualNetAdult],
              backgroundColor: [
                  '#1FA269',
                  '#22C6B3', 
                  '#3CB9D5',],
              borderWidth: 2
             }
            ]
      };
  }

  getEITTransactions() {
    console.log("jkfdjkdfsffjhfsdahffg");
    this.IsReachEnd = false;
    this.EITTransactionsListObj.P_PAGE_LIMIT = this.P_PAGE_LIMIT;
    this.EITTransactionsListObj.P_PAGE_NUM = this.P_PAGE_NUM;
    this.EITTransactionsListObj.P_SELECTED_EMPLOYEE_NUMBER = this.selEmp;
    this.EITTransactionsListObj.P_SELECTED_RESP_ID = this.respID;
    this.EITTransactionsListObj.P_MENU_TYPE = this.selMenu.List_Menu.MENU_TYPE;
    this.EITTransactionsListObj.P_FUNCTION_NAME = this.getPassMnuEntryObj.FUNCTION_NAME;
    this.EITService.getEITTransactionsList(this.EITTransactionsListObj).
      subscribe((result: any) => {
        this.handleEITTransactionsResult(result);
      });
  }

  handleEITTransactionsResult(result) {
    if (this.cs.validResponse(result)) {
      if (this.cs.hasData(result.GetEITTransactionList)) {
        this.getResEITTransactionList = result.GetEITTransactionList;
        this.P_PAGE_NUM++;
        this.EITTransactionsListObj.P_PAGE_NUM = this.P_PAGE_NUM;
        let lastItemIndex = this.getResEITTransactionList.length - 1;
        if (result.GetEITTransactionList[lastItemIndex] && result.GetEITTransactionList[lastItemIndex].Collection_Transaction[0]) {
          let lastitem = result.GetEITTransactionList[lastItemIndex].Collection_Transaction[0];
          if (lastitem.NO_OF_ROWS == lastitem.ROW_NUM) {
            this.IsReachEnd = true;
          } else {
            this.IsReachEnd = false;
          }
        }
      }
    }
  }

  doInfinite(infiniteScroll) {
    if (!this.IsReachEnd) {

      this.EITService.getEITTransactionsList(this.EITTransactionsListObj).
        subscribe((result: any) => {
          if (this.cs.validResponse(result)) {
            if (this.cs.hasData(result.GetEITTransactionList)) {
              this.P_PAGE_NUM++;
              this.EITTransactionsListObj.P_PAGE_NUM = this.P_PAGE_NUM;
              result.GetEITTransactionList.forEach(vr => {
                if (vr.Collection_Transaction[0].ROW_NUM == vr.Collection_Transaction[0].NO_OF_ROWS) {
                  this.IsReachEnd = true;
                } else {
                  this.IsReachEnd = false;
                }
                this.getResEITTransactionList.push(vr);
              });
            } else {
              this.IsReachEnd = true;
            }
          }
          //this.P_PAGE_NUM++;
          if (infiniteScroll)
            infiniteScroll.target.complete();
        }, (Error) => console.log(Error), () => infiniteScroll.target.complete());
    } else {
      if (infiniteScroll)
        infiniteScroll.target.complete();
    }
  }

  addEITRrq(i) {
    this.pAction = EIT_ACTION.ADD;
    // this.sharedData.setSharedData(this.getResEITTransactionList[i].Collection_Transaction,EITTransactionsRequest.SHARED_DATA);
    this.cs.sharedService.setSharedData(this.pAction, EITTransactionsRequest.SUBMIT_EIT_ACTION);
    // this.navCtrl.push("AddEitPage");
    //this.openEit(i);
    this.openEitNew(i);
  }
  updateEITRrq(i) {
    this.pAction = EIT_ACTION.UPDATE;
    this.cs.sharedService.setSharedData(this.getResEITTransactionList[i].Collection_Transaction, EITTransactionsRequest.SHARED_DATA);
    this.cs.sharedService.setSharedData(this.pAction, EITTransactionsRequest.SUBMIT_EIT_ACTION);
    //this.fillEitTransactionTable(i);
    //this.navCtrl.push("AddEitPage");
    //this.openEit(i); 
    this.openEitNew(i);
  }
  deleteEIT(i) {
    this.deleteEITRrq(i);
    // let alert=this.common.showConfirmMsg(this.translate.translate('requestEit.deleteReq'));
    // alert.onDidDismiss((data) => {
    //       if(data==true){
    //         this.deleteEITRrq(i);
    //       }
    // });
  }

  deleteEITRrq(i) {
    let list: any = this.getResEITTransactionList[i];
    if (list.statusID != 2) {
      this.selectedIndex = i;
      // if(this.transactionNo==0)
      this.transactionNo++;
      this.pAction = EIT_ACTION.DELETE;
      //this.sharedData.setSharedData(this.getResEITTransactionList[i].Collection_Transaction,EITTransactionsRequest.SHARED_DATA);
      // this.sharedData.setSharedData(EIT_ACTION.DELETE,EITTransactionsRequest.SUBMIT_EIT_ACTION);
      this.fillEitTransactionTable(i);
      this.validateEITTransaction();
      // this.submitEit();
      //this.navCtrl.push("AddEitPage");
    } else {
      let msg: string = "";
      msg = this.ts.trPK("general", "attemptDel");
      this.cs.presentAlert(msg);

      // alert("You are attempting to delete a row that has already been deleted.");
    }
  }
  openEitNew(index) {
    let item: any = [];
    if (this.pAction == EIT_ACTION.UPDATE)
      item = this.getResEITTransactionList[index].Collection_Transaction;
    this.transactionNo++;
    this.cs.sharedService.setSharedData({ dirfromNotificationPage: false, submitEITObjList: item, transNo: this.transactionNo }, 'AddEITData')
    this.cs.openAddEitPage();
    // this.navCtrl.push('AddEitPage', { dirfromNotificationPage: false, submitEITObjList: item, transNo: this.transactionNo });
  }
  async openEit(index) {
    let item: any = [];
    if (this.pAction == EIT_ACTION.UPDATE)
      item = this.getResEITTransactionList[index].Collection_Transaction;
    this.transactionNo++;
    this.cs.sharedService.setSharedData({ dirfromNotificationPage: false, submitEITObjList: item, transNo: this.transactionNo }, 'AddEITData')
    const modalPage = await this.modalCtrl.create({
      component: AddEitComponent
    });
    // modalPage.present();

    modalPage.onDidDismiss()
      .then((data: any) => {
        if (data) {
          // this.transactionNo++;
          //this.updatedData=this.updatedData?this.updatedData.concat(data.updated):data.updated;
          // this.notificationBodyRes[index].Collection_Transaction=data.updated;
          this.selectedIndex = index;
          this.desxFlexCode = data.eitRequest.P_DESC_FLEX_CONTEXT_CODE;
          if (this.pAction == EIT_ACTION.ADD) {
            index = this.eitAddedList.length + 1;
            let status = this.ts.trPK("eit", ".added");
            let statusID = EIT_ACTION.ADD;
            let obj = { status: status, statusID: statusID, Collection_Transaction: data.updated };
            this.eitAddedList.push(obj);
          } else {
            let status = this.ts.trPK("eit", ".updated");
            let statusID = EIT_ACTION.UPDATE;
            this.getResEITTransactionList[this.selectedIndex].status = status;
            this.getResEITTransactionList[this.selectedIndex].statusID = statusID;
          }
          this.updateTransactionList(data.eitRequest.EITTransactionTBL, false);
        } else {
          if (this.transactionNo != 0)
            this.transactionNo--;
        }
      });

    modalPage.present();
    // modalPage.onDidDismiss(data => {
    //   if (data) {
    //     // this.transactionNo++;
    //     //this.updatedData=this.updatedData?this.updatedData.concat(data.updated):data.updated;
    //     // this.notificationBodyRes[index].Collection_Transaction=data.updated;
    //     this.selectedIndex = index;
    //     this.desxFlexCode = data.eitRequest.P_DESC_FLEX_CONTEXT_CODE;
    //     if (this.pAction == EIT_ACTION.ADD) {
    //       index = this.eitAddedList.length + 1;
    //       let status = this.ts.trPK("eit", ".added");
    //       let statusID = EIT_ACTION.ADD;
    //       let obj = { status: status, statusID: statusID, Collection_Transaction: data.updated };
    //       this.eitAddedList.push(obj);
    //     } else {
    //       let status = this.ts.trPK("eit", ".updated");
    //       let statusID = EIT_ACTION.UPDATE;
    //       this.getResEITTransactionList[this.selectedIndex].status = status;
    //       this.getResEITTransactionList[this.selectedIndex].statusID = statusID;
    //     }
    //     this.updateTransactionList(data.eitRequest.EITTransactionTBL, false);
    //   } else {
    //     if (this.transactionNo != 0)
    //       this.transactionNo--;
    //   }
    // });



  }
  fillEitTransactionTable(index) {
    var obj = { peiObjVer: null, peiExtraInfoID: null };
    let list: any = this.getResEITTransactionList[index].Collection_Transaction;
    let valuseArr: any = [];
    for (let i = 0; i < list.length; i++) {
      let item = list[i];
      if (item.APPLICATION_COLUMN_NAME != "PEI_ACTION" && item.APPLICATION_COLUMN_NAME != "PEI_EXTRA_INFO_ID" && item.APPLICATION_COLUMN_NAME != "PEI_OBJECT_VERSION_NUMBER") {
        this.desxFlexCode = item.DESC_FLEX_CONTEXT_CODE;
        if (item.DATE_VALUE == "") {
          item.DATE_VALUE = null;
        }
        valuseArr.push(
          {
            TRANSACTION_NUMBER: this.transactionNo,
            NAME: item.APPLICATION_COLUMN_NAME,
            VARCHAR2_VALUE: item.VARCHAR2_VALUE,
            NUMBER_VALUE: item.NUMBER_VALUE,
            DATE_VALUE: item.DATE_VALUE,
          }
        )
      } else {
        if (item.APPLICATION_COLUMN_NAME == "PEI_OBJECT_VERSION_NUMBER")
          obj.peiObjVer = item.NUMBER_VALUE;
        else if (item.APPLICATION_COLUMN_NAME == "PEI_EXTRA_INFO_ID")
          obj.peiExtraInfoID = item.NUMBER_VALUE;
      }

    }// end for 
    //}
    valuseArr = this.fillExtraInformation(valuseArr, "DELETE_ROW", obj.peiExtraInfoID, obj.peiObjVer, this.transactionNo);
    this.eitTransactionTbl = valuseArr;
  }

  fillExtraInformation(values: any, peiAction: string, peiExtraInfoID: number, peiObjVer: number, transNo: number): any {
    values.push(
      {
        TRANSACTION_NUMBER: transNo,
        NAME: "PEI_ACTION",
        VARCHAR2_VALUE: peiAction,
        NUMBER_VALUE: null,
        DATE_VALUE: null
      });
    values.push(
      {
        TRANSACTION_NUMBER: transNo,
        NAME: "PEI_EXTRA_INFO_ID",
        VARCHAR2_VALUE: null,
        NUMBER_VALUE: peiExtraInfoID,
        DATE_VALUE: null
      });
    values.push(
      {
        TRANSACTION_NUMBER: transNo,
        NAME: "PEI_OBJECT_VERSION_NUMBER",
        VARCHAR2_VALUE: null,
        NUMBER_VALUE: peiObjVer,
        DATE_VALUE: null
      });

    return values;
  }

  submitEit() {
    this.eitRequest = new EitRequest();
    let list: any = this.fixTransactionNo();
    this.eitRequest.EITTransactionTBL = list;
    this.eitRequest.P_SELECTED_EMPLOYEE_NUMBER = this.selEmp;
    this.eitRequest.P_MENU_TYPE = this.menuType;
    this.eitRequest.P_SELECTED_RESP_ID = this.respID;//this.selMenu.List_Menu.RESP_ID,//-999,
    this.eitRequest.P_FUNCTION_NAME = this.functionName;
    this.eitRequest.P_DESC_FLEX_CONTEXT_CODE = this.desxFlexCode;

    this.EITService.submitEit(this.eitRequest).subscribe((result: AddEitResponse) => {
      this.handleSubmitEitResult(result);
    });
  }
  handleSubmitEitResult(result) {
    if (this.cs.validResponse(result)) {
      this.cs.sharedService.setSharedData(this.eitRequest, EitRequest.SHARED_DATA);
      this.cs.sharedService.setSharedData(result, AddEitResponse.SHARED_DATA);
      //this.addrespList=result.SubmitEITTransactionList;
      // this.itemKey=this.addrespList.P_ITEM_KEY;
      // this.P_TransactionID=result.SubmitEITTransactionList.P_TRANSACTION_ID;
      //   this.sharedData.setSharedData(result,AddEitResponse.SHARED_DATA);

      // //this.cs.sharedService.setSharedData(result.SubmitEITTransactionList.P_TRANSACTION_ID,"TransactionIDResubmit");
      //  //  this.sharedData.setSharedData(this.eitRequest,EitRequest.SHARED_DATA);
      this.cs.sharedService.setSharedData({ isResubmit: false, isDelete: this.isDelete }, 'confirmAddEITData')
      this.cs.openConfirmEitPage();
      // this.navCtrl.push("ConfirmAddEitPage", { isResubmit: false, isDelete: this.isDelete });
    }
  }
  validateEITTransaction() {
    this.isDelete = false;
    this.eitRequest = {
      P_SELECTED_EMPLOYEE_NUMBER: this.selEmp,
      P_MENU_TYPE: this.menuType,
      P_SELECTED_RESP_ID: this.respID,
      P_FUNCTION_NAME: this.functionName,
      P_DESC_FLEX_CONTEXT_CODE: this.desxFlexCode,
      EITTransactionTBL: this.eitTransactionTbl
    }

    this.EITService.validateEITTransaction(this.eitRequest).subscribe((result: any) => {
      this.handleEITValidateTr(result);
    });
  }
  private handleEITValidateTr(result) {
    if (this.cs.validResponse(result)) {
      // public static SHARED_DATA = 'login-request';
      //this.sharedData.setSharedData(this.eitRequest, EitRequest.SHARED_DATA);
      let status = this.ts.trPK("eit", ".deleted");
      let statusID = EIT_ACTION.DELETE;
      this.isDelete = true;
      this.getResEITTransactionList[this.selectedIndex].status = status;
      this.getResEITTransactionList[this.selectedIndex].statusID = statusID;
      this.updateTransactionList(this.eitTransactionTbl, false);
      this.submitEit();
    } else {
      if (this.transactionNo != 0)
        this.transactionNo--;
    }
  }
  updateTransactionList(list, isRemove) {
    //let newlist = this.validEitTransactionTbl.map(a => a.NAME='PEI_EXTRA_INFO_ID');
    let isAnewRow: boolean = false;
    let updateDelTransNo: number;
    if (this.cs.hasData(this.validEitTransactionTbl)) {
      this.validEitTransactionTbl.forEach(element => {
        if (element.NAME == 'PEI_EXTRA_INFO_ID') {
          if (element.NUMBER_VALUE == -1) {
            isAnewRow = true;
            return;
          }
        }
      });
    }
    list.forEach(element => {
      // NAME=PEI_EXTRA_INFO_ID
      //const index = this.validEitTransactionTbl.findIndex(x => x.TRANSACTION_NUMBER === element.TRANSACTION_NUMBER); 
      // let newlist = this.validEitTransactionTbl.map(a => a.NAME==='PEI_EXTRA_INFO_ID');
      if (isAnewRow == true) {
        let index: number = this.validEitTransactionTbl.findIndex(x => x.TRANSACTION_NUMBER === element.TRANSACTION_NUMBER);
        //if(index!=-1)
        //this.validEitTransactionTbl.splice(index, 1); 
      } else {
        let index: number = this.validEitTransactionTbl.findIndex(x => x.NAME === 'PEI_EXTRA_INFO_ID' && x.NUMBER_VALUE === element.NUMBER_VALUE);
        if (index != -1) {
          //this.validEitTransactionTbl.splice(index, 1);
          if (!updateDelTransNo)
            updateDelTransNo = this.validEitTransactionTbl[index].TRANSACTION_NUMBER;
        }
      }

    });
    if (updateDelTransNo)
      this.removeItems(updateDelTransNo);
    if (isRemove == false)
      this.validEitTransactionTbl = this.validEitTransactionTbl ? this.validEitTransactionTbl.concat(list) : list;
  }

  fixTransactionNo(): any[] {
    let list: any = [];
    let newIndex: number = 1;
    let length: number = this.validEitTransactionTbl.length;
    for (let i = 0; i < length; i++) {
      //  let item :any={};
      const item = Object.assign({}, this.validEitTransactionTbl[i]);
      let transNo: number = item.TRANSACTION_NUMBER;
      let obj: any = item;
      if (i == 0) {
        obj.TRANSACTION_NUMBER = newIndex;
        list.push(obj);
      } else {
        let prevEl: any = this.validEitTransactionTbl[i - 1].TRANSACTION_NUMBER;
        if (transNo == prevEl) {
          obj.TRANSACTION_NUMBER = newIndex;
          list.push(obj);
        } else {
          newIndex++;
          obj.TRANSACTION_NUMBER = newIndex;
          list.push(obj);
        }
      }
    }
    return list;
  }
  removeItems(transNo) {
    let list = [];
    for (let i = 0; i < this.validEitTransactionTbl.length; i++) {
      if (this.validEitTransactionTbl[i].TRANSACTION_NUMBER != transNo)
        list.push(this.validEitTransactionTbl[i]);
    }
    this.validEitTransactionTbl = list;
  }
  removeAddedItem(index) {
    let list = [];
    let item: any = [];
    for (let i = 0; i < this.eitAddedList.length; i++) {
      if (i != index)
        list.push(this.eitAddedList[i]);
    }
    item = this.eitAddedList[index];
    this.eitAddedList = list;
    this.removeItems(item.Collection_Transaction[0].TRANSACTION_NUMBER);
  }


}
