import { DashboardService } from './../../../shared/dashboard.service';
import { UserService } from 'src/app/shared/user.service';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-report-communications',
  templateUrl: './report-communications.component.html',
  styleUrls: ['./report-communications.component.css']
})
export class ReportCommunicationsComponent implements OnInit {

  searchValue: number = null;
  userAdminstrationId: number;
  showTable: boolean = false;

  bindingDateSplitEnd;

  maintData:any = [];
  userData:any = [];
  times:any = [];
  locationList: any = [];
  subLocationList: any = [];

  parentCategoriesList = [];
  childsCategoriesList: any = [];
  departmentsIds: any = [];
  departments: any = [];
  selectedDepartments: any = [];


  //reopen object 
  reOpenReasonObject = {
    communication_id: null,
    reopen_closed_communication: '',
  }

  selectedAll: any;
  mainLocationVal = '';
  subLocationVal = '';
  checkSaveClick: boolean = false;
  checkStatusClosed: boolean = false;

  communicationData = {
    parent_category_id: null,
    child_category_id: null,
    time_period_id: '',
    maintenance_notes: '',
  };

  formData = {
    communication_id: null,
    closed_status_reason: '',
    adminstration_notes: '',
    department_status: null,
  }

  countries = [];
  identities = [];

  disabledInput: boolean = true;
  showAttachements: boolean = false;
  disabledVal: boolean = true;
  adminstrationsButtonDisabled: boolean = false;


  constructor( 
    private dashBoardSer: DashboardService,
    private userSer: UserService,
    private http: HttpClient,
    private toastr: ToastrService,
    private spinner: NgxSpinnerService,
    private authSer: AuthServiceService) { }

  
  ngOnInit() {
    this.authSer.notificationLogin = true;
    this.authSer.showSearchHeader = false;
    this.authSer.showHeaderLogin = false;
    this.authSer.showHeaderDashBoard = true;
    this.authSer.showDashboardHeader = true;
    this.authSer.internalHeader = false;
    localStorage.setItem('pageIdActive', '62');
    
        //get sections list 
        this.getsectionsList('');

        //get nationality data
        this.userSer.getNationality().subscribe(
         (responce) => {
           console.log(responce);
           this.countries = responce['countries'];
         },
         (error) => {
           console.log(error);
         }
       );
   
       //get identites
       this.userSer.onGetIdentities().subscribe(
         (responce) => {
           this.identities = responce['identities'];
           console.log('idddentiiiesssssssssss', this.identities);
         },
         (error) => {
           console.log(error);
         }
       );
   
   
       //get parent_categories_list
       this.http.get(this.authSer.pathApi + '/parent_categories_list').subscribe(
         (responce) => {
           console.log('parent_categories_list', responce);
           this.parentCategoriesList = responce['categories'];
         },
         (error) => {
           console.log(error);
         }
       );


    //get time period 
    this.http.get(this.authSer.pathApi + '/page_list/53/1/1000/for_communication').subscribe(
      (response) => {
        console.log('time period', response);
        this.times = response['time_periods'];
      },
      (error) => {
        console.log(error);
      }
    );

    //get location parent
    this.http.get(this.authSer.pathApi + '/parent_locations_list').subscribe(
      (response) => {
        this.locationList = response['locations'];
        console.log('parent location' , this.locationList);
      },
      (error) => {
        console.log(error);
      }
    );
    

  }

 








 //print function 
 onPrint() {
  window.print();
}

