import { Component, OnInit, HostListener } from '@angular/core';
import { MiniInfo } from 'src/app/models/Charts/mini-info.model';
import { LinealChart } from 'src/app/models/Charts/lineal-chart.model';
import { UtilsService } from 'src/app/services/utils.service';
import { MinimizeNumberPipe } from 'src/app/pipes/minimize-number.pipe';
import { HitAWodService } from 'src/app/services/hit-a-wod.service';
import { SubscriptionService } from 'src/app/services/subscription.service';
import { SubscriptionSelection } from 'src/app/models/subscription-selection.model';
import { BoxOrder } from 'src/app/models/box-order.model';
import { SelectionModel } from '@angular/cdk/collections';

@Component({
  selector: 'app-billing',
  templateUrl: './billing.component.html',
  styleUrls: ['./billing.component.css']
})
export class BillingComponent implements OnInit {

  ingresos_chart: LinealChart;
  loading_chart:boolean = true;
  loading_orders:boolean = true;

  subscriptionSelection:SubscriptionSelection;
  company_id:number;
  box_id:number;
  date_fi: Date = new Date();
  date_ini: Date;

  orders:BoxOrder[];
  order_selected:BoxOrder;

  mini_ingresos: MiniInfo;
  mini_ingresos_subtotal: MiniInfo;
  mini_ingresos_vat: MiniInfo;

  toolTips:string[];

  isMobile:boolean;

  //table
  selection:SelectionModel<BoxOrder> = new SelectionModel(true);

  //paginator
  length:number = 0;
  pageSize:number = 10;
  page:number = 0;

  //filtering and sorting
  params = {
    sort_col: 'date_created',
    sort_dir: 'desc',
    paid_filter: null
  };
  paid_filter:number = 3;

  constructor(private api:HitAWodService,
              private subscriptionService: SubscriptionService,
              public utilsService: UtilsService) { }

  ngOnInit(): void {
    this.date_ini = new Date(this.date_fi.getFullYear(), this.date_fi.getMonth(), 1);
    this.initIsMobile();
    this.subscriptionService.currentSubscription.subscribe( s => {
      
      if (s && (s.role.slug === "box_admin" || s.role.slug==="company_admin")) {
        this.subscriptionSelection = s;
        if (s.box) {
          this.company_id = s.box.company_id;
          this.box_id = s.box.id;
        } else {
          this.company_id = s.company.id;
          this.box_id = null;
        }
        this.fetchData();
      }
    });
  }

  fetchData() {
    this.loading_chart = true;
    this.loading_orders = true;
    this.api.getBilling(this.company_id,this.box_id,this.dateFormat(this.date_ini),this.dateFormat(this.date_fi)).subscribe( data => {
      if (data) {
        if (data.ingresos) {
          this.initIngresosChart(data.ingresos.chart);
          this.mini_ingresos = new MiniInfo((data.ingresos.total.total + ' ' + data.ingresos.total.units),'brutos',data.ingresos.evolution,this.date_ini,1);  
          this.mini_ingresos_subtotal = new MiniInfo((data.ingresos.total.subtotal + ' ' + data.ingresos.total.units),'netos',data.ingresos.evolution_subtotal,this.date_ini,1);  
          this.mini_ingresos_vat = new MiniInfo((data.ingresos.total.vat + ' ' + data.ingresos.total.units),'impto.',data.ingresos.evolution_vat,this.date_ini,1);  
        }
        if (data.tool_tips) {
          this.toolTips = data.tool_tips;
        }
        this.loading_chart = false;
      }
    });
    this.getOrders();
  }

  initIngresosChart(res) {
    this.ingresos_chart = new LinealChart();
    this.ingresos_chart.showLegend = false;
    this.ingresos_chart.showXAxisLabel = false;
    this.ingresos_chart.showYAxisLabel = false;
    this.ingresos_chart.colorScheme.domain = this.utilsService.getColorsArray();
    this.ingresos_chart.results = res;
  }

  getOrders() {
    this.api.getOrdersBusinessIntelligence(this.company_id, this.box_id, this.dateFormat(this.date_ini), this.dateFormat(this.date_fi), this.pageSize, this.page, this.params).subscribe( box_orders => {
      if (box_orders) {
        this.orders = box_orders.data;
        this.length = (parseInt(box_orders.page_size)<box_orders.total) ? box_orders.total : null;
        this.loading_orders = false;
      }
    })
  }

  initIsMobile() {
    this.isMobile = window.matchMedia("(max-width: 992px)").matches;
  }

  closeDetail() {
    this.order_selected = null;
  }

  @HostListener('window:resize', ['$event'])
  onResize(e) {
    this.isMobile = e.target.innerWidth < 992;
  }

  selectOrder(order: BoxOrder) {
    this.order_selected = order;
  }

  axisFormatEuro(val) {
    return MinimizeNumberPipe.prototype.transform(parseInt(val.toLocaleString())) + ' €';
  }

  dateFormat(date: Date) {
    const month = (date.getMonth()+1)<=9 ? '0'+(date.getMonth()+1) : (date.getMonth()+1);
    const day = date.getDate()<=9 ? '0'+date.getDate() : date.getDate()
    return date.getFullYear() + '-' + month + '-' + day;
  }

  dateFormat2(d:Date) {
    const date = new Date(d);
    const month = (date.getMonth()+1)<=9 ? '0'+(date.getMonth()+1) : (date.getMonth()+1);
    const day = date.getDate()<=9 ? '0'+date.getDate() : date.getDate()
    return day + '/' + month + '/' + date.getFullYear();
  }

  checkSubscription(o) {
    let subs:boolean = false;
    o.lines.forEach( l => {
      if (l.user_subscription_id) subs = true;
    });
    return subs;
  }

  downloadCSV(){
    this.api.getCSVInvoice(this.company_id.toString(),"1,2").subscribe( c => {
      const blob = new Blob([c], { type: 'text/csv' });
      const url= window.URL.createObjectURL(blob);
      window.open(url);
    })
  }

  setSort(col:string) {
    this.page = 0;
    if(col === this.params.sort_col) {
      //estem ordenant per la mateixa, vol dir que vol canviar la direccio nomes
      if(this.params.sort_dir === "desc") this.params.sort_dir = "asc";
      else if(this.params.sort_dir === "asc") {
        this.params.sort_col = "id";
        this.params.sort_dir = "desc";
      }
    }
    else {
      //vol dir que estem ordenant per una col nova
      this.params.sort_dir = "desc";
      this.params.sort_col = col;
    }

    this.getOrders();
  }

  pageChange(num:number) {
    this.page = num;
    this.getOrders();
  }

  setPaidFilter(val:number) {
    this.paid_filter = val;
    this.params.paid_filter = (val!=3 ? val : null);
    this.page = 0;
    this.fetchData();
  }
}
