import { NgxSpinnerService } from 'ngx-spinner';
import { ActivatedRoute, Params } from '@angular/router';
import { DashboardService } from './../../../shared/dashboard.service';
import { HttpClient } from '@angular/common/http';
import { UserService } from './../../../shared/user.service';
import { FormGroup, Validators, FormControl, NgForm } from '@angular/forms';
import { Component, OnInit, ViewChild } from '@angular/core';
import { AuthServiceService } from '../../../shared/auth-service.service';
import { ToastrService } from 'ngx-toastr';
import { Location } from '@angular/common';

@Component({
  selector: 'app-section-review-trainee-add',
  templateUrl: './section-review-trainee-add.component.html',
  styleUrls: ['./section-review-trainee-add.component.css']
})
export class SectionReviewTraineeAddComponent implements OnInit {

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

  typeLink:string = '';
  userId: number;
  checkSaveClick:boolean = false; //to make save button is disabled when click save 
  disabledInput: boolean = false; //to make button dsabled in create mode 
  showEditField: boolean = false; //to show the field in edit mode 
  showRefusedCause: boolean = false; //to show the cause of refused when ststus is refused
  editMode: boolean = false; //true in edit mode 
  isConfirmedStatus: boolean = false;
  typeMode:boolean = true;
  reportId: number;
  attachments_ids = []; //for edit mode;

  countries: any[] = [];
  identities: any[] = [];
  trainees:any[] = [];
  departments:any[] = [];
  departmentsId:any[] = [];

  bindingDateSplitStart;
  bindingDateSplitEnd;

  @ViewChild('f') traineeForm: NgForm;

  //all form data 
  formData = {
    trainee: '',
    type: '',
    specialization_name: '',
    specific_specialization: '',
    university: '',
    level: '',
    training_period: '',
    registration_number: '',
    authority_card_number: '',
    functional_number: '',
    contract_type: '',
    organization_affiliated_with: '',
    department1: '',
    department2: '',
    department3: '',
    status_description: '',
  }

  //user data object
  userData = {
    name: '',
    email: '',
    nationality_id: '',
    identity_number: '',
    identity_type_id: '',
    birthday: '',
    gender: '',
    phone: '',
  }

  //action form
  
  actionConfirmedForm={
    start_date: '',
    end_date: '',
    in_training: 0,
    id: null,
  }

  actionOpinionForm = {
    department_opinion: '',
    department_id: null,
    request_id: null,
  }

  identity_id: number = 0; //to determine te number of identity to validation
  identity_type: number;

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

  startDate: string = '';
  endDate: string= '';

