import { Component, OnInit, ViewChild } from '@angular/core';
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 { WorkListRequest } from '../models/workListRequest';
import * as moment from 'moment';
import { WorklistService } from '../service/worklist.service';
import { IonInfiniteScroll } from '@ionic/angular';
import { WorklistMainService } from '../service/work-list.main.service';
import { WorklistAdvancedSearchComponent } from '../worklist-advanced-search/worklist-advanced-search.component';
import { DatePipe } from '@angular/common';
import { GetOpenNotificationsResponse } from 'src/app/hmg-common/services/dashbored/models/GetOpenNotificationsResponse';
import { DashboredService } from 'src/app/hmg-common/services/dashbored/dashbored.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  public static REQUSET_NAME = 'requst_name';
  public static REQUSET_INFO = 'requset_info';
  public static ALL_REQUEST = 'all_request';
  public static NOTIFICATION_DATA = 'notification_data';
  public static NOTIFICATION_ARR = 'notification_arr';
  public static NAMES_ALL_iTEMS = 'names-all-items';
  public static IS_ALL_NAME = 'is_all_names';
  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
  private WorkListObj: WorkListRequest;
  WorkListResObj: any;
  notificationType = '1';
  pageNum = 1;
  rowsNo: number;
  noOfrows: number;
  selectedValue = '';
  FromUserName = '';
  ItemKeyDisplayName = '';
  SentDate = '';
  Subject = '';
  inputSearch = '';
  inputDate: string;
  filteredNotificationList: any;
  isReachEnd = false;
  public isAll = true;
  public isPR = false;
  public isPO = false;
  public isMR = false;
  public isHR = false;
  public noData = false;
  public isITG = false;
  public isSearch = false;
  // public direction = 'ltr';
  public direction: string;
  public ITGCount = 0;
  public ITGSegment: { name: string, code: any, data: any, style: boolean, names?: any }[] = [];
  public ITGAllItem: any = [];
  public selectedITGToActive = false;
  public ITGItem: any = [];
  public ITGAllItems: any = [];
  public activeSegment: any;

  public currentActiveIndex = 0;
  public previousActiveIndex = 0;
  public worklistNotifications: any;
  public totalRequestCount = 0;
  public newWorkListResponse = [];
  public showFormattedData = [];
  public allFormattedData = [];
  public selectedFilter = 'ALL';
  public showSearchButton = false;
  public itemType = '';

  public totalHR = 0;
  public totalPO = 0;
  public totalPR = 0;
  public totalMR = 0;

  public showChart = false;
  public isPostNoLoad = true;
  public options = {
    cutoutPercentage: 80,
    tooltips: { enabled: false },
    legend: { display: false }
  };
  public data = {
    datasets: [
      {
        data: [0, 0, 0, 0, 0],
        backgroundColor: [
          '#18a169',
          '#38c9b3',
          '#114475',
          '#3cb9d5',
          '#cc3232'
        ],
        borderWidth: 5
      }]
  };
  public filters = [
    {
      value: 0,
      name: 'All',
      active: true,
      color: '#124375',
      key: 'ALL',
      disable: false
    },
    {
      value: 0,
      name: 'HR',
      active: false,
      color: '#18a169',
      key: 'HRSSA',
      disable: false
    },
    {
      value: 0,
      name: 'PO',
      active: false,
      color: '#38c9b3',
      key: 'POAPPRV',
      disable: false
    },
    {
      value: 0,
      name: 'PR',
      active: false,
      color: '#114475',
      key: 'REQAPPRV',
      disable: false
    },
    {
      value: 0,
      name: 'MR',
      active: false,
      color: '#3cb9d5',
      key: 'INVMOA',
      disable: false
    },
    {
      value: 0,
      name: 'ITG',
      active: false,
      color: '#cc3232',
      key: 'ITG',
      disable: false
    }
  ];
  public slideOptsOne = {
    slidesPerView: 4.3,
    spaceBetween: 10
  };
  public slideOptsTwo = {
    slidesPerView: 1.3,
    spaceBetween: 10
  };
  constructor(
      public common: CommonService,
      public ts: TranslatorService,
      // tslint:disable-next-line: no-shadowed-variable
      public WorklistService: WorklistService,
      public workListService: WorklistMainService,
      public modalController: ModalController,
      public DS: DashboredService
    ) {
      this.WorkListObj = new WorkListRequest();
      this.WorkListObj.P_NOTIFICATION_TYPE = '1';
      this.WorkListObj.P_SEARCH_FROM_USER = '';
      this.WorkListObj.P_SEARCH_SUBJECT = '';
      this.WorkListObj.P_SEARCH_SENT_DATE = '';
      this.WorkListObj.P_SEARCH_ITEM_TYPE_DSP_NAME = '';
      this.WorkListObj.P_PAGE_NUM = 0;
      this.WorkListObj.P_PAGE_LIMIT = 50;
  }

  ngOnInit() {
    this.common.startLoading();
  }

  ionViewWillEnter() {
    console.log(this.filters);
    const loadWorkList = this.common.sharedService.getSharedData('loadWorkList', false);
    if (loadWorkList) {
      this.common.startLoading();
      if (this.infiniteScroll) {
        this.infiniteScroll.complete();
      }
      this.currentActiveIndex = 0;
      this.previousActiveIndex = 0;
      this.itemType = '';
      this.selectedFilter = 'ALL';
      this.isPostNoLoad = true;
      this.disableFilters();
      this.resetData();
      this.direction = TranslatorService.getCurrentLanguageName();
      this.worklistNotifications = this.common.sharedService.getSharedData('worklistNotifications', false);
      this.openNotificationsDashboard();
    }
  }

  callWorkListServices() {
    this.Details();
    this.Count();
    this.getAllPushNotificationFun();
  }

  openNotificationsDashboard() {
    this.DS.getOpenNotifications('', '', this.isPostNoLoad).subscribe((result: GetOpenNotificationsResponse) => {
      if (this.common.validResponse(result)) {
        this.worklistNotifications = result;
        this.totalRequestCount = this.worklistNotifications.P_OPEN_NTF_NUMBER;
        this.common.sharedService.setSharedData(result, 'worklistNotifications');
        this.callWorkListServices();
      }
    });
  }

  assignDataToFilters() {
    this.filters[0].value = this.worklistNotifications.P_OPEN_NTF_NUMBER;
    const openNotificationsArray = this.worklistNotifications.GetOpenNotificationsList;

    for (const notification of openNotificationsArray) {
      if (notification.ITEM_TYPE === 'HRSSA') {
          this.filters[1].value = this.totalHR;
          this.data.datasets[0].data[0] = notification.OPEN_NTF_NUMBER;
      } else if (notification.ITEM_TYPE === 'POAPPRV') {
          this.filters[2].value = this.totalPO;
          this.data.datasets[0].data[1] = notification.OPEN_NTF_NUMBER;
      } else if (notification.ITEM_TYPE === 'REQAPPRV') {
          this.filters[3].value = this.totalPR;
          this.data.datasets[0].data[2] = notification.OPEN_NTF_NUMBER;
      } else if (notification.ITEM_TYPE === 'INVMOA') {
          this.filters[4].value = this.totalMR;
          this.data.datasets[0].data[3] = notification.OPEN_NTF_NUMBER;
      }
      this.data.datasets[0].data[4] = this.ITGCount;
    }
    this.showChart = true;
    this.common.stopLoading();
  }

  activeFilter(index: number) {
    console.log(this.filters);
    if (this.currentActiveIndex !== index) {
      this.previousActiveIndex = this.currentActiveIndex;
      this.currentActiveIndex = index;
      this.filters[this.previousActiveIndex].active = false;
      this.filters[this.currentActiveIndex].active = true;
      this.selectedFilter = this.filters[this.currentActiveIndex].key;
      if (this.selectedFilter !== 'ITG') {
        this.getFilteredData(this.selectedFilter);
      }
    }
  }

  openProfilePage() {
    this.common.openProfile();
  }

  disableFilters() {
    for (const filter of this.filters) {
      if (filter.key === this.itemType) {
        filter.disable = false;
        filter.active = true;
        filter.value = 0;
        this.selectedFilter = filter.name;
      } else if (this.itemType === '') {
        filter.disable = false;
        filter.active = false;
      } else {
        filter.disable = true;
        filter.active = false;
      }
    }
    if (this.itemType === '') {
      this.filters[0].active = true;
    }
  }

  async openSearchModal() {
    const modal = await this.modalController.create({
      component: WorklistAdvancedSearchComponent,
      cssClass: 'advanced-search-modal-custom',
      backdropDismiss: false,
      componentProps: {}
    });
    modal.onDidDismiss().then(result => {
      if (result.data) {
          if (result.data.notificationType !== '' || result.data.selectedValue !== '' || result.data.itemType !== '') {
            this.common.startLoading();
            this.showSearchButton = true;
            this.itemType = result.data.itemType;
            this.notificationType = result.data.notificationType;
            this.selectedValue = result.data.selectedValue;
            this.inputDate = result.data.inputDate;
            this.inputSearch = result.data.inputSearch;
            this.WorkListObj.P_PAGE_NUM = 1;
            this.newWorkListResponse = [];
            this.showFormattedData = [];
            this.selectedFilter = 'ALL';
            this.filters[this.currentActiveIndex].active = false;
            this.currentActiveIndex = 0;
            this.previousActiveIndex = 0;
            this.filters[this.currentActiveIndex].active = true;
            if (this.itemType !== '') {
              this.disableFilters();
            }
            this.isPostNoLoad = false;
            this.getAllPushNotificationFun();
        }
      }
    });
    return await modal.present();
  }

  getAllPushNotificationFun() {
      this.WorkListObj.P_PAGE_NUM = 1;
      this.isReachEnd = false;
      this.WorkListObj.P_SEARCH_FROM_USER = this.selectedValue === '1' ? this.inputSearch : '';
      this.WorkListObj.P_SEARCH_SUBJECT = this.selectedValue === '2' ? this.inputSearch : '';
      this.WorkListObj.P_SEARCH_SENT_DATE = (this.inputDate && this.selectedValue === '3')
       ? moment(this.inputDate).format('DD-MMM-YYYY') : '';
      this.WorkListObj.P_SEARCH_ITEM_TYPE_DSP_NAME = this.selectedValue === '4' ? this.inputSearch : '';
      this.WorkListObj.P_ITEM_TYPE = this.itemType !== '' ? this.itemType : '';
      this.WorkListObj.P_NOTIFICATION_TYPE = this.notificationType !== '' ? this.notificationType : '1';
      if (this.selectedValue === '5') {
        this.WorkListObj.P_SEARCH_FROM_USER = '';
        this.WorkListObj.P_SEARCH_ITEM_TYPE_DSP_NAME = '';
        this.WorkListObj.P_SEARCH_SENT_DATE = '';
        this.WorkListObj.P_SEARCH_SUBJECT = '';
      }
      this.WorklistService.getWorkList(this.WorkListObj, '', '', this.isPostNoLoad).subscribe((result) => {
           if (this.common.validResponse(result)) {
              this.handleWorkListResult(result.GetWorkList);
           }
        }
      );
  }

  getFilteredData(filter: string) {
    if (filter === 'ALL') {
      this.showFormattedData = this.allFormattedData;
    } else {
        let arrayToFilter;
        arrayToFilter = this.newWorkListResponse.filter((workList) => {
          return workList.ITEM_TYPE === filter;
        });
        const categorizeData = this.categorizeData(arrayToFilter);
        this.showFormattedData =  this.sortArray(categorizeData);
        // const sortData = this.sortArray(arrayToFilter);
        // this.showFormattedData =  this.categorizeData(sortData);
    }
  }

  checkDateExistance(currentDate: any, formattedData: any) {
    let existsBefore = false;
    let index = 0;
    for (let i = 0; i < formattedData.length; i++) {
        if (formattedData[i].date === currentDate) {
            existsBefore = true;
            index = i;
            break;
        }
    }
    return {
      exists: existsBefore,
      indexNumber: index
    };
  }

  addCountInFilters(workList: any) {
    if (workList.ITEM_TYPE === 'HRSSA') {
      this.totalHR = this.totalHR + 1;
    } else if (workList.ITEM_TYPE === 'POAPPRV') {
        this.totalPO = this.totalPO + 1;
    } else if (workList.ITEM_TYPE === 'REQAPPRV') {
      this.totalPR = this.totalPR + 1;
    } else if (workList.ITEM_TYPE === 'INVMOA') {
      this.totalMR = this.totalMR + 1;
    }
  }

  categorizeData(arrayToCategorize: any) {
        this.totalHR = 0;
        this.totalPO = 0;
        this.totalPR = 0;
        this.totalMR = 0;

        const datePipe = new DatePipe('en-US');
        const formattedData = [];
        for (const workList of arrayToCategorize) {
            this.addCountInFilters(workList);
            const currentDate = datePipe.transform(new Date(workList.BEGIN_DATE), 'MMMM dd, y');
            const currentObject = {
            date: '',
            data: []
          };
            if (formattedData.length === 0) {
              currentObject.date = currentDate;
              currentObject.data.push(workList);
              formattedData.push(currentObject);
          } else {
            const existsBefore = this.checkDateExistance(currentDate, formattedData);
            if (existsBefore.exists) {
              formattedData[existsBefore.indexNumber].data.push(workList);
            } else {
              currentObject.date = currentDate;
              currentObject.data.push(workList);
              formattedData.push(currentObject);
            }
          }
      }
        return formattedData;
  }

  sortArray(arrayToSort: any) {
    return arrayToSort.sort((a: any, b: any) =>
        new Date(b.date).getTime() - new Date(a.date).getTime()
    );
  }

  private handleWorkListResult(result: any) {
    console.log(this.filters);
    const lastItemIndex = result.length - 1;
    const lastitem = result[lastItemIndex];
    if (lastitem) {
      if (lastitem.NO_OF_ROWS === lastitem.ROW_NUM) {
        this.isReachEnd = true;
        if (this.infiniteScroll) {
          this.infiniteScroll.complete();
        }
      } else {
        this.isReachEnd = false;
        if (this.infiniteScroll) {
          this.infiniteScroll.complete();
        }
      }
    }
    if (this.common.hasData(result)) {
      this.WorkListObj.P_PAGE_NUM++;
      if (this.newWorkListResponse.length === 0) {
        this.newWorkListResponse = result;
      } else {
        this.newWorkListResponse = this.newWorkListResponse.concat(result);
      }
      let categorizedWorkListResponse = [];
      categorizedWorkListResponse = this.categorizeData(this.newWorkListResponse);
      if (categorizedWorkListResponse.length > 0) {
        this.showFormattedData = this.sortArray(categorizedWorkListResponse);
        this.allFormattedData = this.showFormattedData;
        this.common.sharedService.setSharedData(this.newWorkListResponse, HomeComponent.NOTIFICATION_ARR);
        this.assignDataToFilters();
      }
    } else {
      this.newWorkListResponse = [];
      this.data.datasets[0].data[4] = this.ITGCount;
      this.showChart = true;
      this.common.stopLoading();
    }
  }

  openNotificationDetail(obj) {
      this.common.sharedService.setSharedData(false, 'loadWorkList');
      this.common.sharedService.setSharedData(obj, HomeComponent.NOTIFICATION_DATA);
      if (obj.REQUEST_TYPE === 'PR') {
      this.common.openWorklistMainPRPage();
      } else if (obj.REQUEST_TYPE === 'PO') {
        this.common.openWorklistMainPOPage();
        } else if (obj.REQUEST_TYPE === 'MO') {
        this.common.openWorklistMainMRPage();
        } else {
        this.common.openWorklistMainPage();
      }
  }

  resetData() {
    if (this.infiniteScroll) {
      this.infiniteScroll.complete();
    }
    this.showSearchButton = false;
    this.notificationType = '1';
    this.selectedValue = '';
    this.inputDate = '';
    this.inputSearch = '';
    this.newWorkListResponse = [];
    this.showFormattedData = [];
    this.allFormattedData = [];
    this.WorkListObj.P_SEARCH_FROM_USER = '';
    this.WorkListObj.P_SEARCH_ITEM_TYPE_DSP_NAME = '';
    this.WorkListObj.P_SEARCH_SENT_DATE = '';
    this.WorkListObj.P_SEARCH_SUBJECT = '';
  }

  // initializeWorkList() {

  // }

  clearSearch() {
    this.common.startLoading();
    this.itemType = '';
    this.selectedFilter = 'ALL';
    this.isPostNoLoad = true;
    this.disableFilters();
    this.resetData();
    this.getAllPushNotificationFun();
  }

  doInfinite(infiniteScroll) {
    if (!this.isReachEnd && this.selectedFilter !== 'ITG') {
      this.common.startLoading();
      this.WorklistService.getWorkList(this.WorkListObj, '', '', this.isPostNoLoad).subscribe((result) => {
        if (this.common.validResponse(result)) {
          this.handleWorkListResult(result.GetWorkList);
        }
      });
    } else {
      if (this.infiniteScroll) {
        this.infiniteScroll.complete();
      }
    }
  }

  Count() {
    const datas = [];
    const names = [];
    this.workListService.getITGCount('', '', this.isPostNoLoad) 
      .subscribe((result: any) => {
        if(result.RequestType.length > 0){
          this.ITGSegment[0] = {
            name: 'All',
            code: 'All',
            data: null,
            style: false
          };
          this.ITGSegment[0].data = datas;
          this.ITGSegment[0].names = names;
          this.setActive(this.ITGSegment[0].code);
        }
        console.log(result.RequestType);
        let count =1;
        for (let i = 0; i < result.RequestType.length; i++) {
          console.log()
          this.ITGSegment[count] = {
            name: result.RequestType[i].RequestTypeName,
            code: result.RequestType[i].RequestTypeCode,
            data: result.RequestType[i].RequestDetails,
            style: false
          };
          datas[i] = result.RequestType[i].RequestDetails;
          names[i] = result.RequestType[i].RequestTypeCode;
          count++;
        }
        //this.sortArrayOfAll(this.ITGSegment[0].data)
        console.log(this.ITGSegment);

      });
  }

  Details() {
    this.workListService.getITGDetails('', '', this.isPostNoLoad)
      .subscribe((result: any) => {
        this.ITGCount = result.TotalCount;
        this.totalRequestCount = this.totalRequestCount + result.TotalCount;
        this.filters[5].value = result.TotalCount;
      });
  }

  searchBtn() {
    this.isSearch = !this.isSearch;
  }

  setActive(selectedSegment) {
    this.ITGItem = [];
    let count = 0;
    this.activeSegment = selectedSegment;
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < this.ITGSegment.length; i++) {
      if (this.ITGSegment[i].code === selectedSegment) {
        this.ITGSegment[i].style = true;
        this.ITGItem[count] = this.ITGSegment[i].data;
        count++;
      } else {
        this.ITGSegment[i].style = false;
      }
    }
    console.log(this.ITGSegment);
  }


  openITG(segmentInfo, name?) {
    if (name) {
      this.common.sharedService.setSharedData(name, HomeComponent.REQUSET_NAME);
      this.common.sharedService.setSharedData(this.ITGSegment, HomeComponent.NAMES_ALL_iTEMS);
      this.common.sharedService.setSharedData(true, HomeComponent.IS_ALL_NAME);
    } else {
      this.common.sharedService.setSharedData(this.activeSegment, HomeComponent.REQUSET_NAME);
      this.common.sharedService.setSharedData(false, HomeComponent.IS_ALL_NAME);
    }
    this.common.sharedService.setSharedData(segmentInfo, HomeComponent.REQUSET_INFO);
    this.common.sharedService.setSharedData(this.ITGItem, HomeComponent.ALL_REQUEST);
    this.common.sharedService.setSharedData(false, 'loadWorkList');
    this.common.openWorklistITGPage();
  }

  openITGAll(id, item) {
    let count = 0;
    let ITEM: any;
    let NAME: any;
    for (let i = 1; i < this.ITGSegment.length; i++) {
      // tslint:disable-next-line: prefer-for-of
      for (let j = 0; j < this.ITGSegment[i].data.length; j++) {
        if (this.ITGSegment[i].data[j].ID === id && this.ITGSegment[i].data[j].ItemID === item) {
          ITEM = this.ITGSegment[i].data[j];
          NAME = this.ITGSegment[i].code;
          count++;
        }
      }
    }
    this.openITG(ITEM, NAME);
  }
}
