import { Component, OnInit, ViewChild } 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 { MenuResponse } from "src/app/hmg-common/services/menu/models/menu-response";
import { MenuService } from "src/app/hmg-common/services/menu/menuservice.service";
import { AbsenceAttahcmentResponse } from "../models/abs.attach.response";
import { AbsenceListService } from "../service/service.service";
import { IonInfiniteScroll } from "@ionic/angular";
import { AccrualService } from 'src/app/accrual-balances/services/accrual.service';
import { AuthenticationService } from 'src/app/hmg-common/services/authentication/authentication.service';
import { AuthenticatedUser } from 'src/app/hmg-common/services/authentication/models/authenticated-user';

@Component({
  selector: "app-home",
  templateUrl: "./home.component.html",
  styleUrls: ["./home.component.scss"]
})
export class HomeComponent implements OnInit {
  [x: string]: any;
  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
  P_PAGE_NUM: number;
  P_PAGE_LIMIT: number;
  GetAbsenceTransactionList: any;
  IsReachEnd: boolean = false;
  selEmp: string = "";
  respID: number;
  selMenu: MenuResponse;
  leaveAccrualBalance: any;
  data: any;
  accrualNet: any;
  getleaveAccrualBalance: any;
  accrualUsed: any;
  accrualYearly: any;
  effectiveDate: any;
  Sdate: any;
  emp_no: any;
  balance: any;
  ACCRUAL_NET_ENTITLEMENT: any;
  ACCRUAL_USED_ENTITLEMENT: any;
  ACCRUAL_YEARLY_ENTITLEMENT: any;
  totalnumber: any;
  public direction: string;

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

  constructor(
    public common: CommonService,
    public ts: TranslatorService,
    public menuService: MenuService,
    public absService: AbsenceListService,
    public accrualService: AccrualService,
    public authService: AuthenticationService
  ) {
    this.direction = TranslatorService.getCurrentDirection();
    //  this.userData =this.common.sharedService.getSharedData(AuthenticatedUser.SHARED_DATA,false);
  }

  ngOnInit() {

    this.Sdate = new Date().toISOString();

    this.getUserDetails();
    this.getAccrualBalance();
  }
  private getUserDetails() {
    this.authService.loadAuthenticatedUser().subscribe((user: AuthenticatedUser) => {
      if (user) {
        // this.emp_no=user.EMPLOYEE_NUMBER;
        // this.getAccrualBalance();
      }
    });




    this.P_PAGE_LIMIT = 50;
    this.P_PAGE_NUM = 1;
    this.selMenu = this.common.sharedService.getSharedData(
      MenuResponse.SHARED_DATA,
      false
    );
    this.selEmp = this.common.sharedService.getSharedData(
      MenuResponse.SHARED_SEL_EMP,
      false
    );
    this.respID = this.common.sharedService.getSharedData(
      MenuResponse.SHARED_SEL_RESP_ID,
      false
    );
    this.leaveAccrualBalance = this.common.sharedService.getSharedData('leaveAccrualBalance', false);
    console.log("this.leaveAccrualBalance>>>>>>>>>>" + this.leaveAccrualBalance.ACCRUAL_NET_ENTITLEMENT);
    /*** 
    ACCRUAL_NET_ENTITLEMENT: 24.59
    ACCRUAL_USED_ENTITLEMENT: 0
    ACCRUAL_YEARLY_ENTITLEMENT: 50.4*/
    this.accrualNet = this.leaveAccrualBalance.ACCRUAL_NET_ENTITLEMENT;
    this.accrualUsed = this.leaveAccrualBalance.ACCRUAL_USED_ENTITLEMENT;
    this.accrualYearly = this.leaveAccrualBalance.ACCRUAL_YEARLY_ENTITLEMENT;
    this.totalnumber = this.accrualNet + this.accrualUsed + this.accrualYearly;
    this.totalnumber = this.totalnumber.toFixed(3);
    this.request = this.common.sharedService.getSharedData('leaveAccrualBalanceDate', false);
    console.log("this.request" + this.request.P_EFFECTIVE_DATE);
    this.effectiveDate = this.request.P_EFFECTIVE_DATE;
    this.data = {
      // labels: ['earingTotal', 'deductionTotal'],
      datasets: [
        // { data: [this.accrualNet,this.accrualYearly,this.accrualUsed],
        {
          data: [this.accrualNet, this.accrualUsed],
          backgroundColor: [
            // '#1FA269',
            // '#CB3232',],
            '#269DB8',
            '#b60c0c',],
          borderWidth: 1
        }
      ]
    };

    this.getAbsenceTransaction();
  }



  AccrualBalances() {
    this.common.openAccuralPage();
  }
  AttachmentDocuments(id) {
    const request = {
      P_ABSENCE_ATTENDANCE_ID: id
    };
    this.absService
      .getAbsenceAttachment(request)
      .subscribe((result: AbsenceAttahcmentResponse) => {
        this.handleAbsAttachResult(result);
      });
  }

