import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Input} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import {AcademicSemesterService} from '../../../../../../core/service/settings/academic-semester.service';
import {AcademicYearService} from '../../../../../../core/service/settings/academic-year.service';
import {TestingInformationService} from '../../../../../../core/service/testing-information/testing-information.service';
import {TestingFieldService} from '../../../../../../core/service/settings/testing-field.service';
import {FacultysService} from '../../../../../../core/service/settings/facultys.service';
import {DepartmentService} from '../../../../../../core/service/settings/department.service';
import {SubjectsService} from '../../../../../../core/service/settings/subjects.service';
import {TestingCenterService} from '../../../../../../core/service/TestingCenter/testing-center.service';
import {FormArray, FormBuilder} from '@angular/forms';
import {tap} from 'rxjs/operators';
import {TestingRegisterService} from '../../../../../../core/service/testing-register/testing-register.service';
import {SweetalertService} from "../../../../../../core/service/sweetalert/sweetalert";

@Component({
  selector: 'app-receive-payment-detail',
  templateUrl: './receive-payment-detail.component.html',
  styleUrls: ['./receive-payment-detail.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ReceivePaymentDetailComponent implements OnInit {
  form;
  AcademicSemLists;
  AcademicYearLists;
  AcademicYearCode;
  TestInformationID;
  subTestInformtionID;
  TestingInformationLists: any = [];
  newMaintestinginformationuID;
  FacultyLists: any = [];
  DepartmentLists: any = [];
  TestcenterLists: any = [];
  TestFieldLists: any = [];
  TestRoomLists: any = [];
  SubjectLists: any = [];
  EducationTypeLists: any = [];
  PeriodLists: any = [];
  Daterange = {
    testing_start_datetime: null,
    testing_end_datetime: null,
  };
  chooseID = {
    idTest: null,
    startrangedayTest: null,
    endrangedayTest: null,
    idSub: null,
    startrangedaySub: null,
    endrangedaySub: null,
  };
  Lists;
  @Input() userData: any = [];
  constructor(
    public fb: FormBuilder,
    private swSV: SweetalertService,
    private activeRoute: ActivatedRoute,
    private cdr: ChangeDetectorRef,
    private academicsemSV: AcademicSemesterService,
    private academicYearSV: AcademicYearService,
    private testinginformationSV: TestingInformationService,
    private testingFieldSV: TestingFieldService,
    private testingRegisterSV: TestingRegisterService,
    private facultySV: FacultysService,
    private departmentSV: DepartmentService,
    private subjectSV: SubjectsService,
    private testcenterSV: TestingCenterService,
  ) {
    this.form = this.fb.group({
      examinee_card: null,
      student_code: null,
      examinee_full_name: null,
      faculty_uid: null,
      department_name: null,
      candidate_type_uid: null,
      examinee_mobile: null,
      testing_fee: '',
      testing_information_uid: null,
      payment_uid: 0,
      user_name: null,
      is_cancel: false,
      testing_subject_selecteds: this.fb.array([
        this.testing_subject_selecteds()
      ]),
    });
  }

  testing_subject_selecteds(){
    return this.fb.group({
      testing_center_uid: null,
      subject_uid: null,
      testing_datetime: null,
      period_id: null,
      branch_uid: null,
      testing_field_uid: null,
      testing_seat: null,
      is_cancel: false
    });
  }

  ngOnInit(): void {
    this.academicsemSV.getAll().subscribe(
      result => this.AcademicSemLists = result
    );
    this.academicYearSV.getAll().subscribe(
      result => this.AcademicYearLists = result
    );
    this.facultySV.getAll().subscribe(
      result => {
        this.FacultyLists = result;
      }
    );
    this.subjectSV.getAll().subscribe(
      result => {
        this.SubjectLists = result;
      }
    );
    this.testcenterSV.getAll().subscribe(
      result => {
        this.TestcenterLists = result;
      }
    );
    this.testingFieldSV.getAll().subscribe(
      result => {
        this.TestFieldLists = result;
      }
    );
    this.testcenterSV.getAll().subscribe(
      result => {
        this.TestRoomLists = result;
      }
    );
    this.testinginformationSV.getDatatype().subscribe(
      result => this.EducationTypeLists = result
    );
    this.testcenterSV.getAll().subscribe(
      result => {
        console.log(result);
        this.PeriodLists = result;
      }
    );
    this.testinginformationSV.getAll().subscribe(
      result => {
        this.TestingInformationLists = result;
        this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
          return x.is_main === true;
        });
      }
    );
    this.activeRoute.params.subscribe(
      (params: Params) => {
        console.log(params.id);
        const id = params.id;
        this.testingRegisterSV.get(id).pipe(
          tap(x => console.log(x)),
          tap(x => this.form.patchValue(x)),
          tap(x => {
            this.swSV.loadingStart();
          }),
        ).subscribe(
          async () =>{
            console.log('before delay')
            await this.delay(5000);
            this.cdr.detectChanges()
            this.swSV.close()
            // Do something after
            console.log('after delay')
          }
        );
      }
    );
  }

  delay(ms: number) {
    return new Promise( resolve => setTimeout(resolve, ms) );
  }

  add(){
    const form = this.form.get('testing_subject_selecteds') as FormArray;
    form.push(this.testing_subject_selecteds());
  }
  removeArray(i){
    const form = this.form.get('testing_subject_selecteds') as FormArray;
    form.removeAt(i);
  }

  setYearSem(data){
    console.log(data);
    this.TestInformationID = data;
    let subMain: any = [];
    this.newMaintestinginformationuID = null;
    const form = this.form.get('testing_subject_selecteds') as FormArray;
    this.testinginformationSV.get(data).subscribe(
      result => {
        console.log(1);
        console.log(result);
        const subjectlist: any = result;
        if (subjectlist.main_testing_information_uid === null){
          console.log(3);
          this.chooseID.idTest = subjectlist.testing_information_uid;
          this.chooseID.startrangedayTest = this.formatDate(subjectlist.testing_start_datetime);
          this.chooseID.endrangedayTest = this.formatDate(subjectlist.testing_end_datetime);
          console.log(subjectlist.testing_subjects);
          this.Daterange.testing_start_datetime = this.formatDate(subjectlist.testing_start_datetime);
          this.Daterange.testing_end_datetime = this.formatDate(subjectlist.testing_end_datetime);
          this.cdr.detectChanges();
          this.SubjectLists = subjectlist.testing_subjects;
          this.AcademicYearCode = result;
        }
        console.log(subjectlist.testing_rooms);
        this.TestcenterLists = subjectlist.testing_rooms;
        this.TestFieldLists = subjectlist.testing_rooms;
        this.TestRoomLists = subjectlist.testing_rooms;
        this.TestcenterLists = this.TestcenterLists.reduce((unique, o) => {
          if(!unique.some(obj => obj.branch_uid === o.branch_uid)) {
            unique.push(o);
          }
          return unique;
        }, []);
        // console.log(this.TestcenterLists);
        if (this.SubjectLists.length === 1){
          form.patchValue([
            { subject_uid: this.SubjectLists[0].subject_uid , },
          ]);
        }
        this.testinginformationSV.getCheckmaintrue(data).subscribe(
          result => {
            console.log(2);
            console.log(result);
            subMain = result;
            this.newMaintestinginformationuID = subMain[0];
            if (subMain.length !== 0){
              this.chooseID.idSub = subMain[0].testing_information_uid;
              this.chooseID.startrangedaySub = this.formatDate(subMain[0].testing_start_datetime);
              this.chooseID.endrangedaySub = this.formatDate(subMain[0].testing_end_datetime);
              const endDate =  this.newMaintestinginformationuID.testing_end_datetime;
              this.Daterange.testing_end_datetime = this.chooseID.endrangedaySub;
              console.log(this.Daterange);
              this.cdr.detectChanges();
            }
          }
        );
      }
    );
  }

  setregisterdataForm(data){
    console.log(data);
    console.log(this.TestcenterLists);
    this.testcenterSV.get(data).subscribe(
      result => {
        console.log(result);
        this.PeriodLists = result;
      }
    );
  }

  setRoom(data){
    console.log(data);
    this.testcenterSV.getAll().pipe(
      tap(x => console.log(x)),
      tap(x => this.TestRoomLists = x),
    ).subscribe(
      result => {
        this.TestRoomLists = this.TestRoomLists.filter((x) => {
          return x.testing_field_uid === data;
        });
        console.log(this.TestRoomLists);
        this.cdr.detectChanges();
      }
    );
  }

  chooseidDate(data){
    if (this.chooseID.idSub !== null){
      const d1 = this.chooseID.startrangedayTest.split('-');
      const d2 = this.chooseID.endrangedayTest.split('-');
      const s1 = this.chooseID.startrangedaySub.split('-');
      const s2 = this.chooseID.endrangedaySub.split('-');
      const c = data.split('-');
      const from = new Date(d1[0], parseInt(d1[1]) - 1, d1[2]);  // -1 because months are from 0 to 11
      const to = new Date(d2[0], parseInt(d2[1]) - 1, d2[2]);
      const fromsub = new Date(s1[0], parseInt(s1[1]) - 1, s1[2]);  // -1 because months are from 0 to 11
      const tosub = new Date(s2[0], parseInt(s2[1]) - 1, s2[2]);
      const check = new Date(c[0], parseInt(c[1]) - 1, c[2]);
      // console.log(check > from && check < to);
      // console.log(check > fromsub && check < tosub);
      if (check >= from && check <= to){
        console.log(check >= from && check <= to);
        this.form.get('testing_information_uid').setValue(this.chooseID.idTest);
        this.testinginformationSV.getAll().subscribe(
          result => {
            this.TestingInformationLists = result;
            this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
              return x.is_main === true;
            });
          }
        );
      }else if (check >= fromsub && check <= tosub){
        console.log(check >= fromsub && check <= tosub);
        this.testinginformationSV.getAll().subscribe(
          result => {
            this.TestingInformationLists = result;
            this.TestingInformationLists = this.TestingInformationLists.filter((x) => {
              return x.is_main === false;
            });
          }
        );
        this.form.get('testing_information_uid').setValue(this.chooseID.idSub);
      }
    }
  }

  setInformation(data){
    console.log(data);
    let search = '';
    if (data === '6dff8faf-0b30-4fb1-8274-42df8debe8a0'){
      search = 'นักศึกษา';
    }else if (data === 'd056ba6d-5a15-4df6-ade0-c9e8c239d1b1'){
      search = 'บุคคลทั่วไป';
    }else if (data === '5fc44678-8f36-41f6-b0e5-0901ea2231b4'){
      search = 'นักศึกษาโครงการพิเศษ';
    }
    const Detail  = this.userData.details;
    console.log(Detail);
    this.testinginformationSV.querytypeofexaminee(search).subscribe(
      res => {
        console.log(res);
        this.TestingInformationLists = res;
        this.TestingInformationLists =  this.TestingInformationLists.filter((x) => {
          return x.is_main === true;
        });
        this.TestingInformationLists = this.TestingInformationLists.filter((el) => {
          return Detail.some((f) => {
            return f.testing_information_uid === el.testing_information_uid;
          });
        });
        this.cdr.detectChanges();
      }
    );
  }

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

}
