import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { API } from 'src/app/core/services/api.service';
import * as moment from 'moment';
import { ValidationService } from 'src/app/core/common/validation.service';
// import { CancellationDisplay, GetCancellationPolicy, UpdateCancellationPolicy } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-cancellation-policy/edit-cancellation-policy.model';
import { MessageService } from 'primeng/api';
import { CommonService } from 'src/app/core/services/common.service';
import { CancellationDisplay, GetCancellationPolicy, UpdateCancellationPolicy } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-cancellation-policy/edit-cancellation-policy.model';
interface grp {
  name: string,
  code: string
}
@Component({
  selector: 'app-edit-cancelletion-policy',
  templateUrl: './edit-cancelletion-policy.component.html',
})
export class EditCancelletionPolicyComponent implements OnInit {
  Pickup: string[] = [];
  date1!: Date;
  date2!: Date;
  CommonCalender!: string;
  FromData: FormGroup
  Data;
  AllSlots;
  activityContractId;
  RateConfigdata;
  season_list;
  slot_wise_cancellation_policy;
  lovKeyDataObj = {
    RatePeriodType: [],
    DaySelect: [],
    ActivityNoShowPolicyType: [],
    ActivityCancellationPolicyType: [],
    ActivityCancellationChargeType: [],
  };

  constructor(private route: ActivatedRoute,
    public ApiServ: API, public Fb: FormBuilder,
    public validationService: ValidationService,
    private MsgService: MessageService,
    private router: Router,) { }

  ngOnInit(): void {
    this.GetLOVKeys('RatePeriodType,DaySelect,ActivityNoShowPolicyType,ActivityCancellationPolicyType,ActivityCancellationChargeType');
    this.GetRateConfig();
    this.ngOninForm();
    this.GetAllActivitySeason();
  }


  /**
   * @author Abdul Razzak
   * to create form group
   */
  ngOninForm() {
    this.FromData = this.Fb.group({
      activity_name: [''],
      option_name: [''],
      period_type: [''],
      slot_id: [''],
      dates: [''],
      days: [''],
      seasonId: [''],
      _no_show_policy_type: this.validationService.required,
      cancellationDisplays: this.Fb.array([
      ])
    });
  }

  /**
   * @author Abdul Razzak
   *  to get activity contract data by contract id  and set value  
   */
  GetRateConfig() {
    this.route.queryParams.subscribe(obj => {
      if (obj['id']) {
        this.GetActivityById();
        this.activityContractId = obj['id'];
        this.GetSlotsById(obj['id']);
        this.ApiServ.Get('/ActivityContract/GetRateConfig/' + obj['id']).subscribe(d => {
          if (d && d.status) {
            this.RateConfigdata = d.responseObject;
            this.slot_wise_cancellation_policy = d.responseObject.is_slot_wise_cancellation_policy;
            this.FromData.get('option_name').setValue(d.responseObject.option_name);
            this.FromData.get('_no_show_policy_type').setValue(parseInt(d.responseObject._no_show_policy_type));
            if (d.responseObject._no_show_policy_type != 1) {
              this.No_Show_Type(d.responseObject._no_show_policy_type);
              this.FromData.get('no_show_charge_value').setValue(d.responseObject.no_show_charge_value);
            }
          }
        })
      }
    });
  }

  /**
   * @author Abdul Razzak
   * to get slot data by contract id  
   * @param Id 
   */
  GetSlotsById(Id) {
    this.ApiServ.Get('/ActivityContract/GetSlotsById/' + Id).subscribe(res => {
      if (res) {
        this.AllSlots = res.responseObject;
      }
    })
  }
  /**
   * @author Abdul Razzak
   * to get form controls
   */
  get cancelDisplay() {
    return this.FromData.get('cancellationDisplays') as FormArray;
  };

