

const colors: any = {
  red: {
    primary: '#ad2121',
    secondary: '#FAE3E3',
  },
  blue: {
    primary: '#1e90ff',
    secondary: '#D1E8FF',
  },
  yellow: {
    primary: '#e3bc08',
    secondary: '#FDF1BA',
  },
};

import {
  Component,
  OnInit,
  ViewChild
} from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';
import * as FileSaver from 'file-saver';
import jsPDF from 'jspdf';
import 'jspdf-autotable';
import * as moment from 'moment';
import {
  MessageService
} from 'primeng/api';
import { Table } from 'primeng/table/table';
import { AllocationOverview } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-allocation/edit-allocation.model';
import { ActivityAllContract, GetRateDetails } from 'src/app/core/models/Experience-Service/experience-rate-config-Edit/edit-rate-confi/edit-rate-confi.model';
import { GetActivitySlot } from 'src/app/core/models/Experience-Service/slot/add-slots-model';
import { API } from 'src/app/core/services/api.service';
import { BreakpointsService } from 'src/app/core/services/breakpoints.services';
import { CommonService } from 'src/app/core/services/common.service';
@Component({
  selector: 'Overview',
  // changeDetection: ChangeDetectionStrategy.OnPush,

  templateUrl: './Overview.component.html',
})
export class OverviewComponent implements OnInit {
  // items!: MenuItem[];
  dateValue!: Date;
  // responsive code
  isMobile = false;
  DateList: any[] = []
  responsiveOptions;
  activityId;
  // modal: any;
  constructor(
    // private confirmationService: ConfirmationService,
    private messageService: MessageService,
    // responsive constructor
    public MobileBreakpoints: BreakpointsService,
    // private cd: ChangeDetectorRef, // responsive constructor
    public ApiServ: API,
    public MsgService: MessageService,
    private router: Router,
    private fb: FormBuilder
  ) {
    // this.MobileBreakpoints.IsMobile.subscribe({
    //   next: (val) => {
    //     this.isMobile = val;
    //     // this.cd.detectChanges();
    //   },
    // });
  }

  date14!: Date;

  cities = [
    { id: 1, name: 'Vilnius' },
    { id: 2, name: 'Kaunas' },
    { id: 3, name: 'Pavilnys', disabled: true },
    { id: 4, name: 'Pabradė' },
    { id: 5, name: 'Klaipėda' },
  ];

  cols!: any[];
  exportColumns!: any[];
  datelist;
  formgroup: FormGroup;
  OptAddData;
  rateDetails;
  ActivityData;
  activityImages;
  SeasonData;
  AllocationDetails;
  AllSlotsData;
  AllSlots
  ngOnInit() {
    // this.cols = [
    //   { field: 'code', header: 'Code', customExportHeader: 'Product Code' },
    //   { field: 'name', header: 'Name' },
    //   { field: 'category', header: 'Category' },
    //   { field: 'quantity', header: 'Quantity' },
    // ];
    // this.exportColumns = this.cols.map((col) => ({
    //   title: col.header,
    //   dataKey: col.field,
    // }));
    this.activityId = CommonService.getSessionStoage('activity_id');
    this.ngOinitForm();
    this.GetActivityData();
    this.GetallrateDetails(true);
    this.SearchSeason();
    this.GetAllSlot();
  }

  /**
   * @author Abdul Razzak
   * to create form group
   */
  ngOinitForm() {
    this.formgroup = this.fb.group({
      slot_id: [''],
      option_name: [''],
      Calender: this.fb.group({
      })
    });
  }

  /**
   * @author Abdul Razzak
   * to get form controller 
   */
  get Calender() {
    return this.formgroup.get('Calender') as FormGroup
  }


  /**
   * @author Abdul razzak
   * to get all allocation details 
   */
  getAllocationDetails() {
    let value = this.formgroup.getRawValue();
    let postdata = new GetRateDetails();
    postdata.from_date = '';
    postdata.to_date = '';
    postdata.dates = '';
    postdata.slot_id = value.slot_id;
    postdata.seasonId = [];
    postdata.days = '';
    postdata.contract_id = value.option_name;
    this.ApiServ.Post('/ActivityContract/GetAllocationDetails', postdata).subscribe(data => {
      if (data) {
        this.AllocationDetails = data.responseObject;
        this.SetTimeAvali(this.AllocationDetails);
      }
    });
  };