  onSearch() {
    console.log(this.searchValue);
    this.http.get(this.authSer.pathApi + '/report_for_communication/' + this.searchValue).subscribe(
      (responce) => {
        this.maintData = responce['communication'];
        if(this.maintData) {
          this.showTable = true;
        } else {
          this.showTable = false;
        }
        console.log('main data ', this.maintData);
        this.communicationData.maintenance_notes = this.maintData.maintenance_notes;
        this.formData.department_status = this.maintData.status == 'closed' ? this.maintData.status : false;
        this.communicationData.time_period_id = this.maintData.time_period_id;
        this.formData.closed_status_reason = this.maintData.closed_status_reason ? this.maintData.closed_status_reason : '';
        this.communicationData.parent_category_id = this.maintData.parent_category_id;
        this.getChildGategories(this.communicationData.parent_category_id);
        this.communicationData.child_category_id = this.maintData.child_category_id;
        //get main_location_id
        this.mainLocationVal = this.maintData.main_location_id;
        this.getSublocationList(this.mainLocationVal);
        this.subLocationVal = this.maintData.sub_location_id;

        this.returnEditData();
      

        // this.selectedDepartments = [];
        // if(this.maintData.adminstrations.length > 0) {
        //   for(let i = 0; i < this.maintData.departments.length; i++) {
        //     this.selectedDepartments.push(this.maintData.departments[i]);
        //     for(let j = 0; j < this.departments.length; j++) {
        //       if(this.maintData.departments[i].id == this.departments[j].id) {
        //         this.departments[i].selected = true;
        //       }
        //     }
        //   }
        // }

        // console.log('selected adminstrations', this.selectedDepartments);

        
        this.bindingDateSplitEnd = {
          year: parseInt(this.maintData.created_date.split('-')[0]),
          month: parseInt(this.maintData.created_date.split('-')[1]),
          day: parseInt(this.maintData.created_date.split('-')[2]),
        }

        this.userData = responce['communication']['user'];
        this.spinner.hide();
        console.log('gggg', this.maintData);
        if(this.maintData['files'].length > 0) {
          this.showAttachements = true;
        } else {
          this.showAttachements = false;
        }
        console.log('user data ', this.userData);
      },
      (error) => {
        console.log(error);
      }
    );
  }

  changeParentCategory(event) {
    console.log(event.target.value);
    this.getChildGategories(event.target.value);
  }  


  //get child gategories 
  getChildGategories(parentId: number) {
    this.http.get(this.authSer.pathApi + '/childs_categories_list_by_parent_id/' + parentId).subscribe(
      (responce) => {
        console.log('childs_categories_list_by_parent_id', responce);
        this.childsCategoriesList = responce['categories'];
      },
      (error) => {
        console.log(error);
      }
    );
  };

  //get adminstration list 
  getsectionsList(dataSearch) {
    const searchKey = dataSearch ? dataSearch : '';
    console.log('urrrl', this.authSer.pathApi + '/page_list/4/1/1000/' + this.userAdminstrationId);
     this.http.get(this.authSer.pathApi + '/page_list/4/1/1000/' + this.userAdminstrationId  + searchKey).subscribe(
      (responce) => {
        console.log('sections', responce);
        this.departments = responce['departments'];
        console.log('sections', responce);
      },
      (error) => {
        console.log(error);
      }
    );
  };

    //get departments ids 
    getDepartments() {
      this.selectedDepartments = [];
      for(let i = 0; i < this.departments.length; i++) {
        if(this.departments[i].selected == true) {
          this.selectedDepartments.push(this.departments[i]);
        }
      }
      console.log(this.selectedDepartments);
    }
  
    //get sub location list 
    getSublocationList(parentId: any) {
      this.http.get(this.authSer.pathApi + '/childs_locations_list_by_parent_id/' + parentId).subscribe(  
        (response)  => {
          this.subLocationList = response['locations'];
          console.log('sub Location', this.subLocationList);
        },
        (error) => {
          console.log(error)
        }
       );
    }

     //return substring of subject and check negaive and positive time 
     returnEditData() {
      for(let i = 0; i < this.maintData['adminstrations'].length; i++) {
          this.maintData['adminstrations'][i].countdown = this.maintData['adminstrations'][i].countdown ? this.dashBoardSer.secondsToDhms(this.maintData['adminstrations'][i].countdown) : '-';
          console.log(this.maintData['adminstrations'][i].countdown);
      }
    }
  
    //get value of reason reOpen
    getReopenReason(event) {
      console.log(event.target.value);
      console.log(this.reOpenReasonObject);
      this.reOpenReasonObject.reopen_closed_communication = event.target.value;
    }



}
