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-view-requests-for-tenant-details',
  templateUrl: './view-requests-for-tenant-details.component.html',
  styleUrls: ['./view-requests-for-tenant-details.component.css']
})
export class ViewRequestsForTenantDetailsComponent implements OnInit {

  detailsId: number;
  employeeId: any;
  files = [];
  uploaded: boolean = false;
  unitId: any;
  acceptCheak: boolean = false;
  refusedCheak: boolean = false;
  waitingCheak: boolean = false;
  complex_list =[];
  building_types=[];
  buildings = [];
  units =[];
  isComplex = false;
  isBuildingType = false;
  isBuilding = false;
  status = ''
  notvailed: boolean = true
  covenants= []
  confirmedcheck: boolean;
  constructor(
    private dashBoardSer: DashboardService,
    private toastr: ToastrService,
    public authSer: AuthServiceService,
    private route: ActivatedRoute,
    private spinner: NgxSpinnerService,
    private location: Location,
    private http: HttpClient
  ) { }


  @ViewChild('f') linkForm : NgForm;

  formData = {
    request_id:'',
    status:'',
    refused_reason:'',
    waiting_reason:'',
    unit_id: '',
    files: []
  }
  onSending = {
    request_id:'',
    status:'',
  }
  userData = {
    name:'',
    identity_number:'',
    functional_number:'',
    phone:'',
    email:''
  }
  unitInformation = {
    housing_complex_id: '',
    building_type_id: '',
    building_id:'',
    unit_id:'',
    bedrooms_number:'',
    bathrooms_number:'',
    covenants: [],
    independent_kitchen: 'yes',
    sittingrooms_number:''
  }



  ngOnInit() {

    this.spinner.show();
    

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


    this.http.get(this.authSer.pathApi + '/housing_complexes_list').subscribe(
      res => {
        this.complex_list = res[('housing_complexes')];
      }
    );

    this.dashBoardSer.getItemData(this.detailsId, 'viewRequestsForAdminstrationDetails' ).subscribe(
      res => {
        console.log('ssss', res);
        // this.editFunction()
       
        this.employeeId = res['request'].employee_id;
        this.files = res['request'].files;
        this.formData.request_id = res['request'].id;
        this.formData.refused_reason = res['request'].refused_reason;
        this.formData.waiting_reason = res['request'].waiting_reason;
        this.formData.status = res['request'].status
        if(this.formData.status == 'accepted' ||  this.formData.status == 'ended' || this.formData.status == 'confirmed'){
          this.unitInformation.housing_complex_id = res['request'].unit_information.housing_complex_id;
          console.log(this.unitInformation.housing_complex_id );
          this.getBuildingType(this.unitInformation.housing_complex_id);
          this.unitInformation.building_type_id = res['request'].unit_information.building_type_id;
          this.getBuilding(this.unitInformation.building_type_id);
          this.unitInformation.building_id = res['request'].unit_information.building_id;
          this.unitInformation.unit_id = res['request'].unit_id;
          this.unitInformation.bedrooms_number = res['request'].unit_information.bedrooms_number;
          this.unitInformation.bathrooms_number = res['request'].unit_information.bathrooms_number;
          this.unitInformation.covenants = res['request'].unit_information.covenants;
          this.unitInformation.independent_kitchen = res['request'].unit_information.independent_kitchen;
          this.unitInformation.sittingrooms_number = res['request'].unit_information.sittingrooms_number;
          this.covenants =  res['request'].unit_information.covenants;
           if( this.formData.status == 'confirmed'){
            this.confirmed()
           }else{
            this.accept()
           }
        }else if(this.formData.status == 'waiting'){
          this.waiting()
         }else if(this.formData.status == 'refused') {
          this.refuse()
         }else
        this.http.get(this.authSer.pathApi + '/get_user/' + this.employeeId).subscribe(
          res =>{
            console.log('=>',res);
            this.userData.name = res['user'].name;
            this.userData.identity_number = res['user'].identity_number;
            this.userData.functional_number = res['user'].functional_number;
            this.userData.phone = res['user'].phone;
            this.userData.email = res['user'].email;

          },
          err =>{
            console.log(err);
            
          }
        )
        this.files = res['request'].files;
     
        },
    
      err => {
        console.log(err);
      }
    );
    this.spinner.hide();


  }
  confirmed(){
    this.confirmedcheck = true;
    this.refusedCheak = false;
    this.waitingCheak = false;
  }
  
