import { HttpClient } from '@angular/common/http';
import { NgxSpinnerService } from 'ngx-spinner';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ToastrService } from 'ngx-toastr';
import { DashboardService } from './../../../shared/dashboard.service';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
  selector: 'app-register-movement-vehicle-add',
  templateUrl: './register-movement-vehicle-add.component.html',
  styleUrls: ['./register-movement-vehicle-add.component.css']
})


export class RegisterMovementVehicleAddComponent implements OnInit {

  constructor(private dashBoardSer: DashboardService,
    private toastr: ToastrService,
    private authSer: AuthServiceService,
    private route: ActivatedRoute,
    private spinner: NgxSpinnerService,
    private location: Location,
    private http: HttpClient
  ) { }

  @ViewChild('f') vehicleForm : NgForm;

  typePage: string = '';
  vehicleReceiptDate = '';
  vehicleDeliveryDate:string = '';
  bindingDateSplitStart;
  bindingDateSplitEnd;

  checkSaveclick:boolean = false;
  typeMode: boolean = false;

  vehicleId: number;
  vehicleNumber: number;

  vehicle_types:any[] = [];
  modelNames:any[] = [];
  vehicleDataTable:any[]=[];
  registerVehicleId: number;
  startDate: string = '';
  endDate: string = '';

  count: number;
  perPagePagenation: number;
  currentPage:number = 1;
  dataTableNumber: number = 5;

  formData = {
    vehicle_id: '',
    vehicle_recipient_name: '',
    phone: '',
    start_mileage_recording: '',
    end_mileage_recording: '',
    movement_notes: '',
  }

  ngOnInit() {

    this.http.get(this.authSer.pathApi + '/get_vehicle_types_list').subscribe(
      (response) => {
        console.log(response);
        this.vehicle_types = response['types'];
      },
      (error) => {
        console.log(error);
      });

      this.route.params.subscribe(
        (params: Params) => {
          this.registerVehicleId = params['registerMovementVehicleEditId'];
        }
      );

      if(this.registerVehicleId) {
        this.spinner.show();
        this.typePage = 'تعديل';
        this.typeMode = true;
        this.dashBoardSer.getItemData(this.registerVehicleId, 'registerMovementVehicle').subscribe(
          (responce) => {
            console.log(responce);
            this.formData.phone = responce['movement'].phone;
            this.formData.movement_notes = responce['movement'].movement_notes;
            this.formData.vehicle_id = responce['movement'].vehicle_id;
            this.formData.vehicle_recipient_name = responce['movement'].vehicle_recipient_name;
            this.formData.end_mileage_recording = responce['movement'].end_mileage_recording;
            this.formData.start_mileage_recording = responce['movement'].start_mileage_recording;
            this.startDate = responce['movement'].vehicle_receipt_date;
            this.endDate = responce['movement'].vehicle_delivery_date;
            this.bindingDateSplitStart = {
              year: parseInt(responce['movement'].vehicle_receipt_date.split('-')[0]),
              month: parseInt(responce['movement'].vehicle_receipt_date.split('-')[1]),
              day: parseInt(responce['movement'].vehicle_receipt_date.split('-')[2]),
            }
            this.bindingDateSplitEnd = {
             year: parseInt(responce['movement'].vehicle_delivery_date.split('-')[0]),
             month: parseInt(responce['movement'].vehicle_delivery_date.split('-')[1]),
             day: parseInt(responce['movement'].vehicle_delivery_date.split('-')[2]),
           }
            this.spinner.hide();
          },
          (error) => {
            console.log(error);
          }
        );

        this.dashBoardSer.getDataUSerSearchBar(this.vehicleNumber,
          47,
         this.currentPage,
         this.dataTableNumber).subscribe(
         (responce) => {
           console.log('search table edit ', responce);
           this.vehicleDataTable = responce['vehicle_movements'];
         },
         (error) => {
           console.log(error);
         }
       );

      } else {
        this.typePage = 'إضافه';
      }
  }


    //get value date from child component
    public getDate(date: any , type: string):void {

      if(date.month < 10) {
        date.month = '0' + date.month;
      }

      if(date.day < 10) {
        date.day = '0' + date.day;
      }

      console.log( date);


      if(type == 'start') {
        this.startDate = date.year + '-' + date.month + '-' + date.day;
        console.log('start date', this.startDate);
      } else if(type == 'end') {
        this.endDate = date.year + '-' + date.month + '-' + date.day;
        console.log('end date', this.endDate);
      } else {
        console.log('not type recieved !');
      }

    }