  //  ------------------------------------------------       date  overview          ----------------------------------------


  updateinputvalue(group) {
    // console.log('asfdgujvfi')
    // this.SaveAllocation()
  }

  /**
   * @author Abdul Razzak
   * for plus allocation count
   * @param group 
   */
  handleMinus(group) {
    let value = this.Calender.get(group).get('allocation_count').value - 1;
    if (value >= 0) {
      this.Calender.get(group).get('allocation_count').setValue(value);
      this.SaveAllocation(this.Calender.get(group));
    }
  }

  /**
    * @author Abdul Razzak
    * for minus allocation count
    * @param group 
    */
  handlePlus(group) {
    let value = this.Calender.get(group).get('allocation_count').value + 1;
    this.Calender.get(group).get('allocation_count').setValue(value);
    this.SaveAllocation(this.Calender.get(group));
  }

  /**
   * @author Abdul Razzak
   * for save allocation details
   * @param group 
   */
  SaveAllocation(group) {
    let value = group.getRawValue();
    let contractDetails = this.formgroup.getRawValue();
    let postdata = new AllocationOverview();
    postdata._allocation_type = value.allocation_count > 0 ? '3' : value._allocation_type;
    postdata.allocation_count = value.allocation_count ? value.allocation_count : 0;
    postdata.activity_allocation_id = value.activity_allocation_id;
    postdata.activity_contract_id = contractDetails.option_name;
    postdata.activity_slot_id = contractDetails.slot_id;
    this.ApiServ.Post('/ActivityContract/UpdateAllocationViewTab', postdata).subscribe((res) => {
      if (res) {
        this.setvalue(res.responseObject, group)
      }
    })
  }

  /**
   * @author Abdul Razzak
   * for set value when allocation count plus and minus
   * @param data 
   * @param group 
   */
  setvalue(data, group) {
    group.get('allocation_count').setValue(data.allocation_count);
    group.get('_allocation_type').setValue(data._allocation_type);
    group.get('booking_count').setValue(data.booking_count);
    group.get('remaining_count').setValue(data.remaining_count);
  }

  /**
   * for binding 
   * @param date 
   * @returns 
   */
  bindAllocationdate(date) {
    let d = new Date(date.year, date.month, date.day);
    let validate;
    validate = false;
    let format = moment(d).format('MM-DD-YYYY')
    let valid = this.datelist.filter(e => e == format);
    if (valid.length > 0) {
      validate = true;
    }
    return validate;
  }

  /**
   * @author  Abdul Razzak
   * to convert date format MM-DD-YYYY
   */
  convertproperadate(date) {
    let d = new Date(date.year, date.month, date.day);
    let format = moment(d).format('MM-DD-YYYY');
    return format
  }

  /**
   * @author Abdul Razzak
   * to create form controls and set value
   * @param allDate 
   */
  SetTimeAvali(allDate) {
    this.datelist = allDate.map(e => moment(e._date).format('MM-DD-YYYY'));
    allDate.map(e => {
      let date = moment(e._date).format('MM-DD-YYYY');
      this.Calender.addControl(date, this.fb.group({
        activity_allocation_id: e.activity_allocation_id,
        allocation_count: e.allocation_count,
        booking_count: e.booking_count,
        remaining_count: e.remaining_count,
        _allocation_type: e._allocation_type,
      }));
    });
  }

  /**
   * @author Abdul Razzak
   * to stop sale in allocation 
   * @param group 
   */
  StopSale(group) {
    group.get('_allocation_type').setValue('2');
    group.get('allocation_count').setValue(0);
    this.SaveAllocation(group);
  }



