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-my-female-requests-add',
  templateUrl: './view-my-female-requests-add.component.html',
  styleUrls: ['./view-my-female-requests-add.component.css']
})
export class ViewMyFemaleRequestsAddComponent implements OnInit {

  editPageId: number;
  isEdit: boolean;
  typePage: string;
  checkSaveclick: boolean;
  disable: boolean;
  files = [];
  uploaded: boolean = false;
  pageId: number;
  currentPage: number;
  types = [];
  needFiles: boolean = false;
  needdate: boolean  = false;
  require_attachments: any;
  require_date: any;
  whoIsComing: any;
  isAdmin = false;
  acceptCheak = false;
  refusedCheak = false;
  statusAccept : boolean;
  statusrefu: boolean;
  comfoe: string = 'جديد';
  toster: string;
  tookDes = false;
  employeeId: string;
  complex_list = [];
  units = []
  building_types= [];
  buildings = [];
  isBuilding: boolean = false;
  isComplex: boolean = false;
  isBuildingType: boolean = false;
  userInfo: any;
  addNew: boolean = false;
  page__title: string;
  constructor(
    private dashBoardSer: DashboardService,
    private toastr: ToastrService,
    public authSer: AuthServiceService,
    private route: ActivatedRoute,
    private spinner: NgxSpinnerService,
    private location: Location,
    private http: HttpClient
  ) { }

  formData = {
    type_id:'',
    request_reason:'',
    leaving_date:'',
    leaving_time:'',
    return_date:null,
    return_time:null,
    files:[]
  }
  adminForm = {
    request_id :'',
    status:'',
    status_description:'',
  }
  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()
     //init the values of permision boolean
  this.authSer.showAddBtn = false;
  this.authSer.showDeleteBtn = false;
  this.authSer.showEditBtn = false;
  //show / hide notification search in header
  this.authSer.notificationLogin = true;
  this.authSer.showSearchHeader = false;
  this.authSer.showHeaderLogin = false;
  this.authSer.showHeaderDashBoard = true;
  this.authSer.showDashboardHeader = true;
  this.authSer.internalHeader = false;

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

  this.route.params.subscribe(
    (params: Params) => {
      this.editPageId = +params['editPageId'];
      this.whoIsComing = params['type'];
      
      console.log(this.editPageId);
      
    }
  );



  console.log('current page',this.pageId)
  this.dashBoardSer.getRequestTypesList( 1 ,10000 , 'all', 'all', 'all').subscribe(
    res => {
      console.log('x',res);
      this.types = res['types'];
   

  if (this.editPageId) {
    this.spinner.show();
    this.isEdit = true;
    this.page__title = 'عرض طلباتي'

  this.typePage = 'تعديل';
  if(this.isAdmin){
    this.typePage = 'عرض تفاصيل الطلب'
    this.page__title = 'عرض طلبات المستأجر للأدارة'


  }
    this.dashBoardSer.getItemData(this.editPageId, 'femalesRequest' ).subscribe(
      res => {
        const data = res['data'].female_request;
        const unitInfo = res['data'].unit_information
        console.log('ssss', res);
        this.formData.type_id = data.type_id;
        this.formData.request_reason = data.request_reason;
        if(this.isAdmin){
          this.adminForm.request_id = data.id;
        }
        
        this.adminForm.status = data.status;
        if(this.adminForm.status != 'new'){
          this.addNew = false;
          this.tookDes = true;
          if(this.adminForm.status == 'accepted' || this.adminForm.status == 'confirmed'){
            this.statusAccept = true;
            if(this.adminForm.status == 'accepted'){
              this.comfoe = 'مقبول'
            }else{
              this.comfoe = 'مؤكد'
            }
          }else if(this.adminForm.status == 'refused'){
            this.adminForm.status_description = data.status_description;
            this.statusAccept = false;
            this.statusrefu = true;
            this.refusedCheak = true;
            this.comfoe = 'مرفوض'
          }
        }else{
          this.comfoe = 'جديد'
          if(this.whoIsComing == 'AD74'){
            this.isAdmin = true;
            
          }
        }
        this.employeeId = data.employee_id;
        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.onRequestType(this.formData.type_id);
        console.log('>>>>>' ,this.formData.type_id);
     
       if(this.needFiles){
         this.files = data.files; 
         console.log('<><>' , this.files);
          
       }
        if(this.needdate){
          this.formData.return_date = data.return_date;
          this.formData.return_time = data.return_time;
          this.formData.leaving_date =  data.leaving_date;
          this.formData.leaving_time = data.leaving_time;
        }

        this.unitInformation.housing_complex_id = unitInfo.housing_complex_id;
          console.log(this.unitInformation.housing_complex_id );
          this.getBuildingType(this.unitInformation.housing_complex_id);
          this.unitInformation.building_type_id = unitInfo.building_type_id;
          this.unitInformation.building_id = unitInfo.building_id;
          this.getBuilding(this.unitInformation.building_type_id);
          this.unitInformation.unit_id = unitInfo.unit_id;

      },
      (error) => {
        console.log(error);
      }
    );
  }else {
    this.typePage = 'اضافة';
    this.page__title = 'عرض طلباتي'
    this.addNew = true;
    this.tookDes = false;    
    this.userInfo= localStorage.getItem('userData')
    this.userInfo = JSON.parse(this.userInfo);  
    console.log('user  ',this.userInfo);
    this.userData.name = this.userInfo.name;
    this.userData.identity_number = this.userInfo.identity_number;
    this.userData.functional_number = this.userInfo.functional_number;
    this.userData.phone = this.userInfo.phone;
    this.userData.email = this.userInfo.email;

  }

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

)

  }

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

  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);
  }
  accept(){
    this.adminForm.status = 'accepted'
    this.acceptCheak = true;
    this.refusedCheak = false;
    this.adminForm.status_description = ''
   this.toster = 'تم قبول الطلب'
  }
  refuse(){
    this.adminForm.status = 'refused'
    this.acceptCheak = false;
    this.refusedCheak = true;
    this.toster = 'تم رفض الطلب'
  }

