import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatCheckbox } from '@angular/material/checkbox';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { MessageService } from 'primeng/api';
import { ValidationService } from 'src/app/core/common/validation.service';
import { AllocationItems, UpdateAllocation } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-allocation/edit-allocation.model';
import { GetCancellationPolicy } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-cancellation-policy/edit-cancellation-policy.model';
import { GetRateDetails } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-rate-confi/edit-rate-confi.model';
// import { AllocationItems, UpdateAllocation } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-allocation/edit-allocation.model';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';
interface grp {
  name: string;
  code: string;
}
@Component({
  selector: 'app-edit-allocation',
  templateUrl: './edit-allocation.component.html',
})
export class EditAllocationComponent implements OnInit {

  FormData: FormGroup
  activityContractId;
  activityContract;
  DaySelect;
  NoShowPolicyType;
  AllSlotData;
  AllocationDetails;
  SoltDate;
  slot_wise_cancellation_policy;
  RateConfigdata
  AllSlots;
  lovKeyDataObj = {
    RatePeriodType: [],
    DaySelect: [],
    ActivityNoShowPolicyType: [],
    ActivityCancellationPolicyType: [],
    ActivityCancellationChargeType: [],
  };
  season_list;
  constructor(private router: Router, private route: ActivatedRoute, public ApiServ: API, public Fb: FormBuilder, public MsgService: MessageService, public validationService: ValidationService) { }
  ngOnInit(): void {
    this.NgOinitFrom();
    this.GetSlotData();
    this.GetRateConfig();
    this.GetAllActivitySeason();
    this.GetLOVKeys('RatePeriodType,DaySelect,ActivityNoShowPolicyType,ActivityCancellationPolicyType,ActivityCancellationChargeType');
  };


  /**
   * @author Abdul Razzak
   * To  create form group
   */
  NgOinitFrom() {
    this.FormData = this.Fb.group({
      option_name: [''],
      activity_name: [''],
      period_type: [''],
      seasonId: [''],
      dates: [''],
      days: [''],
      Allocation_list: this.Fb.array([
        this.Fb.group({
          allocation_count: [''],
          release_days: [''],
          FreeSale: [false],
          StopSale: [false],
        })
      ])
    });
  }

  /**
    * @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;
            d.responseObject.is_slot_wise_cancellation_policy;
            if (d.responseObject.is_slot_wise_cancellation_policy) {
              this.FormData.addControl('slot_id', this.Fb.control('',[Validators.required]));
            }
            this.FormData.get('option_name').setValue(d.responseObject.option_name);

          }
        })
      }
    });
  }

  /**
  * @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 activity details
 */
  GetActivityById() {
    let activity_id = CommonService.getSessionStoage('activity_id');
    this.ApiServ.Get('/Activity/GetActivity/' + activity_id).subscribe(res => {
      if (res) {
        this.FormData.get('activity_name').setValue(res.responseObject.activityContents[0].activity_name);
      }
    })
  }

  /**
   * @author Abdul razzak
   * to set value 
   */
  CopyOnUi() {
    console.log('this.allocationValue.nativeElement.value')
    let Group = this.Allocation_list.getRawValue();
    let newgroup = Group.splice(0, 1)

    Group.map((e, i) => {
      !newgroup[0].FreeSale ? this.Allocation_list.controls[i + 1].get('allocation_count').setValue(newgroup[0].allocation_count) : '';
      this.StopSalecheck(newgroup[0].StopSale, i + 1);
      this.freesalecheck(newgroup[0].FreeSale, i + 1);
      this.Allocation_list.controls[i + 1].get('StopSale').setValue(newgroup[0].StopSale);
      this.Allocation_list.controls[i + 1].get('FreeSale').setValue(newgroup[0].FreeSale);
      this.Allocation_list.controls[i + 1].get('release_days').setValue(newgroup[0].release_days);
    });

  }


  /**
   * @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 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 form group controls
   */
  get Allocation_list() {
    return this.FormData.get('Allocation_list') as FormArray
  };

