import { ChangeDetectorRef, Component, EventEmitter, Input, Output } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { MyPmsSettingAssessmentModel, PmsSettingAssessmentModel } from 'src/app/shared/model/pms-setting-assessment.model';
import { PmsSettingAssessmentService } from 'src/app/shared/services/pms-setting-assessment.service';
@Component({
  selector: 'app-assessment-system-configuration',
  templateUrl: './assessment-system-configuration.component.html',
  styleUrls: ['./assessment-system-configuration.component.scss']
})
export class AssessmentSystemConfigurationComponent {
  setting: { loading: boolean, data: PmsSettingAssessmentModel } = { loading: false, data: new MyPmsSettingAssessmentModel() }
  currentDate = new Date()
  yearList = [
    (this.currentDate.getFullYear() - 1) + "",
    (this.currentDate.getFullYear()) + "",
    (this.currentDate.getFullYear() + 1) + "",
  ]
  constructor(private pmsSettingAssessmentService: PmsSettingAssessmentService,
    private toastr: ToastrService,
    private cdr: ChangeDetectorRef
  ) { }
  ngOnInit(): void {
    this.getSettingList()
  }
  getSettingList() {
    this.setting.loading = true
    this.pmsSettingAssessmentService.get().subscribe({
      next: response => {
        this.setting.data = new MyPmsSettingAssessmentModel(response)
        this.setting.loading = false
        this.cdr.detectChanges()
      }, error: error => {
        this.setting.loading = false
        this.cdr.detectChanges()
      }
    })
  }
  saveSetting() {
    this.setting.loading = true
    this.pmsSettingAssessmentService.post(new MyPmsSettingAssessmentModel({ ...this.setting.data, active: true, expectationLevel: +(this.setting.data.expectationLevel) })).subscribe({
      next: response => {
        if (response.success) {
          this.showAlert(response.message, 'success')
          this.getSettingList()
        } else {
          this.showAlert(response.message, 'error')
          this.setting.loading = false
          this.cdr.detectChanges()
        }
      }, error: error => {
        this.showAlert(error.message, 'error')
        this.setting.loading = false
        this.cdr.detectChanges()
      }
    })
  }

  showAlert(text: string, type: 'success' | 'error') {
    this.toastr[type](text, 'แจ้งเตือน', {
      timeOut: 3000,
      positionClass: 'toast-top-right',
    })
  }

}