  // AddFormDate() {
  //   this.cancelDisplay.push(this.Fb.group({
  //     _charge_type: this.validationService.required,
  //     charge_value: [''],
  //     _from: [''],
  //     _to: [''],
  //     _date: [''],
  //     activity_cancellation_policy_id: [''],
  //     // _cancellation_policy_type: this.validationService.required,
  //   }))
  // }

  // cancellationDisplays;
  // SetValue(d) {
  //   let value = this.FromData.getRawValue();
  //   this.cancellationDisplays = d.cancellationDisplays;
  //   this.setinputVal(d.cancellationDisplays);
  //   // Object.keys(value).forEach(e => {
  //   //   if (e != 'cancellationDisplays') {
  //   //     this.FromData.get(e).setValue(d[e]);
  //   //   }
  //   // });


  // }



  // setinputVal(data) {
  //   for (let i = 0; i < data.length; i++) {
  //     console.log(i);
  //     this.AddFormDate()
  //     let formval = this.cancelDisplay.controls[i].value
  //     Object.keys(formval).forEach(a => {
  //       console.log(a)
  //       if (a == "_charge_type") {
  //         this.cancelDisplay.controls[i].get('_charge_type').setValue(parseInt(data[i][a]));
  //       }
  //       // else if (a == '_cancellation_policy_type') {
  //       //   this.cancelDisplay.controls[i].get(a).setValue(parseInt(data[i][a]));
  //       // }
  //       else if (a == 'charge_value') {
  //         this.cancelDisplay.controls[i].get('charge_value').setValue(this.cancelDisplay.controls[i].get('_charge_type').value == '1' ? '' : data[i][a]);
  //       }
  //       else {
  //         this.cancelDisplay.controls[i].get(a).setValue(data[i][a]);
  //       }
  //     });
  //   };
  // };

  // LOVCancallationData;
  // LOVCancallationPolicy;
  // GetLOVMater() {
  //   let formdata = {
  //     "lov_types": [
  //       { "lov_type": "NoShowType" },
  //       { "lov_type": "CancellationPolicyType" }
  //     ],
  //     "lov_lang": "EN"
  //   }

  //   this.ApiServ.Post("/LovMaster/GetLov", formdata).subscribe(data => {
  //     if (data) {
  //       this.LOVCancallationData = data.responseObject[0].keys;
  //       this.LOVCancallationPolicy = data.responseObject[1].keys;
  //     }



  /**
   * @author Abdul Razzak
   * to check cancellation type  if full amount is selected then 
   * @param val 
   * @param ind 
   */
  InputClear(val, ind, group) {
    if (val == '1') {
      this.cancelDisplay.controls[ind].get('charge_value').setValue('');
      this.addvalidNum('charge_value', val, group);
    } else this.addvalidNum('charge_value', val, group);
  };


  addvalidNum(name, val, group) {
    if (val == '1') {
      group.controls[name].clearValidators();
      group.controls[name].updateValueAndValidity();
      group.controls[name].markAsUntouched();
    } else {
      group.controls[name].addValidators([Validators.required, Validators.pattern(/^[0-9.]*$/)]);
      group.controls[name].updateValueAndValidity();
    }
  };

  /**
   * @author Abdul Razzak
   * to empty value
   * @param ind 
   */
  No_Show_Type(ind) {
    if (ind != 1) {
      this.FromData.addControl('no_show_charge_value', this.Fb.control('', [Validators.required, Validators.pattern(/^[+-]?([0-9]+\.?[0-9]*|\.[0-9]+)$/)]));
    } else {
      this.FromData.removeControl('no_show_charge_value');
    }
  }

