import { NgxSpinnerService } from 'ngx-spinner';

import { ActivatedRoute, Params, Router } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { Location, formatDate } from '@angular/common';

import { UserService } from 'src/app/shared/user.service';
import { DashboardService } from 'src/app/shared/dashboard.service';
import { HttpClient } from '@angular/common/http';
import { AuthServiceService } from 'src/app/shared/auth-service.service';

@Component({
  selector: 'app-application-for-housing',
  templateUrl: './application-for-housing.component.html',
  styleUrls: ['./application-for-housing.component.css']
})
export class ApplicationForHousingComponent implements OnInit {
  departmentUserLoginId: any;

  constructor(
    private route: ActivatedRoute, 
    private http: HttpClient,
    private toastr: ToastrService,
    private dashBoardSer: DashboardService,
    private spiner: NgxSpinnerService,
    private location: Location,
    public authService: AuthServiceService,
    private userService: UserService,
    private router: Router
  ) { }
  subLocationList = [];
  checkSaveClick: boolean = false;
  bindingDateSplitStart;
  checked : boolean = false;
  pageId: number;
  uploaded: boolean = false;
  disabledVal: boolean = true;
  serviceId: number;
  userId: number = 0;
  search: any;
  reportVal:boolean = false;
  saveTherequist: boolean = false;
  whosend = '';
  applyForOther : boolean = false;
  showdetails : boolean = false;
  showSearch: boolean = false;
  send: boolean = true;
  searchValue = null;
  applyForm = {
    employee_id: null,
    files:[]
  };

  dataForm = {
    id_number: '',
    name : '',
    phoneNum: '',
    functional_number:'',
    email:''
  };

  files = [{
    title : null,
    file: null,
    file_type: null,
    nameFile: null,
  }];

  ngOnInit() {
      //init the values of permision boolean
      this.authService.showAddBtn = false;
      this.authService.showDeleteBtn = false;
      this.authService.showEditBtn = false;
      //show / hide notification search in header
      this.authService.notificationLogin = true;
      this.authService.showSearchHeader = false;
      this.authService.showHeaderLogin = false;
      this.authService.showHeaderDashBoard = true;
      this.authService.showDashboardHeader = true;
      this.authService.internalHeader = false;

      this.route.params.subscribe(
        (parmas: Params) => {
          this.pageId =  +parmas['reportId'];
          localStorage.setItem('pageIdActive', parmas['reportId']);
          this.whosend = parmas['comefrom'];
        }
      );
      this.route.parent.params.subscribe(
        (params:Params) => {
          this.serviceId = params['serviceID'];
          this.userId = params['userID'];
        }
      );

      if(this.whosend == 'new'){
      this.http.get(this.authService.pathApi + '/profile').subscribe(
        res => {
         this.dataForm.id_number = res['user'].identity_number;
         this.dataForm.name = res['user'].name;
         this.dataForm.phoneNum = res['user'].phone;
         this.applyForm.employee_id = res['user'].id;
          console.log(this.applyForm.employee_id);

         this.dataForm.functional_number = res['user'].functional_number;
         this.dataForm.email = res['user'].email;
         console.log('dsf',res)
          this.showdetails = true;
          this.applyForOther = false;
          this.send = false;
        },
        (error) => {console.log(error)},
      );
      }else{
        this.showSearch = true;
      }
      
      if(this.whosend == 'new'){
      this.http.get(this.authService.pathApi + '/get_employee_request_status/' +   this.userId).subscribe(
        res => {
          console.log('ser' , res);
          const status = res['status']
          if(status == 'employee free to make new request'){
            this.location.back();
            this.toastr.warning('لديك طلب بالفعل');
            
          }else if(status == 'employee free to make new request'){
            console.log('Done');
            
          }
        },
        err => {
            console.log(err);
            
        }
      );
      }
  }

  plusImage() {
    this.files.push({
      title: null,
      file: null,
      file_type: null,
      nameFile: null,
    });
    console.log('files after plus ', this.files);
  }

   //delete row from table
 onDeleteRow(index:number) {
  this.files.splice(index , 1);
  console.log('files after delete ',this.files);
}
  //change file 
  onFileChanges(event, index:number) {
    console.log(event);
    console.log(index);
    this.uploaded = true;
    this.files[index].nameFile = event[0].name.substring(0,20) + '....';
    this.files[index].file = event[0].base64;
    this.files[index].file_type = event[0].type.split('/')[1];
      console.log(this.files);
      console.log('files after change ',this.files);
  }

  SearchOnUser(){
    const key = this.searchValue
    console.log(key);
      console.log('here');
      
    this.http.get(this.authService.pathApi + '/find_user/' + key ).subscribe(
      res => {
        console.log('user',res);
        if(res['user'] == null){
          this.showdetails = false;
        }else{
        this.dataForm.id_number = res['user'].identity_number;
         this.dataForm.name = res['user'].name;
         this.dataForm.phoneNum = res['user'].phone;
         this.applyForm.employee_id = res['user'].id;
         this.dataForm.functional_number = res['user'].functional_number;
         this.dataForm.email = res['user'].email;
         this.applyForOther = true;
         this.showdetails = true;
         this.http.get(this.authService.pathApi + '/get_employee_request_status/' +   this.applyForm.employee_id).subscribe(
          res => {
            console.log('ser' , res);
            const status = res['status']
            if(status == 'employee free to make new request'){
              this.toastr.warning('لديه طلب بالفعل');
              this.applyForOther = false;
              this.showdetails = false;
            }
          },
          err => {
              console.log(err);
              
          }
        );

        }
      },
      err => {
        console.log(err);
        this.showdetails = false;        
      }
    );
    // }
  }
  
  onSubmitted(){
    for (let i = 0; i < this.files.length; i++) {
      if(this.files[i].file_type){
        this.files[i].file_type = this.files[i].file_type.toLowerCase();
      }
      if(this.files[i].file != null && this.files[i].title == null){
       this.toastr.warning('ادخل عنوان الملف رقم ' + (i+1) );
       this.checked = true;
      }else if(this.files[i].file == null && this.files[i].title != null){
        this.files.splice(i , 1);
      }else if(this.files[i].file == null && this.files[i].title == null){
        this.files.splice(i , 1);
       } else {
       delete this.files[i].nameFile;
        this.applyForm.files.push(this.files[i]);
      }
    }
    if(!this.checked){
     

    console.log(this.applyForm);
     this.http.post(this.authService.pathApi + '/add_housing_request' , this.applyForm )
      .subscribe(
         res => {
           console.log(res);
           this.checked = false;
           this.toastr.success('تم حفظ الطلب ');
          //  this.router.navigate(['/service/' + this.userId + '/' +  this.serviceId + '/followCommunicationList/58']);
          this.location.back();
          },
          err => {
           console.log(err)
           this.toastr.error('حدث خطأ في الاتصال ');
          }
       );
    }else{
      console.log('i cant send the request');
    }
  
    }


}