  accept(){
    this.formData.status = 'accepted'
    this.acceptCheak = true;
    this.refusedCheak = false;
    this.waitingCheak = false;
    this.formData.waiting_reason = ''
    this.formData.refused_reason = ''
   this.status = 'تم قبول الطلب'
  }
  waiting(){
    this.formData.status = 'waiting'
    this.acceptCheak = false;
    this.refusedCheak = false;
    this.waitingCheak = true;
    this.formData.refused_reason = ''
    this.unitInformation.unit_id = ''
    this.unitInformation.housing_complex_id = ''
    this.unitInformation.building_type_id = ''
    this.unitInformation.building_id = ''
    this.isComplex = false;
    this.isBuildingType = false;
    this.isBuilding = false;
    this.status = 'الطلب في حالة الانتظار'

  }
  refuse(){
    this.formData.status = 'refused'
    this.acceptCheak = false;
    this.refusedCheak = true;
    this.waitingCheak = false;
    this.formData.waiting_reason = ''
    this.unitInformation.unit_id = ''
    this.unitInformation.housing_complex_id = ''
    this.unitInformation.building_type_id = ''
    this.unitInformation.building_id = ''
    this.isComplex = false;
    this.isBuildingType = false;
    this.isBuilding = false;
    this.status = 'تم رفض الطلب'
  }

  getBuildingType(event){
    console.log('sdsdsd',event);
    const id = event;
 
  console.log(id);

    this.http.get(this.authSer.pathApi+ '/building_types_list/' + id ).subscribe(
      res => {
        console.log(res);
        this.building_types = res[('building_types')];
        if(this.building_types.length > 0)
         this.isComplex = true;
         else {
           this.isComplex = false;
           this.isBuildingType = false;
           this.isBuilding = false;
        }
      },
      err => {
        console.log(err);
        
      }
    );
  }

  getBuilding(event){
    this.http.get(this.authSer.pathApi + '/buildings_list_by_type_id/' + event ).subscribe(
      res => {
        console.log('res',res);
        this.buildings = res['buildings'];
        if(this.buildings.length > 0){
          this.isBuildingType = true;
          console.log(this.buildings);
          this.getUnit(this.unitInformation.building_id);         
        }else{
             this.isBuildingType = false;
             this.isBuilding = false;
            
          }
          
      },
      err => {
        console.log(err);
        
      }
    );
}

getUnit(event){
  this.http.get(this.authSer.pathApi + '/units_list_by_building_id/' + event ).subscribe(
    res => {
      console.log(res);
      this.units = res['units'];
      if(this.units.length > 0){
        this.isBuilding = true;
        console.log(this.units);

      }else{
           this.isBuilding = false;
        }

    },
    err => {
      console.log(err);
      
    }
  );
}


onSubmitted(status) {
  this.onSending.request_id = this.formData.request_id; 
  this.notvailed = true;
  this.onSending.status = status;
  console.log(this.onSending);
  this.http.post(this.authSer.pathApi + '/employee_handle_housing_request' , this.onSending).subscribe(
    res => {
      console.log(res);
      if(status == 'confirmed'){
        this.toastr.success('تم تأكيد الطلب')
      }else if (status == 'refused'){
        this.toastr.error('تم رفض الطلب')
      }
      this.location.back()
      
    },
    err => {
      console.log(err);
      this.toastr.error('يرجى المحاولة لاحقا')
      
    }
  )
  
}

}
