import {Component, OnInit, ChangeDetectionStrategy, Input, ChangeDetectorRef, ViewChild} from '@angular/core';
import {BaseForm} from "../../../../../core/base/base-form";
import {Form, FormArray, FormBuilder, FormGroup, Validators} from "@angular/forms";
import {MatDialog} from "@angular/material/dialog";
import {ActivatedRoute, Router} from "@angular/router";
import {Location} from "@angular/common";
import {tap} from "rxjs/operators";
import {RoomInvigilatorsService} from "../../../../../core/service/testing-information/room-invigilators.service";
import {SweetalertService} from "../../../../../core/service/sweetalert/sweetalert";
import { UserOpenidService } from 'src/app/core/service/openid/user.service';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { TestingInformationService } from 'src/app/core/service/testing-information/testing-information.service';
import { isBuffer } from 'util';

// @ts-ignore
@Component({
  selector: 'app-manage-exam-officer-detail',
  templateUrl: './manage-exam-officer-detail.component.html',
  styleUrls: ['./manage-exam-officer-detail.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ManageExamOfficerDetailComponent extends BaseForm implements OnInit  {
  @ViewChild(MatSort,{ static: true }) sort: MatSort;
  @ViewChild(MatPaginator,{ static: true }) paginator: MatPaginator;
  protected updateMatTable(res: any){
      res = new MatTableDataSource(res)
      res.paginator = this.paginator
      res.sort = this.sort
      return res
  }
  exam_date;
  testingInfoData;
  list: any = [];
  specialList: any = [];
  userList: any = [];
  constructor(
    public fb: FormBuilder,
    private swSV: SweetalertService,
    private dialog: MatDialog,
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private cdr: ChangeDetectorRef,
    private roomInvigilatorSV: RoomInvigilatorsService,
    private userOpenidSV: UserOpenidService,
    private testingInformationSV: TestingInformationService
  ) {
    super(router,activeRoute,fb,location);
  }

  ngOnInit(): void {
    this.form.valueChanges.pipe(
      tap(x => this.list = this.updateMatTable(x.invigilator_list)),
    ).subscribe()
    this.userOpenidSV.getAll().pipe(tap(x => this.userList = x)).subscribe()
    this.roomInvigilatorSV.search(`?testing_information_uid=${this.id}`).pipe(
      tap(x => this.setupForm(x)),
    ).subscribe()
    this.testingInformationSV.get(this.id).pipe(
      tap(x => this.testingInfoData = x),
      tap(x => this.cdr.detectChanges())
    ).subscribe()
  }

  setupForm(data){
    const dataReduce = data.reduce((a,c) => {
      if(a[c.examination_date]){
        a[c.examination_date].invigilator_list.push(c)
      }else{
        a[c.examination_date] = {
          examination_date : c.examination_date,
          invigilator_list: [c]
        }
      }
      return a;
    },{})
    const newData = Object.values(dataReduce)
    const invigilator_form = this.form.get('invigilator_list') as FormArray
    const special_list_form = this.form.get('special_list') as FormArray
    newData.map((x:any) => {
      if(x.examination_date){
        special_list_form.push(this.updateSpecialList(x))
      }else{
        x.invigilator_list.map(a => invigilator_form.push(this.createUpdateInvigilatorForm(a)))
      }
    })
    this.cdr.detectChanges()
  }

  createForm(){
    return this.fb.group({
      invigilator_list: this.fb.array([],Validators.required),
      special_list: this.fb.array([])
    })
  }

  addSpecial(){
    const form = this.form.get('special_list') as FormArray
    form.push(this.createSpecialList())
  }

  createSpecialList(){
    return this.fb.group({
      examination_date: [null,Validators.required],
      invigilator_list: this.fb.array([],Validators.required)
    })
  }

  updateSpecialList(data){
    return this.fb.group({
      examination_date: data.examination_date,
      invigilator_list: this.fb.array(data.invigilator_list.map(x => this.createUpdateInvigilatorForm(x)))
    })
  }

  addSpecialInvi(user,form){
    const invigilatorList = this.form.get('invigilator_list') as FormArray
    const array = form.get('invigilator_list') as FormArray
    const date = form.get('examination_date').value
    if(!array.getRawValue().some(x => x.invigilator_uid == user.user_uid) && !invigilatorList.getRawValue().some(x => x.invigilator_uid == user.user_uid)){
      array.push(this.createInvigilatorForm(user,date))
    }else{
      this.swSV.errText('มีผู้คุมสอบซ้ำ')
    }
  }


  createUpdateInvigilatorForm(x){
    return this.fb.group({
      status_id: x.status_id,
      created_by: x.created_by,
      created_datetime: x.created_datetime,
      updated_by: x.updated_by,
      updated_datetime: x.updated_datetime,
      deleted_by: x.deleted_by,
      deleted_datetime: x.deleted_datetime,
      testing_invigilator_uid: x.testing_invigilator_uid,
      testing_information_uid: [x.testing_information_uid],
      invigilator_uid: [x?.invigilator_uid,Validators.required],
      invigilator_code: [x?.invigilator_code,Validators.required],
      invigilator_name: [x?.invigilator_name,Validators.required],
      examination_date: x.examination_date,
    })
  }
  createInvigilatorForm(special?,date?): FormGroup {
    return this.fb.group({
      status_id: null,
      created_by: null,
      created_datetime: null,
      updated_by: null,
      updated_datetime: null,
      deleted_by: null,
      deleted_datetime: null,
      testing_invigilator_uid: null,
      testing_information_uid: this.id,
      invigilator_uid: [special?.user_uid,Validators.required],
      invigilator_code: [special?.login_name,Validators.required],
      invigilator_name: [special?.display_name,Validators.required],
      examination_date: date,
    })
  }

  addInvigilator(){
    const form = this.form.get('invigilator_list') as FormArray
    form.push(this.createInvigilatorForm())
  }

  setDisplayName(x,index){
    const form = this.form.get('invigilator_list') as FormArray
    const list = this.form.getRawValue()
    const array = []
    list.special_list.map(x => {x.invigilator_list.map(b => array.push(b))})
    const allList = [...list.invigilator_list,...array]
    if(!allList.some(data => data.invigilator_uid == x.user_uid)){
      form.at(index).get('invigilator_name').setValue(x.display_name)
      form.at(index).get('invigilator_uid').setValue(x.user_uid)
      form.at(index).get('invigilator_code').setValue(x.login_name)
    }else{
      this.swSV.errText('มีผู้คุมสอบซ้ำ')
      form.at(index).get('invigilator_name').setValue(null)
      form.at(index).get('invigilator_uid').setValue(null)
      form.at(index).get('invigilator_code').setValue(null)
    }
    // const specialList = (this.form.get('special_list') as FormArray).value
    // const invigilatorList = (this.form.get('invigilator_list') as FormArray).value
    // if(specialList.find(data => x))
    // console.log(specialList.find(data => data.invigilator_name == x.display_name))
    // form.at(index).get('invigilator_name').setValue(x.display_name)
    // form.at(index).get('invigilator_uid').setValue(x.user_uid)
    // form.at(index).get('invigilator_code').setValue(x.login_name)
  }


  removeInvigilator(index){
    const form = this.form.get('invigilator_list') as FormArray
    form.removeAt(index)
  }

  removeChip(form,index){
    const arrayForm = form.get('invigilator_list') as FormArray
    arrayForm.removeAt(index)
  }

  addDate(event,form){
    const arrayForm = form.get('invigilator_list') as FormArray
    arrayForm.controls.map(x => x.get('examination_date').setValue(event.value))
  }

  removeSpecial(index){
    const form = this.form.get('special_list') as FormArray
    form.removeAt(index)
  }

  save(){
    const form = this.form.getRawValue()
    const array = []
    form.special_list.map(x => {
      x.invigilator_list.map(b => array.push(b))
    })
    const save = [...form.invigilator_list,...array]
    this.roomInvigilatorSV.putMany(save).pipe(
      tap(x => this.swSV.saveSuccess()),
      tap(x => this.location.back())
    ).subscribe()
  }


}