// makeItValid(){
//   this.disable = false;
//   }


  
  onRequestType(event){
    const id = event;
    this.needFiles = false;
    this.needdate = false;
    this.disable = false;
    for (let i = 0 , n = this.types.length; i < n; i++) {
        if(this.types[i].id  == id){

          console.log('here' + id);
          const c = this.types[i]; 
          this.require_attachments = c.require_attachments;
          this.require_date = c.require_date;
          if( c.require_attachments == '1'){
           this.needFiles = true;
          
          }else{
            this.disable = false
          }
          if( c.require_date == '1'){
            this.needdate = true;
         
           }else{
             this.disable = false;
           }

          
        }
      
    }
  }

  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() {
    console.log('HERE',this.formData);
  
    
    this.disable = true;
    if(this.addNew){
      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){
          this.files.splice(i , 1);
        }
       else  if(!this.files[i].title){
        this.toastr.warning('ادخل عنوان الملف رقم ' + (i+1) );
        return 0;
       } else {
         delete this.files[i].nameFile;
          this.formData.files.push(this.files[i]);
        }
      }
    }
  if(this.isAdmin){
  
    console.log(this.adminForm);
    this.dashBoardSer.addItem( this.adminForm , 'addFemaleRequestAdmin').subscribe(
      (responce) => {
        console.log('ADD',responce);
        this.toastr.success(this.toster);
        this.checkSaveclick = false;
        this.location.back();
      },
      (error) => {
        console.log(error);
        this.checkSaveclick = false;
        this.disable = false;

        this.toastr.error('خطأ في الخادم ، حاول لاحقا');
      }
    );
    
  }else{
   
    if(this.require_date == '1'){
      if(this.formData.return_date == null || this.formData.return_time == null){
       this.toastr.warning('يجب اضافة وقت و تاريخ العوده')
        this.disable = false;

        return 0;
      }
      if(this.formData.leaving_date >= this.formData.return_date){
        this.toastr.warning('تاريخ العوده يجب ان يكون بعد تاريخ المغادرة');
        this.disable = false;
        return 0;
      }
    }
    if(this.editPageId) {
      if(this.files.length > 0){
        this.formData.files = this.files
      }
      if(this.require_attachments == '1'){
        if(this.formData.files.length <= 0){
          this.toastr.warning('يجب اضافة مرفق')
          this.disable = false;
  
          return 0;
        }
      }
      this.dashBoardSer.editItem(this.editPageId, this.formData, 'editFemaleRequest').subscribe(
        (responce) => {
          this.disable = true;
          console.log(responce);
          this.toastr.success('تم التعديل بنجاح');
          this.location.back();
        },
        (error) => {
          this.disable = false;
          console.log(error);
          this.toastr.error('خطأ في الخادم ، رجاء المحارله لاحقا');
        }
      )
    } else {

    this.dashBoardSer.addItem( this.formData , 'addFemaleRequest').subscribe(
      (responce) => {
        console.log('ADD',responce);
        this.toastr.success('تم الإضافه بنجاح');
        this.checkSaveclick = false;
        this.location.back();
      },
      (error) => {
        
        this.checkSaveclick = false;
        this.disable = false;
        if (true) {
          
        }

        this.toastr.error('خطأ في الخادم ، حاول لاحقا');
      }
    );
    }
  }
  }
}
