import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { throwError } from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
import { AuthService } from '../auth/services/auth.service';
import { CartModel } from '../models/cart.model';
import { ResultApi } from '../models/result-api.model';
import { PreOrderItens } from '../models/pre-order-itens.model';

@Injectable({
  providedIn: 'root'
})
export class PreOrderService {

  constructor(
    private readonly http: HttpClient,
    private authService: AuthService
  ) { }

  create(cart: CartModel) {
    const url = environment.url + 'preorder/create';
    try {
      return this.http.post<ResultApi>(url, cart)
        .pipe(
          map((response) => {
            console.log(response);
            return response;
          })
        );
    } catch (e) {
      console.log('Erro ao gravar orçamento');
      console.log(e);
    }
  }

  getPreOrders(store: string, dataIni: string, dataFinal: string, idPreOrder: number, document: string, nameCustomer: string) {
    const url = environment.url + 'preorder/list';
    let sellerId = this.authService.getSeller();

    if (this.authService.isManager()) {
      sellerId = 0;
    }

    let params = new HttpParams();
    params = params.append('seller', sellerId);
    params = params.append('store', store);
    params = params.append('start', dataIni);
    params = params.append('end', dataFinal);
    params = params.append('idPreOrder', idPreOrder.toString());
    params = params.append('document', document);
    params = params.append('nameCustomer', nameCustomer);

    /*{
        headers: {
          'x-seller': this.authService.getSeller()
        }, params
      } */
    try {
      return this.http.get<ResultApi>(url, { params })
        .pipe(
          map((response) => {
            console.log(response);
            return response;
          })
        );
    } catch (err) {
      console.log(err);
      return throwError(err);
    }
  }

  getCartId(preOrderId: number) {
    console.log('consultando orçamentos.');
    const url = environment.url + 'preorder/cart';
    let params = new HttpParams();
    params = params.append('preOrderId', preOrderId.toString());
    return this.http.get<any>(url, { params });
  }

  getItensPreOrder(orderId: string ) {
    const url = environment.url + `preorder/itens/${orderId}`;
    const response = this.http.get<PreOrderItens[]>(url);
    return response;
  }

}
