import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { forkJoin, of } from 'rxjs';
import { CommonFunctionService } from 'src/app/core/common/common-function.service';
import { securityFunctions } from 'src/app/core/common/security';
import { ValidationService } from 'src/app/core/common/validation.service';
import { changeUserLoginPassword } from 'src/app/core/models/common-model/userModel';
import { API } from 'src/app/core/services/api.service';

@Component({
  selector: 'app-user-add',
  templateUrl: './user-add.component.html',
})
export class UserAddComponent implements OnInit {

  constructor(
    private router: Router,
    private activateRoute: ActivatedRoute,
    public fb: FormBuilder,
    public commonService: CommonFunctionService,
    private ApiServ: API,
    public validationService: ValidationService,

  ) { }

  formdata: FormGroup;
  Editid = null
  PasswordForm: FormGroup;
  NewPass = false;
  confirmPass = false;
  AllCountryNamePhone = [];
  TimeZonedata = [];

  ngOnInit(): void {
    this.Editid = this.activateRoute.snapshot.paramMap.get('RuleId') as string;
    this.pageSetUp();
  };
  pageSetUp() {
    this.FormOnInit();
    this.GetAllData();

  };
  GetAllData() {
    forkJoin(
      this.GetUserDetailsById(this.Editid),
      this.GetAllCountryNamePhone(),
      this.getAllTimezoneData()
    ).subscribe(res => {
      if (res && res.length > 0) {
        if (res[0]) this.FormSetvalue(res[0]['Result'])
        else this.GetRoleData();;

        if (!this.Editid) this.formdata.addControl('password', this.validationService.passwordV2);
        this.AllCountryNamePhone = res[1];
        this.TimeZonedata = res[2];
      }
    })
  };
  FormOnInit() {
    let VData = JSON.parse(securityFunctions.getSessionStorage('VData'));
    this.formdata = this.fb.group({
      vendor_name: [VData.vendor_name],
      first_name: this.validationService.required,
      user_mobile_country_code: this.validationService.required,
      user_mobile: ['', [Validators.required, Validators.pattern("^[0-9]*$"),
      Validators.minLength(5), Validators.maxLength(13)]],
      email: this.validationService.email,
      country: this.validationService.required,
      timezone: this.validationService.required,
      city: [{ value: null, disabled: true }, Validators.required],
      is_active: [],
      role_id: this.validationService.required,
      extranet_vendor_id: [],
    });
  };
  initPasswordForm() {
    this.PasswordForm = this.fb.group({
      new_password: this.validationService.passwordV2,
      Confirm_password: this.validationService.required
    })
  };
  save() {
    if (this.formdata.invalid) {
      this.validationService.showValidationsMsg(this.formdata)
      return
    }
    let value = this.formdata.getRawValue();
    let user_login = {
      first_name: value.first_name,
      user_mobile_country_code: value.user_mobile_country_code,
      user_mobile: value.user_mobile,
      email: value.email.trim(),
      country: value.country,
      timezone: value.timezone,
      city: value.city,
      role_id: value.role_id,
      password: this.Editid ? '' : value.password,
      user_id: this.userDetails?.user_id ? this.userDetails?.user_id : '',
      extranet_vendor_id: this.commonService.LoginUserData.extranet_vendor_id,
      user_type: this.userDetails?.user_type ? this.userDetails?.user_type : '210526104324609566',
    };
    let url = this.Editid ? '/Update' : '/Save';
    this.ApiServ.AdminGoPost('/ExtranetUserMaster'+url, user_login).subscribe(res => {
      if (res) {
        this.commonService.showMessage(res.Resp, res.Message);
        setTimeout(() => {
          res.Resp ? this.backClick() : '';
        }, 500);
      }
    })
  };
  UpdateUserPassword() {
    let formValue = this.PasswordForm.getRawValue();
    if (this.PasswordForm.status == "INVALID") {
      this.validationService.showValidationsMsg(this.PasswordForm);
      return;
    }
    if (formValue.new_password === formValue.Confirm_password) {
      let formData = new changeUserLoginPassword();
      formData.user_id = this.userDetails.user_id;
      formData.password = formValue.Confirm_password;
      formData.email = this.userDetails.email;
      formData.user_type = this.userDetails.user_type;
      let obj = {
        key: securityFunctions.encryptRSA(securityFunctions.rsa_public_key, JSON.stringify(formData)),
      };
      this.ApiServ.AdminGoPost('/ExtranetUserMaster/ChangedPassword', obj).subscribe(data => {
        if (data) {
          this.commonService.showMessage(data['Resp'], data['Message']);
          setTimeout(() => {
            data['Resp'] ? this.displayPosition = false : "";
          }, 500);
        }
      })
    } else {
      this.commonService.showMessage(false, 'password does not match');
    }
  };
  userDetails = undefined;
  FormSetvalue(data) {
    this.userDetails = data;
    this.formdata.get('first_name').setValue(data.first_name);
    this.formdata.get('user_mobile_country_code').setValue(data.user_mobile_country_code);
    this.formdata.get('user_mobile').setValue(data.user_mobile);
    this.formdata.get('email').setValue(data.email);
    this.formdata.get('email').disable();
    this.formdata.get('country').setValue(data.country);
    this.UpdateCountry();
    this.formdata.get('timezone').setValue(data.timezone);
    this.formdata.get('city').setValue(data.city);
    this.formdata.get('role_id').setValue(data.role_id);
    if (data.user_type == '210526104324609565') {
      this.formdata.get('role_id').disable();
    }
    this.formdata.get('extranet_vendor_id').setValue(data.extranet_vendor_id);
    data.user_type == '210526104324609565' ? this.UserTypeCheck = true : this.UserTypeCheck = false;
    this.GetRoleData();
    let Countries = [];
    let Cities = [];
    if (data.Cities.length > 0) {
      data.Cities.forEach(e => {
        Cities.push({
          city_code: e._key,
          city_name: e._value
        });
      });
      this.commonService.CityList = Cities;
    };
    if (data.Countries.length > 0) {
      data.Countries.forEach(e => {
        Countries.push({
          country_code: e._key,
          country_name: e._value
        });
      });
      this.commonService.CountryList = Countries;
    };
  }
  displayPosition!: boolean;
  position!: string;
  showPositionDialog(position: string) {
    this.initPasswordForm();
    this.position = position;
    this.displayPosition = true;
  };

