import { Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef } from '@angular/core';
import { throwError } from 'rxjs';
import { catchError, filter, tap } from 'rxjs/operators';
import { BaseList } from 'src/app/core/base/base-list';
import { StudentPaymentService } from 'src/app/core/service/student-payment/student-payment.service';
import { StudentPaymentUploadService } from 'src/app/core/service/student-payment/student-upload.service';
import { SweetalertService } from 'src/app/core/service/sweetalert/sweetalert';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListComponent extends BaseList implements OnInit {
  @Input() importList: any = [];
  column = ['1','2','3','4','5','6']
  selectfile;
  data;
  confirmData;
  constructor(
    private studentUploadSV: StudentPaymentUploadService,
    private swSV: SweetalertService,
    private cdr: ChangeDetectorRef,
    private studentPaymentSV: StudentPaymentService
  ) {
    super()
   }

  ngOnInit(): void {
  }

  save(){
    this.studentUploadSV.confirm(this.confirmData).pipe(
      tap(x => console.log(x)),
      tap(x => this.swSV.saveSuccess()),
      tap(x => this.clear()),
      catchError(err => {
        this.swSV.errText('บันทึกไม่สำเร็จ')
        return throwError(err)
      })
    ).subscribe()
  }

  clear(){
    this.data = []
    this.confirmData = null
    this.cdr.detectChanges()
    console.log(this.confirmData)
  }

  onSelectFile(event) {
    if (event.target.files && event.target.files[0]) {
      this.selectfile = event.target.files[0];
      this.upload()
    }
  }

  upload(){
    const formData: FormData = new FormData();
    formData.append('file', this.selectfile, this.selectfile.name);
    this.studentUploadSV.uploadDocument(formData).pipe(
      filter((x:any) => x.status == 'success'),
      tap(x => this.confirmData = x.message),
      tap(x => this.data = x.message.bill_receivable_items),
      tap(x => this.data = this.updateMatTable(this.data)),
      tap(x => this.cdr.detectChanges()),
      catchError(err => {
        this.swSV.errText('มีข้อผิดพลาดในการนำเข้า')
        return throwError(err)
      })
    ).subscribe()
  }

}