  /**
   * @author Abdul Razzak
   * to set value for each form list
   * @param data 
   */
  setValue(data) {
    this.Allocation_list.clear();
    this.addForm();
    for (let i = 0; i < data.length; i++) {
      this.addForm();
      let formval = this.Allocation_list.controls[i + 1].value;
      Object.keys(formval).forEach(a => {
        if (a == 'StopSale' || a == 'FreeSale') {
          if (data[i]['_allocation_type'] == '1') {
            this.Allocation_list.controls[i + 1].get('FreeSale').setValue(true);
            this.freesalecheck(true, i + 1);
          }
          if (data[i]['_allocation_type'] == '2') {
            this.Allocation_list.controls[i + 1].get('StopSale').setValue(true);
            this.StopSalecheck(true, i + 1);
          }
        }
        else {
          this.Allocation_list.controls[i + 1].get(a).setValue(data[i][a]);
        }
      });
    }
  };

  /**
   * @author Abdul Razzak
   * to create allocation form group
   * 
   */
  addForm() {
    this.Allocation_list.push(this.Fb.group({
      allocation_count: [''],
      release_days: [''],
      FreeSale: [false],
      StopSale: [false],
      _date: [''],
      activity_allocation_id: [''],
    }));
  };

  /**
   * @author Abdul Razzak
   * to get slots list by contract id
   */
  GetSlotData() {
    this.ApiServ.Get('/ActivityContract/GetSlotsById/' + this.activityContractId).subscribe(data => {
      if (data) {
        this.AllSlotData = data.responseObject;
      }
    });
  };

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

  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;

  /**
   * @author Abdul razzak
   * to get all allocation details 
   */
  getAllocationDetails() {
    let val = this.FormData.getRawValue();
    let postdata = new GetRateDetails();
    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.dates = '';
    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/GetAllocationDetails', postdata).subscribe(data => {
      if (data) {
        this.AllocationDetails = data.responseObject;
        data.responseObject ? this.setValue(data.responseObject) : '';
      }
    });
  };



  /**
   * @author Abdul Razzak
   * to update allocation value
   * @returns 
   */
  updateAllocation() {
    if (this.FormData.status == "INVALID") {
      this.validationService.showValidationsMsg(this.FormData);
      const firstElementWithError = document.querySelector('.ng-invalid');
      if (firstElementWithError) {
        firstElementWithError.scrollIntoView({ behavior: 'smooth' });
      }
      return;
    }
    let value = this.FormData.getRawValue();
    let postArr = [];
    value.Allocation_list.splice(0, 1)
    value.Allocation_list.map((e, i) => {
      let items = new AllocationItems();
      if (value.Allocation_list[i].FreeSale) {
        items._allocation_type = '1';
      } else if (value.Allocation_list[i].StopSale) {
        items._allocation_type = '2';
      } else items._allocation_type = '3';
      items.allocation_count = value.Allocation_list[i].allocation_count ? value.Allocation_list[i].allocation_count : 0;
      items.release_days = value.Allocation_list[i].release_days ? value.Allocation_list[i].release_days : 0;
      items.activity_allocation_id = value.Allocation_list[i].activity_allocation_id;
      postArr.push(items)
    })

    let PostData = new UpdateAllocation();
    PostData.activity_contract_id = this.activityContractId;
    PostData.activity_slot_id = value.slot_id ? value.slot_id : '';
    PostData.allocationItems = postArr;
    this.ApiServ.Post('/ActivityContract/UpdateActivityAllocation', PostData).subscribe((res) => {
      if (res) {
        this.showToastrMsg(res)
      }
    });
  };

  /**
   * @author Abdul Razzak
   * to show toaster
   * @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
   */
  btnClick() {
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage'])
  }

  /**
   * @author Abdul Razzak
   * to disable checkbox
   * @param Check 
   * @param Ind 
   */
  freesalecheck(Check, Ind) {
    if (Check) {
      this.Allocation_list.controls[Ind].get('StopSale').disable();
      this.Allocation_list.controls[Ind].get('allocation_count').disable();
      this.Allocation_list.controls[Ind].get('allocation_count').setValue('');
    } else {
      this.Allocation_list.controls[Ind].get('allocation_count').enable();
      this.Allocation_list.controls[Ind].get('StopSale').enable();
    }
  };

  /**
 * @author Abdul Razzak
 * to disable checkbox
 * @param Check 
 * @param Ind 
 */
  StopSalecheck(Check, Ind) {
    if (Check) {
      this.Allocation_list.controls[Ind].get('FreeSale').disable();
    } else {
      this.Allocation_list.controls[Ind].get('FreeSale').enable();
    }
  };

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

}