  private handleAbsAttachResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.GetAbsenceAttachmentsList)) {
        this.common.sharedService.setSharedData(
          result.GetAbsenceAttachmentsList,
          AbsenceAttahcmentResponse.SHARED_DATA
        );
        this.common.openviewAbsenceAttachment();
        // this.navCtrl.push("AbsenceAttachmentPage");
      } else {
        let msg: string = "";
        msg = this.ts.trPK("general", "noFileSelect");
        this.common.presentAlert(msg);
      }
      //this.GetAbsenceTransactionList =result.GetAbsenceTransactionList;
    }
  }
  getAbsenceTransaction() {
    this.IsReachEnd = false;
    const request = {
      P_SELECTED_EMPLOYEE_NUMBER: this.selEmp,
      P_MENU_TYPE: this.selMenu.List_Menu.MENU_TYPE,
      P_SELECTED_RESP_ID: this.respID,
      P_PAGE_NUM: this.P_PAGE_NUM,
      P_PAGE_LIMIT: this.P_PAGE_LIMIT
    };
    this.absService.getAbsenceList(request).subscribe((result: any) => {
      this.handleAbsListResult(result);
    });
  }

  handleAbsListResult(result) {
    if (this.common.validResponse(result)) {
      if (this.common.hasData(result.GetAbsenceTransactionList)) {
        this.GetAbsenceTransactionList = result.GetAbsenceTransactionList;
        this.P_PAGE_NUM++;
        let lastItemIndex = this.GetAbsenceTransactionList.length - 1;
        if (result.GetAbsenceTransactionList[lastItemIndex]) {
          let lastitem = result.GetAbsenceTransactionList[lastItemIndex];
          if (lastitem.NO_OF_ROWS == lastitem.ROW_NUM) {
            this.IsReachEnd = true;
          } else {
            this.IsReachEnd = false;
          }
        }
      }
    }
  }
  doInfinite(event: any) {
    if (!this.IsReachEnd) {
      // this.P_PAGE_NUM++;
      const request = {
        P_SELECTED_EMPLOYEE_NUMBER: this.selEmp,
        P_MENU_TYPE: this.selMenu.List_Menu.MENU_TYPE,
        P_SELECTED_RESP_ID: this.respID,
        P_PAGE_NUM: this.P_PAGE_NUM,
        P_PAGE_LIMIT: this.P_PAGE_LIMIT
      };
      this.absService.getAbsenceList(request).subscribe(
        (result: any) => {
          if (this.common.validResponse(result)) {
            if (this.common.hasData(result.GetAbsenceTransactionList)) {
              this.P_PAGE_NUM++;
              result.GetAbsenceTransactionList.forEach(vr => {
                if (vr.ROW_NUM == vr.NO_OF_ROWS) {
                  this.IsReachEnd = true;
                } else {
                  this.IsReachEnd = false;
                }
                this.GetAbsenceTransactionList.push(vr);
              });
            } else {
              this.IsReachEnd = true;
            }
          }
          if (this.infiniteScroll) {
            this.infiniteScroll.complete();
          }
        },
        Error => console.log(Error),
        () => this.infiniteScroll.complete()
      );
    } else {
      if (this.infiniteScroll) {
        this.infiniteScroll.complete();
      }
    }
  }
  createAbsence() {
    this.common.openSubmitAbsencePage();
  }

  ///////////////////////////////////////////////////////////////
  getAccrualBalance() {
    if (this.Sdate) {
      let today = new Date(this.Sdate);
      let day = today.getDate();
      let month = today.getMonth() + 1;
      let year = today.getFullYear();
      let todayDate = month + '/' + day + '/' + year;
      let effectiveDate = todayDate;
      const request = {
        P_SELECTED_EMPLOYEE_NUMBER: this.selEmp,
        P_EFFECTIVE_DATE: effectiveDate
      };

      this.accrualService
        .getAccrualBalances(request)
        .subscribe((result: any) => {
          this.handleAccrualResult(result);
        });
    }
  }

  handleAccrualResult(result) {
    if (this.common.validResponse(result)) {
      this.balance = result.GetAccrualBalancesList;
    }
    if (this.balance) {
      this.accrualNet = this.balance[0].ACCRUAL_NET_ENTITLEMENT;
      this.accrualUsed = this.balance[0].ACCRUAL_USED_ENTITLEMENT;
      // this.accrualYearly = this.balance[0].ACCRUAL_YEARLY_ENTITLEMENT; 
      // this.totalnumber= this.accrualNet +  this.accrualUsed + this.accrualYearly;
      this.totalnumber = this.accrualNet + this.accrualUsed;
      this.totalnumber = this.totalnumber.toFixed(3);
      this.data = {
        // labels: ['earingTotal', 'deductionTotal'],
        datasets: [
          // {  data: [this.accrualNet,this.accrualYearly,this.accrualUsed],
          {
            data: [this.accrualNet, this.accrualUsed],
            backgroundColor: [
              '#269DB8',
              '#b60c0c',],
            borderWidth: 1
          }
        ]
      };

    }
  }
}
