import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, ElementRef, ViewChild} from '@angular/core';
import {FormArray, FormBuilder, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {SweetalertService} from '../../../../../../core/service/sweetalert/sweetalert';
import {BaseForm, sortByProperty} from '../../../../../../core/base/base-form';
import { UserCountersService } from 'src/app/core/service/permission/user-counters.service';
import { catchError, tap } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { splitAtColon } from '@angular/compiler/src/util';

@Component({
  selector: 'app-user-couter-form',
  templateUrl: './user-couter-form.component.html',
  styleUrls: ['./user-couter-form.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserCouterFormComponent extends BaseForm implements OnInit {
  today = new Date();
  constructor(
    public fb: FormBuilder,
    public router: Router,
    public activeRoute: ActivatedRoute,
    public location: Location,
    private swSV: SweetalertService,
    private cdr: ChangeDetectorRef,
    private userCounterSV: UserCountersService
  ) {
    super(router,activeRoute,fb,location);
  }

  ngOnInit(): void {
    if(this.state == 'edit'){
      this.userCounterSV.get(this.id).pipe(
        tap(x => this.setupForm(x)),
        tap(x => this.cdr.detectChanges())
      ).subscribe()
    }
  }

  setupForm(x){
    this.form.patchValue(x)
    this.form.get('counter_amount').setValue(x.counter_details.length)
    this.form.setControl('counter_periods',this.fb.array(x.counter_periods.map(a => this.createCounterPeriods(a))))
    this.form.setControl('counter_details',this.fb.array(x.counter_details.sort(sortByProperty('counter_no')).map(a => this.createCounterDetails(null,a))))
  }

  createForm(){
    return this.fb.group({
      counter_amount: null,
      status_id: null,
      created_by: null,
      created_datetime: null,
      updated_by: null,
      updated_datetime: null,
      deleted_by: null,
      deleted_datetime: null,
      counter_uid: null,
      counter_open_date: [null,Validators.required],
      counter_close_date: [null,Validators.required],
      total_counter: [null],
      fiscal_year: null,
      counter_periods: this.fb.array([
        this.createCounterPeriods()
      ]),
      counter_details: this.fb.array([],Validators.required)
    })
  }

  createCounterPeriods(update?){
    return this.fb.group({
      status_id: update?.status_id,
      created_by: update?.created_by,
      created_datetime: update?.created_datetime,
      updated_by: update?.updated_by,
      updated_datetime: update?.updated_datetime,
      deleted_by: update?.deleted_by,
      deleted_datetime: update?.deleted_datetime,
      counter_period_uid: update?.counter_period_uid,
      counter_uid: update?.counter_uid,
      period: [update?.period,Validators.required],
      counter_open_time: [update?.counter_open_time,Validators.required],
      counter_close_time: [update?.counter_close_time,Validators.required],
      summary_end_time: [update?.summary_end_time,Validators.required],
    })
  }

  createCounterDetails(pin,update?){
    return this.fb.group({
      status_id: update?.status_id,
      created_by: update?.created_by,
      created_datetime: update?.created_datetime,
      updated_by: update?.updated_by,
      updated_datetime: update?.updated_datetime,
      deleted_by: update?.deleted_by,
      deleted_datetime: update?.deleted_datetime,
      counter_detail_uid: update?.counter_detail_uid,
      counter_uid: update?.counter_uid,
      counter_no: [update?.counter_no,Validators.required],
      counter_pin: update? update.counter_pin : pin,
      is_use: [update?.is_use? update.is_use: false]
    })
  }

  addCounterPeriods(){
    const form = this.form.get('counter_periods') as FormArray
    form.push(this.createCounterPeriods())
  }

  removeCounterPeriods(index){
    const form = this.form.get('counter_periods') as FormArray
    form.removeAt(index)
  }

  addCounterDetails(){
    const no = this.form.get('counter_amount').value
    const form = this.form.get('counter_details') as FormArray
    form.clear()
    Array.from({ length: no }, (x, i) => {
      const pin = Math.floor(10000 + Math.random() * 90000).toString();
      form.push(this.createCounterDetails(pin))
    });
  }

  save(){
    const form = this.form.getRawValue()
    form.total_counter = form.counter_details.length
    if(this.state == 'add'){
      this.userCounterSV.add(form).pipe(
        tap(x => this.swSV.saveSuccess()),
        tap(x => this.location.back()),
        catchError(err => {
          this.swSV.errText(err.error)
          return throwError(err)
        })
      ).subscribe()
    }else{
      this.userCounterSV.update2(form).pipe(
        tap(x => this.swSV.updateSuccess()),
        tap(x => this.location.back()),
        catchError(err => {
          this.swSV.errText(err.error)
          return throwError(err)
        })
      ).subscribe()
    }
  }

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

  checkTimeValidation(event,currentForm,type){
    const formRawValue = currentForm.getRawValue()
    const isOpenTimeInitial = formRawValue.counter_open_time? false : true
    const isCloseTimeInitial = formRawValue.counter_close_time? false : true
    const isEndTimeInitial = formRawValue.summary_end_time? false : true
    const openTimeStamp = new Date(`2022-01-01 ${formRawValue.counter_open_time? formRawValue.counter_open_time: ""}`).getTime()
    const closeTimeStamp = new Date(`2022-01-01 ${formRawValue.counter_close_time? formRawValue.counter_close_time: ""}`).getTime()
    const endTimeStamp = new Date(`2022-01-01 ${formRawValue.summary_end_time? formRawValue.summary_end_time: ""}`).getTime()

    if(type == 'open'){
      if(isCloseTimeInitial) return
      if(openTimeStamp > closeTimeStamp) {
        this.swSV.errText('เวลาเปิดเค้าเตอร์มากกว่าเวลาปิดเค้าเตอร์')
        return currentForm.get('counter_open_time').setValue("00:00")
      }
    }
    if(type == 'close'){
      if(openTimeStamp > closeTimeStamp) {
        if(isOpenTimeInitial) return
        this.swSV.errText('เวลาปิดเค้าเตอร์มากกว่าเวลาเปิดเค้าเตอร์')
        if(!isEndTimeInitial) return currentForm.get('counter_close_time').setValue(currentForm.get('summary_end_time').value)
        return currentForm.get('counter_close_time').setValue("23:59")
      }
      if(endTimeStamp < closeTimeStamp){
        if(isEndTimeInitial) return
        this.swSV.errText('เวลาปิดเค้าเตอร์มากกว่าเวลาสรุปยอด')
        return currentForm.get('counter_close_time').setValue(currentForm.get('summary_end_time').value)
      }
    }
    if(type == 'end'){
      if(isCloseTimeInitial) return
      if(endTimeStamp < closeTimeStamp) {
        this.swSV.errText('เวลาสรุปยอดน้อยกว่าเวลาปิดเค้าเตอร์')
        return currentForm.get('summary_end_time').setValue(currentForm.get('counter_close_time').value)
      }
    }
  }

}
