import { formatDate } from '@angular/common';
import { Component, OnInit, ChangeDetectionStrategy, Input } from '@angular/core';
import { Router } from '@angular/router';
import { tap } from 'rxjs/operators';
import { CardPrintingService } from 'src/app/core/service/card-print/card-printing.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';
import { createQueryStringFromObject } from 'src/app/shared/util/func';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SearchComponent implements OnInit {
  @Input() testingInfo: any = [];
  @Input() branch: any = [];
  query = {
    testing_information_uid: null,
    branch_uid: null,
    testing_date: null
  }
  constructor(
    private router: Router,
    private cardSV: CardPrintingService,
    private swSV: SweetalertService
  ) { }

  ngOnInit(): void {
    // console.log(this.branch)
    // console.log(this.testingInfo)
  }

  onSearch(){
    this.query.testing_date = formatDate(this.query.testing_date, 'yyyy-MM-dd', 'en-US')
    const query = createQueryStringFromObject(this.query)
    // this.router.navigate(["print-exam-card/info"])
    this.cardSV.search('?'+query).pipe(
      tap((x:any) => {
        if(x.length == 0) this.swSV.errText('ไม่พบข้อมูล')
        if(x.length != 0){
          this.router.navigate(["print-exam-card/info"])
          this.cardSV.studentList = x
        }
      })
    ).subscribe()
  }

  display(item:string){
    if (item) return this.testingInfo.find(x => x.testing_information_uid == item)?.testing_information_name
  }

  displayBranch(item:string){
    if (item) return this.branch.find(x => x.branch_uid == item)?.branch_name_th
  }

}
