import { Component, OnInit } 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 { MessageService } from 'primeng/api';
import { StaticDataService } from 'src/app/core/common/static-data.service';
import { API } from 'src/app/core/services/api.service';
import { CommonService } from 'src/app/core/services/common.service';


@Component({
  selector: 'app-exp-services-search',
  templateUrl: './exp-services-search.component.html',
})
export class ExpServicesSearchComponent implements OnInit {
  ExpSearch: FormGroup;
  ExpData;
  SubCategory;
  ExpCatData;
  cols: any[];
  exportColumns;
  CityData;
  ExpSupData: any;
  CountryData: any;
  Experience_Type;
  constructor(
    private router: Router,
    private fb: FormBuilder,
    public ApiServ: API,
    private MsgService: MessageService,
    private commonVari: StaticDataService

  ) { }




  /**
   * @author Abdul Razzak
   * to get supplier data
   */
  ExpSupplier() {
    this.ApiServ.Get('/HotelSupplierMapping/GetAllHotelSupplierMapping').subscribe(data => {
      if (data) {
        this.ExpSupData = data['responseObject'];
      }
    });
  };


  /**
   * @author Abdul Razzak
   * to get city based on country
   */
  ExpCity() {
    let val = this.ExpSearch.getRawValue();
    this.ApiServ.Get('/City/GetCity/' + val.country_code).subscribe((data) => {
      if (data) {
        this.CityData = data;
      }
    });
  };

  /**
   * @author Abdul Razzak
   * to get all country
   */
  ExpCounrty() {
    this.ApiServ.Get('/Country/GetCountry').subscribe(data => {
      if (data) {
        this.CountryData = data;
        console.log(this.CountryData)
      }
    });
  };

  /**
   * @author Abdul Razzak
   * to get all category
   */
  GetAllCategory() {
    this.ApiServ.Get('/ActivityCategoryMaster/GetAllCategory').subscribe(data => {
      if (data) {
        this.Experience_Type = data['responseObject']
      }
    });
  };

  /**
   * @author Abdul Razzak
   * to get sub category based on category
   */
  GetSubCategory(value) {
    this.ExpSearch.get('sub_category_id').setValue('')
    this.ApiServ.Get('/ActivityCategoryMaster/GetSubCategory?Id=' + value).subscribe(data => {
      if (data) {
        this.SubCategory = data['responseObject']
      }
    });
  };

  ngOnInit(): void {
    this.ExpCounrty();
    this.GetAllCategory()
    this.ExpSupplier();
    CommonService.resetLocalStoage('activity_id');
    this.initForm();
    this.cols = [
      { field: "activity_id", header: "Experience Id" },
      { field: "activity_name", header: "Experience Name" },
      { field: "category_name", header: "Experience Type" },
      { field: "country_name", header: "Country" },
      { field: "city_name", header: "City" },
      { field: "is_pickup_included", header: "Pickup Included" },
      { field: "is_drop_included", header: "Drop Off Included" },
      { field: "is_active", header: "Status" }
    ];
    this.exportColumns = this.cols.map(col => ({
      title: col.header,
      dataKey: col.field
    }));
  }

  /**
   * @author Abdul Razzak
   * to get supplier data
   * @param Activity_id 
   */
  Edit(activity_id) {
    let obj = { id: activity_id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/Add'], { queryParams: obj });
  }

  /**
   * @author Abdul Razzak
   *  method to store  Activity id
   */
  Manage(activity_id) {
    CommonService.setSessionStorage('activity_id', activity_id);
    this.router.navigate(['/Services/ActivityServices/ExpServices/Manage']);
    this.commonVari.ActivityOverViewtab = 0;
  }

  manageTrans(activity_id) {
    let obj = { id: activity_id };
    this.router.navigate(['/Services/ActivityServices/ExpServices/ManageTranslation'], { queryParams: obj });
  };

  /**
   * @author Abdul Razzak
   * to create form group
   */
  initForm() {
    this.ExpSearch = this.fb.group({
      activity_name: [''],
      city_id: [''],
      category_id: [''],
      sub_category_id: [''],
      country_code: [''],
      is_pickup_included: [false],
      is_drop_included: [false],
    });
  }

  /**
   * @author Abdul Razzak
   * to get all activitys  
   */
  SearchExp() {
    this.ApiServ.Post('/Activity/GetAllActivity', this.ExpSearch.getRawValue()).subscribe(e => {
      if (e) {
        this.ExpData = e['responseObject'];
      }
    });
  };

  /**
   * @author Abdul Razzak
   *  to active or deactive 
   * @param exp_id 
   * @param status 
   */
  UpdateStatus(exp_id, status) {
    let obj = { id: exp_id, status: status ? false : true, updatedBy: '' }
    this.ApiServ.Post('/Activity/UpdateStatus', obj).subscribe((data) => {
      if (data) {
        this.MsgService.add({
          severity: data["status"] ? "success" : "error",
          detail: data["message"],
        });
        this.SearchExp();
      }
    });
  };

  /**
   * @author Abdul Razzak
   * to reset search form value
   */
  ResetExp() {
    this.ExpSearch.get('activity_name').setValue('')
    this.ExpSearch.get('city_id').setValue('')
    this.ExpSearch.get('country_code').setValue('')
    this.ExpSearch.get('category_id').setValue('')
    this.ExpSearch.get('sub_category_id').setValue('')
    this.ExpSearch.get('is_pickup_included').setValue(false)
    this.ExpSearch.get('is_drop_included').setValue(false)
    this.SearchExp();
  };

  /**
    * @author Abdul Razzak
    * to download excel sheet
    */
  exportExcel() {
    import('xlsx').then((xlsx) => {
      const worksheet = xlsx.utils.json_to_sheet(this.ExpData);
      const workbook = { Sheets: { data: worksheet }, SheetNames: ['data'] };
      const excelBuffer: any = xlsx.write(workbook, {
        bookType: 'xlsx',
        type: 'array',
      });
      this.saveAsExcelFile(excelBuffer, 'Experience_Service');
    });
  };
  /**
    * @author Abdul Razzak
    *  to download Excel
    */
  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,
      });
      FileSaver.saveAs(
        data,
        fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION
      );
    });
  };
  /**
    * @author Abdul Razzak
    *  to download PDF
    */
  exportPdf() {
    // const doc = new jsPDF();
    const doc = new jsPDF('p', 'pt');
    doc['autoTable'](this.exportColumns, this.ExpData);
    // doc.autoTable(this.exportColumns, this.products);
    doc.save("Experience_Service_export_" + new Date().getTime() + ".pdf");
  };



}
