import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { ActivityAddOn, ActivityAddOnDetails } from 'src/app/core/models/optional-ons/optional-ons.model'
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-add-optional-add-on',
  templateUrl: './add-optional-add-on.component.html',
})
export class AddOptionalAddOnComponent implements OnInit {
  uploadedFiles: any[] = [];
  fileArr = [];
  fileInfo = [];
  AddOptForm: FormGroup;
  showImgBox;
  RateTypes;
  Currency;
  addOne_Id;
  constructor(
    private router: Router,
    private ApiServ: API,
    private MsgService: MessageService,
    private route: ActivatedRoute,
    public validationService: ValidationService,
    private fb: FormBuilder
  ) { }

  ngOnInit(): void {
    this.initForm();
    this.GetRateType();
    this.GetCurrency();

    this.route.queryParams.subscribe(obj => {
      if (obj['id']) {
        this.showImgBox = true;
        this.ApiServ.Get('/ActivityAddOn/GetActivityAddOn/' + obj['id']).subscribe(d => {
          this.SetValue(d['responseObject']);

          this.addOne_Id = obj['id'];
        });
      }
    })
  }

  SetValue(val) {
    Object.keys(val).forEach(li => {
      if (li == "rate" || li == "currency_code") {
        this.AddOptForm.get(li).setValue(val[li]);
      } else if (li == "_rate_type") {
        this.AddOptForm.get(li).setValue(parseInt(val[li]));
        this.RateTypesCheck();
        if (parseInt(val[li]) == 1) {
          this.AddOptForm.get('adult_rate').setValue(val['adult_rate']);
          this.AddOptForm.get('senior_rate').setValue(val['senior_rate']);
          this.AddOptForm.get('youth_rate').setValue(val['youth_rate']);
          this.AddOptForm.get('child_rate').setValue(val['child_rate']);
        } else if (parseInt(val[li]) == 2) this.AddOptForm.get('per_service_rate').setValue(val['per_service_rate']);
      }
      if (li == 'activityAddOnDetails') {
        this.setAddOnsDetail(val[li]);
      }
    })
  }

  setAddOnsDetail(val) {
    val.map(obj => {
      Object.keys(obj).forEach(li => {
        if (li == "add_on_image" || li == "add_on_description" || li == "add_on_name" || li == 'activity_add_on_id') {
          this.AddOptForm.get(li).setValue(obj[li]);
        }
      })
    })
  }

  GetRateType() {
    this.ApiServ.Get('/LovMaster/GetLovByType/AddOnRateType').subscribe(obj => {
      if (obj) {
        this.RateTypes = obj['responseObject'];
      }
    })
  }

  GetCurrency() {
    this.ApiServ.Get('/Currency/GetCurrency').subscribe(obj => {
      if (obj) {
        this.Currency = obj;
      }
    })
  }

