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, ElementRef } from '@angular/core';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-link-unit-to-covenants-add',
  templateUrl: './link-unit-to-covenants-add.component.html',
  styleUrls: ['./link-unit-to-covenants-add.component.css']
})
export class LinkUnitToCovenantsAddComponent implements OnInit {


  typePage: string = '';
  isComplex = false;
  isBuildingType = false;
  show_amount = false;
  isBuilding = false;
  amount = [];
  complex_list =[];
  building_types=[];
  buildings = [];
  valueType: string = '';
  checkSaveclick:boolean = false;
  check : boolean = false;
  isEdit: boolean = false;
  isConvenat = false;
  editPageId: number;
  units =[];
  covenant_categories = [];
  covenants = [];
  final = [] ;
  over : boolean = false;
  unitId = '';
  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;
  @ViewChild('amountVal') amountVal: ElementRef;

  formData = {
    housing_complex_id:'',
    building_type_id:'',
    building_id: '',
    unit_id:'',
    covenants:[],
  }


  categoryId:number;



  ngOnInit() {

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

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

    this.http.get(this.authSer.pathApi+ '/get_covenant_categories_list').subscribe(
      res=>{
        this.covenant_categories = res['covenant_categories'];
        console.log(this.covenant_categories);
        this.covenant_categories.forEach(conv => {
          conv.covenants.forEach(con => {
            con.covenant_amount = 0;
          })
          this.formData.covenants.push({
            category_id: conv.id,
            covenants_data: conv.covenants
          })
        });
        console.log(this.formData);
      },
      err =>{
        console.log(err);
      }
    )

    if (this.editPageId) {
      this.spinner.show();
      this.isEdit = true;
      this.show_amount = true;
      // this.showTypes = true;
      
      
      this.typePage = 'تعديل';
      this.dashBoardSer.getItemData(this.editPageId, 'linkUnitToCovenants' ).subscribe(
        res => {
          console.log('ssss', res);
          this.formData.housing_complex_id = res['unit'].housing_complex_id;
          this.getBuildingType( this.formData.housing_complex_id);
          this.formData.building_type_id = res['unit'].building_type_id;
          this.unitId = res['unit'].id;
          
          this.getBuilding(this.formData.building_type_id);
          this.formData.building_id = res['unit'].building_id;
          this.covenant(this.formData.covenants[0].category_id);
          this.covenants = res['unit'].covenants;
          console.log('conv form',this.formData.covenants);
          console.log('conv', this.covenants);
        
        for (let i = 0 , n = this.formData.covenants.length; i < n; i++) {
          const arr= this.formData.covenants[i].covenants_data; 
          for (let ii = 0, k = arr.length; ii < k; ii++) {
            for (let j = 0 , m = this.covenants.length; j < m; j++) {
              if(arr[ii].id == this.covenants[j].covenant_id){
                arr[ii].selected = true;
                arr[ii].covenant_amount = this.covenants[j].covenant_amount;
              }
            }
            
              
            }
            
          }
          this.spinner.hide();
          },
      
        err => {
          console.log(err);
        }
      );
     
    }else {
      this.typePage = 'اضافة';
    }

  }

  getBuildingType(event){
    this.building_types = []
    console.log('sdsdsd',event);
    const id = event;
    this.isComplex = false;
    this.isBuildingType = false;
    this.show_amount = false;
    this.isBuilding = false;
 
  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;
           this.toastr.warning('لا يوجد انواع مباني لهذا المجمع')

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

  getBuilding(event){
    this.buildings = []
    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);
          if(this.editPageId) {
            this.getUnit(this.formData.building_id );
          }
        }else{
             this.isBuildingType = false;
             this.isBuilding = false;
             this.isConvenat = false;
           this.toastr.warning('لا يوجد بيانات لهذا النوع من المباني')
            
          }
          
      },
      err => {
        console.log(err);
        
      }
    );
}

getUnit(event){
  console.log('unit id >>' , this.unitId);
  this.units = []
  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;
           this.isConvenat = false;
           this.toastr.warning('لا يوجد وحدات لهذا المبنى ')
        }

    },
    err => {
      console.log(err);
      
    }
  );
  this.formData.unit_id = this.unitId;
  console.log('dffd',this.formData.unit_id);
  if (this.editPageId) {
    this.showcovenant_categories()

  }
  
  
}

    covenant(event){ 
      const id = event;
      console.log(id);
      this.categoryId = id;
      console.log(this.formData.covenants);
    } 

    check_max(value, max, name){
      console.log( 'ss',value, max, name);
      if(value > max){
        this.toastr.warning('عفوا لقد تجاوزت العدد المحدد لـ'+name)
      }
    } 
    showcovenant_categories(){
      this.isConvenat = true;
    }

    checked(event){
      console.log(event);
      for(let i = 0, m = this.formData.covenants.length; i < m ; i++) {

        //final finalCov array to add categories in covenants
       for(let j = 0 , n =  this.formData.covenants[i].covenants_data.length; j < n; j++) {
          
              if(event == this.formData.covenants[i].covenants_data[j].id ){

                // this.formData.covenants[i].covenants_data[j].covenant_amount = 1
                  if(this.formData.covenants[i].covenants_data[j].selected == false){
                    this.formData.covenants[i].covenants_data[j].covenant_amount = 0
                    }else{
                      this.formData.covenants[i].covenants_data[j].covenant_amount = 1
                    }
                
                              
              }
        }
       
     };
      
    }

    onSubmitted(){
      //final array to add covenants
      
      const finalCov = [];
      for(let i = 0; i < this.formData.covenants.length; i++) {

        //final finalCov array to add categories in covenants
       for(let j = 0; j < this.formData.covenants[i].covenants_data.length; j++) {
         if(this.formData.covenants[i].covenants_data[j].selected != undefined && this.formData.covenants[i].covenants_data[j].selected == true) {
        const  realamount = this.formData.covenants[i].covenants_data[j].covenant_amount;
        const  available_amount =   this.formData.covenants[i].covenants_data[j].available_amount;
           if (realamount > available_amount){
            this.over = true;
            return 0;
           }
          finalCov.push({
            covenant_id:this.formData.covenants[i].covenants_data[j].id,
            covenant_amount: this.formData.covenants[i].covenants_data[j].covenant_amount,
            category_id: this.formData.covenants[i].covenants_data[j].category_id
          })
         }
        }
       
     };

     this.final =  this.formData.covenants
     this.formData.covenants = finalCov;
     console.log(finalCov.length);
     
     if(finalCov.length == 0){
       this.toastr.warning('من فضلك قم بأختيار عهدة!!');
       this.formData.covenants = this.final;
       this.final = [];
       return 0;
     }

      console.log(this.formData);

        if(this.editPageId) {
          this.dashBoardSer.editItem(this.editPageId, this.formData, 'linkUnitToCovenants').subscribe(
            res => {
              console.log(res);
              this.toastr.success('تم التعديل بنجاح');
              this.location.back();
            },
            err => {
              this.formData.covenants = this.final;
              this.final = [];
              console.log(err);
              this.toastr.error('خطأ في الخادم ، رجاء المحارله لاحقا');

            }
          )
        } else {
          this.dashBoardSer.addItem( this.formData , 'linkUnitToCovenants').subscribe(
            res => {
                console.log('ADD',res);
                this.toastr.success('تم الإضافه بنجاح');
                this.checkSaveclick = false;
                this.location.back();
              },
              err => {
                this.formData.covenants = this.final;
                this.final = [];
                console.log(err);
                this.checkSaveclick = false;
                this.toastr.error('خطأ في الخادم ، حاول لاحقا');
              }
          );
        }
      
    }



  }