     //change page
    onPageChange(pagenationNumber) {
      this.spinner.show();
      this.currentPage = pagenationNumber;
      this.vehicleDataTable = [];
      //console.log(pagenationNumber);
      //console.log(this.pageId);
      this.dashBoardSer.getListData(47, pagenationNumber, this.dataTableNumber).subscribe(
      (responce) => {
        console.log('search result ', responce);
        this.vehicleDataTable = responce['vehicle_movements'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        console.log(this.vehicleDataTable);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
      );
    };

    //determine the list count from select element
    onGetValue(event) {
      this.spinner.show();
      this.vehicleDataTable = [];
      this.dataTableNumber = event.target.value;
      this.dashBoardSer.getListData(47, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.vehicleDataTable = responce['vehicle_movements'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    };
    onChangeVehicleType(event) {
      const typeId = event.target.value;
      this.getModelName(typeId);
    }
    getModelName(typeVehicleId) {
      this.http.get(this.authSer.pathApi + '/get_vehicle_models_by_type_id/' + typeVehicleId).subscribe(
        (responce) => {
          console.log('types names of vehicles ', responce);
          this.modelNames = responce['models'];
          if(this.modelNames.length == 0) {
            this.toastr.warning('لا يوجد اسماء موديل لهذا النوع');
          }
        },
        (error) => {
          console.log(error);
        }
      )
    }

    onSubmitted() {

      this.checkSaveclick = true;

      this.vehicleForm.value['vehicle_receipt_date'] = this.startDate;
      this.vehicleForm.value['vehicle_delivery_date'] = this.endDate;

      console.log(this.vehicleForm.value);
      const startDateData = this.startDate.split('-');
      const endDateData = this.endDate.split('-');

      if(this.typeMode) {

        if(startDateData[0] > endDateData[0]) {
          this.toastr.warning('سنه تاريخ الإنتهاء يجب أن تكون أكبر من سنه تاريخ الإنتهاء !');
          this.checkSaveclick = false;
        } else if(startDateData[0] == endDateData[0] && startDateData[1] > endDateData[1]){
          this.toastr.warning('شهر تاريخ الانتهاء يجب أن يكون أكبر من شهر تاريخ الإبتداء !');
          this.checkSaveclick = false;
        } else if(startDateData[1] == endDateData[1] && startDateData[2] > endDateData[2]){
          this.toastr.warning(' يوم تاريخ الإنتهاء يجب أن يكون أكبر من يوم تاريخ الإبتداء!');
          this.checkSaveclick = false;
        } else {
          this.dashBoardSer.editItem( this.registerVehicleId, this.vehicleForm.value, 'registerMovementVehicle').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم التعديل بنجاح');
              this.location.back();
            },
            (error) => {
              console.log(error);
              this.toastr.error('خطأ في الخادم ، حاول لاحقاً');
              this.checkSaveclick = false;
            }
          );
        }

      } else {

        if(startDateData[0] > endDateData[0]) {
          this.toastr.warning('سنه تاريخ الإنتهاء يجب أن تكون أكبر من سنه تاريخ الإنتهاء !');
          this.checkSaveclick = false;
        } else if(startDateData[0] == endDateData[0] && startDateData[1] > endDateData[1]){
          this.toastr.warning('شهر تاريخ الانتهاء يجب أن يكون أكبر من شهر تاريخ الإبتداء !');
          this.checkSaveclick = false;
        } else if(startDateData[1] == endDateData[1] && startDateData[2] > endDateData[2]){
          this.toastr.warning(' يوم تاريخ الإنتهاء يجب أن يكون أكبر من يوم تاريخ الإبتداء!');
          this.checkSaveclick = false;
        } else {
          this.dashBoardSer.addItem(this.vehicleForm.value, 'registerMovementVehicle').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الإضافه بنجاح');
              this.location.back();
              this.checkSaveclick = false;
            },
            (error) => {
              this.checkSaveclick = false;
              console.log(error);
              console.log(this.vehicleForm.value['phone'].length);
              if(this.vehicleForm.value['phone'].length < 10) {
                this.toastr.warning('رقم الجوال يجب أن يكون مكون 10 أرقام')
              } else {
                this.toastr.error('خطأ في الخادم ، برجاء المحاوله لاحقا');
              }
            }
          );
        }

      }

    }

}
