import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { MessageService } from 'primeng/api';
import { Observable, ReplaySubject } from 'rxjs';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { ValidationService } from 'src/app/core/common/validation.service';
import { ActivityContent, experience_add } from 'src/app/core/models/Experience-Service/experience-sevice-add/experience-service-add.model';
import { API } from 'src/app/core/services/api.service';
import { environment } from 'src/environments/environment';

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

  selectedCities: string[] = [];
  uploadedFiles: any[] = [];
  //
  user_id = '2205290611511299310'
  //
  formData: FormGroup;
  Experience_Type;
  SubCategory;
  Service_Language;
  CategroyDetails;
  activity_id;
  AllHotelContent;
  HotelPickupPointType;
  HotelPickupType;
  showThumbnailImg: boolean;
  allCityDetials = [];
  Allstartingcity = [];
  sequence = [];
  AdultNoArray = [];
  childNoArray = [];
  InfantNoArray = [];
  SaveBtn = false;
  AllCountry;
  AllActivityHotelZone;
  PhoneCode;
  constructor(
    private messageService: MessageService,
    public ApiServ: API,
    public Fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    public validationService: ValidationService,
    public CommonVari: StaticDataService
  ) { }


  ngOnInit(): void {

    this.GetCountryPhone();
    this.agelength();
    this.showThumbnailImg = false
    this.ngOinitForm();
    this.allCityDetials.push('');
    this.GetAllRequirementView();
    this.GetLOVLanguage();
    this.getexperienceCate();
    this.GetAllHotel();
    this.GetLOVHotelPickupPointType();
    this.GetLOVHotelPickupType();
    this.getCountry();
    this.PickupIncludes('No');
    this.GetAllActivityHotelZone();
    this.getID();
  }


  ngOinitForm(){
    this.formData = this.Fb.group({
      activity_name: this.validationService.required,
      category_id: this.validationService.required,
      Sub_Category: this.validationService.required,
      emergency_phone_nbr: this.validationService.mobNo,
      emergency_phone_code: this.validationService.required,
      default_lang_code: this.validationService.required,
      _service_language: this.validationService.required,
      service_days: this.validationService.required,
      service_hours: this.validationService.required,
      service_minutes: this.validationService.required,
      country_code: this.validationService.required,
      starting_city: this.validationService.required,
      city_id: this.validationService.required,
      is_pickup_included: this.validationService.required,
      additional_pick_up_details: [''],
      Requirment: this.Fb.array([]),
      pickup_hotel: [''],
      is_drop_included: ['No'],
      drop_point: [''],
      min_pax: this.validationService.required,
      max_pax: this.validationService.required,

      is_adult: [true],
      adult_age_from: this.validationService.required,
      adult_age_to: this.validationService.required,

      is_senior: [false],
      senior_age_from: [null],
      senior_age_to: [null],

      is_youth: [false],
      youth_age_from: [null],
      youth_age_to: [null],

      is_child: [false],
      child_age_from: [null],
      child_age_to: [null],

      max_child_count: [''],
      free_child_age_from: [null],
      free_child_age_to: [null],
      is_child_seat: [false],
      Itinerary: this.Fb.array([
      ]),
      activity_highlight: [''],
      activity_description: [''],
      activity_restriction: [''],
      activities_details: [''],
      activity_inclusion: [''],
      activity_exclusion: [''],
      VideoURL: this.Fb.array([
        this.Fb.group({ activity_videos: [''] })
      ]),
      thumnailImg: this.validationService.required,
      images: this.Fb.array([]),
    })
  }
  getCountry() {
    this.ApiServ.Get('/Country/GetCountry').subscribe(data => {
      if (data) {
        this.AllCountry = data;
      }
    });
  };

  GetStartingCity(check) {
      let val = this.formData.getRawValue();
      let allcity = [];
      val.city_id.forEach(e => {
        let city = this.allCityDetials[0].filter(a => a.city_id == e)
        allcity.push(...city);
      });
      this.Allstartingcity = allcity;
      if (val.city_id.length > 1) {
        check ?  this.formData.get('starting_city').setValue('') : '';
      } else {
        this.formData.get('starting_city').setValue(val.city_id.join(','))
      }
  };

  getID() {
    this.route.queryParams.subscribe(d => {
      if (d['id']) {
        this.activity_id = d['id']
        this.ApiServ.Get('/Activity/GetActivity/' + d['id']).subscribe(data => {
          if (data) {
            this.AllSetvalue(data['responseObject']);
          }
        });
      }
    });
  };
  getcity(countryId, check, ind , startcity) {
    this.allCityDetials[ind] = [];
    this.allCityDetials[ind].push(...[]);
    let countrycode;
    if (check == 'set') countrycode = countryId;
    else {
      let country_code = [];
      countryId.map(d => {
        country_code.push(d.alpha_2_code);
      });
      countrycode = country_code;
    }
    if (check == 'CountryManda') this.formData.get('city_id').setValue('');
    if (countrycode.length > 0) {
      this.ApiServ.Get('/City/GetCity/' + countrycode.join(',')).subscribe(data => {
        if (data) {
          this.allCityDetials[ind] = [];
          this.allCityDetials[ind].push(...data);
          startcity ?  this.GetStartingCity(false) : '';
        }
      });
    }
  };

  getexperienceCate() {
    this.ApiServ.Get('/ActivityCategoryMaster/GetAllCategory').subscribe(data => {
      if (data) {
        this.Experience_Type = data['responseObject']
      }
    });
  };

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

  AllSetvalue(d) {
    let value = this.formData.getRawValue()
    Object.keys(value).forEach(e => {
      if (e == 'thumnailImg') {
        this.formData.get(e).setValue(d['thumbnail_image'])
        d['thumbnail_image'] != "" ? this.showThumbnailImg = true : this.showThumbnailImg = false
      } else if (e == 'images') {
        let multiImgs = JSON.parse(d['activity_images'])
        this.setmultiimage(multiImgs);
      } else if (e == 'category_id') {
        this.formData.get(e).setValue(d['category_id']);
        let sub_category_id = d['sub_category_id'].split(',');
        this.GetSubCategory(d['category_id']);
        setTimeout(() => {
          this.formData.get('Sub_Category').setValue(sub_category_id);
        }, 50);
      } else if (e == "country_code") {
        let value = d[e] ? d[e].split(",") : null;
        this.getcity(value, 'set', 0 , true);
        this.formData.get(e).setValue(value);
        let city = d['city_id'] ? d['city_id'].split(",") : null;
        this.formData.get('city_id').setValue(city);
        
        this.formData.get('starting_city').setValue(d['starting_city']);
      }
      else if (e == '_service_language') {
        let value = d[e] ? d[e].split(",") : null;
        this.formData.get(e).setValue(value);
      } else if (e == 'default_lang_code') {
        this.formData.get(e).setValue(d[e]);
      }
      else if (e == 'VideoURL') {
        this.setUrlLink(d['activity_videos']);
      }
      else if (e == 'activity_name' || e == 'departure_point' || e == 'activity_highlight'
        || e == 'activity_description' || e == 'activity_restriction' || e == 'activities_details' ||
        e == 'activity_exclusion' || e == 'activity_inclusion' || e == 'drop_point' || e == 'additional_pick_up_details') {
        this.formData.get(e).setValue(d['activityContents'][0][e] ? d['activityContents'][0][e] : "");
      }
      else if (e == 'is_drop_included') {
        if (e == 'is_drop_included') {
          this.formData.get(e).setValue(d[e] ? 'Yes' : 'No');
          this.dropoffvalid(d[e] ? 'Yes' : 'No');
        }
      } else if (e == 'is_pickup_included') {
        this.formData.get(e).setValue(d[e] ? 'Yes' : 'No');
        this.PickupIncludes(d[e] ? 'Yes' : 'No');
        if (!d[e]) {
          this.formData.get('meeting_before_hour').setValue(d['meeting_before_hour']);
          this.formData.get('meeting_before_minute').setValue(d['meeting_before_minute']);
          this.formData.get('meeting_point').setValue(d['activityContents'][0]['meeting_point']);
        } else if (d[e]) {
          this.formData.get('_pickup_point_type').setValue(parseInt(d['_pickup_point_type']))
          this.PickupPointValid();
          if (d['_pickup_point_type'] == '2') {
            this.formData.get('departure_point').setValue(d['activityContents'][0]['departure_point'])
            this.formData.get('departure_hour').setValue(d['pickup_before_hour'])
            this.formData.get('departure_minute').setValue(d['pickup_before_minute'])
          } else if (d['_pickup_point_type'] == '1') {
            this.formData.get('_hotel_pickup_type').setValue(parseInt(d['_hotel_pickup_type']));
            this.Hotel_Type_AddPickupValid();
            if (d['_hotel_pickup_type'] == '1') {
              this.formData.get('All_Hotel_hour').setValue(d['pickup_before_hour'])
              this.formData.get('All_Hotel_minute').setValue(d['pickup_before_minute'])
            } else if (d['_hotel_pickup_type'] == '2') {
              let pickup_hotel = d['pickup_hotel'].split(',');
              this.formData.get('pickup_hotel').setValue(pickup_hotel);
              this.formData.get('Specific_Hotel_hour').setValue(d['pickup_before_hour']);
              this.formData.get('Specific_Hotel_minute').setValue(d['pickup_before_minute']);
            } else if (d['_hotel_pickup_type'] == '3') {
              let hotel_zone = d['hotel_zone'].split(',');
              this.formData.get('hotel_zone').setValue(hotel_zone);
              this.formData.get('hotel_zone_hour').setValue(d['pickup_before_hour']);
              this.formData.get('hotel_zone_minute').setValue(d['pickup_before_minute']);
            }
          }
        }
      } else if (e == "is_adult" || e == "is_senior" || e == "is_youth" || e == "is_child") {
        if (e == "is_adult" && d['is_adult']) {
          this.formData.get(e).setValue(d[e]);
          this.adultValid(d[e]);
          this.formData.get('adult_age_from').setValue(d['adult_age_from']);
          this.formData.get('adult_age_to').setValue(d['adult_age_to']);
        } else if (e == "is_senior" && d['is_senior']) {
          this.formData.get(e).setValue(d[e]);
          this.SeniorValid(d[e]);
          this.formData.get('senior_age_from').setValue(d['senior_age_from']);
          this.formData.get('senior_age_to').setValue(d['senior_age_to']);
        } else if (e == "is_youth" && d['is_youth']) {
          this.formData.get(e).setValue(d[e]);
          this.YouthValid(d[e]);
          this.formData.get('youth_age_from').setValue(d['youth_age_from']);
          this.formData.get('youth_age_to').setValue(d['youth_age_to']);
        } else if (e == "is_child" && d['is_child']) {
          this.formData.get(e).setValue(d[e]);
          this.ChildValid(d[e]);
          this.formData.get('child_age_from').setValue(d['child_age_from']);
          this.formData.get('child_age_to').setValue(d['child_age_to']);
        }
      } else if (e == 'Requirment') {
        let required = d['requirements'] ? d['requirements'].split(',') : false;
        if (required) {
          this.Requirment.controls.forEach(x => {
            Object.keys(x['controls']).forEach(l => {
              let check = required.filter(m => m == x.get('header_id').value);
              if (check.length > 0) {
                x.get('is_header').setValue(true);
                x.get('requirements')['controls'].forEach(re => {
                  Object.keys(re['controls']).forEach(li => {
                    let check = required.filter(m => m == re.get('requirement_id').value);
                    if (check.length > 0) re.get('is_requirement').setValue(true);
                  })
                });
              }
            })
          })
        }
      }
      else if (e == 'max_pax' || e == 'min_pax' || e == 'emergency_phone_nbr' || e == 'emergency_phone_code' || e == 'service_minutes' ||
        e == 'service_hours' || e == 'is_child_seat' || e == 'max_child_count'
        || e == 'free_child_age_to' || e == 'free_child_age_from') {
        this.formData.get(e).setValue(d[e]);
      } else if (e == 'service_days') {
        this.formData.get(e).setValue(d[e]);
        this.DaysItineryForm(d[e]);
        let obj = JSON.parse(d['activityContents'][0]['daywise_itinerary']);
        obj.forEach((z, i) => {
          Object.keys(z).forEach((q) => {
            if (q == 'Text_html') {
              this.Itinerary.controls[i].get(q).setValue(z[q]);
            } else if (q == 'country_code') {
              this.Itinerary.controls[i].get(q).setValue(z[q]);
              this.getcity(z[q], 'set', i + 1 , false);
              this.Itinerary.controls[i].get('city_code').setValue(z['city_code']);
            }
          })
        })
      }
    });
  };


  setUrlLink(URL) {
    let val = JSON.parse(URL);
    val.map((valLi, i) => {
      i != 0 ? this.addvideo() : "";
      this.VideoURl.controls[i].get('activity_videos').setValue(valLi.activity_videos);
    });
  };
  setmultiimage(image) {
    this.MultiImageGallery = [];
    image.map((valLi, i) => {
      this.addPackageImgGallery();
      this.ImgGallery.controls[i].get('image_url').setValue(valLi.image_url);
      this.MultiImageGallery.push(valLi.image_url);
    });
  }


  // get form controls

  get allFormGroup() {
    return this.formData.getRawValue();
  };
  get VideoURl() {
    return this.formData.get('VideoURL') as FormArray;
  };
  get Requirment() {
    return this.formData.get('Requirment') as FormArray;
  };
  // GetDetailsByID(id) {
  //   this.ApiServ.Get('/GetHotel/{Id}')
  // }

  GetAllHotel() {
    this.ApiServ.Get('/HotelContent/GetAllHotelContent').subscribe(data => {
      if (data) {
        this.AllHotelContent = data['responseObject'];
      }
    });
  };

  GetSubCategory(value) {
    this.formData.get('Sub_Category').setValue('')
    this.ApiServ.Get('/ActivityCategoryMaster/GetSubCategory?Id=' + value).subscribe(data => {
      if (data) {
        this.SubCategory = data['responseObject']
      }
    });
  };

  GetLOVHotelPickupPointType() {
    let formdata = {
      "lov_types": [{ "lov_type": "HotelPickupPointType" }],
      "lov_lang": "en"
    }
    this.ApiServ.Post("/LovMaster/GetLov", formdata).subscribe(data => {
      if (data) {
        console.log(data)
        this.HotelPickupPointType = data['responseObject']['0']['keys']
        console.log(this.HotelPickupPointType)
      }
    });
  };
  requirementCheck(check, formgroup) {
    if (check) {
      formgroup.get('requirements').controls.forEach(e => {
        e.get('is_requirement').setValue(true);
      })
    } else {
      formgroup.get('requirements').controls.forEach(e => {
        e.get('is_requirement').setValue(false);
      })
    }
  }


  GetLOVHotelPickupType() {
    let formdata = {
      "lov_types": [{ "lov_type": "HotelPickupType" }],
      "lov_lang": "en"
    }
    this.ApiServ.Post("/LovMaster/GetLov", formdata).subscribe(data => {
      if (data) {
        console.log(data)
        this.HotelPickupType = data['responseObject']['0']['keys']
        console.log(this.HotelPickupPointType)
      }
    });
  };

  GetLOVLanguage() {
    let formdata = {
      "lov_types": [{ "lov_type": "Language" }],
      "lov_lang": "en"
    }
    this.ApiServ.Post("/LovMaster/GetLov", formdata).subscribe(data => {
      if (data) {
        console.log(data)
        this.Service_Language = data['responseObject']['0']['keys']
        console.log(this.Service_Language)
      }
    });
  };

  //  save 

  SaveFormData() {
    let value = this.formData.getRawValue();
    if (this.formData.status == "INVALID") {
      this.validationService.showValidationsMsg(this.formData);
      const firstElementWithError = document.querySelector('.ng-invalid');
      if (firstElementWithError) {
        firstElementWithError.scrollIntoView({ behavior: 'smooth' });
      }
      return;
    }
    this.SaveBtn = true;

    let org_id = '2105311837100000021';
    let supplier_id = '2205221841391724322';

    let dataArr = [];
    let postArrayData = new ActivityContent();
    postArrayData.activity_name = value.activity_name;
    postArrayData.meeting_point = value.is_pickup_included == 'No' ? value.meeting_point : '';
    postArrayData.drop_point = value.is_drop_included == 'Yes' ? value.drop_point : "";
    postArrayData.activity_highlight = value.activity_highlight;
    postArrayData.activity_description = value.activity_description;
    postArrayData.activity_restriction = value.activity_restriction;
    postArrayData.activities_details = value.activities_details;
    postArrayData.activity_inclusion = value.activity_inclusion;
    postArrayData.activity_exclusion = value.activity_exclusion;
    postArrayData.org_id = org_id;
    let daysiternery = this.Itinerary.getRawValue();
    postArrayData.daywise_itinerary = JSON.stringify(daysiternery);
    postArrayData.additional_pick_up_details = value.additional_pick_up_details;

    postArrayData.language_code = 'EN'; //
    postArrayData.supplier_id = supplier_id; //
    dataArr.push(postArrayData)

    // undefine  hardcode
    postArrayData.activity_content_id = '';
    postArrayData.activity_id = this.activity_id ? this.activity_id : "";
    postArrayData.created_by = 'Razzak';
    postArrayData.updated_by = 'Razzak';
    //

    //
    let PostData = new experience_add();
    PostData.org_id = org_id;
    PostData.category_id = value.category_id;
    PostData._pickup_point_type = value.is_pickup_included == 'Yes' ? value._pickup_point_type.toString() : '';
    PostData._service_language = value._service_language.join(",");
    PostData.default_lang_code = value.default_lang_code;
    PostData.emergency_phone_code = value.emergency_phone_code;
    PostData.emergency_phone_nbr = value.emergency_phone_nbr;

    PostData.service_days = value.service_days;
    PostData.service_hours = value.service_hours;
    PostData.service_minutes = value.service_minutes;
    PostData.supplier_id = supplier_id; //
    PostData.activity_id = this.activity_id ? this.activity_id : "";

    // undefined hardcode
    PostData.sub_category_id = value.Sub_Category.join(",");
    PostData.activity_content_json = '';
    PostData.category_name = '';

    this.Requirment.getRawValue();
    let AllReqirement = this.Requirment.getRawValue();
    let All_Id = [];
    AllReqirement.forEach(e => {
      if (e.is_header) {
        All_Id.push(e.header_id);
        if (e.requirements) {
          e.requirements.forEach(d => {
            d.is_requirement ? All_Id.push(d.requirement_id) : '';
          });
        };
      };
    });
    PostData.requirements = All_Id.length > 0 ? All_Id.join(',') : '';
    PostData.starting_city = value.starting_city;
    //  multi images
    this.ImageGalleryArr = [];
    value.images.map((galLi, i) => {
      if (typeof (galLi.image_url) == 'object') {
        this.fileArr.push(galLi.image_url);
        this.fileInfo.push({ 'fileName': "Activity/Add_Act_Id_gallery_" + (i + 1) + "." + galLi.image_url.name.split('.')[1], 'pathToSave': 'ThemeImages/ORGID' });
      }
      let imagedata = {
        image_url: typeof (galLi.image_url) == 'object' ? environment.cdnFileUrl + "ThemeImages/ORGID/Activity/Add_Act_Id_gallery_" + (i + 1) + "." + galLi.image_url.name.split('.')[1] : galLi.image_url,
        sequence: i + 1
      }
      this.ImageGalleryArr.push(imagedata);
    });
    PostData.activity_images = JSON.stringify(this.ImageGalleryArr);

    //  thumnail images

    if (typeof (value.thumnailImg) == 'object') {
      this.fileArr.push(value.thumnailImg);
      this.fileInfo.push({ 'fileName': "Activity/Add_Act_Id." + value.thumnailImg.name.split('.')[1], 'pathToSave': 'ThemeImages/ORGID' });
    }
    let thumnail_img = typeof (value.thumnailImg) == 'object' ? environment.cdnFileUrl + "ThemeImages/ORGID/Activity/Add_Act_Id." + value.thumnailImg.name.split('.')[1] : value.thumnailImg.split('.')[0];
    PostData.thumbnail_image = thumnail_img;

    PostData.created_by = ''
    PostData.updated_by = ''
    PostData.activity_videos = JSON.stringify(this.VideoURl.getRawValue())

    PostData.country_code = value.country_code.join(",");
    PostData.city_id = value.city_id.join(",");

    // condition based pickup before time
    postArrayData.departure_point = '';
    PostData._hotel_pickup_type = '';
    PostData.pickup_hotel = '';
    PostData.hotel_zone = '';
    if (value.is_pickup_included == 'Yes') {
      if (value._pickup_point_type == 2) {
        postArrayData.departure_point = value.departure_point;
        PostData.pickup_before_hour = value.departure_hour;
        PostData.pickup_before_minute = value.departure_minute;
      } else if (value._pickup_point_type == 1) {
        PostData._hotel_pickup_type = value._hotel_pickup_type.toString();
        if (value._hotel_pickup_type == 1) {
          PostData.pickup_before_hour = value.All_Hotel_hour;
          PostData.pickup_before_minute = value.All_Hotel_minute;
        } else if (value._hotel_pickup_type == 2) {
          PostData.pickup_hotel = value.pickup_hotel.join(',');
          PostData.pickup_before_hour = value.Specific_Hotel_hour;
          PostData.pickup_before_minute = value.Specific_Hotel_minute;
        } else if (value._hotel_pickup_type == 3) {
          PostData.hotel_zone = value.hotel_zone.join(',');
          PostData.pickup_before_minute = value.hotel_zone_hour;
          PostData.pickup_before_hour = value.hotel_zone_minute;
        }
      }
    }

    PostData.is_pickup_included = value.is_pickup_included == 'No' ? false : true;
    PostData.meeting_before_hour = value.is_pickup_included == 'No' ? value.meeting_before_hour : 0;
    PostData.meeting_before_minute = value.is_pickup_included == 'No' ? value.meeting_before_minute : 0;
    /////
    PostData.is_drop_included = value.is_drop_included == 'No' ? false : true;
    PostData.min_pax = value.min_pax;
    PostData.max_pax = value.max_pax;
    PostData.is_adult = value.is_adult;
    PostData.adult_age_from = value.is_adult ? value.adult_age_from : 0;
    PostData.adult_age_to = value.is_adult ? value.adult_age_to : 0;
    PostData.is_senior = value.is_senior;
    PostData.senior_age_from = value.is_senior ? value.senior_age_from : 0;
    PostData.senior_age_to = value.is_senior ? value.senior_age_to : 0;
    PostData.is_youth = value.is_youth;
    PostData.youth_age_from = value.is_youth ? value.youth_age_from : 0;
    PostData.youth_age_to = value.is_youth ? value.youth_age_to : 0;
    PostData.is_child = value.is_child;
    PostData.child_age_from = value.is_child ? value.child_age_from : 0;
    PostData.child_age_to = value.is_child ? value.child_age_to : 0;
    PostData.max_child_count = value.is_child ? value.max_child_count ? value.max_child_count : 0 : 0;
    PostData.free_child_age_from = value.is_child ? value.free_child_age_from ? value.free_child_age_from : 0 : 0;
    PostData.free_child_age_to = value.is_child ? value.free_child_age_to ? value.free_child_age_to : 0 : 0;
    PostData.is_child_seat = value.is_child_seat;
    PostData.activityContents = dataArr;


    if (this.activity_id) {
      this.ApiServ.Post('/Activity/UpdateActivity', PostData).subscribe(data => {
        if (data) {
          (data['status'] && this.fileInfo.length > 0) ? this.saveImg(data, this.fileArr, this.fileInfo) : this.showToastrMsg(data);

        }
      });
    } else {
      this.ApiServ.Post('/Activity/SaveActivity', PostData).subscribe(data => {
        if (data) {
          (data['status'] && this.fileInfo.length > 0) ? this.saveImg(data, this.fileArr, this.fileInfo) : this.showToastrMsg(data);
        }
      });
    }
  }

  showToastrMsg(respData) {
    this.messageService.add({
      severity: respData['status'] ? 'success' : 'error',
      detail: respData['message'],
    });
    this.SaveBtn = false;
    setTimeout(() => {
      respData['status'] ? this.btnClick() : '';
    }, 500);
  }
  // ng select



  option = [
    { id: 0, name: 'Yes' },
    { id: 1, name: 'No' },
  ];

  optionDropOff = [
    { id: 0, name: 'Yes' },
    { id: 1, name: 'No' },
  ];
  selectOption = this.option[0].name;

  onUpload(event: { files: any }) {
    for (let file of event.files) {
      this.uploadedFiles.push(file);
    }

    this.messageService.add({
      severity: 'info',
      summary: 'File Uploaded',
      detail: '',
    });
  }

  addvideo() {
    this.VideoURl.push(this.Fb.group({ activity_videos: [''] }))
  }
  removevideo(index: number) {
    this.VideoURl.removeAt(index)
  }


  //  hours and minutes option dropdown  

  agelength() {
    for (let i = 0; i <= 100; i++) {
      i >= 0 && i <= 18 ? this.childNoArray.push({ value: i }) : "";
      i >= 0 && i <= 2 ? this.InfantNoArray.push({ value: i }) : "";
      this.AdultNoArray.push({ value: i })
      i != 0 ? this.sequence.push(i) : ''
    };
  };



  GetAllRequirementView() {
    this.ApiServ.Get('/ActivityRequirement/GetAllRequirementView').subscribe(res => {
      if (res) {
        let requirementObj = res.responseObject.sort((a, b) => a.header_sequence - b.header_sequence);
        requirementObj.forEach((e, i) => {
          let req_menu = e.requirements.sort((a, b) => a.sub_sequence - b.sub_sequence)
          this.Requirment.push(
            this.Fb.group({
              header_name: [e.header_name],
              header_id: [e.header_id],
              is_header: [false],
              requirements: this.Fb.array([
              ])
            })
          )
          if (req_menu) {
            req_menu.forEach(d => {
              let form = this.Requirment.controls[i].get('requirements') as FormArray;
              form.push(this.Fb.group({
                requirement_id: [d.requirement_id],
                requirement_name: [d.requirement_name],
                is_requirement: [false]
              }))
            })
          }
        })
      }
    })
  }





  /// images save 
  fileArr = [];
  fileInfo = [];

  //
  MultiImageGallery = [];
  ImageGalleryArr = [];
  get ImgGallery() {
    return this.formData.get('images') as FormArray;
  }
  get Itinerary() {
    return this.formData.get('Itinerary') as FormArray;
  }


  getMultiGalleryImg(e) {
    console.log(e)
    if (e.currentFiles.length != 0) {
      for (let i = 0; i < e.files.length; i++) {
        this.addPackageImgGallery();
        let file = e.files[i];
        this.ImgGallery.controls[this.MultiImageGallery.length + i].get('image_url').setValue(file)
        //base 64
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.MultiImageGallery.push(reader.result)
        };
      }
    }
  }
  emptyImgGallery(i) {
    this.ImgGallery.removeAt(i);
    this.MultiImageGallery.splice(i, 1);
    console.log(this.MultiImageGallery)
  }


  addPackageImgGallery() {
    this.ImgGallery.push(
      this.Fb.group({
        image_url: [''],
        sequence: ['']
      })
    )
  }
  /////
  getThumnailImg(e) {
    this.onFileSelected(e)
    if (e.currentFiles.length != 0) {
      let file = e.files[0];
      this.showThumbnailImg = true
      this.formData.get('thumnailImg').setValue(file);
    }
  };
  base64Output;
  onFileSelected(event) {
    this.convertFile(event.files[0]).subscribe(base64 => {
      if (base64) {
        this.base64Output = 'data:image/png;base64,' + base64;
        console.log(this.base64Output);
      }
    });
  }
  convertFile(file: File): Observable<string> {
    const result = new ReplaySubject<string>(1);
    const reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (event) => result.next(btoa(event.target.result.toString()));
    return result;
  }

  emptyThunailImg() {
    this.base64Output = '';
    this.showThumbnailImg = false
    this.formData.get('thumnailImg').setValue('');
  };


  btnClick() {
    this.router.navigate(['/Services/ActivityServices/ExpServices/Search']);
  }
  saveImg(respData, file_arr, file_info) {
    var formdata = new FormData();
    file_arr.forEach(x => {
      formdata.append("files", x);
    })
    let Id = this.activity_id ? this.activity_id : respData['responseObject'].activity_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)
      }
    });
  }

  //  add validation 
  PickupIncludes(val) {
    if (val == 'No') {
      this.formData.addControl('meeting_point', this.Fb.control('', Validators.required));
      this.formData.addControl('meeting_before_hour', this.Fb.control(null, Validators.required));
      this.formData.addControl('meeting_before_minute', this.Fb.control(null, Validators.required));
      this.formData.removeControl('_pickup_point_type');
    } else {
      this.formData.addControl('_pickup_point_type', this.Fb.control(1, [Validators.required]));
      this.formData.removeControl('meeting_point');
      this.formData.removeControl('meeting_before_hour');
      this.formData.removeControl('meeting_before_minute');
      this.PickupPointValid();
    }

  }
  PickupPointValid() {
    let val = this.formData.getRawValue();
    if (val._pickup_point_type == 1) {
      this.formData.removeControl('departure_point');
      this.formData.removeControl('departure_hour');
      this.formData.removeControl('departure_minute');
      this.formData.addControl('_hotel_pickup_type', this.Fb.control(1, Validators.required));
      this.Hotel_Type_AddPickupValid();
    } else {
      this.formData.removeControl('_hotel_pickup_type');
      this.formData.addControl('departure_point', this.Fb.control('', Validators.required));
      this.formData.addControl('departure_hour', this.Fb.control(null, Validators.required));
      this.formData.addControl('departure_minute', this.Fb.control(null, Validators.required));
      this.Hotel_Type_AddPickupValid();
    }
  }
  Hotel_Type_AddPickupValid() {
    let val = this.formData.getRawValue();
    this.formData.removeControl('All_Hotel_hour');
    this.formData.removeControl('All_Hotel_minute');
    this.formData.removeControl('pickup_hotel');
    this.formData.removeControl('Specific_Hotel_hour');
    this.formData.removeControl('Specific_Hotel_minute');
    this.formData.removeControl('hotel_zone');
    this.formData.removeControl('hotel_zone_hour');
    this.formData.removeControl('hotel_zone_minute');
    if (val._hotel_pickup_type == 1) {
      this.formData.addControl('All_Hotel_hour', this.Fb.control(null, Validators.required));
      this.formData.addControl('All_Hotel_minute', this.Fb.control(null, Validators.required));
    } else if (val._hotel_pickup_type == 2) {
      this.formData.addControl('pickup_hotel', this.Fb.control(null, Validators.required));
      this.formData.addControl('Specific_Hotel_hour', this.Fb.control(null, Validators.required));
      this.formData.addControl('Specific_Hotel_minute', this.Fb.control(null, Validators.required));
    } else if (val._hotel_pickup_type == 3) {
      this.formData.addControl('hotel_zone', this.Fb.control(null, Validators.required));
      this.formData.addControl('hotel_zone_hour', this.Fb.control(null, Validators.required));
      this.formData.addControl('hotel_zone_minute', this.Fb.control(null, Validators.required));
    }
  }
  /// check box validation 
  adultValid(check) {
    if (check) {
      this.addvalid("adult_age_from", 'add');
      this.addvalid("adult_age_to", 'add');
    } else {
      this.addvalid("adult_age_from", 'remove');
      this.addvalid("adult_age_to", 'remove');
    }

  }
  SeniorValid(check) {
    if (check) {
      this.addvalid("senior_age_from", 'add');
      this.addvalid("senior_age_to", 'add');
    } else {
      this.addvalid("senior_age_from", 'remove');
      this.addvalid("senior_age_to", 'remove');
    }
  }
  YouthValid(check) {
    if (check) {
      this.addvalid("youth_age_from", 'add');
      this.addvalid("youth_age_to", 'add');
    } else {
      this.addvalid("youth_age_from", 'remove');
      this.addvalid("youth_age_to", 'remove');
    }
  };
  ChildValid(check) {
    if (check) {
      this.addvalid("child_age_from", 'add');
      this.addvalid("child_age_to", 'add');
    } else {
      this.addvalid("child_age_from", 'remove');
      this.addvalid("child_age_to", 'remove');
    }
  };
  InfantValid(check) {
    if (check) {
      this.addvalid("infant_age_from", 'add');
      this.addvalid("infant_age_to", 'add');
    } else {
      this.addvalid("infant_age_from", 'remove');
      this.addvalid("infant_age_to", 'remove');
    }

  };
  dropoffvalid(val) {
    if (val == 'No') {
      this.addvalid("drop_point", 'remove');
    } else {
      this.addvalid("drop_point", 'add');
    }
  };

  addvalid(name, type) {
    if (type == 'add') {
      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();
    }
  };

  GetAllActivityHotelZone() {
    let SearchObj = {
      city_id: '',
      country_code: '',
      zone_name: '',
    }
    this.ApiServ.Post('/ActivityHotelZone/GetAllActivityHotelZone', SearchObj).subscribe(res => {
      if (res) {
        this.AllActivityHotelZone = res.result.responseObject;
      }
    })
  }

  DaysItineryForm(ind) {
    let val = this.formData.getRawValue();
    this.Itinerary.clear()
    for (let i = 0; i < ind; i++) {
      this.Itinerary.push(this.Fb.group({
        Text_html: [''],
        country_code: [''],
        city_code: [''],
      }));
    }
  }

}

