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

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

  constructor(private userSer: UserService,
      private spineer: NgxSpinnerService,
      private route: ActivatedRoute,
      private authSer: AuthServiceService,
      private location: Location,
      private toastr: ToastrService) {
        this.spineer.show();
       }

  adminstration = [];
  countries = [];
  jobTitils = [];
  specializations = [];
  contracts = [];
  staffs = [];
  departments = [];
  identities = [];
  userID: number;
  signupForm: FormGroup;
  typeMode: boolean = false;
  hideConfirmPassword: boolean = true;
  showDepart: boolean = false;
  checkChangeImage: boolean = false;
  typeFirstLink: string = '';
  typeLink: string = '';
  typeEditPage: string = '';
  typeCreatePage: string = '';
  imageBase64: string = '';
  photoType: string = '';
  userProfileId: number;
  identity_id: number = 0;
  identity_type: number;
  number_identitiy:number;
  checkPageAppear: boolean  = true;
  checkRequiredSpan:boolean = true;
  urlImg: string =  '../../../../assets/image/avatar.png';
  higriDateVal = "";
  bindingDateSplit;
  checkSaveDisabled:boolean = false;
  checkUserType:number;

  end:any;

  ngOnInit() {
    this.spineer.show();
      //show / hide notification search in header
      this.authSer.notificationLogin = true;
      this.authSer.showSearchHeader = false;
      this.authSer.showHeaderLogin = false;
      this.authSer.showHeaderDashBoard = true;
       //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 profile data
      this.userSer.getUserDataProfile();
  
      //get adminstration
      this.userSer.getAdministration().subscribe(
        (responce) => {
          console.log(responce);
          this.adminstration = responce['adminstrations'];
        },
        (error) => {
          console.log(error)
        }
      );
  
      
  
      //get nationality
      this.userSer.getNationality().subscribe(
        (responce) => {
          console.log(responce);
          this.countries = responce['countries'];
        },
        (error) => {
          console.log(error);
        }
      );
  
      //get job titile
      this.userSer.getJobTitle().subscribe(
        (responce) => {
          console.log(responce);
          this.jobTitils = responce['job_titles'];
        },
        (error) =>{console.log(error)}
      );
  
      //get specialization
      this.userSer.getSpecialization().subscribe(
        (responce) => {
          console.log(responce);
          this.specializations = responce['specialization'];
        }
      );
  
      //get contract list
      this.userSer.getContract().subscribe(
        (responce) => {
          console.log(responce);
          this.contracts = responce['contract_types'];
        }
      );

      this.userSer.getAdministration().subscribe(
        (responce) => {
          this.adminstration = responce['adminstrations'];
        }
      );
  
      //get staff list
      this.userSer.getStaff().subscribe(
        (responce) => {
          console.log(responce);
          this.staffs = responce['staff'];
        }
      );
  
      //get identites
      this.userSer.onGetIdentities().subscribe(
      (responce) => {
        this.identities = responce['identities'];
      },
      (error) => {
        console.log(error);
      }
    );

    this.route.params.subscribe(
      (params: Params) => {
        this.typeCreatePage = params['type_add'];
        if(this.typeCreatePage == 'user') {
          this.typeFirstLink = 'المستخدمين';
          this.typeLink = 'إنشاء جديد';
          this.spineer.hide();
        }
      }
    );

    this.route.params.subscribe(
      (params:Params) => {
        if(params['typemode'] == 'editUs') {
          this.typeFirstLink = 'المستخدمين';
          this.typeLink = 'تعديل';
          this.checkPageAppear = true;
          this.checkRequiredSpan = false;
          this.userID = params['userEditId'];
          this.typeMode = true;
          this.hideConfirmPassword = false;
          this.showDepart = true;
          this.typeEditPage = 'editUs';
          this.userSer.onGetUserData(this.userID, 'editUs').subscribe(
            (responce) => {
              console.log('data user' , responce);
              if(responce['user'].type == '0') {
                this.signupForm.patchValue(
                  {
                    name: responce['user'].name,
                    type: responce['user'].type,
                    position: responce['user'].position,
                    email: responce['user'].email,
                    password: responce['user'].password,
                    password_confirmation: responce['user'].password_confirmation,
                    phone: responce['user'].phone,
                    gender: responce['user'].gender,
                    birthday: responce['user'].birthday,
                    nationality_id: responce['user'].nationality_id,
                    date_of_employment_gre: responce['user'].date_of_employment_gre,
                    job_title_id: responce['user'].job_title_id,
                    specialization_id: responce['user'].specialization_id,
                    functional_number: responce['user'].functional_number,
                    adminstration_id: responce['user'].adminstration_id,
                    department_id: responce['user'].department_id,
                    contract_type_id: responce['user'].contract_type_id,
                    staff_id: responce['user'].staff_id,
                    status: responce['user'].status,
                    identity_type_id: responce['user'].identity_type_id,
                    identity_number: responce['user'].identity_number,
                  }
                );
              } else {
                this.signupForm.patchValue(
                  {
                    name: responce['user'].name,
                    type: responce['user'].type,
                    email: responce['user'].email,
                    phone: responce['user'].phone,
                    gender: responce['user'].gender,
                    birthday: responce['user'].birthday,
                    nationality_id: responce['user'].nationality_id,
                    status: responce['user'].status,
                    identity_type_id: responce['user'].identity_type_id,
                    identity_number: responce['user'].identity_number,
                  }
                );
              }
              
              this.urlImg = responce['user'].photo ? this.authSer.pathImg + responce['user'].photo : this.urlImg;
              console.log(this.urlImg);
              const date = responce['user'].date_of_employment_hij.split('-');
            
              this.bindingDateSplit = {
                'year': parseInt(date[0]),
                'month': parseInt(date[1]),
                'day': parseInt(date[2])
              };
              
              this.higriDateVal = responce['user'].date_of_employment_hij;
              console.log(this.bindingDateSplit);
              
              this.getDepartment();
              this.spineer.hide();
            },
            (error) => {console.log(error)},
          );
        }
      }
    );
    
    //user form json
    if(!this.typeMode){
      //creating user create form
      this.signupForm = new FormGroup({
        name: new FormControl(null, Validators.required),
        type: new FormControl('0'),
        identity_type_id: new FormControl(null, [Validators.required]),
        identity_number: new FormControl(null,Validators.required),
        position: new FormControl(null, Validators.required),
        email: new FormControl(null, [Validators.required,Validators.email]),
        password: new FormControl(null, [Validators.required, Validators.minLength(6)]),
        password_confirmation: new FormControl(null, [Validators.required, Validators.minLength(6)]),
        phone: new FormControl(null, Validators.required),
        gender: new FormControl(null, Validators.required),
        birthday: new FormControl(null, Validators.required),
        adminstration_id: new FormControl(null, Validators.required),
        department_id: new FormControl(null, Validators.required),
        nationality_id: new FormControl(null, Validators.required),
        date_of_employment_gre: new FormControl(null, Validators.required),
        job_title_id: new FormControl(null),
        specialization_id: new FormControl(null),
        functional_number: new FormControl(null, Validators.required),
        contract_type_id: new FormControl(null),
        staff_id: new FormControl(null),
        status: new FormControl(null, Validators.required),
      });

      this.spineer.hide();
  
    }else{
      //creating edit form user 
      this.signupForm = new FormGroup({
        name: new FormControl(null, Validators.required),
        type: new FormControl(null),
        identity_type_id: new FormControl(null, [Validators.required]),
        identity_number: new FormControl(null, Validators.required),
        position: new FormControl(null, Validators.required),
        email: new FormControl(null, [Validators.required,Validators.email]),
        password: new FormControl(null, [Validators.minLength(6)]),
        phone: new FormControl(null, Validators.required),
        gender: new FormControl(null, Validators.required),
        birthday: new FormControl(null, Validators.required),
        adminstration_id: new FormControl(null, Validators.required),
        department_id: new FormControl(null, Validators.required),
        nationality_id: new FormControl(null, Validators.required),
        date_of_employment_gre: new FormControl(null, Validators.required),
        job_title_id: new FormControl(null),
        specialization_id: new FormControl(null),
        functional_number: new FormControl(null, Validators.required),
        contract_type_id: new FormControl(null),
        staff_id: new FormControl(null),
        status: new FormControl(null, Validators.required),
      });
    }
    //catch params to show edit mode
  }

  //get value date from child component 
  public getDate(date: any):void {
    console.log( date);
    this.higriDateVal = date.year + '-' + date.month + '-' + date.day;
    console.log('higrii date', this.higriDateVal);
  }


  //get departmants 
  getDepartment() {
    const adminstrationId = this.signupForm.get('adminstration_id').value;
    console.log(adminstrationId);
    this.userSer.getDepartments(adminstrationId).subscribe(
      (responce) => {
        console.log(responce);
        this.departments = responce['departments'];
        this.showDepart = true;
      }
    );
  }

  checkTypeUser(typeUser) {
    console.log(typeUser.target.value);
    this.checkUserType = typeUser.target.value;
    if(typeUser.target.value == 1) {
      this.signupForm = new FormGroup({
        name: new FormControl(null, Validators.required),
        type: new FormControl('1'),
        identity_type_id: new FormControl(null, [Validators.required]),
        identity_number: new FormControl(null, Validators.required),
        email: new FormControl(null, [Validators.required,Validators.email]),
        password: new FormControl(null, [Validators.required, Validators.minLength(6)]),
        password_confirmation: new FormControl(null, [Validators.required, Validators.minLength(6)]),
        gender: new FormControl(null, Validators.required),
        birthday: new FormControl(null, Validators.required),
        nationality_id: new FormControl(null, Validators.required),
        phone: new FormControl(null, Validators.required),
        status: new FormControl(null , Validators.required),
      });
    } else {
      this.signupForm = new FormGroup({
        name: new FormControl(null, Validators.required),
        type: new FormControl('0'),
        identity_type_id: new FormControl(null, [Validators.required]),
        identity_number: new FormControl(null, Validators.required),
        position: new FormControl(null, Validators.required),
        email: new FormControl(null, [Validators.required,Validators.email]),
        password: new FormControl(null, [Validators.required, Validators.minLength(6)]),
        password_confirmation: new FormControl(null, [Validators.required, Validators.minLength(6)]),
        phone: new FormControl(null, Validators.required),
        gender: new FormControl(null, Validators.required),
        birthday: new FormControl(null, Validators.required),
        adminstration_id: new FormControl(null, Validators.required),
        department_id: new FormControl(null, Validators.required),
        nationality_id: new FormControl(null, Validators.required),
        date_of_employment_gre: new FormControl(null, Validators.required),
        date_of_employment_hij: new FormControl(null,Validators.required),
        job_title_id: new FormControl(null),
        specialization_id: new FormControl(null),
        functional_number: new FormControl(null, Validators.required),
        contract_type_id: new FormControl(null),
        staff_id: new FormControl(null),
      });
    } 
  }



  //submitted form
  onSubmittedForm() {

    this.checkSaveDisabled = true;
    const userData = this.signupForm.value;
    let joinJopYear;
    let birthDate;
    if(userData['type'] == 0){
      userData['date_of_employment_hij'] = this.higriDateVal;
       birthDate = userData['birthday'].split('-')[0];
       joinJopYear = userData['date_of_employment_gre'].split('-')[0];
      console.log(joinJopYear);
    }
 
   

    if(this.checkChangeImage) {
      userData['photo'] = this.imageBase64;
      userData['photo_type'] = this.photoType[1];
    }

    console.log(userData);

    if(this.typeCreatePage == 'user') {

      if(this.signupForm.get('password').value != this.signupForm.get('password_confirmation').value){
        this.toastr.warning('من فضلك تأكد أن كلمه المرور هي نفس تأكيد كلمه المرور ');
        this.checkSaveDisabled = false;
      } else if(this.imageBase64 == ''){
        this.toastr.warning('قم بإختيار صوره المستخدم !');
        this.checkSaveDisabled = false;
      } else if(userData['date_of_employment_hij'] == "") {
          this.toastr.warning('من فضلك ، أدخل تاريخ التوظيف الهجري !');
          this.checkSaveDisabled = false;
     } else if(this.signupForm.get('identity_number').value.substring(0,1) != 1 && this.signupForm.get('identity_type_id').value == 1){
        this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
        this.checkSaveDisabled = false;
      } else if(this.signupForm.get('identity_number').value.substring(0,1) != 2 && this.signupForm.get('identity_type_id').value == 3){
        this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
        this.checkSaveDisabled = false;
      } else if(this.signupForm.get('phone').value.substring(0,2) != '05') {
        this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
        this.checkSaveDisabled = false;
      } else if(birthDate > joinJopYear) {
        this.toastr.warning('تاريخ التوظيف الميلادي أكبر من تاريخ الميلاد !');
        this.checkSaveDisabled = false;
      } 
      else {
        this.userSer.addUser(userData, 'user').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم الاضافه بنجاح');
            this.location.back();
            this.checkSaveDisabled = true;
          },
          (error) => {
            console.log(error);
            this.checkSaveDisabled = false;
            if(error.error['error'].email) {
              this.toastr.warning('الايميل تم التسجيل به من قبل !');
            } else if(error.error['error'].identity_number) {
              this.toastr.warning('رقم الهويه تم التسجيل به من قبل !');
            }
          }
        );
      };

    }

    if(this.typeMode) {
      if(this.typeEditPage == 'editUs') {
        userData['id'] = this.userID;
        if(this.signupForm.get('identity_number').value.substring(0,1) != 1 && this.signupForm.get('identity_type_id').value == 1){
          this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
          this.checkSaveDisabled = false;
        }else if(this.signupForm.get('identity_number').value.substring(0,1) != 2 && this.signupForm.get('identity_type_id').value == 3){
          this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
          this.checkSaveDisabled = false;
        } else if(birthDate > joinJopYear) {
          this.toastr.warning('تاريخ التوظيف الميلادي أكبر من تاريخ الميلاد !');
          this.checkSaveDisabled = false;
        } else if(this.signupForm.get('phone').value.substring(0,2) != '05') {
          this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
          this.checkSaveDisabled = false;
        } else {
          this.userSer.onEditUser(userData, 'user').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم التعديل بنجاح');
              this.location.back();
            },
            (error) => {
              console.log(error);
              this.toastr.error('خطأ التعديل');
            }
          );
        }
      }
    }

  };

  getSelectedOptionText(event){
    console.log(event.target.value);
    this.identity_id = event.target.value;
    this.identity_type = event.target.value;
  }

  onFileChanges(event) {
    console.log(event);
    this.imageBase64 = event[0].base64;
    this.photoType = event[0].type.split('/');
    console.log(this.photoType[1]);
    console.log(this.imageBase64);
    this.checkChangeImage = true;
  }

  getUrl(event) {   
    if (event.target.files && event.target.files[0]) {
    var reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]); // read file as data url
    reader.onload = (event) => { // called once readAsDataURL is completed
      this.urlImg = event.target['result'];
    }
  }
 }

  //identitiy input change 
  onIdentitiyChange(event) {
    if(event.length >= 10) {
      this.identity_id = 0;
    } else {
      this.identity_id = this.identity_type;
    }
  }

  //validatiors return funcrtion 
  get password() {
    return this.signupForm.get('password');
  }

  //validatiors return funcrtion 
  get phone() {
    return this.signupForm.get('phone');
  }
  
  get repeatPassword() {
    return this.signupForm.get('password_confirmation');
  }


}
