import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  ViewChild,
  AfterViewInit
} from '@angular/core';
import { formatDate } from '@angular/common';
import {MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {FormArray, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {BaseForm} from '../../../../../core/base/base-form';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {catchError, tap} from 'rxjs/operators';
import {Observable, throwError} from 'rxjs';
import {SubjectsService} from '../../../../../core/service/settings/subjects.service';
import {SelectionModel} from '@angular/cdk/collections';
import {PeriodicElement} from '../../../../manage-test-center/presenter/manage-test-center-table/manage-test-center-table.component';
import {TestingCenterService} from '../../../../../core/service/TestingCenter/testing-center.service';
import {SweetalertService} from '../../../../../core/service/sweetalert/sweetalert';
import {TestingInformationService} from '../../../../../core/service/testing-information/testing-information.service';
import {EducationTypesService} from '../../../../../core/service/settings/education-types.service';
import {AcademicYearService} from '../../../../../core/service/settings/academic-year.service';
import {AcademicSemesterService} from '../../../../../core/service/settings/academic-semester.service';
import {MatDialog} from '@angular/material/dialog';
import {SetExamInformationDialogComponent} from '../../dialog/set-exam-information-dialog/set-exam-information-dialog.component';
import {BranchService} from '../../../../../core/service/settings/branch.service';
import {TestingFieldService} from '../../../../../core/service/settings/testing-field.service';
import {data} from 'autoprefixer';
import {CalendarTypeService} from '../../../../../core/service/settings/calendar-type.service';
import {MatDatepicker, MatDatepickerInputEvent} from '@angular/material/datepicker';
import {MatSlideToggleModule} from '@angular/material/slide-toggle';

// @ts-ignore
@Component({
  selector: 'app-set-exam-information-form',
  templateUrl: './set-exam-information-form.component.html',
  styleUrls: ['./set-exam-information-form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SetExamInformationFormComponent extends BaseForm implements OnInit , AfterViewInit {
  statusMock = [{id: 1, name: 'ใช้งาน'}, {id: 2, name: 'ยกเลิก'}];
  typeofdetails = [
    {id: 1, name: 'อัพโหลดเอกสารยืนยันตัวตน', type_of_data: 1, is_check: false},
    {id: 2, name: 'ลงทะเบียนเพื่อยืนยันตันตน', type_of_data: 1, is_check: false},
    {id: 3, name: 'สมัครผ่านระบบลงทะเบียน', type_of_data: 2, is_check: false},
    {id: 4, name: 'สมัครผ่านเคาเตอร์รับสมัคร', type_of_data: 2, is_check: false},
    {id: 5, name: 'อัพโหลดเอกสารยืนยันตัวตน', type_of_data: 2, is_check: false},
    {id: 6, name: 'สมัครผ่านระบบลงทะเบียน', type_of_data: 3, is_check: false},
    {id: 7, name: 'สมัครผ่านเคาเตอร์รับสมัคร', type_of_data: 3, is_check: false},
    {id: 8, name: 'อัพโหลดเอกสารยืนยันตัวตน', type_of_data: 3, is_check: false},
  ];
  daywithout = {
    days_without_testing_uid: null,
    date_without_testing: null,
  };
  sectionsFake = [
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 1,
      "is_check": true,
      "start_time": "09:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 2,
      "is_check": true,
      "start_time": "12:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 3,
      "is_check": true,
      "start_time": "15:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 4,
      "is_check": true,
      "start_time": "18:00"
    }
  ];
  sectionsFakeFalse = [
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 1,
      "is_check": false,
      "start_time": "09:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 2,
      "is_check": false,
      "start_time": "12:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 3,
      "is_check": false,
      "start_time": "15:00"
    },
    {
      "status_id": 1,
      "testing_center_period_uid": null,
      "period_id": 4,
      "is_check": false,
      "start_time": "18:00"
    }
  ];
  private curSub: any;
  private curSub2: any;
  private curSub3: any;
  constructor(
    private subjectSV: SubjectsService,
    private testcenterSV: TestingCenterService,
    private testFiledSV: TestingFieldService,
    private branchSV: BranchService,
    private testingFieldSV: TestingFieldService,
    private formBuilder: FormBuilder,
    private dialog: MatDialog,
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private swSV: SweetalertService,
    private cdRef: ChangeDetectorRef,
    private TestInformationSV: TestingInformationService,
    private EductiontionTypeSV: EducationTypesService,
    private AcademicYearSV: AcademicYearService,
    private AcademicSemSV: AcademicSemesterService,
    private CalendarTypeSV: CalendarTypeService,
  ) {
    super(
      router,
      activeRoute,
      formBuilder,
      location
    );
    this.setexamform = this.formBuilder.group({
        status_id: null,
        created_by: null,
        created_datetime: null,
        updated_by: null,
        updated_datetime: null,
        deleted_by: null,
        deleted_datetime: null,
        testing_information_uid: null,
        testing_information_name: [null, Validators.required],
        testing_information_code: null,
        academic_semester_code: [null, Validators.required],
        academic_year_code: [null, Validators.required],
        testing_information_status: null,
        type_of_examinee: [null, Validators.required],
        is_student_code: false,
        first_student_code: '',
        last_student_code: '',
        registration_start_datetime: null,
        registration_end_datetime: null,
        testing_start_datetime: null,
        testing_end_datetime: null,
        is_number_of_times_testing: false,
        is_online_register: true,
        number_of_times_testing: null,
        times_the_score_is_calculated: 1,
        is_main: true,
        main_testing_information_uid: null,
        registration_type: 1,
        is_upload_document: false,
        is_register_verify: false,
        is_register: false,
        is_counter: false,
      days_without_testings: this.formBuilder.array([
        this.block_days(null)
      ]),
      testing_calendars: this.formBuilder.array([
        this.testing_calendars(null)
      ]),
      testing_subjects: this.formBuilder.array([
        this.testing_subjects()
      ]),
      testing_rooms: this.formBuilder.array([
        this.testing_rooms()
      ]),
      testing_periods: this.formBuilder.array([
        this.testing_periods()
      ])
    });
    this.calendarForm = this.formBuilder.group({
      calendar_type_uid: null,
      calendar_type_name_th: null,
      start_datetime: null,
      end_datetime: null,
    });
    this.subjectForm = this.formBuilder.group({
      subjectcode: null,
      subjectname: null,
    });
    this.setroomcenterForm = this.formBuilder.group({
      branch_name_th: null,
      branch_uid: null,
      testing_center_uid: null,
      testing_field_name_th: null,
      testing_field_uid: null,
      testing_room_name_th: null,
      testing_auth_name: null,
      is_random_seat: null,
    });
  }
  // MainForm
  setexamform: FormGroup;
  // Subform
  SubjectGetCheck$ = new Observable;
  subjectListSend = [];
  calendarForm: FormGroup;
  subjectForm: FormGroup;
  setroomcenterForm: FormGroup;
  EducationTypeLists;
  eductionTypeList;
  academicYearList;
  calendarLists;
  academicSemList;
  saveUsername = true;
  subjectList;
  subjectList2: any = [];
  subjectList3;
  isDisable = true;
  selectCalendar;
  fixSubjectlist = false;
  Today;
  // selected = new FormControl(0);
  selectdIndex = 0;
  form;
  selection = new SelectionModel(true, []);
  public CLOSE_ON_SELECTED = false;
  public init = new Date();
  public resetModel = new Date(0);
  public model = [
    // new Date('2/8/2022'),
    // new Date('2/9/2022'),
    // new Date('2/11/2022'),
  ];
  @ViewChild('picker7', { static: true }) _picker: MatDatepicker<Date>;
  @ViewChild(MatSort, { static: true }) sort: MatSort;
  @ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;
  candidateTypes =
    [
      {
        candidate_type_uid: '6dff8faf-0b30-4fb1-8274-42df8debe8a0',
        candidate_type_name_th: 'นักศึกษา',
      },
      {
        candidate_type_id: 'd056ba6d-5a15-4df6-ade0-c9e8c239d1b1',
        candidate_type_name_th: 'บุคคลทั่วไป',
      },
    ];
  displayedColumns: string[] = ['1', '2', '3', '4'];
  displayedColumns2: string[] = ['select', '1', '2'];
  displayedColumns3: string[] = ['1', '2', '3', '4', '5', '6', '7'];
  dataSource = new MatTableDataSource();
  dataSource2;
  dataSource3 = new MatTableDataSource();
  setupdata = {
    testing_center_uid: null,
    testing_center_name_th: null,
    branch_uid: null,
    branch_name_th: null,
    testing_field_uid: null,
    testing_field_name_th: null,
    testing_room_uid: null,
    testing_room_name_th: null,
    testing_auth_name: null,
  };

  i = {
    education_type_id: null,
  };
  calendar = {
    name: null,
    dateStart: null,
    dateEnd: null,
  };
  testing_seats(data?){
    return this.formBuilder.group({
      status_id: null,
      // created_by: null,
      // created_datetime: null,
      // updated_by: null,
      // updated_datetime: null,
      // deleted_by: null,
      // deleted_datetime: null,
      no_of_seats: data?.no_of_seats,
      row_name: data?.row_name,
      testing_seat_uid: data?.testing_seat_uid,
      testing_center_row_uid: data?.testing_center_row_uid,
      is_specify_subject: data?.is_specify_subject,
      testing_room_uid: data?.testing_room_uid,
      testing_seat_subjects: this.formBuilder.array([
        this.testing_seat_subjects(data?.testing_seat_subjects)
      ]),
    });
  }

  testing_seat_subjects(data?){
      return this.formBuilder.group({
        status_id: null,
        testing_seat_subject_uid: data?.testing_seat_subject_uid,
        subject_uid: data?.subject_uid,
        subject_code: data?.subject_code,
        subject_name_th: data?.subject_name_th,
        start_seat_no: data?.start_seat_no,
        end_seat_no: data?.end_seat_no,
        testing_seat_uid: data?.testing_seat_uid,
      });
  }

  block_days(blockdays?){
    return this.formBuilder.group({
      status_id: null,
      testing_information_uid: blockdays?.testing_information_uid,
      days_without_testing_uid: blockdays?.days_without_testing_uid,
      date_without_testing: blockdays?.date_without_testing,
    });
  }

  testing_calendars(calender?){
    return this.formBuilder.group({
      status_id: null,
      testing_calendar_uid: calender?.testing_calendar_uid,
      start_datetime: calender?.start_datetime,
      end_datetime: calender?.end_datetime,
      calendar_type_uid: calender?.calendar_type_uid,
      calendar_type_name_th: calender?.calendar_type_name_th,
      testing_information_uid: calender?.testing_information_uid,
    });
  }

  testing_subjects(data?){
    return this.formBuilder.group({
      status_id: null,
      // created_by: null,
      // created_datetime: null,
      // updated_by: null,
      // updated_datetime: null,
      // deleted_by: null,
      // deleted_datetime: null,
      testing_subject_uid: data?.testing_subject_uid,
      subject_uid: data?.subject_uid,
      subject_code: data?.subject_code,
      subject_name_th: data?.subject_name_th,
    });
  }

  testing_periods(data?){
    return this.formBuilder.group({
      status_id: null,
      // created_by: null,
      // created_datetime: null,
      // updated_by: null,
      // updated_datetime: null,
      // deleted_by: null,
      // deleted_datetime: null,
      // deleted_datetime: null,
      is_check: data?.is_check,
      testing_information_uid: data?.testing_information_uid,
      testing_period_uid: data?.testing_period_uid,
      period_id: data?.period_id,
      start_time: data?.start_time,
    });
  }

  testing_rooms(data?){
    return this.formBuilder.group({
      testing_room_uid: data?.testing_room_uid,
      testing_center_uid: data?.testing_center_uid,
      // testing_center_name_th: data?.testing_center_name_th,
      branch_uid: data?.branch_uid,
      branch_name_th: data?.branch_name_th,
      testing_field_uid: data?.testing_field_uid,
      testing_information_uid: data?.testing_information_uid,
      testing_field_name_th: data?.testing_field_name_th,
      testing_room_name_th: data?.testing_room_name_th,
      testing_auth_name: data?.testing_auth_name,
      is_random_seat: data?.is_random_seat,
      testing_seats: this.formBuilder.array([
        this.testing_seats(data?.testing_seats)
      ]),
    });
  }

  ngOnInit(): void {
    this.getCommondata()
  }

  async  getCommondata(){
    await this.EductiontionTypeSV.getAll().subscribe(
      result => {
        this.eductionTypeList = result;
      }
    );
    await this.AcademicYearSV.getAll().subscribe(
      result => {
        this.academicYearList = result;
      }
    );
    await this.AcademicSemSV.getAll().subscribe(
      result => {
        this.academicSemList = result;
      }
    );
    await this.TestInformationSV.getDatatype().subscribe(
      result => {
        this.EducationTypeLists = result;
      }
    );
    await this.CalendarTypeSV.getAll().subscribe(
      result => {
        this.calendarLists = result;
      }
    );
    await this.branchSV.getAll().pipe(
      tap(x => this.subjectList = x),
    ).subscribe();
    // await this.testingFieldSV.getAll().pipe(
    //   tap(x => this.subjectList2 = x),
    // ).subscribe();
    await this.testcenterSV.getAll().pipe(
      tap(x => this.subjectList3 = x),
    ).subscribe();
    await this.subjectSV.getAll().pipe(
      tap(x => this.subjectListSend = x),
      // tap(x => {
      //    this.dataSource2 = new MatTableDataSource(x);
      //    this.dataSource2.paginator = this.paginator;
      //    this.dataSource2.sort = this.sort;
      //  }),
    ).subscribe();
    await this.AftergetCommonData();
  }

  AftergetCommonData(){
    this.Today = this.formatDate(new Date());
    const form = this.setexamform.get('testing_calendars') as FormArray;
    const form2 = this.setexamform.get('testing_subjects') as FormArray;
    const form3 = this.setexamform.get('testing_rooms') as FormArray;
    const form4 = this.setexamform.get('testing_periods') as FormArray;
    const form5 = this.setexamform.get('days_without_testings') as FormArray;
    switch (this.state) {
      case 'edit':
        this.TestInformationSV.get(this.id).pipe(
          tap(x => console.log(x)),
          tap(x =>  {
            form.clear();
            // form2.clear();
            form3.clear();
            form4.clear();
            form5.clear();
          }),
          tap(x => {
            const data: any = x;
            if (data.number_of_times_testing != null){
              this.setexamform.get('is_number_of_times_testing').setValue(true);
            }
            data.registration_start_datetime = this.formatDate(data.registration_start_datetime);
            data.registration_end_datetime = this.formatDate(data.registration_end_datetime);
            data.testing_start_datetime = this.formatDate(data.testing_start_datetime);
            data.testing_end_datetime = this.formatDate(data.testing_end_datetime);
            this.setexamform.patchValue(data);
          }),
          tap(x => this.addCalendaEdit(x)),
          tap(x => this.add3Edit(x)),
          tap(x => this.addPeriodEdit(x)),
          // tap(x => this.checkPeriodEdit(x)),
          tap(x => this.addEditBlockadd(x)),
          // tap(x => this.selectValueEdit(x)),
          tap(x => this.cdRef.detectChanges()),
        ).subscribe();
        break;
      case 'add':
        form.clear();
        form2.clear();
        form3.clear();
        form4.clear();
        for (let i = 0; i < this.sectionsFake.length; i++) {
          form4.push(this.testing_periods(this.sectionsFake[i]));
        }
        form5.clear();
        break;
    }
  }

  formatDate(date) {
    let d = new Date(date),
      month = '' + (d.getMonth() + 1),
      day = '' + d.getDate(),
      year = d.getFullYear();

    if (month.length < 2) {
      month = '0' + month;
    }
    if (day.length < 2) {
      day = '0' + day;
    }

    return [year, month, day].join('-');
  }

  ngAfterViewInit() {
  }

  list(res){
    res = new MatTableDataSource(res);
    res.paginator = this.paginator;
    res.sort = this.sort;
    return res;
  }

  selectionValue(data, i){
    switch (this.state) {
      case 'edit':
        break;
      case 'add':
        let israndom = true;
        if (data.is_random_seat === true){
          israndom = false;
        }else if (data.is_random_seat === false){
          israndom = true;
        }
        const form = this.setexamform.get('testing_rooms') as FormArray;
        form.at(i).get('is_random_seat').setValue(israndom);
        const table = form.getRawValue();
        this.dataSource3.data = table;
        break;
    }
  }
  selectValueEdit(x){
    const subjectForm = this.setexamform.get('testing_subjects') as FormArray;
    console.log(subjectForm.getRawValue())
    // this.SubjectGetCheck = subjectForm.getRawValue();
    subjectForm.clear();
    // for (let option of x.testing_subjects) {
    //   subjectForm.push(this.testing_subjects(option));
    //   const exists = this.dataSource2.data.filter(x => x.subject_uid === option.subject_uid)[0];
    //   this.selection.toggle(exists);
    // }
    // console.log(this.selection.selected);
    this.cdRef.detectChanges();
  }

  moveToSelectedTab(tabName: string) {
    console.log(tabName);
    this.selectdIndex ++;

  }

  changeRegisterType(){
    const regisType = this.setexamform.get('registration_type').value;
    this.setexamform.get('is_register_verify').setValue(false);
    this.setexamform.get('is_register').setValue(false);
    this.setexamform.get('is_counter').setValue(false);
    this.setexamform.get('is_upload_document').setValue(false);
  }

  OpenForm(){
    const isStudent = this.setexamform.get('is_student_code').value;
    console.log(isStudent);
    if (isStudent === false){
      // อย่าลืมล้างค่า
      this.setexamform.controls.is_student_code.setValue(true);
    }else {
      // this.setexamform.controls['this.setexamform'].setValue(false);
      this.setexamform.controls.is_student_code.setValue(false);
    }
  }

  addEditBlockadd(x){
    const form = this.setexamform.get('days_without_testings') as FormArray;
    for (let i = 0; i < x.days_without_testings.length; i++) {
      x.days_without_testings[i].date_without_testing = formatDate(x.days_without_testings[i].date_without_testing, 'yyyy-MM-dd', 'en-US')
      form.push(this.block_days(x.days_without_testings[i]));
      this.model.push(x.days_without_testings[i].date_without_testing);
    }
  }


  addCalendar(){
    const form = this.calendarForm.getRawValue();
    const form2 = this.setexamform.get('testing_calendars') as FormArray;
    console.log(form);
    form2.push(this.testing_calendars(form));
    const table = form2.getRawValue();
    this.dataSource.data = table;
  }
  addCalendaEdit(x){
    const form2 = this.setexamform.get('testing_calendars') as FormArray;
    for (let i = 0; i < x.testing_calendars.length; i++) {
      x.testing_calendars[i].end_datetime = this.formatDate(x.testing_calendars[i].start_datetime);
      x.testing_calendars[i].start_datetime = this.formatDate( x.testing_calendars[i].start_datetime);
      form2.push(this.testing_calendars(x.testing_calendars[i]));
    }
    const table = form2.getRawValue();
    this.dataSource.data = table;
  }
  addPeriodEdit(x){
    console.log(x.testing_periods);
    const form = this.setexamform.get('testing_periods') as FormArray;
    // for (let i = 0; i < x.testing_periods.length; i++) {
    //   // console.log(x.testing_periods[i].period_id);
    //   this.sectionsFakeFalse.find(v => v.period_id === x.testing_periods[i].period_id).is_check = true;
    // }
    for (let i = 0; i < x.testing_periods.length; i++) {
      const foundIndex = this.sectionsFakeFalse.findIndex(v => v.period_id === x.testing_periods[i].period_id);
      this.sectionsFakeFalse[foundIndex].is_check = true;
      this.sectionsFakeFalse[foundIndex].start_time = x.testing_periods[i].start_time;
    }
    console.log(this.sectionsFakeFalse);
    for (let i = 0; i < this.sectionsFakeFalse.length; i++) {
      form.push(this.testing_periods(this.sectionsFakeFalse[i]));
    }
  }
  checkPeriodEdit(x){
    console.log(this.sectionsFake);
    for (let i = 0; i < x.testing_periods.length; i++) {
      // console.log(x.testing_periods[i].period_id);
      this.sectionsFake.find(v => v.period_id === x.testing_periods[i].period_id).is_check = true;
    }
    console.log(this.sectionsFake);
    this.cdRef.detectChanges();
  }
  removeArray(i){
    const form = this.setexamform.get('testing_calendars') as FormArray;
    form.removeAt(i);
    const table = form.getRawValue();
    this.dataSource.data = table;
  }



  add3(){
    const form = this.setroomcenterForm.getRawValue();
    const form3 = this.setexamform.get('testing_rooms') as FormArray;
    // this.setupdata.testing_auth_name = form.testing_auth_name;
    form3.push(this.testing_rooms(form));
    const table = form3.getRawValue();
    this.dataSource3.data = table;
  }

  add3Edit(data){
    const form = this.setexamform.get('testing_rooms') as FormArray;
    this.SubjectGetCheck$ = data.testing_subjects;
    for (let i = 0; i < data.testing_rooms.length; i++) {
      form.push(this.testing_rooms(data.testing_rooms[i]));
      const formArray = form.controls[i].get('testing_seats') as FormArray;
      const FormArraySeat = form.controls[i].get('testing_seat_subjects') as FormArray;
      formArray.clear();
      for (let j = 0; j < data.testing_rooms[i].testing_seats.length; j++) {
        formArray.push(this.testing_seats(data.testing_rooms[i].testing_seats[j]));
        const formArraySeatSubject = formArray.controls[j].get('testing_seat_subjects') as FormArray;
        formArraySeatSubject.clear();
        // console.log(data.testing_rooms[i].testing_seats[j].testing_seat_subjects[0]);
        // formArraySeatSubject.push(this.testing_seat_subjects(data.testing_rooms[i].testing_seats[j].testing_seat_subjects[0]));
        for (let k = 0; k < data.testing_rooms[i].testing_seats[j].testing_seat_subjects.length; k++) {
          // console.log(data.testing_rooms[i].testing_seats[j].testing_seat_subjects[k]);
          formArraySeatSubject.push(this.testing_seat_subjects(data.testing_rooms[i].testing_seats[j].testing_seat_subjects[k]));
        }
      }
    }
    const table = form.getRawValue();
    this.dataSource3.data = table;
  }
  removeArray3(i){
    const form = this.setexamform.get('testing_rooms') as FormArray;
    form.removeAt(i);
    const table = form.getRawValue();
    this.dataSource3.data = table;
  }

  add2(data){
    console.log(data);
    const form = this.setexamform.get('testing_subjects') as FormArray;
    form.push(this.testing_subjects(data));
  }

  setBranchname(data){

  }

  displayBranchname(uid){
    if (uid && this.subjectList) return this.subjectList.find(x => x.branch_uid === uid)?.branch_name_th
    if (uid && !this.subjectList) return this.curSub?.branch_name_th
  }

  displayFieldname(uid){
    if (uid && this.subjectList2) return this.subjectList2.find(x => x.testing_field_uid === uid)?.testing_field_name_th
    if (uid && !this.subjectList2) return this.curSub2?.testing_field_name_th
  }

  displayRoomname(uid){
    if (uid && this.subjectList3) return this.subjectList3.find(x => x.testing_center_uid === uid)?.testing_room_name_th
    if (uid && !this.subjectList3) return this.curSub3?.testing_room_name_th
  }

  setFieldname(uid){
    const branch = this.subjectList.filter((x) => {
      return x.branch_uid === uid;
    });
    this.setroomcenterForm.get('branch_name_th').setValue(branch[0].branch_name_th);
    this.testingFieldSV.getByBrandID(uid).pipe(
      tap(x => console.log(x)),
      tap(x => this.subjectList2 = x),
    ).subscribe();
  }

  setRoomname(uid){
    const branch = this.subjectList2.filter((x) => {
      return x.testing_field_uid === uid;
    });
    this.setroomcenterForm.get('testing_field_name_th').setValue(branch[0].testing_field_name_th);
    this.testcenterSV.getByFiledID(uid).pipe(
      tap(x => console.log(x)),
      tap(x => this.subjectList3 = x),
    ).subscribe();
  }

  setRoomnameth(uid){
    const branch = this.subjectList3.filter((x) => {
      return x.testing_center_uid === uid;
    });
    this.setroomcenterForm.get('testing_room_name_th').setValue(branch[0].testing_room_name_th);
  }



  openDialogexam(id:any,index:any){
    console.log(id);
    console.log(index);
    const form = this.setexamform.get('testing_rooms') as FormArray;
    const subjectForm = this.setexamform.get('testing_subjects') as FormArray;
    const centerList = form.getRawValue();
    switch (this.state) {
      case 'edit':
        const uidInformtion = this.id;
        const dialogRefedit = this.dialog.open(SetExamInformationDialogComponent, {
          width: '1000px',
          height: '700px',
          data: {
            id,
            centerList : centerList[index],
            subjectlist : subjectForm.getRawValue(),
            state : this.state,
          }
        });
        dialogRefedit.afterClosed().subscribe(
          result => {
            const testseatdata = result.data;
            const testseat = testseatdata.getRawValue();
            const formArray3 = form.at(index).get('testing_seats') as FormArray;
            formArray3.clear();
            console.log(data);
            const formArray = form.controls[index].get('testing_seats') as FormArray;
            for (let j = 0; j < testseat.testing_seat.length; j++) {
              formArray.push(testseatdata.get('testing_seat').controls[j]);
            }
            // for (let i = 0; i < form.getRawValue().length; i++) {
            //   const formArray = form.controls[index].get('testing_seats') as FormArray;
            //   for (let j = 0; j < testseat.testing_seat.length; j++) {
            //     formArray.push(testseatdata.get('testing_seat').controls[j]);
            //   }
            // }
            this.cdRef.detectChanges();
          }
        );
        break;
      case 'add':
        const dialogRefadd = this.dialog.open(SetExamInformationDialogComponent, {
          width: '1000px',
          height: '700px',
          data: {
            id,
            subjectlist : subjectForm.getRawValue(),
            state : this.state,
          }
        });
        dialogRefadd.afterClosed().subscribe(
          result => {
            const testseatdata = result.data;
            const data = testseatdata.getRawValue();
            const formArray3 = form.at(index).get('testing_seats') as FormArray;
            formArray3.clear();
            console.log(data);
            const testseat = data;
            const formArray = form.controls[index].get('testing_seats') as FormArray;
            for (let i = 0; i < testseat.testing_seat.length; i++) {
              formArray.push(testseatdata.get('testing_seat').controls[i]);
            }
            // for (let i = 0; i < form.getRawValue().length; i++) {
            //   const formArray = form.controls[index].get('testing_seats') as FormArray;
            //   for (let j = 0; j < testseat.testing_seat.length; j++) {
            //     formArray.push(testseatdata.get('testing_seat').controls[j]);
            //   }
            // }
            this.cdRef.detectChanges();
          }
        );
        break;
    }
  }

  openDialogEdit(testseat){
    console.log(testseat);
    const form = this.setexamform.get('testing_rooms') as FormArray;
    console.log(form.getRawValue());
    switch (this.state) {
      case 'edit':
        const uidInformtion = this.id;
        const dialogRefedit = this.dialog.open(SetExamInformationDialogComponent, {
          width: '1000px',
          height: '700px',
          data: {
            id : uidInformtion,
            centerList : form.getRawValue(),
            testseat : testseat,
            subjectlist : this.selection.selected,
            state : this.state,
          }
        });
        dialogRefedit.afterClosed().subscribe(
          result => {
            const testseatdata = result.data;
            const data = testseatdata.getRawValue();
            const formArray3 = form.at(0).get('testing_seats') as FormArray;
            formArray3.clear();
            console.log(data);
            const testseat = data;
            for (let i = 0; i < form.getRawValue().length; i++) {
              const formArray = form.controls[i].get('testing_seats') as FormArray;
              for (let j = 0; j < testseat.testing_seat.length; j++) {
                formArray.push(testseatdata.get('testing_seat').controls[j]);
              }
            }
            this.cdRef.detectChanges();
          }
        );
        break;
    }
  }

  save(){
    switch (this.state) {
      case 'edit':
        const form1 = this.setexamform.getRawValue();
        const dataselect2 = this.selection.selected;
        const results2 = dataselect2.map(({ subject_uid }) => ({ subject_uid }));
        form1.testing_periods = form1.testing_periods.filter((member) => {
          return member.is_check === true;
        });
        // const formEdit = this.setexamform.get('testing_subjects') as FormArray;
        // formEdit.clear();
        // for (const key of Object.keys(results2)) {
        //   const mealName = results2[key];
        //   this.add2(mealName);
        // }
        this.TestInformationSV.update2(form1).pipe(
          tap(x => this.swSV.updateSuccess()),
          tap(x => window.history.back()),
          catchError(err => {
            this.swSV.err();
            return throwError(err);
          })
        ).subscribe();
        break;

      case 'add':
        const form = this.setexamform.getRawValue();
        form.testing_periods = form.testing_periods.filter((member) => {
          return member.is_check === true;
        });
        // tslint:disable-next-line:max-line-length
        if (form.testing_start_datetime == null || form.testing_end_datetime == null || form.registration_start_datetime == null || form.registration_end_datetime == null){
          return this.swSV.errText('กรุณาใส่วันที่');
        }
        this.TestInformationSV.add(form).pipe(
          tap(x => this.swSV.saveSuccess()),
          tap(x => window.history.back()),
          catchError(err => {
            this.swSV.err();
            return throwError(err);
          })
        ).subscribe();
        break;
    }
  }

  setcalendarForm(selectCalendar){
    const CalendarChoose = this.calendarLists.filter(x => x.calendar_type_uid === selectCalendar);
    this.calendarForm.get('calendar_type_name_th').setValue(CalendarChoose[0].calendar_type_name_th);
  }

  setDatecalendarForm(choose, Date){
    const Dateset:any = formatDate(Date, 'yyyy-MM-dd', 'en-US')
    switch(choose) {
      case 'start': {
        this.calendarForm.get('start_datetime').setValue(Dateset);
        break;
      }
      case 'end': {
        this.calendarForm.get('end_datetime').setValue(Dateset);
        break;
      }
    }
  }

  onChangeSelection(selected) {
    console.log(selected);
    // this.i.education_type_id = parseInt(selected);
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource2.filter = filterValue.trim().toLowerCase();
  }

  GetSubjectChoose(data){
    const form = this.setexamform.get('testing_subjects') as FormArray;
    form.clear();
    for (let i = 0; i < data.length; i++) {
      form.push(this.testing_subjects(data[i]));
    }
  }

  convert(str) {
    var date = new Date(str),
      mnth = ("0" + (date.getMonth() + 1)).slice(-2),
      day = ("0" + date.getDate()).slice(-2);
    return [date.getFullYear(), mnth, day].join('-');
  }

  onCheckChange(event,choice) {
    const formArraySecttion = this.setexamform.get('testing_periods') as FormArray;
    // /* Selected */
    if (event.target.checked) {
      // Add a new control in the arrayForm
      formArraySecttion.push(this.testing_periods(choice));
    } else {
      // console.log(formArraySecttion.getRawValue())
      const ArrayPeriods = formArraySecttion.getRawValue();
      const Found = ArrayPeriods.findIndex(x => x.period_id === choice.period_id)
      // console.log(Found);
      formArraySecttion.removeAt(Found);

    }
  }

  removeChoice(i){
    // const form = this.setexamform.get('testing_periods') as FormArray;
    // form.removeAt(i);
  }
  toggle(event){
    console.log(event);
    console.log(event.checked);
    console.log(event.value);
  }
  public dateClass = (date: Date) => {
    if (this._findDate(date) !== -1) {
      return [ 'selected' ];
    }
    return [ ];
  }

  public dateChanged(event: MatDatepickerInputEvent<Date>): void {
    const formblockdays = this.setexamform.get('days_without_testings') as FormArray;
    if (event.value) {
      const date = event.value;
      const index = this._findDate(date);
      if (index === -1) {
        this.model.push(date);
        this.updateBlockdate(date);
      } else {
        this.model.splice(index, 1);
        formblockdays.removeAt(index);
      }

      this.resetModel = new Date(0);
      if (!this.CLOSE_ON_SELECTED) {
        const closeFn = this._picker.close;
        this._picker.close = () => { };
        this._picker['_popupComponentRef'].instance._calendar.monthView._createWeekCells()
        setTimeout(() => {
          this._picker.close = closeFn;
        });
      }
    }
  }

  public remove(date: Date): void {
    const formblockdays = this.setexamform.get('days_without_testings') as FormArray;
    const index = this._findDate(date);
    formblockdays.removeAt(index)
    this.model.splice(index, 1);
  }

  private _findDate(date: Date): number {
    return this.model.map((m) => +m).indexOf(+date);
  }

  updateBlockdate(date){
    const formblockdays = this.setexamform.get('days_without_testings') as FormArray;
    switch (this.state) {
      case 'edit':
        this.daywithout.date_without_testing = formatDate(date, 'yyyy-MM-dd', 'en-US');
        formblockdays.push(this.block_days(this.daywithout));
        break;
      case 'add':
        // this.daywithout.id_day = null;
        this.daywithout.date_without_testing = formatDate(date, 'yyyy-MM-dd', 'en-US');
        formblockdays.push(this.block_days(this.daywithout));
        break;
    }
  }
}