  UpdateCountry() {
    this.formdata.get('city').setValue(null);
    if (this.formdata.get('country').value) {
      this.formdata.get('city').enable();
    } else {
      this.formdata.get('city').disable();
    }
  };

  backClick() {
    this.router.navigateByUrl("/UserConfiguration/UserManagement/Search");
  };

  GetAllVendorGroup() {
    let searchObj = {
      vendor_group_name: '',
    }
    return this.ApiServ.AdminGoPost('/ExtranetVendorGroupMaster/GetAll', searchObj)
  };
  GetUserDetailsById(Editid) {
    if (Editid)
      return this.ApiServ.AdminGOGet('/ExtranetUserMaster/GetById/' + Editid)
    else
      return of(null)
  };
  UserTypeCheck = false;
  GetAllRoleByType() {
    return this.ApiServ.AdminGet(`/RoleMaster/GetAllRoleByType/Extranet`)
  }

  // All API
  GetAllCountryNamePhone() {
    return this.ApiServ.AdminGet('/CountryNamePhone/GetAllCountryNamePhone')
  };

  getAllTimezoneData() {
    return this.ApiServ.AdminGet('/TimezoneCity/GetAllTimezoneCity')
  };
  // ddLoader = false
  // timer;
  // AllVendor
  // ExtranetVendorMaster(val) {
  //   if (val.length >= 2) {
  //     let searchObj = {
  //       vendor_name: val,
  //     };
  //     this.ddLoader = true;
  //     clearTimeout(this.timer);
  //     this.timer = setTimeout(() => {
  //       this.ApiServ.AdminGoPost('/ExtranetVendorMaster/GetAll', searchObj).subscribe(res => {
  //         if (res) {
  //           this.AllVendor = res.Result;
  //           this.ddLoader = false;
  //         }
  //       });
  //     }, 500);
  //   }
  //   if (!val) {
  //     this.AllVendor = [];
  //   }
  // };
  allRoleList = []
  GetRoleData() {
    if (this.commonService?.LoginUserData?.extranet_vendor_id) {
      this.GetAllRoleByType().subscribe(res => {
        if (res) {
          this.allRoleList = res;
        }
      })
    } else {
      this.allRoleList = []
    }
  };

}
