import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatCheckbox } from '@angular/material/checkbox';
import { ActivatedRoute } from '@angular/router';
import * as moment from 'moment';
import { ValidationService } from 'src/app/core/common/validation.service';
import { EditActivityContractDetail } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-details/edit-deatils.model';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';

@Component({
  selector: 'app-edit-details',
  templateUrl: './edit-details.component.html',
})
export class EditDetailsComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    public Fb: FormBuilder,
    public APIServ: API,
    public validationService: ValidationService
  ) {}
  Pickup: string[] = [];
  CommonCalender: string[] = [];
  //
  FormData: FormGroup;
  currencyList;
  activityContractId;
  PhoneCode;
  include_nationality_list;
  exclude_nationality_list;
  fil_exclude_nationality_list;
  PaxDetails;
  vahicleDetails;
  LangList = [];
  DaySelect = [];
  AllSlotData;
  SoltDate;
  @ViewChild('Vehicle_Rate_copy') Vehicle_Rate_copy: ElementRef;
  @ViewChild('myCalendar') datePicker;
  ngOnInit(): void {
    this.FormData = this.Fb.group({
      option_name: this.validationService.required,
      emergency_phone_code: this.validationService.required,
      emergency_phone: this.validationService.mobNo,
      currency_code: this.validationService.required,
      is_exclude_nationality: [false],
      include_nationality_code: [''],
      exclude_nationality_code: [''],
      contract_remark: [''],
      rate_inclusion: [''],
      _nationality_type: [''],
      Solt_data: [''],
      Search_date: [''],
      Days: [''],
      is_pickup_included: [false],
      is_drop_off_included: [false],
      is_guide_included: [false],
      guide_languages: [''],

      PaxDetails: this.Fb.array([
        this.Fb.group({
          adult_rate: [''],
          child_rate: [''],
          infant_rate: [''],
          senior_rate: [''],
          youth_rate: [''],
        }),
      ]),
      vahicle_list: this.Fb.array([]),
    });
    this.GetLOVMater();
    this.GetAllCurrency();
    this.GetAllNationality();
    this.getRateConfig();
    this.GetPhoneCode();
    // hard code
    // this.getVehicleRateDetails()
    // this.getPerPaxDetails()
    this.getPaxType();
  }

  //  form get
  get paxform() {
    return this.FormData.get('PaxDetails') as FormArray;
  }
  get Vahicleform() {
    return this.FormData.get('vahicle_list') as FormArray;
  }
  Months = [
    { id: 1, name: 'Jan' },
    { id: 2, name: 'Feb' },
    { id: 3, name: 'Mar' },
    { id: 4, name: 'Apr' },
    { id: 5, name: 'Jun' },
    { id: 6, name: 'Jun' },
    { id: 7, name: 'Jul' },
    { id: 8, name: 'Aug' },
    { id: 9, name: 'Sep' },
    { id: 10, name: 'Oct' },
    { id: 11, name: 'Nov' },
    { id: 12, name: 'Dec' },
  ];
  MonthsList = this.Months[0].name;

  getRateConfig() {
    this.route.queryParams.subscribe((obj) => {
      if (obj['id']) {
        this.activityContractId = obj['id'];
        this.GetSlotData();
        this.APIServ.Get(
          '/ActivityContract/GetRateConfig/' + obj['id']
        ).subscribe((data) => {
          if (data) {
            // this.activityContract = data.responseObject;
            console.log(data);
            console.log(data.result.responseObject);
            this.SetValueConfi(data.result.responseObject);
          }
        });
      }
    });
  }

  SetValueConfi(d) {
    let value = this.FormData.getRawValue();
    Object.keys(value).map((e) => {
      if (e == 'guide_languages') {
        let value = d[e] ? d[e].split(',') : null;
        let Arr = [];
        value.map((e) => Arr.push(parseInt(e)));
        setTimeout(() => {
          this.FormData.get(e).setValue(Arr);
        }, 100);
      } else if (e == 'is_guide_included') {
        this.FormData.get(e).setValue(d[e]);
        d[e] ? this.is_guideLang('guide_languages') : '';
      } else if (
        e == 'include_nationality_code' ||
        e == 'exclude_nationality_code'
      ) {
        let value = d[e] ? d[e].split(',') : null;
        this.FormData.get(e).setValue(value);
      } else if (e == '_nationality_type') {
        this.FormData.get(e).setValue(d[e]);
        d[e] == 'specific_nationality'
          ? this.is_Nationality('specific_nationality')
          : '';
      } else if (e == 'is_exclude_nationality') {
        this.FormData.get(e).setValue(d[e]);
        d[e] ? this.is_exclude(true) : '';
      } else if (
        e == 'PaxDetails' ||
        e == 'vahicle_list' ||
        e == 'Solt_data' ||
        e == 'Search_date' ||
        e == 'Days'
      ) {
        console.log('nice razzak ');
      } else this.FormData.get(e).setValue(d[e]);
    });
  }

  GetAllCurrency() {
    this.APIServ.Get('/Currency/GetCurrency').subscribe((d) => {
      if (d) this.currencyList = d;
    });
  }

  GetAllNationality() {
    this.APIServ.Get('/Country/GetCountry').subscribe((d) => {
      this.include_nationality_list = d;
      this.exclude_nationality_list = d;
      this.fil_exclude_nationality_list = d;
    });
  }

  GetLOVMater() {
    let formdata = {
      lov_types: [{ lov_type: 'Language' }, { lov_type: 'DaySelect' }],
      lov_lang: 'EN',
    };

    this.APIServ.Post('/LovMaster/GetLov', formdata).subscribe((data) => {
      if (data) {
        this.LangList = data.responseObject[0].keys;
        this.DaySelect = data.responseObject[1].keys;
      }
    });
  }

  GetSlotData() {
    // this.APIServ.Get('/ActivityContract/GetSlotsById/' + this.activityContractId).subscribe(data => {
    //   if (data) {
    //     this.AllSlotData = data.responseObject;
    //     console.log(data)
    //   }
    // });

    this.APIServ.Get(
      '/ActivityContract/GetSlotsById/' + '2207140719598616047'
    ).subscribe((data) => {
      if (data) {
        this.AllSlotData = data.responseObject;
      }
    });
  }

  GetSoltDetails(val) {
    // this.SoltDate = val.date.split(",")
    this.getPerPaxDetails();
  }

  getPerPaxDetails() {
    let val = this.FormData.getRawValue();
    let obj = {
      contract_id: this.activityContractId,
      slot_id: val.Solt_data.activity_slot_id,
      dates: val.Search_date
        ? moment(val.Search_date[0]).format('dd MMM YYYY') +
          'to' +
          moment(val.Search_date[1]).format('dd MMM YYYY ')
        : val.Solt_data.date,
      days: val.Days ? val.Days.join(',') : '7',
    };

    // hard code
    let new_obj = {
      contract_id: '2206290724107915812',
      slot_id: '2206290724110863052',
      dates: '2022-05-30,2022-05-31',
      days: '1,2',
    };

    this.APIServ.Post('/ActivityContract/GetRatePerPax', new_obj).subscribe(
      (data) => {
        if (data) {
          console.log(data);
          if (data.result.responseObject) {
            this.PaxDetails = data.result.responseObject;
            this.setpaxValue(data.result.responseObject);
          }
        }
      }
    );

    /// GetVehicleRate

    // hard code

    // let vahicle_obj = {
    //   "contract_id": "2206290730562842277",
    //   "slot_id": "2206290730584999007",
    //   "dates": "2022-06-01,2022-06-02",
    //   "days": "0,1,2,3,4,5"
    // }

    this.APIServ.Post('/ActivityContract/GetVehicleRate', obj).subscribe(
      (data) => {
        if (data) {
          console.log(data);
          if (data.result.responseObject) {
            this.vahicleDetails = data.result.responseObject;
            this.setvahicleValue(data.result.responseObject);
          }
        }
      }
    );
  }

  // getVehicleRateDetails() {
  //   let new_obj = {
  //     "contract_id": "2206290730562842277",
  //     "slot_id": "2206290730584999007",
  //     "dates": "2022-06-01,2022-06-02",
  //     "days": "0,1,2,3,4,5"
  //   }
  //   let val = this.FormData.getRawValue();
  //   let obj = {
  //     "contract_id": this.activityContractId,
  //     "slot_id": val.Solt_data.activity_slot_id,
  //     "dates": val.Search_date ? val.Search_date.join(',') : val.Solt_data.date,
  //     "days": val.Days ? val.Days.join(',') : '7'
  //   }
  //   console.log(obj)
  //   // this.APIServ.Post('/ActivityContract/GetVehicleRate', new_obj).subscribe(data => {
  //   //   if (data) {
  //   //     console.log(data)
  //   //     this.vahicleDetails = data.result.responseObject;
  //   //     this.setvahicleValue(data.result.responseObject);
  //   //   }
  //   // });
  // };

  setpaxValue(data) {
    for (let i = 0; i < data.length; i++) {
      this.AddPaxGroup();
      Object.keys(data[i]).map((e) => {
        this.paxform.controls[i + 1].get(e).setValue(data[i][e]);
      });
    }
  }

  setvahicleValue(data) {
    for (let i = 0; i < data.length; i++) {
      this.addvahicleGroup();
      Object.keys(data[i]).map((e) => {
        this.Vahicleform.controls[i].get(e).setValue(data[i][e]);
      });
    }
  }

  AddPaxGroup() {
    this.paxform.push(
      this.Fb.group({
        date: [''],
        adult_rate: [''],
        child_rate: [''],
        infant_rate: [''],
        senior_rate: [''],
        youth_rate: [''],
      })
    );
  }

  addvahicleGroup() {
    this.Vahicleform.push(
      this.Fb.group({
        date: [''],
        rate: [''],
      })
    );
  }

  getPaxType() {
    this.APIServ.Get(
      '/Activity/GetActivity/' + CommonService.getSessionStoage('activity_id')
    ).subscribe((data) => {
      if (data) {
        // this.AllSetvalue(data['responseObject']);
        console.log(data);
      }
    });
  }

  // vehicle selection

  Vehicle_Selection = [
    { id: 1, name: 'Mercedes S Class' },
    { id: 2, name: 'Coach 20 Seater' },
    { id: 3, name: 'Helicopter' },
  ];

  GetPhoneCode() {
    this.APIServ.Get('/CountryPhone/GetCountryPhone').subscribe((data) => {
      if (data) {
        this.PhoneCode = data;
      }
    });
  }

  UpdateRateConfi() {
    let value = this.FormData.getRawValue();
    console.log(this.FormData);
    console.log(value);
    let PostData = new EditActivityContractDetail();
    PostData.contract_id = this.activityContractId;
    PostData.option_name = value.option_name;
    PostData.currency_code = value.currency_code;
    PostData.include_nationality_code = value.include_nationality_code
      ? value.include_nationality_code.join(',')
      : '';
    PostData.exclude_nationality_code = value.exclude_nationality_code
      ? value.exclude_nationality_code.join(',')
      : '';
    PostData._nationality_type = value._nationality_type;
    PostData.is_exclude_nationality = value.is_exclude_nationality;
    PostData.rate_inclusion = value.rate_inclusion;
    PostData.contract_remark = value.contract_remark;
    PostData.is_pickup_included = value.is_pickup_included;
    PostData.is_drop_off_included = value.is_drop_off_included;
    PostData.is_guide_included = value.is_guide_included;
    PostData.guide_languages = value.guide_languages
      ? value.guide_languages.join(',')
      : '';
  }

  addvalid(name, type, num) {
    if (type == 'add') {
      if (num == 'number') {
        this.FormData.controls[name].addValidators([
          Validators.pattern(/^[0-9]*$/),
        ]);
        this.FormData.controls[name].updateValueAndValidity();
      } else {
        this.FormData.controls[name].addValidators([Validators.required]);
        this.FormData.controls[name].updateValueAndValidity();
      }
    } else {
      this.FormData.controls[name].clearValidators();
      this.FormData.controls[name].updateValueAndValidity();
      this.FormData.controls[name].markAsUntouched();
    }
  }
  is_exclude(check) {
    check
      ? this.addvalid('exclude_nationality_code', 'add', 'required')
      : this.addvalid('exclude_nationality_code', 'remove', '');
  }

  is_Nationality(val) {
    val == 'specific_nationality'
      ? this.addvalid('include_nationality_code', 'add', 'required')
      : this.addvalid('include_nationality_code', 'remove', 'required');
  }

  is_guideLang(check) {
    check
      ? this.addvalid('guide_languages', 'add', 'required')
      : this.addvalid('guide_languages', 'remove', '');
  }

  SetVahicleValCopyUi() {
    let value = this.Vehicle_Rate_copy.nativeElement.value;
    if (value != '') {
      let obj = this.Vahicleform.getRawValue();
      obj.map((e) => {
        Object.keys(e).forEach((ol, i) => {
          this.Vahicleform.controls[i].get('rate').setValue(value);
        });
      });
    }
  }

  checkcleander() {
    let value = this.FormData.getRawValue();
    if (value.Search_date[0] && value.Search_date[1]) {
      this.datePicker.overlayVisible = false;
      this.getPerPaxDetails();
    }
  }

  setpaxValueFromUi() {
    let val = this.paxform.getRawValue();
    if (val[0].adult_rate != '') {
      this.setValueFormUi('adult_rate');
    }
    if (val[0].senior_rate != '') {
      this.setValueFormUi('senior_rate');
    }
    if (val[0].youth_rate != '') {
      this.setValueFormUi('youth_rate');
    }
    if (val[0].child_rate != '') {
      this.setValueFormUi('child_rate');
    }
    if (val[0].infant_rate != '') {
      this.setValueFormUi('infant_rate');
    }
  }

  setValueFormUi(name) {
    let obj = this.paxform.getRawValue();
    for (let i = 1; i < obj.length; i++) {
      Object.keys(obj[i]).map((e) => {
        if (e == name) {
          this.paxform.controls[i].get(e).setValue(obj[0][name]);
        }
      });
    }
  }

  Pax_Type = [
    { id: 0, name: 'Adult' },
    { id: 1, name: 'Senior' },
    { id: 2, name: 'Youth' },
    { id: 3, name: 'Child' },
    { id: 4, name: 'Infant' },
  ];
}
