import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {BaseForm} from '../../../../../../core/base/base-form';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {MatTableDataSource} from '@angular/material/table';
import {AcademicSemesterService} from '../../../../../../core/service/settings/academic-semester.service';
import {AcademicYearService} from '../../../../../../core/service/settings/academic-year.service';
import {SubjectsService} from '../../../../../../core/service/settings/subjects.service';
import {TestingCenterService} from '../../../../../../core/service/TestingCenter/testing-center.service';
import {TestingFieldService} from '../../../../../../core/service/settings/testing-field.service';
import {BranchService} from '../../../../../../core/service/settings/branch.service';
import {MatDialog} from '@angular/material/dialog';
import {ActivatedRoute, Router} from '@angular/router';
import {formatDate, Location} from '@angular/common';
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 {CalendarTypeService} from '../../../../../../core/service/settings/calendar-type.service';
import {catchError, tap} from 'rxjs/operators';
import {Subject, throwError} from 'rxjs';
import {
  SetExamInformationDialogComponent
} from '../../../../../set-exam-information/presenter/dialog/set-exam-information-dialog/set-exam-information-dialog.component';

@Component({
  selector: 'app-extend-information-room-form',
  templateUrl: './extend-information-room-form.component.html',
  styleUrls: ['./extend-information-room-form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExtendInformationRoomFormComponent extends BaseForm implements OnInit{

  setroomcenterForm: FormGroup;
  subjectList: any = [];
  subjectList2: any = [];
  subjectList3: any = [];
  dataSource3 = new MatTableDataSource();
  displayedColumns3: string[] = ['1', '2', '3', '5', '6', '7'];
  testingInfoData;
  private curSub: any;
  private curSub2: any;
  private curSub3: any;
  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'
    }
  ];
  constructor(
    private academicSemSV: AcademicSemesterService,
    private academicYearSV: AcademicYearService,
    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: '',
      start_datetime: null,
      end_datetime: null,
      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_open: null,
      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.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,
    });
  }
  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({
      is_new: data?.is_new,
      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)
      ]),
    });
  }

  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,
    });
  }
  // MainForm
  setexamform: FormGroup;

  ngOnInit(): void {
    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;
    // this.testcenterSV.getAll().pipe(
    //   tap(x =>  this.subjectList = this.clearBranchList(x)),
    // ).subscribe();
    // await this.testingFieldSV.getAll().pipe(
    //   tap(x => this.subjectList2 = x),
    // ).subscribe();
    // this.testcenterSV.getAll().pipe(
    //   tap(x => this.subjectList3 = x),
    // ).subscribe();
    // this.testcenterSV.getAll().pipe(
    //   tap(x => this.subjectList3 = x),
    // ).subscribe();
    switch (this.state) {
      case 'edit':
        this.TestInformationSV.get(this.id).pipe(
          tap(x => this.testingInfoData = x),
          tap(x => {
            const res: any = x;
            console.log(res)
            this.getBranchList(res)
          }),
          tap(x =>  {
            form5.clear();
            form3.clear();
            form2.clear();
            form.clear();
          }),
          tap(x => {
            const data: any = x;
            this.setexamform.patchValue(data);
          }),
          tap(x => this.add3Edit(x)),
          tap(x => this.addPeriodEdit(x)),
          tap(x => this.addCalendaEdit(x)),
          tap(x => this.addSubject(x)),
          tap(x => this.addEditBlockadd(x)),
          tap(x => this.cdRef.detectChanges()),
        ).subscribe();
        break;
    }
  }

  checkAcaSemandAcaYear(data){
    const returndata = {
      academic_year_uid: null,
      academic_semester_uid: null
    };
    const result = new Subject<any>();
    this.academicSemSV.query(`?academic_semester_code=${data.academic_semester_code}`).subscribe(
      res => {
        returndata.academic_semester_uid = res[0].academic_semester_uid
        this.academicYearSV.query(`?academic_year_code=${data.academic_year_code}`).subscribe(
          res2 => {
            returndata.academic_year_uid = res2[0].academic_year_uid
            result.next(returndata);
          }
        );
      }
    );
    return result.asObservable();
  }

  async getBranchList(data){
    await this.checkAcaSemandAcaYear(data).subscribe(
      res => {
        if (res.academic_year_uid != null && res.academic_semester_uid != null){
          this.testcenterSV.query(`?academic_year_uid=${res.academic_year_uid}&academic_semester_uid=${res.academic_semester_uid}`).pipe(
            // tap(x =>  this.subjectList = x),
            tap(x =>  this.subjectList = this.clearBranchlist(x)),
          ).subscribe();
        }
      }
    );
  }

  clearBranchlist(arr){
    const resArr = [];
    arr.filter(function(item: any): any{
      const i = resArr.findIndex(x => (x.branch_name_th === item.branch_name_th));
      if (i <= -1){
        resArr.push(item);
      }
      return null;
    });
    return resArr
  }

  add3Edit(data){
    console.log(data)
    const form = this.setexamform.get('testing_rooms') as FormArray;
    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();
        for (let k = 0; k < data.testing_rooms[i].testing_seats[j].testing_seat_subjects.length; 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;
  }

  add3EditReserve(data){
    console.log(data)
    const form = this.setexamform.get('testing_rooms') as FormArray;
    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();
        for (let k = 0; k < data.testing_rooms[i].testing_seats[j].testing_seat_subjects.length; 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;
  }

  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 = formatDate(x.testing_calendars[i].end_datetime, 'yyyy-MM-dd', 'en-US');
      x.testing_calendars[i].start_datetime = formatDate(x.testing_calendars[i].start_datetime, 'yyyy-MM-dd', 'en-US');
      form2.push(this.testing_calendars(x.testing_calendars[i]));
    }
  }

  addPeriodEdit(x){
    const form = this.setexamform.get('testing_periods') as FormArray;
    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;
    }
    for (let i = 0; i < this.sectionsFakeFalse.length; i++) {
      form.push(this.testing_periods(this.sectionsFakeFalse[i]));
    }
  }

  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]));
    }
  }

  addSubject(x){
    const form = this.setexamform.get('testing_subjects') as FormArray;
    if (x.testing_subjects != null){
      for (let i = 0; i < x.testing_subjects.length; i++) {
        form.push(this.testing_subjects(x.testing_subjects[i]));
      }
    }
  }

  add3(){
    const form = this.setroomcenterForm.getRawValue();
    const form3 = this.setexamform.get('testing_rooms') as FormArray;
    console.log(form)
    console.log(form3.getRawValue())
    const everyResult = form3.getRawValue().some((member) => {
      return member.testing_center_uid === form.testing_center_uid
    })
    console.log(everyResult)
    if (everyResult){
      return this.swSV.errText('มีห้องสอบซ้ำ')
    }
    // this.setupdata.testing_auth_name = form.testing_auth_name;
    form.is_new = true;
    form3.push(this.testing_rooms(form));
    const table = form3.getRawValue();
    this.dataSource3.data = table;
    const index = table.findIndex(
      member => member.testing_center_uid === form.testing_center_uid &&
        member.branch_uid === form.branch_uid &&
        member.testing_field_uid === form.testing_field_uid
    );
    if (index !== -1){
      this.setroomcenterForm.reset();
      this.openDialogexam(form.testing_center_uid , index)
    }else {
      this.swSV.errText('ไม่พบห้องสอบกรุณาลบสร้างห้องสอบใหม่')
    }
  }

  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);
  }

  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
  }

  selectionValue(data, i){
    switch (this.state) {
      case 'edit':
        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;
    }
  }

  openDialogexam(id:any,index:any){
    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':
        console.log(centerList[index])
        const uidInformtion = this.id;
        const dialogRefedit = this.dialog.open(SetExamInformationDialogComponent, {
          width: '1200px',
          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(testseat);
            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]);
            }
            this.cdRef.detectChanges();
          }
        );
        break;
    }
  }

  removeArray3(i){
    const form = this.setexamform.get('testing_rooms') as FormArray;
    form.removeAt(i);
    const table = form.getRawValue();
    this.dataSource3.data = table;
  }

  save(){
    switch (this.state) {
      case 'edit':
        const form1 = this.setexamform.getRawValue();
        form1.testing_periods = form1.testing_periods.filter((member) => {
          return member.is_check === true;
        });
        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;
    }
  }

  back(){
    this.location.back()
  }

  onView(id,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':
        console.log(centerList[index])
        const uidInformtion = this.id;
        const dialogRefedit = this.dialog.open(SetExamInformationDialogComponent, {
          width: '1200px',
          height: '700px',
          data: {
            id,
            centerList : centerList[index],
            subjectlist : subjectForm.getRawValue(),
            state : 'view',
          }
        });
        break;
    }
  }

}