  /**
   * @author Abdul Razzak
   *  to get data from LOV
   * @param lov_key_names  
   */
  GetLOVKeys(lov_key_names) {
    let lov_key_names_arr = lov_key_names.split(',');
    let lov_obj = {
      "lov_types": [],
      "lov_lang": "en"
    }
    lov_key_names_arr.forEach(key_name => {
      lov_obj.lov_types.push({ "lov_type": key_name });
    });
    this.ApiServ.Post('/LovMaster/GetLov', lov_obj).subscribe(lov_data => {
      if (lov_data && lov_data.status) {
        this.GetActivityById();
        lov_key_names_arr.forEach(key_name => {
          let arr = lov_data.responseObject.filter(el => el.lov_type == key_name);
          arr.length > 0 ? this.lovKeyDataObj[key_name] = arr[0].keys : '';
        });
      }
    });
  }

  /**
   * @author Abdul Razzak
   * to get activity details
   */
  GetActivityById() {
    let activity_id = CommonService.getSessionStoage('activity_id');
    this.ApiServ.Get('/Activity/GetActivity/' + activity_id).subscribe(res => {
      if (res) {
        this.FromData.get('activity_name').setValue(res.responseObject.activityContents[0].activity_name);
      }
    })
  }

  /**
   * @author Abdul Razzak
   * to remove specific row of cancellation policy list 
   * @param ind 
   */
  remove(ind) {
    this.cancelDisplay.removeAt(ind);
  }

  CopyValue() {
    let val = this.cancelDisplay.getRawValue();
    for (let i = 1; i < val.length; i++) {
      this.cancelDisplay.controls[i].get('charge_value').setValue(this.cancelDisplay.controls[i].get('_charge_type').value != '1' ? val[0].charge_value : '');
    }
  }

  CopyBlocksValue() {
    let val = this.cancelDisplay.getRawValue();
    for (let i = 1; i < val.length; i++) {
      this.cancelDisplay.controls[i].get('_cancellation_policy_type').setValue(val[0]._cancellation_policy_type);
      this.cancelDisplay.controls[i].get('_charge_type').setValue(val[0]._charge_type);
      this.cancelDisplay.controls[i].get('charge_value').setValue(this.cancelDisplay.controls[i].get('_charge_type').value != '1' ? val[0].charge_value : '');

    }
  }

  /**
   * @author Abdul Razzak
   * to get all activity season data
   */
  GetAllActivitySeason() {
    this.ApiServ.Get('/ActivitySeason/GetAllActivitySeason?activityId=' + CommonService.getSessionStoage('activity_id')).subscribe(d => {
      if (d && d.status) {
        this.season_list = d.responseObject;
      }
    });
  }

  /**
   * @author  Abdul Razzak
   * to get all cancellation details
   */
  SearchCancellationPolicy() {
    let val = this.FromData.getRawValue();
    let postdata = new GetCancellationPolicy();
    postdata.from_date = val.dates[0] ? moment(val.dates[0]).format('YYYY-MM-DD') : '';
    postdata.to_date = val.dates[1] ? moment(val.dates[1]).format('YYYY-MM-DD') : '';
    postdata.slot_id = val.slot_id ? val.slot_id : '';
    postdata.seasonId = val.seasonId ? val.seasonId : [];
    postdata.days = val.days ? val.days.join(',') : '';
    postdata.contract_id = this.activityContractId;
    this.ApiServ.Post('/ActivityContract/GetCancellationPolicy', postdata).subscribe(res => {
      if (res) {
        this.SetPolicyValue(res.responseObject)
      }
    })
  }
  /**
   * @author Abdul Razzak
   * method to create form group controler and set value 
   * @param data 
   */
  SetPolicyValue(data) {
    this.cancelDisplay.clear()
    data.forEach(d => {
      this.cancelDisplay.push(this.Fb.group({
        _charge_type: [parseInt(d._charge_type), [Validators.required]],
        charge_value: parseInt(d._charge_type) == 1 ? [''] : [d.charge_value, [Validators.required, Validators.pattern(/^[0-9.]*$/)]],
        _from: [d._from],
        _to: [d._to],
        _date: [d._date],
        activity_cancellation_policy_id: [d.activity_cancellation_policy_id],
        _cancellation_policy_type: [parseInt(d._cancellation_policy_type), [Validators.required]]
      }))
    })
  }