  // -----------------------------------------------------                     ------------------------------------------------------
  /**
   * @author Abdul Razzak
   * to get activity details by Id 
   */
  GetActivityData() {
    let activityid = CommonService.getSessionStoage('activity_id');
    this.ApiServ.Get('/Activity/GetActivity/' + activityid).subscribe((e) => {
      if (e) {
        this.ActivityData = e.responseObject;
        this.activityImages = JSON.parse(e.responseObject.activity_images);
        CommonService.setSessionStorage('Def_Lang_code', e.responseObject.default_lang_code);
        this.GetActivityAddOn();
      }
    });
  }

  // -----------------------------------------------------      Season Details           ------------------------------------------------------

  UpdateSeasonStatus(exp_id, status) {
    let obj = { id: exp_id, status: status ? false : true, updatedBy: '' };
    this.ApiServ.Post('/ActivitySeason/UpdateStatus', obj).subscribe((data) => {
      if (data) {
        this.MsgService.add({
          severity: data['status'] ? 'success' : 'error',
          detail: data['message'],
        });
        this.SearchSeason();
      }
    });
  }

  SearchSeason() {
    this.ApiServ.Get('/ActivitySeason/GetAllActivitySeason?activityId=' + this.activityId + '&seasonName=' + '').subscribe((e) => {
      if (e) {
        this.SeasonData = e['responseObject'];
      }
    });
  }

  EditSeason(sea_id) {
    let obj = { id: sea_id };
    this.router.navigate(['/Services/ExpServices/Manage/AddNewSeason'], {
      queryParams: obj,
    });
  }

