import { Component, OnInit, Output, EventEmitter, Input, SimpleChanges } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { LocalStorageService, LeadService } from '../../../../modules/shared/services';


@Component({
  selector: 'app-dailog-create-lead',
  templateUrl: './dailog-create-lead.component.html',
  styleUrls: ['./dailog-create-lead.component.scss']
})
export class DailogCreateLeadComponent implements OnInit {
  @Input() leadLabels;
  @Output() public createCustomer: EventEmitter<any> = new EventEmitter();
  @Output() public ignoreCustomerForm: EventEmitter<any> = new EventEmitter();
  @Output() public redirectToLeadsView: EventEmitter<any> = new EventEmitter();
  customerModel = {};
  leadForm: FormGroup;
  unsavedLeadForm: Boolean= false;
  showSpinner: Boolean = false;
  customerDetailData;
  status = '';
  message = '';

  leadModel = {
    company_UCID__c: '',
    current_Vehicle_1_Text__c: '',
    current_Vehicle_2_Text__c: '',
    customer_Type__c: '',
    dealerID: 'MBK09F',
    dealer_Comments__c: '',
    dealer_GC_Code__c: 'GC0011422',
    dealer_GS_Code__c: 'GS0015968',
    dealer_Lead_status_c: 'on-going',
    interested_Vehicle_Note__c: '',
    leadNo: '',
    leadPriority: '',
    lead_Type_c: '',
    mbK_Lead_Data_Source: '',
    mD__c: "KR",
    owner: "D823456",
    personal_UCID__c: '30000013012680631C',
    interested_brand: '',
    interestedmodelclass: '',
    interestedenginevariant: '',
    preferred_Contact_Date__c: '',
    preferred_Contact_Time__c: '',
    purchase_Time__c: '',
    re_visit__c: '',
    source_Campaign__c: '',
    stouchLeadID: '',
    test_Drive_Date__c: '',
    trade_in_Vehicle_Text2__c: '',
    corporateLead: ''
  };

  reqheaderdataLeads = {
    'x-api-key': '1be8403f-fe61-42a6-ad5f-90ff196e41ef'
  };

  constructor(
    private localStorageService: LocalStorageService,
    private leadService: LeadService
  ) { }

  ngOnInit() {
    this.leadForm = new FormGroup({
      brand: new FormControl('', Validators.required),
      modelClass: new FormControl('', Validators.required),
      variantCode: new FormControl('', Validators.required),
      dataSource: new FormControl('', Validators.required)
    });
    this.getCustomerDetailData();
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.leadLabels) {
      this.leadLabels = changes.leadLabels.currentValue;
    }
  }

  validateAllFields(formGroup: FormGroup) {         
    Object.keys(formGroup.controls).forEach(field => { 
        const control = formGroup.get(field);            
        if (control instanceof FormControl) {             
            control.markAsTouched({ onlySelf: true });
        } else if (control instanceof FormGroup) {        
            this.validateAllFields(control);  
        }
    });
  }

  goBackToLeads(){
    if (this.leadForm.dirty) {
      this.unsavedLeadForm = true;
    } else {
      this.ignoreChanges();
    }
  }

  cancelChanges() {
    this.unsavedLeadForm = false;
  }

  ignoreChanges() {
    this.ignoreCustomerForm.emit(true);
  }

  getCustomerDetailData() {
    this.customerDetailData = this.localStorageService.getLocalStorageData("customerData");
  }

  public createLeadFormSubmit(): void {
    this.validateAllFields(this.leadForm);
    if (this.leadForm.valid) {
      this.unsavedLeadForm = false;
      this.showSpinner= true;
      this.leadModel.personal_UCID__c = this.customerDetailData.Personal_UCID__c;
      const body = this.leadModel;
      this.leadService.getCreateLeadData(body, this.reqheaderdataLeads).subscribe(
        data => {
          this.showSpinner= false;
          this.redirectToLeads();
        },
        error => {
          this.status = 'error';
          this.message = 'Lead creation failed.';
        }
      );
    }
  }

  redirectToLeads(){
    this.redirectToLeadsView.emit(true);
  }

}