  /**
   * @author Abdul Razzak
   * method to update cancellation details
   */
  UpdateCancellationDetails() {
    let postArrayData = [];
    if (this.FromData.status == 'INVALID') {
      this.validationService.showValidationsMsg(this.FromData);
      const firstElementWithError = document.querySelector('.ng-invalid');
      if (firstElementWithError) {
        firstElementWithError.scrollIntoView({ behavior: 'auto' });
      }
      return;
    };
    let val = this.FromData.getRawValue()
    let ValArr = this.cancelDisplay.getRawValue();
    ValArr.map(e => {
      let PostArray = new CancellationDisplay();
      PostArray._cancellation_policy_type = e._cancellation_policy_type.toString();
      PostArray._charge_type = JSON.stringify(e._charge_type);
      PostArray.charge_value = e.charge_value ? e.charge_value : 0;
      PostArray.activity_cancellation_policy_id = e.activity_cancellation_policy_id;
      PostArray.date = e.date;
      PostArray.from = e.from;
      PostArray.to = e.to;
      postArrayData.push(PostArray);
    })
    let PostData = new UpdateCancellationPolicy();
    PostData.activity_contract_id = this.activityContractId;
    PostData._no_show_policy_type = val._no_show_policy_type.toString();
    PostData.no_show_value = val.no_show_charge_value ? val.no_show_charge_value : 0;
    PostData.cancellation_policy = postArrayData;
    this.ApiServ.Post('/ActivityContract/UpdateActivityCancellation', PostData).subscribe(data => {
      if (data) {
        this.showToastrMsg(data)
      }
    });
  };
  /**
   * @author Abdul Razzak
   * to show toastr
   * @param respData 
   */
  showToastrMsg(respData) {
    this.MsgService.add({
      severity: respData['status'] ? 'success' : 'error',
      detail: respData['message'],
    });
    setTimeout(() => {
      respData['status'] ? this.btnClick() : '';
    }, 500);
  }

  /**
   * @author Abdul razzak
   * to navigate overview tab
   */
  btnClick() {
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage'])
  }



  /**
 * @author Abdul Razzak
 * to clear hide field value
 */
  ClearSearchField() {
    let val = this.FromData.getRawValue()
    if (val.period_type == 2) this.FromData.get('dates').setValue('');
    else if (val.period_type == 1) this.FromData.get('seasonId').setValue([]);
  }



  AllMonths = []
  Checkdate() {
    let date = this.FromData.get('dates').value
    console.log(date)
    if (date.length > 1) {
      // var result = eachMonthOfInterval({
      //   start: new Date(date[0]),
      //   end: new Date(date[1])
      // });
      // console.log(result);
      let allname = []
      // this.AllMonths = result.map(e => allname.push(moment(e).format("MMM")))
      this.AllMonths = [...new Set(allname)];
    }
  }

  checkMonthOfSeason() {
    this.season_list
    console.log(this.season_list)
    let alldate = [];
    let val = this.FromData.get('seasonId').value;
    val.forEach(ID => {
      this.season_list.forEach(q => {
        if (q.activitySeason.activity_season_id == ID) {
          q.seasondateRange.forEach(t => {
            // var result = eachMonthOfInterval({
            //   start: new Date(t.fromDate),
            //   end: new Date(t.toDate)
            // });
            // let list = result.map(r => moment(r).format("MMM"));
            // alldate.push(...list);
          });
        };
      });
    });
    let AllDateName = [...new Set(alldate)];
    this.AllMonths = AllDateName;
  }

  MonthCheck(data) {
    console.log(data)
  }

  /**
   * @author Abdul Razzak
   * to reset search value
   */
  reset() {
    this.FromData.get('seasonId').setValue([]);
    this.FromData.get('dates').setValue('');
    this.FromData.get('period_type').setValue('');
    this.FromData.get('slot_id').setValue('');
    this.FromData.get('days').setValue('');
  }


}