  ngOnInit() {

    //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;

    //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 trainee data
    this.http.get(this.authSer.pathApi + '/get_trainees').subscribe(
      (responce) => {
        this.trainees = responce['users'];
        console.log(this.trainees);
      },
      (error) => {
        console.log(error);
      }
    );

    //get departments
    this.http.get(this.authSer.pathApi + '/training_adminstration_departments').subscribe(
      (responce) => {
        this.departments = responce['departments'];
        console.log(this.departments);
      },
      (error) => {
        console.log(error);
      }
    );

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

    if(this.reportId) {
      this.spinner.show();
      this.actionOpinionForm.request_id = this.reportId;
      this.actionConfirmedForm.id = this.reportId;
      this.files = [];
      this.dashBoardSer.getItemData(this.reportId, 'sectionReviewTrainee').subscribe(
        (responce) =>{
          console.log('datarequest ', responce);
          this.disabledInput = true;
          if(responce['data']['request'].status == 'accepted') {
            this.isConfirmedStatus = true;
          } else {
            this.isConfirmedStatus = false;
          }

          this.formData.trainee = responce['data']['user'].id;
          this.formData.type = responce['data']['request'].type;
          this.formData.specialization_name = responce['data']['request'].specialization_name;
          this.formData.specific_specialization = responce['data']['request'].specific_specialization;
          this.formData.level = responce['data']['request'].level;
          this.formData.contract_type = responce['data']['request'].contract_type;
          this.formData.university = responce['data']['request'].university;
          this.formData.authority_card_number = responce['data']['request'].authority_card_number;
          this.formData.training_period = responce['data']['request'].training_period;
          this.formData.functional_number = responce['data']['request'].functional_number;
          this.formData.organization_affiliated_with = responce['data']['request'].organization_affiliated_with;
          this.formData.registration_number = responce['data']['request'].registration_number;
          this.userData.name = responce['data']['user'].name;
          this.userData.email = responce['data']['user'].email;
          this.userData.identity_number = responce['data']['user'].identity_number;
          this.userData.identity_type_id = responce['data']['user'].identity_type_id;
          this.userData.phone = responce['data']['user'].phone;
          this.userData.birthday = responce['data']['user'].birthday;
          this.userData.gender = responce['data']['user'].gender;
          this.userData.nationality_id = responce['data']['user'].nationality_id;
          this.userId = responce['data']['user'].id;
          this.userData['id'] = this.userId;
          this.userData.name = responce['data']['user'].name;
          this.userData.nationality_id = responce['data']['user'].nationality_id;
          this.userData.identity_type_id = responce['data']['user'].identity_type_id;
          this.userData.identity_number = responce['data']['user'].identity_number;
          this.userData.email = responce['data']['user'].email;
          this.userData.birthday = responce['data']['user'].birthday;
          this.userData.phone = responce['data']['user'].phone;
          this.userData.gender = responce['data']['user'].gender;
          this.userId = responce['data']['user'].id;

          this.actionConfirmedForm.start_date = responce['data']['request'].start_date;
          this.actionConfirmedForm.end_date = responce['data']['request'].end_date;

          this.bindingDateSplitStart = {
            year: parseInt(responce['data']['request'].start_date ? responce['data']['request'].start_date.split('-')[0] : ''),
            month: parseInt(responce['data']['request'].start_date ? responce['data']['request'].start_date.split('-')[1] : ''),
            day: parseInt(responce['data']['request'].start_date ? responce['data']['request'].start_date.split('-')[2] : ''),
          }

          this.bindingDateSplitEnd = {
           year: parseInt(responce['data']['request'].end_date ? responce['data']['request'].end_date.split('-')[0] : ''),
           month: parseInt(responce['data']['request'].end_date ? responce['data']['request'].end_date.split('-')[1] : ''),
           day: parseInt(responce['data']['request'].end_date ? responce['data']['request'].end_date.split('-')[2] : ''),
         }
            //add departmrnts ids 
            if(responce['data']['request'].departments.length > 0) {
              for(let i = 0; i < responce['data']['request'].departments.length; i++) {
                if(i == 0) {
                  this.formData.department1 = responce['data']['request'].departments[0].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
                } else if(i == 1) {
                  this.formData.department2 = responce['data']['request'].departments[i].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
                } else if(i == 2) {
                  this.formData.department3 = responce['data']['request'].departments[i].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
              }
            }
          }

          for(let i = 0; i < responce['data']['request'].departments.length; i++) {
            if(responce['data']['request'].departments[i].asked_for_opinion == 1) {
              this.actionOpinionForm.department_id = responce['data']['request'].departments[i].department_id;
            }
          }
  
  
          if(responce['data']['request'].attachments.length > 0) {
            for(let i = 0; i < responce['data']['request'].attachments.length; i++) {
              this.attachments_ids.push(responce['data']['request'].attachments[i].id);
              this.files.push({
                title: responce['data']['request'].attachments[i].title,
                file: '',
                nameFile: responce['data']['request'].attachments[i].file,
                file_type: '',
                id: responce['data']['request'].attachments[i].id,
              })
            }
            console.log('attachements ids', this.attachments_ids);
          } else {
            console.log('no attachements user add !');
          }

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

  }

  //when click in start trianning
  beginTrainning() {
    this.actionConfirmedForm.in_training = 1;
    this.toastr.success('لقد تم تسجيل البدأ ');
  }

  //get value date from child component 
  public getDate(date: any , type: string):void {
    
    if(date.month < 10) {
      date.month = '0' + date.month;
    } 

    if(date.day < 10) {
      date.day = '0' + date.day;
    }

    console.log( date);

    if(type == 'start') {
      this.startDate = date.year + '-' + date.month + '-' + date.day;
      this.actionConfirmedForm.start_date = this.startDate;
      console.log('start date', this.startDate);
    } else if(type == 'end') {
      this.endDate = date.year + '-' + date.month + '-' + date.day;
      this.actionConfirmedForm.end_date = this.endDate;
      console.log('end date', this.endDate);
    } else {
      console.log('not type recieved !');
    }
  }

  onSubmittedForm() {

    this.checkSaveClick = true;
    
    if(this.isConfirmedStatus) {
      const startDateObj = this.actionConfirmedForm.start_date.split('-');
      const endDateObj = this.actionConfirmedForm.end_date.split('-');
      console.log(startDateObj[2]);
      console.log(endDateObj[2]);
      
      console.log(this.actionConfirmedForm);
      if(endDateObj[0] < startDateObj[0]) {
        this.toastr.warning('تاريخ الإنتهاء يجب أن يكون أكبر من تاريخ الإبتداء !');
        this.checkSaveClick = false;
      } else if(endDateObj[0] == startDateObj[0] && endDateObj[1] < startDateObj[1]){
        this.toastr.warning('شهر تاريخ الإنتهاء يجب أن يكون أكبر من شهر تاريخ الإبتداء');
        this.checkSaveClick = false;
      } else if(endDateObj[1] == startDateObj[1] && endDateObj[2] < startDateObj[2]){
        this.toastr.warning('يوم تاريخ الإنتهاء يجب أن يكون أكبر من يوم تاريخ الإبتداء');
        this.checkSaveClick = false;
      } else {
        this.http.post(this.authSer.pathApi + '/manage_request_time_status', this.actionConfirmedForm).subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('يوكد مشكله في الحفظ ، حاول لاحقاً');
          }
        );
      }
    } else {
      console.log(this.actionOpinionForm);
      this.http.post(this.authSer.pathApi +  '/department_shows_opinion', this.actionOpinionForm).subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم بنجاح');
          this.location.back();
        },
        (error) => {
          console.log(error);
          this.toastr.warning('خطأ في الحفظ ، نعمل علي حلها ، حاول لاحقا');
          this.location.back();
        }
      )
    }
   

   
    console.log(this.actionConfirmedForm);
  }

}
