Untitled

 avatar
unknown
plain_text
4 years ago
9.2 kB
5
Indexable
import { Component, ViewChild } from '@angular/core';
import { SiteData } from '../providers/site-data';
import { Router } from '@angular/router';
import { Storage } from '@ionic/storage';
import { Events } from '../providers/events/events.service';
import { ActionSheetController, AlertController, ToastController } from '@ionic/angular';
import { TranslateService } from '@ngx-translate/core';
import { Subscription } from 'rxjs';
import { SitesService } from '../providers/sites/sites.service';
import { SystemService } from '../providers/system.service';
import { IonInfiniteScroll } from '@ionic/angular';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
  @ViewChild(IonInfiniteScroll) infiniteScroll: IonInfiniteScroll;
  _companyType = localStorage.getItem('company_type');
  _loading: boolean = false;
  _sites: any = [];
  _initializedSites: any = [];
  allSiteDataSub: Subscription;
  allSiteDataServerSub: Subscription;
  _sitesSkeleton = [
    'primary', 'secondary', 'warning', 'tertiary', 'primary', 'secondary', 'warning', 'tertiary', 'primary', 'secondary', 'warning', 'tertiary'
  ];

  page = 1;
  constructor(
    private _siteData: SiteData,
    private _router: Router,
    private _storage: Storage,
    private _events: Events,
    public _actionSheetController: ActionSheetController,
    private _alertController: AlertController,
    private _translate: TranslateService,
    private _siteService: SitesService,
    private _toastController: ToastController,
    private _systemService: SystemService
  ) {
    this._events.subscribe('sites:update', (data: any) => {
      this._sites = [];
      this.ionViewWillEnter();
    });
  }
  ngOnInit() {
    
  }

  ionViewWillEnter() {
    this.getAllSiteDataFromServer();
  }

  ionViewWillLeave(){
    this._sites = [];
  }

  getAllSiteDataFromServer() {
    let skip = (this.page - 1) * 10;
    let take = 10;

    let filterData = {
      skip: skip,
      take: take 
    };
    this._loading = true;
    this.allSiteDataServerSub = this._siteService.getAllSiteDataFromServer(filterData).subscribe(
      res => {
        let data = res.data;

        for ( let i = 0; i < res.data.length; i++ ) {
          this._initializedSites.push(data[i]);
          this._sites.push(data[i]);
        }

        this._loading = false;

        if ( data.length === 0 ) {
          this.infiniteScroll.disabled = true;
        } else {   
          this.page++;
        }

      },
      err => {
        this._loading = false;
        console.log("SitePage == getAllSiteDataFromServer == error = ", err);
        this.infiniteScroll.disabled = true;
      }
    );
  }

  getAllSiteData() {
    this._siteService.getAllSiteData().subscribe(
      res => {
          // console.log("SitePage == getAllRegionData == response (was not null) = ", res);

          for ( let i = 0; i < res.length; i++ ) {
            this._initializedSites.push(res[i]);
            this._sites.push(res[i]);
          }
          
          console.log(this._sites);
          //this._sites = res;
          //this._initializedSites = res;
          //this.initializeSites();  
      },
      err => {
        console.log("SitePage == getAllSiteData == error = ", err);
      }
    );
  }

  loadData(event) {
    setTimeout(() => {
      event.target.complete();
      this.getAllSiteDataFromServer();
    }, 500);
  }

  openThemesPage(siteName, companyId, siteId, siteChecked) {
    //console.log(siteChecked);
    localStorage.setItem('site_name', siteName);
    localStorage.setItem('site_checked', siteChecked);
    this._router.navigateByUrl('/themes/' + siteName + '/' + companyId + '/' + siteId);
  }

  async presentAlert(header, subtitle, message) {
    const alert = await this._alertController.create({
      cssClass: 'my-custom-class',
      header: header,
      subHeader: '',
      message: message,
      buttons: ['OK']
    });

    await alert.present();
  }


  async presentActionSheet(siteIndex) {
    const actionSheet = await this._actionSheetController.create({
      header: this._translate.instant('SITES.ACTIONS'),
      cssClass: 'my-custom-class',
      buttons: [{
        text: this._translate.instant('SITES.CONFORMITY'),
        icon: 'bar-chart-outline',
        handler: () => {
          if ( this._sites[siteIndex].checked ){
            this._router.navigateByUrl('/conformity/' + this._sites[siteIndex].id);
          } else {
            this.presentAlert(this._translate.instant('SITES.ALERT'), "Information", this._translate.instant('SITES.MESSAGE'));
          }
          
        }
      }, {
        text: this._translate.instant('SITES.KO_QUESTIONS'),
        icon: 'help-outline',
        handler: () => {
          if ( this._sites[siteIndex].checked ) {
            this._router.navigateByUrl('/site-ko-questions/' + this._sites[siteIndex].id + '/' + this._sites[siteIndex].name);
          } else {
            this.presentAlert(this._translate.instant('SITES.ALERT'), "Information", this._translate.instant('SITES.MESSAGE'));
          }
        }
      },
      {
        text: this._translate.instant('SITES.HISTORY'),
        icon: 'help-outline',
        handler: () => {
          this._router.navigateByUrl('/history/' + this._sites[siteIndex].id + '/' + this._sites[siteIndex].name);
        }
      },
      {
        text: this._translate.instant('SITES.RECHECK'),
        icon: 'help-outline',
        handler: () => {
          if ( this._sites[siteIndex].checked ) {
            this.recheckSite(this._sites[siteIndex].id);
          } else {
            this.presentAlert(this._translate.instant('SITES.ALERT'), "Information", this._translate.instant('SITES.MESSAGE_RECHECK'));
          }
        }
      },
      {
        text: this._translate.instant('SITES.REPORT'),
        icon: 'document',
        handler: () => {
          if ( this._sites[siteIndex].site_visit_id ) {
            location.href = this._systemService.apiWebURL + 'company/site/pdf/report' + '/' + this._sites[siteIndex].company.id + '/' + this._sites[siteIndex].id + '/' + this._sites[siteIndex].site_visit_id + '/' + localStorage.getItem('language');
          } else {
            this.presentAlert(this._translate.instant('SITES.ALERT'), "Information", this._translate.instant('SITES.MESSAGE_RECHECK'));
          }
        }
      },{
        text: this._translate.instant('ACTION_PLAN.ACTION_PLAN_REPORT'),
        icon: 'document',
        handler: () => {
          if ( this._sites[siteIndex].site_visit_id ) {
            location.href = this._systemService.apiRootURL + 'pdf/action-plan/' + this._sites[siteIndex].id + '/' + localStorage.getItem('language');
          } else {
            this.presentAlert(this._translate.instant('SITES.ALERT'), "Information", this._translate.instant('SITES.MESSAGE_RECHECK'));
          }
        }
      }, {
        text: this._translate.instant('SITES.CANCEL'),
        icon: 'close',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }

  async recheckSite(siteId) {
    const alert = await this._alertController.create({
      cssClass: 'my-custom-class',
      header: this._translate.instant('SITES.CONFIRM'),
      message: this._translate.instant('SITES.SURE'),
      buttons: [
        {
          text: this._translate.instant('SITES.CANCEL'),
          role: 'cancel',
          cssClass: 'secondary',
          handler: (blah) => {
            console.log('Confirm Cancel: blah');
          }
        }, {
          text: this._translate.instant('SITES.YES'),
          handler: () => {
            this._siteService.recheckSite(siteId).subscribe(async res => {
              if ( res.status == '0' ) {
                const toast = await this._toastController.create({
                  message: 'Site has been rechecked',
                  duration: 2000
                });
                toast.present();
                this.ionViewWillEnter();
              } else {
                const toast = await this._toastController.create({
                  message: 'Something went wrong, please try again!',
                  duration: 2000
                });
                toast.present();
              }
            }, async error => {
              const toast = await this._toastController.create({
                message: 'Something went wrong, please try again!',
                duration: 2000
              });
              toast.present();
            });
          }
        }
      ]
    });

    await alert.present();
  }

  initializeSites() {
    this._sites = this._initializedSites;
  }

  getSites(ev: any) {

    this.initializeSites();
    
    // set val to the value of the searchbar
    const val = ev.target.value;

    // if the value is an empty string don't filter the items
    if (val && val.trim() != '') {
      this._sites = this._sites.filter((item) => {
        //return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
        return (item.name.toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

}
Editor is loading...