  RateTypesCheck() {
    let val = this.AddOptForm.getRawValue();
    if (val._rate_type == '1') {
      this.AddOptForm.addControl('adult_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[0-9]*$/)]));
      this.AddOptForm.addControl('senior_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[0-9]*$/)]));
      this.AddOptForm.addControl('youth_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[0-9]*$/)]));
      this.AddOptForm.addControl('child_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[0-9]*$/)]));
      this.AddOptForm.removeControl('per_service_rate');
    } else if (val._rate_type == '2') {
      this.AddOptForm.addControl('per_service_rate', this.fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
      this.AddOptForm.removeControl('adult_rate');
      this.AddOptForm.removeControl('senior_rate');
      this.AddOptForm.removeControl('youth_rate');
      this.AddOptForm.removeControl('child_rate');
    }
  }

  initForm() {
    this.AddOptForm = this.fb.group({
      activity_add_on_id: [''],
      add_on_name: this.validationService.required,
      add_on_description: [''],
      add_on_image: this.validationService.required,
      supplier_id: ['2205221841391724322'],
      _rate_type: this.validationService.required,
      currency_code: this.validationService.required,
      // per_service_rate: this.validationService.decimal,
    })
  }

  getImage(e) {
    if (e.currentFiles.length != 0) {
      let file = e.files[0];
      this.AddOptForm.get('add_on_image').setValue(file);
    }
  }

  emptyValue() {
    this.showImgBox = false;
    this.AddOptForm.get('add_on_image').setValue('');
  }

  SaveOpt() {
    if (this.AddOptForm.status == "INVALID") {
      this.validationService.showValidationsMsg(this.AddOptForm);
      return;
    }
    this.fileArr = [];
    this.fileInfo = [];
    let value = this.AddOptForm.getRawValue();
    this.showImgBox = false;
    let ActAddOnModel = new ActivityAddOn();
    let ActAddOnDetailArr = new Array<ActivityAddOnDetails>();
    let ActAddOnDetailObj = new ActivityAddOnDetails();
    debugger
    ActAddOnModel._rate_type = value._rate_type.toString();
    ActAddOnModel.currency_code = value.currency_code;
    ActAddOnModel.per_service_rate = value.per_service_rate ? parseInt(value.per_service_rate) : 0;
    ActAddOnModel.activity_add_on_id = value.activity_add_on_id;
    ActAddOnModel.supplier_id = value.supplier_id;
    ActAddOnModel.org_id = '2105311837100000021';
    ActAddOnModel.is_deleted = false;
    ActAddOnModel.activity_id = CommonService.getSessionStoage('activity_id');

    if (value._rate_type == '1') {
      ActAddOnModel.adult_rate = value.adult_rate;
      ActAddOnModel.child_rate = value.child_rate;
      ActAddOnModel.senior_rate = value.senior_rate;
      ActAddOnModel.youth_rate = value.youth_rate;
    } else if (value._rate_type == '2') ActAddOnModel.per_service_rate = value.per_service_rate;

    ActAddOnDetailObj.is_deleted = false;
    ActAddOnDetailObj.org_id = '2105311837100000021';
    ActAddOnDetailObj.activity_id = CommonService.getSessionStoage('activity_id');
    ActAddOnDetailObj.add_on_description = value.add_on_description;
    if (typeof (value.add_on_image) == 'object') {
      this.fileArr.push(value.add_on_image);
      this.fileInfo.push({ 'fileName': "AddOns/Add_Act_Id." + value.add_on_image.name.split('.')[1], 'pathToSave': 'ThemeImages/ORGID' });
    }
    ActAddOnDetailObj.add_on_image = typeof (value.add_on_image) == 'object' ? environment.cdnFileUrl + "ThemeImages/ORGID/AddOns/Add_Act_Id." + value.add_on_image.name.split('.')[1] : value.add_on_image.split('?')[0];
    ActAddOnDetailObj.add_on_name = value.add_on_name;
    ActAddOnDetailObj.language_code = CommonService.getSessionStoage('Def_Lang_code');
    ActAddOnDetailObj.supplier_id = value.supplier_id;
    ActAddOnDetailArr.push(ActAddOnDetailObj)
    ActAddOnModel.activityAddOnDetails = ActAddOnDetailArr;
    if (this.addOne_Id) {
      this.ApiServ.Post('/ActivityAddOn/UpdateActivityAddOn', ActAddOnModel).subscribe(data => {
        if (data) {
          (data['status'] && this.fileInfo.length > 0) ? this.saveImg(data, this.fileArr, this.fileInfo) : this.showToastrMsg(data);
        }
      })
    } else {
      this.ApiServ.Post('/ActivityAddOn/SaveActivityAddOn', ActAddOnModel).subscribe(data => {
        if (data) {
          (data['status'] && this.fileInfo.length > 0) ? this.saveImg(data, this.fileArr, this.fileInfo) : this.showToastrMsg(data);
        }
      })
    }
  }

  showToastrMsg(respData) {
    this.MsgService.add({
      severity: respData['status'] ? 'success' : 'error',
      detail: respData['message'],
    });
    setTimeout(() => {
      respData['status'] ? this.btnClick() : '';
    }, 500);
  }
  saveImg(respData, file_arr, file_info) {
    var formdata = new FormData();
    file_arr.forEach(x => {
      formdata.append("files", x);
    })
    let Id = this.addOne_Id ? this.addOne_Id : respData['responseObject'].activity_add_on_id;
    let a = JSON.stringify(file_info).replaceAll('Add_Act_Id', Id);
    formdata.append("fileInfo", a);

    this.ApiServ.PostFile('/FileUpload/SaveFile', formdata).subscribe(imdata => {
      if (imdata['status']) {
        this.showToastrMsg(respData);
      }
    })
  }

  btnClick() {
    this.router.navigateByUrl("/Services/ActivityServices/ExpServices/Manage");
  }

}
