import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
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 { DashboardSeller } from '../models/dashboard-seller.model';
import { OrderItens } from '../models/order-itens.model';
import { Order } from '../models/order.model';
import { ResultApi } from '../models/result-api.model';
import { StoreERP } from '../models/store.model';
import { OrderShipping } from '../models/order-shipping.model';
import { ProductsOrder } from '../models/products-order.model';
import { SaleHistory } from '../models/sale-history.model';

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

  private _productsOrder: ProductsOrder[] = [];

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

  create(cart: CartModel) {
    const url = environment.url + 'order/create';
    console.log(JSON.stringify(cart));
    try {
      return this.http.post<ResultApi>(url, cart)
        .pipe(
          map((response) => {
            console.log(response);
            return response;
          })
        );
    } catch (e) {
      console.log('Erro ao cadastrar pedido');
      console.log(e);
    }
  }

  getStore() {
    const url = environment.url + 'lists/store';
    try {
      return this.http.get<StoreERP[]>(url)
        .pipe(
          map((response) => {
            console.log(response);
            return response;
          })
        );
    } catch (e) {
      console.log(e);
    }
  }

  getOrder(store: string, initialDate: string, finalDate: string, customerId: number) {
    const url = environment.url + 'order/orders';

    try {
      const params = new HttpParams(
        {
          fromObject: {
            'x-store': store,
            codigoCliente: customerId.toString(),
            initialDate,
            finalDate,
          }
        });
      const response = this.http.get<ResultApi>(url, { params });
      /*      .pipe(
              map((response) => {
                console.log(response);
                return response.data as Order[];
              })
            );*/
      return response;
    } catch (e) {
      console.log(e);
    }
  }

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


  getProductsWithoutTax(cartId: string, customerId: number) {
    const url = environment.url + 'order/productsTax';

    try {

      const params = new HttpParams(
        {
          fromObject: {
            cartId: cartId,
            customerId: customerId.toString()
          }
        });
      const response = this.http.get<any[]>(url, { params });
      console.log(JSON.stringify(response));
      return response;
    } catch (e) {
      console.log(e);
    }
  }

  getOrders(store: string, initialDate: string, finalDate: string, document: string, name: string, idOrder: string) {
    const url = environment.url + 'order/list';

    try {

      let sellerId = this.authService.getSeller();

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

      sellerId = 0;

      const params = new HttpParams(
        {
          fromObject: {
            'x-store': store,
            document,
            name,
            initialDate,
            finalDate,
            sellerId,
            idOrder
          }
        });
      const response = this.http.get<Order[]>(url, { params });

      return response;
    } catch (e) {
      console.log(e);
    }
  }

  findProductsOrder(store: string, initialDate: string, finalDate: string, document: string, name: string,
            idOrder: string, typeFilterProduct: string, productText: string) {
    const url = environment.url + 'order/products-order';

    try {

      let sellerId = this.authService.getSeller();

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

      sellerId = 0;

      const params = new HttpParams(
        {
          fromObject: {
            'x-store': store,
            document,
            name,
            initialDate,
            finalDate,
            sellerId,
            idOrder,
            typeFilterProduct,
            productText
          }
        });
      const response = this.http.get<ProductsOrder[]>(url, { params });

      return response;
    } catch (e) {
      console.log(e);
    }
  }

  getDashboardSeller(sellerId: number) {
    const url = environment.url + `sales/analisevenda/${sellerId}`;
    try {
      const response = this.http.get<DashboardSeller>(url);
      return response;
    } catch (e) {
      throw new Error(e.message);
    }
  }

  getSaleSeller(sellerId: number) {
    const url = environment.url + `sales/historicovenda/${sellerId}`;
    try {
      const response = this.http.get<SaleHistory[]>(url);
      return response;
    } catch (e) {
      throw new Error(e.message);
    }
  }

  getCartId(orderId: number) {
    console.log('consultando pedido de venda.');
    const url = environment.url + 'order/cart';
    let params = new HttpParams();
    params = params.append('orderId', orderId.toString());
    return this.http.get<any>(url, { params });
  }

  getOrdersShipping() {
    const url = environment.url + `order/orderretiraposterior`;
    try {
      const response = this.http.get<OrderShipping[]>(url);
      return response;
    } catch (e) {
      throw new Error(e.message);
    }
  }

  setProductsOrder(productsOrder: ProductsOrder[]) {
    this._productsOrder = productsOrder;
  }

  getProductsOrder() {
    return this._productsOrder;
  }

}