  exportseasonExcel() {
    import('xlsx').then((xlsx) => {
      console.log(xlsx);
      const worksheet = xlsx.utils.json_to_sheet(this.SeasonData);
      const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
      const excelBuffer: any = xlsx.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
      });
      this.saveAsExcelFile(
        excelBuffer,
        'Season_Data_export_' + new Date().getTime()
      );
    });
  }

  exportseasonPdf() {
    // const doc = new jsPDF();
    const doc = new jsPDF('p', 'pt');
    doc['autoTable'](this.exportColumns, this.SeasonData);
    doc.save('Season_Data_export_' + new Date().getTime() + '.pdf');
  }

  // -----------------------------------------------------    Add Optional Add-Ons        ------------------------------------------------------




  GetActivityAddOn() {
    let obj = {
      activityId: this.activityId,
      _add_on_name: "",
      _language_code: CommonService.getSessionStoage('Def_Lang_code')
    }
    this.ApiServ.Post('/ActivityAddOn/GetActivityAddOn', obj).subscribe(e => {
      if (e) {
        this.OptAddData = e['responseObject'];
      }
    })
  }

  EditOpt(pk_id) {
    let obj = { id: pk_id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage/AddOptionalAddOn'], { queryParams: obj })
  }

  UpdateOptStatus(exp_id, status) {
    let obj = { id: exp_id, status: status ? false : true, updatedBy: '' };
    this.ApiServ.Post('/ActivityAddOn/UpdateStatus', obj).subscribe((data) => {
      if (data) {
        this.MsgService.add({
          severity: data['status'] ? 'success' : 'error',
          detail: data['message'],
        });
        this.GetActivityAddOn();
      }
    });
  }

  exportOptPdf() {
    const doc = new jsPDF('p', 'pt');
    doc['autoTable'](this.exportColumns, this.OptAddData);
    doc.save('Option_Add_Ons_export_' + new Date().getTime() + '.pdf');
  }

  exportOptExcel() {
    import('xlsx').then((xlsx) => {
      console.log(xlsx);
      const worksheet = xlsx.utils.json_to_sheet(this.OptAddData);
      const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
      const excelBuffer: any = xlsx.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
      });
      this.saveAsExcelFile(excelBuffer, 'Option_Add_Ons');
    });
  }

  // -----------------------------------------------------    rate Details       ------------------------------------------------------

  EditCancelPoli(Id) {
    let obj = { id: Id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage/EditCancelletionPolicy'], { queryParams: obj })
  }
  EditAllocation(Id) {
    let obj = { id: Id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage/EditAllocation'], { queryParams: obj })
  }
  EditRateConfig(Id) {
    let obj = { id: Id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage/EditModifyRate'], { queryParams: obj })
  }

  EditDetails(Id) {
    let obj = { id: Id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage/EditDetails'], { queryParams: obj })
  }


  UpdateRateStatus(ID, Status) {
    let Obj = {
      id: ID,
      updatedBy: "",
      "status": Status ? false : true
    }
    this.ApiServ.Post('/ActivityContract/UpdateStatus', Obj).subscribe(data => {
      if (data) {
        this.MsgService.add({
          severity: data["status"] ? "success" : "error",
          detail: data["message"],
        });
        this.GetallrateDetails(false);
      }
    });
  };

  SoltsDetailsConvParse(data) {
    let obj = data ? JSON.parse(data) : '';
    let html = [];
    obj ? obj.forEach(e => html.push({ 'date': moment(e.start_time).format('hh:mm') + '-' + moment(e.end_time).format('hh:mm') })) : ''
    return html
  }

  GetallrateDetails(check) {
    let activityid = CommonService.getSessionStoage('activity_id');
    let postdata = new ActivityAllContract();
    postdata.activity_id = activityid;
    postdata.is_drop_off_included = false;
    postdata.is_pickup_included = false;
    postdata.option_name = '';
    this.ApiServ.Post('/ActivityContract/GetAllActivityRates', postdata).subscribe(data => {
      if (data) {
        this.rateDetails = data.responseObject;
        if (check) {
          this.formgroup.get('option_name').setValue(this.rateDetails[0].activity_contract_id);
          this.GetSlotsById(this.rateDetails[0].activity_contract_id, true);
        }
      }
    })
  }

  // -----------------------------------------------------    rate Details       ------------------------------------------------------


  GetAllSlot() {
    let post = new GetActivitySlot();
    post.activity_id = this.activityId;
    post.from_hour = null;
    post.from_minute = null;
    post.to_hour = null;
    post.to_minute = null;
    console.log(post)
    this.ApiServ.Post('/ActivitySlot/GetAllSlot', post).subscribe(res => {
      if (res) {
        this.AllSlotsData = res['responseObject'];
      }
    });
  }

  EditSlot(pk_id) {
    let obj = { id: pk_id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage/AddSlots'], { queryParams: obj });
  }

  UpdateStatusSlot(slot_id, status) {
    let obj = { Id: slot_id, Status: status ? false : true }
    this.ApiServ.Post('/ActivitySlot/UpdateStatus', obj).subscribe(data => {
      if (data) {
        this.GetAllSlot();
        this.MsgService.add({
          severity: data["status"] ? "success" : "error",
          detail: data["message"],
        });
      }
    })
  }

  /**
    * @author Abdul Razzak
    * to get slot data by contract id  
    * @param Id 
    */
  GetSlotsById(Id, check) {
    this.formgroup.get('slot_id').setValue('')
    this.ApiServ.Get('/ActivityContract/GetSlotsById/' + Id).subscribe(res => {
      if (res) {
        this.AllSlots = res.responseObject;
        if (check) {
          this.formgroup.get('slot_id').setValue(this.AllSlots[0].activity_slot_id);
          this.getAllocationDetails();
        }
      }
    })
  }



























































  @ViewChild('dt')
  table!: Table;

  // exportExcel() {
  //   import('xlsx').then((xlsx) => {
  //     console.log(xlsx);
  //     const worksheet = xlsx.utils.json_to_sheet(this.products);
  //     const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
  //     const excelBuffer: any = xlsx.write(workbook, {
  //       bookType: 'xlsx',
  //       type: 'array',
  //     });
  //     this.saveAsExcelFile(excelBuffer, 'products');
  //   });
  // }

  saveAsExcelFile(buffer: any, fileName: string): void {
    import('file-saver').then((abc) => {
      let EXCEL_TYPE =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
      let EXCEL_EXTENSION = '.xlsx';
      const data: Blob = new Blob([buffer], {
        type: EXCEL_TYPE,
      });
      console.log(FileSaver);
      FileSaver.saveAs(
        data,
        fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION
      );
    });
  }


}
