import {
  AfterViewInit,
  Component,
  HostListener,
  OnChanges,
  OnDestroy,
  OnInit,
  SimpleChanges,
  ViewContainerRef,
} from '@angular/core';
import {
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from '@angular/forms';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import {
  ActionsLayout,
  DialogCloseResult,
  DialogRef,
  DialogService,
  WindowState,
} from '@progress/kendo-angular-dialog';
import {
  BadgeAlign,
  BadgeFill,
  BadgePosition,
  BadgeSize,
  BadgeThemeColor,
} from '@progress/kendo-angular-indicators';
import { Observable, of, Subscription } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { AuthService } from 'src/app/auth/services/auth.service';
import { Billing } from 'src/app/models/billing.model';
import { CartItensModel } from 'src/app/models/cart-itens.model';
import { CartModel } from 'src/app/models/cart.model';
import { CustomerAddress } from 'src/app/models/customer-address.model';
import { Customer } from 'src/app/models/customer.model';
import { LogOrder } from 'src/app/models/log-order.model';
import { OrderDelivery } from 'src/app/models/order-delivery.model';
import { PartnerSales } from 'src/app/models/partners-sales.model';
import { PaymentPlan } from 'src/app/models/payment-plan.model';
import { Place } from 'src/app/models/places.model';
import { StoreERP } from 'src/app/models/store.model';
import { CustomerService } from 'src/app/services/customer.service';
import { LookupService } from 'src/app/services/lookup.service';
import { MessageService } from 'src/app/services/messages.service';
import { OrderService } from 'src/app/services/order.service';
import { PreOrderService } from 'src/app/services/pre-order.service';
import { ProductService } from 'src/app/services/product.service';
import { ShoppingService } from 'src/app/services/shopping.service';
import { AuthUser } from '../../models/auth.user.model';
import { DeliveryTaxTable } from '../../models/delivery-tax-table.model';
import { ProductModalComponent } from '../components/product-modal/product-modal.component';
import {
  ApplyDiscountOrderAction,
  DeleteItemAction,
  LoadShoppingAction,
  LoadShoppingItemsAction,
} from '../store/actions/shopping.action';
import { OrderDeliveryTax } from '../store/models/order-delivery-tax.model';
import { OrderDiscount } from '../store/models/order-discount.model';
import { SaleState } from '../store/models/sale-state.model';
import { ShoppingItem } from '../store/models/shopping-item';
import { Shopping } from '../store/models/shopping.model';
import { THIS_EXPR } from '@angular/compiler/src/output/output_ast';

export interface JsonModel {
  shippingDate: string;
}

@Component({
  selector: 'app-cart-sales',
  templateUrl: './cart-sales.component.html',
  styleUrls: [
    './cart-sales.component.scss',
    './cart-sales-compl.component.scss',
  ],
})
export class CartSalesComponent
  implements OnInit, AfterViewInit, OnDestroy, OnChanges {
  public containerRef: ViewContainerRef;
  public resultQuestion;

  shoppingItems$: Observable<ShoppingItem[]>;
  shopping$: Observable<Shopping>;
  subscriptionShoppingItems: Subscription;
  shoppingItems: ShoppingItem[] = [];
  subscriptionShopping: Subscription;
  shopping: Shopping;
  totalWeight = 0;
  shoppingSubscription: Subscription;
  discountUserSubscription: Subscription;
  subscriptionUpdatePayment: Subscription;
  subscriptionLoad: Subscription;
  placesInteriorSubscription: Subscription;
  placesInterior: any[];
  loading$: Observable<boolean>;
  updating$: Observable<boolean>;
  error$: Observable<Error>;
  billing$: Observable<Billing[]>;
  billing: Billing[] = [];
  subscriptionBilling: Subscription;
  paymentPlan$: Observable<PaymentPlan[]>;
  paymentPlans: PaymentPlan[];
  subscritpionPaymentPlan: Subscription;
  partners$: Observable<PartnerSales[]>;
  invoiceStores$: Observable<StoreERP[]>;
  stores: StoreERP[] = [];
  subscriptionStores: Subscription;
  searchCustomerSubscription: Subscription;
  subscriptionCustomer: Subscription;
  deliveryDaysSubscription: Subscription;
  places$: Observable<Place[]>;
  storePlaces$: Observable<Place[]>;
  totalCart$: Observable<number>;
  formCustomer: FormGroup;
  formResumeOrder: FormGroup;
  formAddress: FormGroup;
  formPayment: FormGroup;
  formNotes: FormGroup;
  formDiscountOrder: FormGroup;
  idPaymentPlan: number;
  selectPaymentPlan: any;
  idBilling: string;
  itemSelect: ShoppingItem; // utilizado para editar (desconto) / excluir item do pedido
  showDiscountItem = false;
  updateItem = false;
  inProcess = false;

  pageCustomer = true;
  pageAddress = false;
  pagePayment = false;
  pageNotesDelivery = false;
  denyScheduleDelivery = true;
  percentSeller = 0;
  percentAuth = 0;
  preOrderNumber = 0;
  orderNumber = 0;
  orderStatus = '';
  urlPrintPreOrder = '';
  urlPrintOrder = '';
  modelPrintPreOrder = 'B';
  modelPrintOrder = 'A';
  openedModelPrintPreOrder = false;
  formModelPreOrder: FormGroup;
  formModelOrder: FormGroup;
  formPreCustomer: FormGroup;
  openedPreCustomer = false;

  showProductsWithoutTax = false;
  productsWithoutTax: any[];

  openedConfirmation = false;
  openInformation = false;
  openedConfirmationTax = false;
  openedConfirmationCancelItem = false;
  showCreateCustomer = false;
  showSelectCustomer = false;
  showCreateAddress = false;
  showInformationCreateOrder = false;
  titleMessage = 'Confirmar';
  messageConfirmation = 'Confirma processamento?';
  informationDelivery = '';
  textButtonConfirmation = 'OK';
  textButtonCancel = 'Cancelar';
  openConfirmChangePayment: any;

  // Definições padrão para centralização
  windowWidth: number = 600; // Ajuste para desktop
  windowHeight: number = 500;
  windowTop: number = 100;
  windowLeft: number = 50;

  isMobile: boolean = false;

  showInformation = false;
  titleInformation = '';
  messageInformation = '';
  informationDescription = '';

  showSelectAddress = false;

  openedAuthUser = false;
  openedConfirmationOrder = false;

  public size: BadgeSize = 'medium';
  public fill: BadgeFill = 'solid';
  public themeColor: BadgeThemeColor = 'primary';
  public vertical: 'top';
  public horizontal: 'end';

  public position: BadgePosition = 'edge';

  public get align(): BadgeAlign {
    return { vertical: this.vertical, horizontal: this.horizontal };
  }

  /* Header */
  public userName: string;
  public storeName: string;

  /* Auth partner for sale */
  showAuthPartner = false;

  /* Confirm user for tax */
  public showConfirmUser = false;
  userForm: FormGroup;

  /* Dialog Discount Order */
  showDialogDiscountOrder = false;
  public actionsLayout: ActionsLayout = 'normal';
  userManager: boolean;

  /* Loadings */
  loadingIconPreOrder = '';
  isLoadingPreOrder = false;

  loadingIconOrder = '';
  isLoadingOrder = false;

  showSelectDeliveryTax = false;
  dataDeliveryTax: DeliveryTaxTable[];
  loadingDeliveryTax = false;

  customer: Customer;
  payment: PaymentPlan;
  public cartData: {
    orderValue: number;
    taxValue: number;
    discountValue: number;
    carrierId: number;
  } = {
      taxValue: 0,
      discountValue: 0,
      orderValue: 0,
      carrierId: 0,
    };

  public windowState: WindowState = 'maximized';
  public openedPrintPreOrder = false;
  public openedPrintOrder = false;

  public openedModelPrintOrder = false;

  public openClosePrintPreOrder(isOpened: boolean): void {
    this.openedPrintPreOrder = isOpened;
  }

  public openClosePrintOrder(isOpened: boolean): void {
    this.openedPrintOrder = isOpened;
  }

  /* Delivery in Store */
  showDeliveryStore = false;
  storePlaceSelected: Place;
  showConfirmCreateOrder = true;

  /* Days for Delivery */
  deliveryDays: number;
  retiraPosteriorDays: number;

  constructor(
    private store: Store<SaleState>,
    private readonly shoppingService: ShoppingService,
    private fb: FormBuilder,
    private readonly lookupService: LookupService,
    private dialogService: DialogService,
    private readonly authService: AuthService,
    private readonly preOrderService: PreOrderService,
    private readonly router: Router,
    private readonly orderService: OrderService,
    private readonly messageService: MessageService,
    private readonly productService: ProductService,
    private readonly customerService: CustomerService
  ) { }

  ngOnChanges(changes: SimpleChanges): void {
    //this.loadShopping();
  }

  ngAfterViewInit(): void { }

  ngOnDestroy(): void {
    if (this.shoppingSubscription) {
      this.shoppingSubscription.unsubscribe();
    }
    if (this.placesInteriorSubscription) {
      this.placesInteriorSubscription.unsubscribe();
    }
    if (this.discountUserSubscription) {
      this.discountUserSubscription.unsubscribe();
    }
    if (this.subscriptionUpdatePayment) {
      this.subscriptionUpdatePayment.unsubscribe();
    }
    if (this.subscriptionLoad) {
      this.subscriptionLoad.unsubscribe();
    }
    if (this.subscriptionShopping) {
      this.subscriptionShopping.unsubscribe();
    }
    if (this.subscriptionStores) {
      this.subscriptionStores.unsubscribe();
    }
    if (this.subscritpionPaymentPlan) {
      this.subscritpionPaymentPlan.unsubscribe();
    }
    if (this.subscriptionBilling) {
      this.subscriptionBilling.unsubscribe();
    }
    if (this.subscriptionShoppingItems) {
      this.subscriptionShoppingItems.unsubscribe();
    }
    if (this.searchCustomerSubscription) {
      this.searchCustomerSubscription.unsubscribe();
    }
    if (this.subscriptionCustomer) {
      this.subscriptionCustomer.unsubscribe();
    }

    if (this.deliveryDaysSubscription) {
      this.deliveryDaysSubscription.unsubscribe();
    }
  }

  getTaxValue() {
    const taxDelivery = JSON.parse(localStorage.getItem('taxDelivery'));
    if (!this.formResumeOrder) return 0;
    const taxValue = Number.parseFloat(
      this.formResumeOrder.get('taxValue').value
    );
    console.log('taxValue: ' + taxValue);
    return taxDelivery != null ? taxDelivery.taxValue : taxValue;
  }

  loadFormOrder(data?: Shopping) {
    if (!data && this.shopping) {
      data = this.shopping;
    }
    if (!data) return;

    const taxDelivery = JSON.parse(localStorage.getItem('taxDelivery'));
    if (this.formResumeOrder) {
      this.formResumeOrder.patchValue({
        taxValue:
          taxDelivery != null && taxDelivery.taxValue > 0
            ? taxDelivery.taxValue.toFixed(2)
            : '0',
        discount: data.vldesconto > 0 ? data.vldesconto.toFixed(2) : '0,00',
        carrierId: taxDelivery != null ? taxDelivery.carrierId : 0,
        deliveryTaxId: taxDelivery != null ? taxDelivery.deliveryTaxId : 0,
      });
    }
  }

  ngOnInit(): void {
    this.userForm = this.fb.group({
      userName: new FormControl('', [Validators.required]),
      password: new FormControl('', [Validators.required]),
      notation: new FormControl('', [Validators.required]),
    });

    this.formCustomer = this.fb.group({
      name: new FormControl({ value: '', disabled: true }, []),
      document: new FormControl({ value: '', disabled: true }, []),
      cellPhone: new FormControl({ value: '', disabled: true }, []),
      cep: new FormControl({ value: '', disabled: true }, []),
      address: new FormControl({ value: '', disabled: true }, []),
      number: new FormControl({ value: '', disabled: true }, []),
      city: new FormControl({ value: '', disabled: true }, []),
      state: new FormControl({ value: '', disabled: true }, []),
      complement: new FormControl({ value: '', disabled: true }, []),
    });
    this.formAddress = this.fb.group({
      cellPhone: new FormControl({ value: '', disabled: true }, []),
      zipCode: new FormControl({ value: '', disabled: true }, []),
      address: new FormControl({ value: '', disabled: true }, []),
      number: new FormControl({ value: '', disabled: true }, []),
      city: new FormControl({ value: '', disabled: true }, []),
      state: new FormControl({ value: '', disabled: true }, []),
      complement: new FormControl({ value: '', disabled: true }, []),
      referencePoint: new FormControl({ value: '', disabled: true }, []),
      note: new FormControl({ value: '', disabled: true }, []),
    });

    let dataDeliveryComp = localStorage.getItem('dataDelivery');
    let dataShippingDate = null;
    let dataScheduleDelivery = null;
    let dataShippingPriority = null;
    let dataText1 = null;
    let dataText2 = null;
    let dataDeliveryText1 = null;
    let dataDeliveryText2 = null;
    let dataDeliveryText3 = null;

    console.log(dataDeliveryComp);

    if (dataDeliveryComp != null) {
      const data = JSON.parse(localStorage.getItem('dataDelivery'));
      dataShippingDate = data.shippingDate;
      dataScheduleDelivery = data.scheduleDelivery;
      dataShippingPriority = data.shippingPriority;
      dataText1 = data.notification1;
      dataText2 = data.notification;
      dataDeliveryText1 = data.notificationDelivery1;
      dataDeliveryText2 = data.notificationDelivery2;
      dataDeliveryText3 = data.notificationDelivery3;
    } else {
      const data = {
        dateDelivery: null,
        notification: null,
        notification1: null,
        notificationDelivery1: null,
        notificationDelivery2: null,
        notificationDelivery3: null,
        priorityDelivery: 'B',
        scheduleDelivery: false,
      };

      localStorage.setItem('dataDelivery', JSON.stringify(data));
      const resultado = JSON.parse(localStorage.getItem('dataDelivery'));
      dataShippingDate = data.dateDelivery;
      dataScheduleDelivery = data.scheduleDelivery;
      dataShippingPriority = data.priorityDelivery;
      dataText1 = resultado.notification1;
      dataText2 = resultado.notification;
      dataDeliveryText1 = resultado.notificationDelivery1;
      dataDeliveryText2 = resultado.notificationDelivery2;
      dataDeliveryText3 = resultado.notificationDelivery3;
    }

    this.formNotes = this.fb.group({
      shippingDate: new FormControl(dataShippingDate),
      scheduleDelivery: new FormControl(dataScheduleDelivery),
      shippingPriority: new FormControl(dataShippingPriority),
      notesText1: new FormControl(dataText1),
      notesText2: new FormControl(dataText2),
      notesDeliveryText1: new FormControl(dataDeliveryText1),
      notesDeliveryText2: new FormControl(dataDeliveryText2),
      notesDeliveryText3: new FormControl(dataDeliveryText3),
    });
    this.formResumeOrder = this.fb.group({
      taxValue: new FormControl(this.cartData.taxValue.toFixed(2), []),
      discount: new FormControl(this.cartData.discountValue.toFixed(2), []),
      carrierId: new FormControl(this.cartData.carrierId, []),
      deliveryTaxId: new FormControl(0, []),
    });
    this.formPayment = this.fb.group({
      invoiceStore: new FormControl(null),
      paymentPlan: new FormControl(null),
      billing: new FormControl(null),
      partner: new FormControl(null),
    });
    this.formModelPreOrder = this.fb.group({
      model: new FormControl('B'),
    });
    this.formModelOrder = this.fb.group({
      model: new FormControl('A'),
    });

    this.formPreCustomer = this.fb.group({
      document: ['', Validators.required],
      name: ['', Validators.required],
      phone: ['', Validators.required],
    });

    const dataDelivery = JSON.parse(
      localStorage.getItem('dataDelivery')
    ) as OrderDelivery;

    this.formNotes.patchValue({
      scheduleDelivery: dataDelivery.scheduleDelivery,
      shippingPriority: dataDelivery.priorityDelivery,
      notesText1: dataDelivery.notification,
      notesText2: dataDelivery.notification1,
      notesDeliveryText1: dataDelivery.notificationDelivery1,
      notesDeliveryText2: dataDelivery.notificationDelivery2,
      notesDeliveryText3: dataDelivery.notificationDelivery3,
    });

    this.setDataDelivery();

    this.userName = this.authService.getUserName();
    this.storeName = this.authService.getStoreName();

    this.shopping$ = this.store.select((store) => store.shopping.shopping);
    this.shoppingItems$ = this.store.select((store) => store.shopping.list);
    this.loading$ = this.store.select((store) => store.shopping.loading);
    this.updating$ = this.store.select((store) => store.shopping.updating);
    this.error$ = this.store.select((store) => store.shopping.error);
    this.totalCart$ = this.store.select((store) => store.shopping.total);

    this.shoppingSubscription = this.shopping$.subscribe((data) => {
      this.shopping = data;
      if (this.shopping !== null) {
        this.totalWeight = data.totpeso;
        this.loadFormOrder(data);
      }
    });

    this.placesInteriorSubscription = this.shoppingService
      .getPlacesInterior()
      .subscribe((places) => (this.placesInterior = places));

    // calculate days for delivery //
    this.deliveryDays = this.calculateDeliveryTime();
    const customer: Customer = JSON.parse(localStorage.getItem('customer'));
    const address: CustomerAddress = JSON.parse(
      localStorage.getItem('address')
    );
    const invoiceStore = JSON.parse(
      localStorage.getItem('invoiceStore')
    ) as StoreERP;
    const cartId = localStorage.getItem('cart');

    const saleDate = new Date();
    const saleYear = saleDate.getFullYear();
    const saleMonth = saleDate.getMonth() + 1;
    const day = saleDate.getDate();
    const stringDate =
      ('00' + day).slice(-2) +
      '-' +
      ('00' + saleMonth).slice(-2) +
      '-' +
      saleYear;
    console.log('Data atual: ' + stringDate);
    this.deliveryDaysSubscription = this.shoppingService
      .getDeliveryDays(
        stringDate,
        invoiceStore == null ? this.authService.getStore() : invoiceStore.id,
        address != null
          ? address.placeId
          : customer != null
            ? customer.placeId
            : 0,
        cartId
      )
      .subscribe((data) => {
        this.deliveryDays = data.deliveryDays;
        this.retiraPosteriorDays = data.retiraPosteriorDays;
        console.log('Dias de entrega: ' + this.deliveryDays);
        // let deliveryTime = 0;
        // if (this.authService.getDeliveryTime() != null) {
        //   deliveryTime = Number.parseInt(this.authService.getDeliveryTime(), 10);
        //   console.log("Dias entrega: " + deliveryTime);
        // }
        const deliveryDate = new Date();
        let Days = deliveryDate.getDate() + this.deliveryDays;
        if (this.formNotes.get('shippingPriority').value == 'M') {
          Days = deliveryDate.getDate() + this.retiraPosteriorDays;
        }
        deliveryDate.setDate(Days);
        console.log(deliveryDate);

        if (
          this.formNotes.get('shippingDate').value == undefined ||
          this.formNotes.get('shippingDate').value == null ||
          Date.parse(this.formNotes.get('shippingDate').value) <
          Date.parse(deliveryDate.toDateString())
        ) {
          const model: JsonModel = {
            shippingDate: deliveryDate != null ? deliveryDate.toString() : null,
          };
          this.formNotes.patchValue({
            shippingDate:
              deliveryDate != null ? new Date(model.shippingDate) : null,
          });
        }
      });

    this.partners$ = this.lookupService.getPartners();
    this.invoiceStores$ = this.lookupService.getStore();
    this.places$ = this.lookupService.getPlaces();
    this.storePlaces$ = this.lookupService.getStorePlaces();
    this.store.dispatch(new LoadShoppingAction(this.shoppingService.getCart()));
    this.store.dispatch(
      new LoadShoppingItemsAction(this.shoppingService.getCart())
    );
    this.pageCustomer = true;

    this.billing$ = this.lookupService.getBilling(
      customer !== null ? customer.customerId : 1
    );
    this.paymentPlan$ = this.lookupService.getPaymentPlan();
    const saveBilling = localStorage.getItem('billing');
    const savePartner = localStorage.getItem('partner');

    this.subscriptionShoppingItems = this.shoppingItems$.subscribe((data) => {
      this.shoppingItems = data;
      console.log('Itens do pedido: ' + JSON.stringify(this.shoppingItems));
      //calculo da taxa de entrega
      this.calculateTaxDelivery(false);
    });
    this.subscriptionStores = this.invoiceStores$.subscribe((data) => {
      console.log('Filial de venda: ' + JSON.stringify(data));
      this.stores = data;
      let saveStoreInvoice = localStorage.getItem('invoiceStore');
      if (saveStoreInvoice == null) {
        saveStoreInvoice = JSON.stringify(
          this.stores.find((s) => s.id === this.authService.getStore())
        );
        localStorage.setItem('invoiceStore', saveStoreInvoice);
        this.updateCart(this.shoppingService.getCart());

      }
      this.formPayment.patchValue({
        invoiceStore: JSON.parse(saveStoreInvoice),
      });
    });

    const billing = JSON.parse(saveBilling) as Billing;
    if (billing !== null) {
      this.subscriptionBilling = this.billing$.subscribe((data) => {
        this.billing = data;
        if (
          saveBilling !== undefined &&
          saveBilling != null &&
          saveBilling !== 'undefined'
        ) {
          if (billing != null) {
            this.formPayment.patchValue({
              billing,
            });
          }
        }
      });
    }

    if (billing !== null) {
      const savePayment = localStorage.getItem('paymentPlan');
      this.paymentPlan$ = this.lookupService.getPaymentPlan(billing.codcob, customer !== null ? customer.customerId : 1);
      this.subscritpionPaymentPlan = this.paymentPlan$.subscribe((data) => {
        this.paymentPlans = data;
        if (
          savePayment !== undefined &&
          savePayment != null &&
          savePayment !== 'undefined'
        ) {
          const paymentPlan = JSON.parse(savePayment) as PaymentPlan;
          if (paymentPlan != null) {
            this.formPayment.patchValue({
              paymentPlan,
            });
          }
        }
      });
    }

    if (
      savePartner !== undefined &&
      savePartner != null &&
      savePartner !== 'undefined'
    ) {
      const partner = JSON.parse(savePartner) as PartnerSales;
      if (partner != null) {
        this.formPayment.patchValue({
          partner,
        });
      }
    }

    if (dataDelivery != null) {
      const delivery = dataDelivery;
      const newDate =
        delivery.dateDelivery != null ? delivery.dateDelivery : null; // new Date().getDate();
      const model: JsonModel = {
        shippingDate: newDate != null ? newDate.toString() : null,
      };
      this.formNotes.patchValue({
        shippingDate: newDate != null ? new Date(model.shippingDate) : null, // delivery.dateDelivery, // delivery.dateDelivery,
        scheduleDelivery: delivery.scheduleDelivery,
        shippingPriority: delivery.priorityDelivery,
        notesText1: delivery.notification,
        notesText2: delivery.notification1,
        notesDeliveryText1: delivery.notificationDelivery1,
        notesDeliveryText2: delivery.notificationDelivery2,
        notesDeliveryText3: delivery.notificationDelivery3,
      });
    }

    this.formDiscountOrder = this.fb.group({
      value: new FormControl(0.0),
      profit: new FormControl(0.0),
      discount: new FormControl(0.0),
      discountValue: new FormControl(0.0),
      netValue: new FormControl(0.0),
      netProfit: new FormControl(0.0),
    });

    if (customer != null) {
      this.updateFormCustomer(customer);
    }
    if (address != null) {
      this.updateFormAddress(address);
    }
  }

  async showConfirmation() {
    this.isLoadingPreOrder = true;
    const dialog: DialogRef = this.dialogService.open({
      title: 'Por favor, confirme',
      content: 'Deseja gravar como orçamento ?',
      actions: [
        { text: 'Não', confirm: false },
        { text: 'Sim', confirm: true, themeColor: 'primary' },
      ],
      width: 450,
      height: 200,
      minWidth: 250,
    });

    dialog.result.subscribe((result) => {
      if (result instanceof DialogCloseResult) {
        console.log('close');
        this.isLoadingPreOrder = false;
      } else {
        const resultConfirmation = JSON.stringify(result);
        console.log('action1', resultConfirmation);
        if (JSON.parse(resultConfirmation).text === 'Sim') {
          console.log('criando orçamento');
          this.createPreOrder();
        }
        this.isLoadingPreOrder = false;
      }
    });
  }

  async showErrorMessage(message: string) {
    const dialog: DialogRef = this.dialogService.open({
      title: 'Ops, houve um problema no processamento',
      content: message,
      actions: [{ text: 'Ok', themeColor: 'primary' }],
      width: 450,
      height: 200,
      minWidth: 250,
    });
  }

  async showInformationMessage(message: string) {
    const dialog: DialogRef = this.dialogService.open({
      title: 'Sucesso!!',
      content: message,
      actions: [{ text: 'Ok', themeColor: 'primary' }],
      width: 450,
      height: 200,
      minWidth: 250,
    });
  }

  async setPaymentPlan(paymentPlan: any) {
    if (localStorage.getItem('paymentPlan') === 'undefined') {
      localStorage.setItem('paymentPlan', JSON.stringify(paymentPlan));
      this.selectPaymentPlan = paymentPlan;
      this.updateCart(this.shoppingService.getCart());
      this.confirmChangePaymentPlan(true);
    } else {
      this.selectPaymentPlan = paymentPlan;
      this.titleMessage = 'Alteração plano de pagamento';
      this.messageConfirmation =
        'Confirma a alteração do plano de pagamento, todos os descontos serão retirados do pedido?';
      this.openConfirmChangePayment = true;
    }
  }

  confirmChangePaymentPlan(result: any) {
    if (result) {
      this.openConfirmChangePayment = false;
      localStorage.setItem(
        'paymentPlan',
        JSON.stringify(this.selectPaymentPlan)
      );
      this.updateCart(this.shoppingService.getCart());
      const billing = JSON.parse(localStorage.getItem('billing')) as Billing;
      this.idPaymentPlan = this.selectPaymentPlan.codplpag;
      this.subscriptionUpdatePayment = this.shoppingService
        .updatePricePaymentPlan(this.selectPaymentPlan, billing.codcob)
        .subscribe((d) => {
          this.store.dispatch(
            new LoadShoppingItemsAction(this.shoppingService.getCart())
          );
          this.store.dispatch(
            new LoadShoppingAction(this.shoppingService.getCart())
          );

          this.loadFormOrder();
        });
    } else {
      this.openConfirmChangePayment = false;
      const paymentPlan = JSON.parse(
        localStorage.getItem('paymentPlan')
      ) as PaymentPlan;
      this.formPayment.patchValue({
        paymentPlan,
      });
    }
  }

  setBilling(billing: any) {
    localStorage.setItem('billing', JSON.stringify(billing));
    const customer = JSON.parse(localStorage.getItem('customer')) as Customer;
    this.idBilling = billing.codcob;
    console.log(JSON.stringify(billing));
    localStorage.removeItem('paymentPlan');
    this.formPayment.patchValue({
      paymentPlan: null,
    });
    this.paymentPlan$ = this.lookupService.getPaymentPlan(billing.codcob,
      customer !== null ? customer.customerId : 1
    );
    this.subscritpionPaymentPlan = this.paymentPlan$
      .pipe(
        tap((data) => (this.paymentPlans = data)),
        tap((planos) => console.log(planos))
      )
      .subscribe();
    this.updateCart(this.shoppingService.getCart());
  }

  setPartner(partner: any) {
    localStorage.setItem('partner', JSON.stringify(partner));
  }

  setInvoiceStore(invoiceStore: any) {
    localStorage.setItem('invoiceStore', JSON.stringify(invoiceStore));
    this.updateCart(this.shoppingService.getCart());
  }

  isInvoiceStore9Or10() {
    return JSON.parse(localStorage.getItem('user')).store === '9' ||
      JSON.parse(localStorage.getItem('user')).store === '10'
      ? true
      : false;
  }

  setDataDelivery() {
    console.log(this.formNotes.value);
    this.calculateTaxDelivery(true);
    let deliveryTime = 0;
    if (this.authService.getDeliveryTime() != null) {
      deliveryTime = Number.parseInt(this.authService.getDeliveryTime(), 3);
    }
    const deliveryDate = new Date();
    let Days = deliveryDate.getDate() + this.deliveryDays;

    const shippingPriority = this.formNotes.get('shippingPriority').value;
    if (shippingPriority == 'M') {
      Days = deliveryDate.getDate() + this.retiraPosteriorDays;
    }
    if (shippingPriority == 'A') {
      Days = deliveryDate.getDate() + 1;
    }

    deliveryDate.setDate(Days);

    let dtDelivery = new Date(this.formNotes.get('shippingDate').value);
    const dateToday = new Date();
    if (dtDelivery < dateToday || dtDelivery < deliveryDate) {
      dtDelivery = null;
    }

    //   console.log("data de entrega: " + dtDelivery.toString());

    // tslint:disable-next-line: prefer-const
    let orderDelivery = new OrderDelivery();
    orderDelivery.dateDelivery = dtDelivery;
    orderDelivery.scheduleDelivery =
      this.formNotes.get('scheduleDelivery').value;

    if (shippingPriority == 'M') {
      const newDate = deliveryDate != null ? deliveryDate : null; // new Date().getDate();
      const model: JsonModel = {
        shippingDate: newDate != null ? newDate.toString() : null,
      };
      console.log('data de retira posterior: ' + deliveryDate.toString());
      this.formNotes.patchValue({
        shippingDate:
          deliveryDate != null ? new Date(model.shippingDate) : null,
      });
    } else {
      const newDate = deliveryDate != null ? deliveryDate : null; // new Date().getDate();
      const model: JsonModel = {
        shippingDate: newDate != null ? newDate.toString() : null,
      };
      if (dtDelivery < dateToday || dtDelivery < deliveryDate) {
        this.formNotes.patchValue({
          shippingDate:
            deliveryDate != null ? new Date(model.shippingDate) : null,
        });
      }
    }

    if (dtDelivery != null && dtDelivery > deliveryDate) {
      orderDelivery.scheduleDelivery = dtDelivery > deliveryDate ? true : false;
      this.formNotes.patchValue({
        scheduleDelivery: orderDelivery.scheduleDelivery,
      });
    }
    // const dataDelivery = localStorage.getItem('dataDelivery')
    //   ? (JSON.parse(localStorage.getItem('dataDelivery')!) as OrderDelivery)
    //   : null;
    // console.log(`data de entrega:  ${dataDelivery}`);
    // if (dataDelivery != null) {
    //   this.formNotes.get('notesText1').setValue(dataDelivery.notification1);
    // } else {
    orderDelivery.notification = this.formNotes.get('notesText1').value;
    // }
    orderDelivery.priorityDelivery =
      this.formNotes.get('shippingPriority').value;
    orderDelivery.notification1 = this.formNotes.get('notesText2').value;

    orderDelivery.notificationDelivery1 =
      this.formNotes.get('notesDeliveryText1').value;
    orderDelivery.notificationDelivery2 =
      this.formNotes.get('notesDeliveryText2').value;
    orderDelivery.notificationDelivery3 =
      this.formNotes.get('notesDeliveryText3').value;
    orderDelivery.scheduleDelivery =
      this.formNotes.get('scheduleDelivery').value;
    localStorage.setItem('dataDelivery', JSON.stringify(orderDelivery));
  }

  activePageCustomer() {
    this.pageCustomer = true;
    this.pageAddress = false;
    this.pagePayment = false;
    this.pageNotesDelivery = false;
  }

  activePageAddress() {
    this.pageCustomer = false;
    this.pageAddress = true;
    this.pagePayment = false;
    this.pageNotesDelivery = false;
  }

  activePagePayment() {
    console.log(JSON.stringify(localStorage.getItem('customer')));
    const customer = JSON.parse(localStorage.getItem('customer')) as Customer;

    if (localStorage.getItem('customer') != undefined) {
      // if (customer.place.id == 19) {
      //   this.titleInformation = 'Pedido de venda';
      //   this.messageInformation = 'ATENÇÃO! Cliente com praça do E-COMMERCE!';
      //   this.informationDescription =
      //     'Altere a praça do cliente pela opção NOVO CLIENTE para continuar.';
      //   this.showInformation = true;
      //   return;
      // }
      if (
        customer.place.name == 'INATIVO' ||
        customer.place.name == 'INATIVA'
      ) {
        this.titleInformation = 'Pedido de venda';
        this.messageInformation = 'ATENÇÃO! Cliente com praça INATIVA!';
        this.informationDescription =
          'Altere a praça do cliente pela opção NOVO CLIENTE para continuar.';
        this.showInformation = true;
        return;
      }
    }
    this.pageCustomer = false;
    this.pageAddress = false;
    this.pagePayment = true;
    this.pageNotesDelivery = false;
  }

  activePageNoteDelivery() {
    this.pageCustomer = false;
    this.pageAddress = false;
    this.pagePayment = false;
    this.pageNotesDelivery = true;
  }

  async selectCustomer() {
    this.showSelectCustomer = true;

    /*const dialog: DialogRef = this.dialogService.open({
      title: 'Selecione o cliente desejado',
      content: SelectCustomerComponent,
      actions: [{ text: 'Cancelar', confirm: false }, { text: 'Confirmar', confirm: true, themeColor: 'primary' }],
      width: 850,
      height: 650,
      minWidth: 250,
    });

    dialog.result.subscribe((result) => {
      if (result instanceof DialogCloseResult) {
        console.log('close');
      } else {
        const resultDialog = JSON.parse((JSON.stringify(result)));
        if (resultDialog.confirm === true) {
          const customer = (dialog.content.instance as SelectCustomerComponent)
            .customer;
          this.updateFormCustomer(customer);
        } else {
          console.log('action', result);
        }

      }
    });*/
  }

  resultSelectCustomer(result: any) {
    this.showSelectCustomer = false;
    if (result != null) {
      if (result.customerId !== 1) {
        localStorage.removeItem('preCustomer');
      }
      this.updateFormCustomer(result);
      localStorage.setItem('customer', JSON.stringify(result));
      this.updateCart(this.shoppingService.getCart());
      this.updateTaxDelivery();
    }
  }

  private updateFormCustomer(customer: Customer) {
    let preCustomer = null;
    if (localStorage.getItem('preCustomer') !== undefined) {
      preCustomer = JSON.parse(localStorage.getItem('preCustomer'));
    }
    localStorage.setItem('customer', JSON.stringify(customer));
    this.billing$ = this.lookupService.getBilling(customer.customerId);
    this.subscriptionBilling = this.billing$.subscribe((data) => {
      this.billing = data;
    });
    this.customer = customer;
    this.formCustomer.patchValue({
      name: preCustomer === null ? customer.name : preCustomer.name,
      document: preCustomer === null ? customer.cpfCnpj : preCustomer.document,
      cellPhone: preCustomer === null ? customer.cellPhone : preCustomer.phone,
      cep: customer.zipCode,
      address: customer.address,
      number: customer.addressNumber,
      city: customer.city,
      state: customer.state,
      complement: customer.complement,
    });
  }

  async updateTaxDelivery() {
    this.formResumeOrder.patchValue({
      taxValue: 0,
    });
    this.returnConfirmationTax(true);
    this.calculateTaxDelivery(true);
    this.returnConfirmationTax(true);
  }

  async getItens() {
    const itensCart: CartItensModel[] = [];
    this.subscriptionShoppingItems = this.shoppingItems$.subscribe((data) => {
      this.shoppingItems = data;
      data.forEach((itemShopping) => {
        const item: CartItensModel = {
          idProduct: itemShopping.idProduct,
          idStock: itemShopping.stockStore,
          deliveryMethod: itemShopping.deliveryType,
          quantity: itemShopping.quantity,
          listPrice: itemShopping.listPrice,
          salePrice: itemShopping.price,
          ean: itemShopping.ean,
          descriptionAux: itemShopping.auxDescription,
          environment: itemShopping.environment,
        };
        itensCart.push(item);
      });
    });

    return itensCart;
  }

  async createPreOrder() {
    const invoiceStore = JSON.parse(
      localStorage.getItem('invoiceStore')
    ) as StoreERP;
    const customer = JSON.parse(localStorage.getItem('customer')) as Customer;
    const preCustomer = JSON.parse(localStorage.getItem('preCustomer'));
    const address = JSON.parse(
      localStorage.getItem('address')
    ) as CustomerAddress;
    const paymentPlan = JSON.parse(
      localStorage.getItem('paymentPlan')
    ) as PaymentPlan;
    const billing = JSON.parse(localStorage.getItem('billing')) as Billing;
    const partner = JSON.parse(localStorage.getItem('partner')) as PartnerSales;

    if (invoiceStore === null) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Favor selecione uma filial de venda para o orçamento.';
      this.showInformation = true;
      return;
    }

    if (customer === null) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Favor informe um cliente ou consumidor final para gerar o orçamento de venda.';
      this.showInformation = true;
      return;
    }

    if (
      (customer === null || customer.customerId === 1) &&
      preCustomer === null
    ) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Favor informe um cliente ou um pré-Cadastro de cliente para gerar o orçamento de venda.';
      this.showInformation = true;
      return;
    }

    if (this.formNotes.get('shippingDate').value === null) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Favor informe a data de entrega do pedido.';
      this.showInformation = true;
      return;
    }

    let deliveryTime = 0;
    if (this.authService.getDeliveryTime() != null) {
      deliveryTime = Number.parseInt(this.authService.getDeliveryTime(), 10);
    }
    const deliveryDate = new Date();
    const Days = deliveryDate.getDate() + this.deliveryDays;
    deliveryDate.setDate(Days);
    console.log(deliveryDate);

    if (
      Date.parse(this.formNotes.get('shippingDate').value) <
      Date.parse(deliveryDate.toDateString())
    ) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription = `Data de entrega inferior ao período mínimo definido para entrega. (${deliveryTime} dias)`;
      this.showInformation = true;
      return;
    }

    //validar itens com descrição diferente de ++ com cobrança CHM1
    if (billing.codcob == 'CHM1') {
      const chequeMoradiaItens = this.shoppingItems.filter((item) =>
        item.smallDescription.startsWith('++', 0)
      );
      if (chequeMoradiaItens.length < this.shoppingItems.length) {
        this.titleInformation = 'Pedido de venda';
        this.messageInformation =
          'Existem itens não permitidos para a cobrança utilizada.';
        this.informationDescription = `Existem produtos que não são permitidos serem vendidos na cobrança CHM1.`;
        this.showInformation = true;
        this.isLoadingOrder = false;
        return;
      }
    }

    if (!this.orderValid()) {
      this.isLoadingOrder = false;
      return;
    }

    const deliveryItens = this.shoppingItems.filter(
      (item) => item.deliveryType === 'EF' || item.deliveryType === 'EN'
    );
    const taxValue = Number.parseFloat(
      this.formResumeOrder.get('taxValue').value
    );

    console.log(deliveryItens);

    // if (deliveryItens.length > 0 && taxValue === 0 &&
    //      this.formNotes.get('shippingPriority').value !== 'M') {
    //   this.titleInformation = 'Pedido de venda';
    //   this.messageInformation = 'Não foi possível gerar o pedido de venda!';
    //   this.informationDescription =
    // 'Existem items a serem entregues e não foi informado a taxa de entrega, para concluir o pedido informe a taxa de entrega.';
    //   this.showInformation = true;
    //   return;
    // }

    // if (deliveryItens.length > 0 && customer.customerId === 1) {
    //   this.titleInformation = 'Pedido de venda';
    //   this.messageInformation = 'Não foi possível gerar o pedido de venda!';
    //   this.informationDescription = 'Pedido para consumidor final com itens a serem entregues, favor informar um cliente cadastrado.';
    //   this.showInformation = true;
    //   return;
    // }

    const itemRI = this.shoppingItems.filter(
      (item) =>
        item.deliveryType === 'RI' && item.stockStore !== invoiceStore.id
    );
    if (itemRI.length > 0) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Existem items com tipo de entrega RETIRA IMEDIATA com a filial retira diferente da filial de faturamento.';
      this.showInformation = true;
      return;
    }

    const itensCart = await this.getItens();
    const cart: CartModel = {
      id: this.shoppingService.getCart(),
      saleStore: invoiceStore.id,
      userId: this.authService.getUser(),
      idCustomer: customer.customerId,
      idPaymentPlan: paymentPlan.codplpag,
      idBilling: billing.codcob,
      idSeller: this.authService.getSeller(),
      idProfessional: partner != null ? partner.id : 0,
      shippingDate: this.formNotes.get('shippingDate').value,
      scheduleDelivery: this.formNotes.get('scheduleDelivery').value,
      shippingPriority: this.formNotes.get('shippingPriority').value,
      shippingValue: this.formResumeOrder.get('taxValue').value,
      carrierId:
        this.formResumeOrder.get('carrierId').value == null
          ? 0
          : this.formResumeOrder.get('carrierId').value,
      idAddress: address != null ? address.idAddress : 0,
      notation1: this.formNotes.get('notesText1').value,
      notation2: this.formNotes.get('notesText2').value,
      notation3: '', // this.formNotation.get('observacao3').value,
      deliveryNote1: this.formNotes.get('notesDeliveryText1').value,
      deliveryNote2: this.formNotes.get('notesDeliveryText2').value,
      deliveryNote3: this.formNotes.get('notesDeliveryText3').value,
      itens: itensCart,
      preCustomerDocument:
        customer.customerId === 1 ? preCustomer.document : null,
      preCustomerName: customer.customerId === 1 ? preCustomer.name : null,
      preCustomerPhone: customer.customerId === 1 ? preCustomer.phone : null,
    };

    const result$ = this.preOrderService.create(cart);
    this.isLoadingPreOrder = true;
    this.loadingIconPreOrder = 'loading';
    result$
      .pipe(
        map((result) => {
          if (result.success) {
            // this.openClosePrintPreOrder(true);
            this.preOrderNumber = result.data.numorca;
            this.selectModelPreOrder();
            //    this.urlPrintPreOrder = 'http://10.1.1.205:8068/Viewer/{action}?order=' + result.data.numorca;
            // this.urlPrintPreOrder = 'http://localhost:4200/Viewer/{action}?order=' +
            //   result.data.numorca + '&model=' + this.modelPrintPreOrder;
            // this.titleInformation = 'Gravar pedido de venda';
            // this.messageInformation = 'Orçamento gerado com sucesso!';
            // this.informationDescription = `Número do orçamento gerado: ${result.data.numorca}`;
            // this.showInformationCreateOrder = true;
            // this.openedPrintPreOrder = true;
          }
        }),
        tap(() => {
          this.isLoadingPreOrder = false;
          this.loadingIconPreOrder = '';
        }),
        catchError((err) => {
          this.messageInformation = 'Houve um erro ao gerar o orçamento!';
          this.informationDescription = err.error.message;
          this.showInformation = true;
          return of();
        })
      )
      .subscribe();
  }

  public closeSale() {
    console.log('Fechamento venda.');
    localStorage.removeItem('cart');
    localStorage.removeItem('customer');
    localStorage.removeItem('preCustomer');
    localStorage.removeItem('paymentPlan');
    localStorage.removeItem('billing');
    localStorage.removeItem('address');
    localStorage.removeItem('invoiceStore');
    localStorage.removeItem('partner');
    localStorage.removeItem('shoppingItem');
    localStorage.removeItem('dataDelivery');
    localStorage.removeItem('authorizationTax');
    localStorage.removeItem('taxDelivery');
    localStorage.removeItem('authorizationTax');
    localStorage.removeItem('authorizationPartner');
    this.router.navigate(['/sales/menu']);
  }

  async showConfirmationDiscountOrder() {
    const discountValue =
      this.formResumeOrder.get('discount').value != null
        ? Number.parseFloat(this.formResumeOrder.get('discount').value)
        : 0;
    const percentOrder = Number.parseFloat(
      ((discountValue / this.shopping.vlpedido) * 100).toPrecision(2)
    );
    this.titleMessage = 'Aplicar desconto sobre pedido';
    this.messageConfirmation = `Confirma o desconto de R$ ${discountValue.toFixed(
      2
    )} sobre o valor total do pedido ?
                                Todos os descontos lançados no pedido serão desconsiderados. Confirma a aplicação do desconto?`;
    this.textButtonConfirmation = 'Confirma';
    this.openedConfirmation = true;
  }

  async showConfirmationTax() {
    this.showSelectDeliveryTax = true;

    // const taxValue = Number.parseFloat(this.formResumeOrder.get('taxValue').value);

    // if (taxValue < 0) {
    //   this.titleInformation = 'Taxa de Entrega';
    //   this.messageInformation = 'Valor da taxa de entrega inválido!';
    //   this.informationDescription = 'O valor da taxa de entrega não pode ser inferior a ZERO! Obrigado tentar burlar o sistema, foi gerado LOG de audoria e enviado a diretoria! Aguarde... ';
    //   this.showInformation = true;
    //   return;
    // }

    // this.titleMessage = 'Taxa de entrega';
    // this.messageConfirmation = `Confirma valor da taxa de entrega?`;
    // this.textButtonConfirmation = 'Confirma';
    // this.openedConfirmationTax = true;
  }

  confirmSelectDeliveryTax(show: boolean) {
    this.showSelectDeliveryTax = false;
  }

  async showConfirmationCancelItem({ action, rowIndex, dataItem, sender }) {
    this.itemSelect = dataItem;
    this.titleMessage = 'Pedido de venda';
    this.messageConfirmation = `Confirma a exclusão do item do pedido?`;
    this.textButtonConfirmation = 'Confirma';
    this.openedConfirmationCancelItem = true;
  }

  async showPageDiscountItem({ action, rowIndex, dataItem, sender }) {
    this.itemSelect = dataItem;
    console.log(dataItem);
    if (this.itemSelect.promotion > 0) {
      this.titleInformation = 'Desconto sobre item de venda';
      this.messageInformation = 'Produto em promoção, desconto não permitido!';
      this.informationDescription =
        'Produtos em promoção não é permitido informar desconto.';
      this.showInformation = true;
      return;
    }

    const payment = JSON.parse(
      localStorage.getItem('paymentPlan')
    ) as PaymentPlan;
    if (payment == null) {
      this.titleInformation = 'Desconto sobre item de venda';
      this.messageInformation =
        'Venda sem plano de pagamento informado, desconto não permitido!';
      this.informationDescription =
        'Selecione primeiro um plano de pagamento para aplicar um desconto!';
      this.showInformation = true;
      return;
    }

    this.authService.getUser();
    if (payment.numdias > 30 && !this.authService.isManager()) {
      this.titleInformation = 'Desconto sobre item de venda';
      this.messageInformation =
        'Plano de pagamento parcelado, desconto não permitido!';
      this.informationDescription =
        'Desconto autorizado apenas para venda a vista ou em 1x no cartão!';
      this.showInformation = true;
      return;
    }

    this.showDiscountItem = true;
  }

  async returnConfirmation(result: boolean) {
    if (this.openedConfirmation) {
      this.openedConfirmation = false;
      console.log('Resultado desconto: ' + result);
      if (result) {
        const discountValue = Number.parseFloat(
          this.formResumeOrder.get('discount').value
        );
        let percentOrder = (discountValue / this.cartData.orderValue) * 100;
        if (this.percentSeller < percentOrder) {
          this.openedAuthUser = true;
          console.log('Desconto acima do permitido.');
          return;
        }
        if (discountValue <= 0.01) {
          percentOrder = 0;
        }
        const order: OrderDiscount = {
          id: this.shoppingService.getCart(),
          percentDiscount: percentOrder,
          idUserAuth: this.authService.getUser(),
        };
        this.store.dispatch(new ApplyDiscountOrderAction(order));
        this.store.dispatch(
          new LoadShoppingAction(this.shoppingService.getCart())
        );
        this.loadFormOrder();
      } else {
        this.loadFormOrder();
      }
    }

    if (this.openedConfirmationTax) {
      this.returnConfirmationTax(true);
    }
  }

  async returnConfirmationTax(result: boolean) {
    this.openedConfirmationTax = false;
    if (result) {
      const taxValue = Number.parseFloat(
        this.formResumeOrder.get('taxValue').value
      );
      const dataDelivery = JSON.parse(
        localStorage.getItem('dataDelivery')
      ) as OrderDelivery;

      let deliveryTaxId = 0;
      let carrierId = 0;
      if (taxValue >= 0) {
        deliveryTaxId = Number.parseFloat(
          this.formResumeOrder.get('deliveryTaxId') ? this.formResumeOrder.get('deliveryTaxId').value : 0
        );
        carrierId = Number.parseFloat(
          this.formResumeOrder.get('carrierId') ? this.formResumeOrder.get('carrierId').value : 0
        );
      }
      const order: OrderDeliveryTax = {
        id: this.shoppingService.getCart(),
        taxValue,
        deliveryTaxId: deliveryTaxId,
        carrierId: carrierId,
      };
      localStorage.setItem('taxDelivery', JSON.stringify(order));
      this.loadFormOrder();

      /*  this.store.dispatch(new UpdateDeliveryTaxAction(order));
        this.updating$.subscribe((update) => {
          if (!update) {
            this.store.dispatch(new LoadShoppingAction(this.shoppingService.getCart()));
            this.loadFormOrder();
            this.loadShopping();
          }
        }); */
    } else {
      this.loadFormOrder();
    }
  }

  async returnConfirmationCancelItem(result: any) {
    console.log('Item:' + this.itemSelect);
    this.openedConfirmationCancelItem = false;
    if (result) {
      this.store.dispatch(new DeleteItemAction(this.itemSelect.id));
      this.updating$.subscribe((update) => {
        if (!update) {
          this.store.dispatch(
            new LoadShoppingItemsAction(this.shoppingService.getCart())
          );
          this.store.dispatch(
            new LoadShoppingAction(this.shoppingService.getCart())
          );
          this.loadFormOrder();
        }
      });
    }
  }

  async returnAuthUser(userAuth: any) {
    this.openedAuthUser = false;
    console.log(userAuth);
    if (userAuth.id != null) {
      this.authService.getDiscount(userAuth.id).subscribe((result) => {
        this.percentAuth = result.data.discountUser;
        console.log('desconto autorizado: ' + this.percentAuth);
        const discountValue = Number.parseFloat(
          this.formResumeOrder.get('discount').value
        );
        if (discountValue === 0) {
          return;
        }
        const initialValue = 0;
        const orderValue = this.shoppingItems
          .filter((i) => i.promotion == null || i.promotion === 0)
          .reduce(
            (previousValue, item) =>
              previousValue + item.listPrice * item.quantity,
            initialValue
          );
        const percentOrder = (discountValue / orderValue) * 100;
        console.log('VALOR desconto pedido: ' + discountValue);
        console.log('VALOR DO pedido: ' + orderValue);
        console.log('desconto pedido: ' + percentOrder);
        if (percentOrder > this.percentAuth) {
          this.openInformation = true;
          this.loadFormOrder();
          return;
        }
        const order: OrderDiscount = {
          id: this.shoppingService.getCart(),
          percentDiscount: percentOrder,
          idUserAuth: userAuth.id,
        };
        this.store.dispatch(new ApplyDiscountOrderAction(order));
        this.updating$.subscribe((update) => {
          if (!update) {
            console.log('atualizando carrinho');
            this.store.dispatch(
              new LoadShoppingAction(this.shoppingService.getCart())
            );
            this.loadFormOrder();
          }
        });
      });
    } else {
      this.loadFormOrder();
    }
  }

  async returnDiscountItem(result: any) {
    this.showDiscountItem = false;
    if (result) {
      this.store.dispatch(
        new LoadShoppingItemsAction(this.shoppingService.getCart())
      );
      this.store.dispatch(
        new LoadShoppingAction(this.shoppingService.getCart())
      );
      this.loadFormOrder();
      this.calculateTaxDelivery(true);
    }
  }

  async getPercentAuth(id: number) {
    this.authService
      .getDiscount(id)
      .pipe(map((auth) => (this.percentAuth = auth.data.discountUser)));
  }

  closeInformation(close: boolean) {
    this.openInformation = close;
  }

  showDialogCreateCustomer() {
    this.showCreateCustomer = true;
  }

  async returnCreateCustomer(result: any) {
    this.showCreateCustomer = false;
    if (result != null) {
      this.updateFormCustomer(result);
    }
  }

  showDialogCreateAddress() {
    if (this.customer == null) {
      this.titleInformation = 'Cadastro de endereços';
      this.messageInformation =
        'Ops! Não existe cliente selecionado para a venda.';
      this.informationDescription =
        'Para cadastrar endereço de entrega é necessário selecionar um cliente.';
      this.showInformation = true;
      return;
    }
    this.showCreateAddress = true;
  }

  returnShowInformation() {
    this.showInformation = false;
  }

  async returnCreateAddress(result: any) {
    this.showCreateAddress = false;
    console.log('Retorno cadastro endereço: ' + result);
    if (result != null) {
      localStorage.setItem('address', JSON.stringify(result));
      this.updateFormAddress(result);
    }
  }

  public updateCart(
    cartId: string
  ) {
    console.log('Atualizando carrinho: ' + cartId);
    this.shoppingService.getShopping(cartId).subscribe((shopping) => {
      if (shopping) {
        console.log('Carrinho encontrado: ' + JSON.stringify(shopping));
        const invoiceStore = JSON.parse(
          localStorage.getItem('invoiceStore')
        ) as StoreERP;
        const customer = JSON.parse(localStorage.getItem('customer')) as Customer;
        const address = JSON.parse(
          localStorage.getItem('address')
        ) as CustomerAddress;
        const paymentPlan = JSON.parse(
          localStorage.getItem('paymentPlan')
        ) as PaymentPlan;
        const billing = JSON.parse(localStorage.getItem('billing')) as Billing;

        shopping.codcli = customer ? customer.customerId : 0;
        shopping.codendentcli = address ? address.idAddress : 0;
        shopping.saleStore = invoiceStore ? invoiceStore.id : this.authService.getStore();
        shopping.codplpag = paymentPlan ? paymentPlan.codplpag : 0;
        shopping.codcob = billing ? billing.codcob : '';

        this.shoppingService.updateShopping(shopping).subscribe(
          (response) => {
            console.log('Cart updated successfully:', response);
            this.store.dispatch(
              new LoadShoppingAction(this.shoppingService.getCart())
            );
            this.loadFormOrder();
          },
          (error) => {
            console.error('Error updating cart:', error);
          }
        );
      } else {
        console.error('Shopping cart not found for ID:', cartId);
      }
    });
  }

  showDialogSelectAddress() {
    if (this.customer == null) {
      this.titleInformation = 'Selecionar endereço de entrega';
      this.messageInformation =
        'Ops! Não existe cliente selecionado para a venda.';
      this.informationDescription =
        'Para cadastrar endereço de entrega é necessário selecionar um cliente.';
      this.showInformation = true;
      return;
    }
    this.showSelectAddress = true;
  }

  returnSelectAddress(result: any) {
    console.log(result);
    this.showSelectAddress = false;
    if (result != null) {
      localStorage.setItem('address', JSON.stringify(result));
      this.updateCart(this.shoppingService.getCart());
      this.updateFormAddress(result);
      this.updateTaxDelivery();
    }
  }

  updateFormAddress(address: any) {
    if (address.enderent != null) {
      this.formAddress.patchValue({
        address: address.enderent,
        number: address.numeroent,
        neighborhood: address.bairroent,
        complement: address.complementoent,
        city: address.municent,
        state: address.estent,
        zipCode: address.cepent,
        note: address.observacao,
        referencePoint: address.pontorefer,
      });
    } else {
      this.formAddress.patchValue({
        address: address.street,
        number: address.numberAddress,
        neighborhood: address.neighbourhood,
        complement: address.complement,
        city: address.city,
        state: address.state,
        zipCode: address.zipCode,
        note: address.note,
        referencePoint: address.referencePoint,
      });
    }
  }

  removeSelectAddress() {
    localStorage.removeItem('address');
    this.formAddress.reset();
    this.updateTaxDelivery();
  }

  confirmCreateOrder() {
    const dataDelivery = JSON.parse(
      localStorage.getItem('dataDelivery')
    ) as OrderDelivery;
    this.informationDelivery = '';

    if (dataDelivery !== null) {
      // const dateDelivery = new Date(dataDelivery.dateDelivery);
      const dateDelivery = new Date(this.formNotes.get('shippingDate').value);
      const dataTexto =
        dateDelivery.getDate().toString().padStart(2, '0') +
        '/' +
        (dateDelivery.getMonth() + 1).toString().padStart(2, '0') +
        '/' +
        dateDelivery.getFullYear().toString();

      this.informationDelivery = `Pedido com data de entrega para o dia
                    ${dataTexto}
                    - Tipo de entrega: ${dataDelivery.scheduleDelivery ? 'PROGRAMADA' : 'NORMAL'
        }`;
    }

    this.titleMessage = 'Gerar pedido de venda';
    this.messageConfirmation = 'Confirma a geração do pedido de venda?';
    this.informationDelivery = this.informationDelivery;
    this.textButtonConfirmation = 'Confirma';
    this.openedConfirmationOrder = true;
  }

  async createOrder(confirmOrder: boolean) {
    this.openedConfirmationOrder = false;
    this.isLoadingOrder = true;
    if (!confirmOrder) {
      this.isLoadingOrder = false;
      return;
    }
    if (!this.orderValid()) {
      this.isLoadingOrder = false;
      return;
    }
    const invoiceStore = JSON.parse(
      localStorage.getItem('invoiceStore')
    ) as StoreERP;
    const customer = JSON.parse(localStorage.getItem('customer')) as Customer;
    const preCustomer = JSON.parse(localStorage.getItem('preCustomer'));
    const address = JSON.parse(
      localStorage.getItem('address')
    ) as CustomerAddress;
    const paymentPlan = JSON.parse(
      localStorage.getItem('paymentPlan')
    ) as PaymentPlan;
    const billing = JSON.parse(localStorage.getItem('billing')) as Billing;
    const partner = JSON.parse(localStorage.getItem('partner')) as PartnerSales;

    if (invoiceStore === null) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Favor selecione uma filial de venda para o orçamento.';
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }
    if (customer === null) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Favor informe um cliente para gerar o orçamento de venda.';
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    if (this.formNotes.get('shippingDate').value === null) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Favor informe a data de entrega do pedido.';
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    let deliveryTime = 0;
    if (this.authService.getDeliveryTime() != null) {
      deliveryTime = Number.parseInt(this.authService.getDeliveryTime(), 10);
    }
    const deliveryDate = new Date();
    let Days = deliveryDate.getDate() + this.deliveryDays;
    if (this.formNotes.get('shippingPriority').value == 'M') {
      Days = deliveryDate.getDate() + this.retiraPosteriorDays;
    }
    deliveryDate.setDate(Days);
    const deliveryDateOnly = new Date(
      deliveryDate.getFullYear(),
      deliveryDate.getMonth(),
      deliveryDate.getDate()
    );

    if (
      Date.parse(this.formNotes.get('shippingDate').value) <
      Date.parse(deliveryDateOnly.toDateString())
    ) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription = `Data de entrega inferior ao período mínimo definido para entrega. (${this.deliveryDays} dias)`;
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    if (
      Date.parse(this.formNotes.get('shippingDate').value) ==
      Date.parse(deliveryDate.toDateString()) &&
      this.formNotes.get('scheduleDelivery').value == true
    ) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation =
        'Programação de entrega não permitida para a data de entrega informada!';
      this.informationDescription = `Para realizar a programação da entrega a data de entrega deve superior a ${deliveryTime} dias.`;
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    //validar itens com descrição diferente de ++ com cobrança CHM1
    if (billing.codcob == 'CHM1') {
      const chequeMoradiaItens = this.shoppingItems.filter((item) =>
        item.smallDescription.startsWith('++', 0)
      );
      if (chequeMoradiaItens.length < this.shoppingItems.length) {
        this.titleInformation = 'Pedido de venda';
        this.messageInformation =
          'Existem itens não permitidos para a cobrança utilizada.';
        this.informationDescription = `Existem produtos que não são permitidos serem vendidos na cobrança CHM1.`;
        this.showInformation = true;
        this.isLoadingOrder = false;
        return;
      }
    }

    const deliveryItens = this.shoppingItems.filter(
      (item) => item.deliveryType === 'EF' || item.deliveryType === 'EN'
    );
    const retiraItens = this.shoppingItems.filter(
      (item) => item.deliveryType === 'RP'
    );
    const taxValue = Number.parseFloat(
      this.formResumeOrder.get('taxValue').value
    );
    const user = this.authService.getUser();
    const supervisorId = this.authService.getSupervisor();

    const addressCustomer = JSON.parse(localStorage.getItem('address'));
    //    const customer = JSON.parse(localStorage.getItem('customer')) as Customer;
    const cityIds = [11289, 11298, 11348, 11280, 11383];

    let cityId = 0;
    let ibgeCode = 0;
    if (addressCustomer != undefined || addressCustomer != null) {
      cityId = addressCustomer.cityCode;
      ibgeCode = addressCustomer.ibgeCode;
    } else {
      cityId = customer.cityId;
      ibgeCode = Number.parseInt(customer.ibgeCode);
    }

    const authorizationTax = localStorage.getItem('authorizationTax');
    if (
      deliveryItens.length > 0 &&
      taxValue === 0 &&
      !(
        (supervisorId == 7 ||
          supervisorId == 14 ||
          supervisorId == 21 ||
          supervisorId == 22) &&
        cityIds.includes(cityId)
      ) &&
      this.formNotes.get('shippingPriority').value !== 'M' &&
      authorizationTax !== '1'
    ) {
      this.showConfirmUser = true;

      // this.titleInformation = 'Pedido de venda';
      // this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      // this.informationDescription = 'Existem items a serem entregues e não foi informado a taxa de entrega, para concluir o pedido informe a taxa de entrega.';
      //      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    const authorizationPartner = localStorage.getItem('authorizationPartner');
    if (partner != null && authorizationPartner !== '1') {
      this.userForm.reset();
      this.showAuthPartner = true;
      this.isLoadingOrder = false;
      return;
    }

    if (
      (deliveryItens.length > 0 || retiraItens.length > 0) &&
      customer.customerId === 1
    ) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Pedido para consumidor final com itens a serem entregues ou retira posterior, favor informar um cliente cadastrado.';
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    const itemRI = this.shoppingItems.filter(
      (item) =>
        item.deliveryType === 'RI' && item.stockStore !== invoiceStore.id
    );
    if (itemRI.length > 0) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Não foi possível gerar o pedido de venda!';
      this.informationDescription =
        'Existem items com tipo de entrega RETIRA IMEDIATA com a filial retira diferente da filial de faturamento.';
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    const itensNotDelivery = this.shoppingItems.filter(
      (item) => item.stockStore != '4' && item.stockStore != '6'
    );

    const placeId =
      addressCustomer != undefined || addressCustomer != null
        ? addressCustomer.placeId
        : customer.placeId;

    if (
      this.formNotes.get('shippingPriority').value == 'A' && //itensNotDelivery.length > 0 ||
      (this.totalWeight > 220 ||
        this.placesInterior.filter((p) => p.CODPRACA == placeId).length > 0)
    ) {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation =
        'Pedido não atende as regras para entrega DELIVERY!';
      this.informationDescription =
        'Pedido excede a 200 kg ou praça de entrega fora da região metropolitana (BELEM e ANANINDEUA).';
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    if (
      this.formNotes.get('shippingPriority').value == 'M' &&
      this.storePlaceSelected == null
    ) {
      this.showDeliveryStore = true;
      return;
    }

    const idAddress = address == null ? 0 : address.idAddress;
    const itensCart = await this.getItens();
    let preCadastroDocument = '';
    let preCadastroName = '';
    let preCadastroPhone = '';
    if (preCustomer !== null) {
      preCadastroDocument = preCustomer.document;
      preCadastroName = preCustomer.name;
      preCadastroPhone = preCustomer.phone;
    }
    const cart: CartModel = {
      id: this.shoppingService.getCart(),
      userId: this.authService.getUser(),
      saleStore: invoiceStore.id,
      idCustomer: customer.customerId,
      idPaymentPlan: paymentPlan.codplpag,
      idBilling: billing.codcob,
      idSeller: this.authService.getSeller(),
      idProfessional: partner != null ? partner.id : 0,
      scheduleDelivery: this.formNotes.get('scheduleDelivery').value,
      shippingDate: this.formNotes.get('shippingDate').value,
      shippingPriority: this.formNotes.get('shippingPriority').value,
      idStorePlace:
        this.formNotes.get('shippingPriority').value == 'M'
          ? this.storePlaceSelected.id
          : null,
      shippingValue: this.formResumeOrder.get('taxValue').value,
      idAddress,
      notation1: this.formNotes.get('notesText1').value,
      notation2: this.formNotes.get('notesText2').value,
      notation3: '',
      deliveryNote1: this.formNotes.get('notesDeliveryText1').value,
      deliveryNote2: this.formNotes.get('notesDeliveryText2').value,
      deliveryNote3: this.formNotes.get('notesDeliveryText3').value,
      itens: itensCart,
      preCustomerDocument:
        customer.customerId === 1 ? preCadastroDocument : null,
      preCustomerName: customer.customerId === 1 ? preCadastroName : null,
      preCustomerPhone: customer.customerId === 1 ? preCadastroPhone : null,
      carrierId: this.formResumeOrder.get('carrierId').value,
    };

    this.orderService
      .getProductsWithoutTax(localStorage.getItem('cart'), customer.customerId)
      .pipe(
        map((products) => {
          if (products.length > 0) {
            this.productsWithoutTax = products;
            this.isLoadingOrder = false;
            this.showProductsWithoutTax = true;
          } else {
            const result$ = this.orderService.create(cart);
            result$
              .pipe(
                map((result) => {
                  if (result.success) {
                    this.orderNumber = result.data.idOrder;
                    this.orderStatus = result.data.status;
                    this.openedModelPrintOrder = true;

                    /*this.titleInformation = 'Gravar pedido de venda';
                  this.messageInformation = 'Pedido de venda gerado com sucesso!';
                  this.informationDescription = `Número do pedido gerado: ${result.data.idOrder} com a posição ${result.data.status}`;
                  this.isLoadingOrder = false;
                  this.urlPrintOrder = 'http://10.1.1.205:8068/Viewer/{action}?orderId=' + this.orderNumber;
                  this.openedPrintOrder = true;
                  this.showInformationCreateOrder = true; */
                    // this.closeSale();
                  }
                }),
                catchError((err) => {
                  console.log(err);
                  this.titleInformation = 'Gravar pedido de venda';
                  this.messageInformation =
                    'Ops, houve um problema na geração do pedido de venda.';
                  this.informationDescription = err.error.message;
                  this.showInformation = true;
                  this.isLoadingOrder = false;
                  return of();
                })
              )
              .subscribe();
          }
        })
      )
      .subscribe();
  }

  orderValid() {
    const customer = JSON.parse(localStorage.getItem('customer')) as Customer;
    if (customer == null) {
      this.titleInformation = 'Gravar pedido de venda';
      this.messageInformation =
        'Atenção! Não foi informado um cliente para a venda.';
      this.informationDescription =
        'Para gerar um pedido de venda é necessário selecionar um cliente.';
      this.showInformation = true;
      return false;
    }
    const address = JSON.parse(
      localStorage.getItem('address')
    ) as CustomerAddress;
    const paymentPlan = JSON.parse(
      localStorage.getItem('paymentPlan')
    ) as PaymentPlan;
    if (paymentPlan == null) {
      this.titleInformation = 'Gravar pedido de venda';
      this.messageInformation =
        'Atenção! Não foi informado um plano de pagamento para a venda.';
      this.informationDescription =
        'Para gerar um pedido de venda é necessário selecionar um plano de pagamento para o pedido.';
      this.showInformation = true;
      return false;
    }
    const billing = JSON.parse(localStorage.getItem('billing')) as Billing;
    // Validar se foi informada a cobrança para venda //
    if (billing == null) {
      this.titleInformation = 'Gravar pedido de venda';
      this.messageInformation =
        'Atenção! Não foi informado uma cobrança para a venda.';
      this.informationDescription =
        'Para gerar um pedido de venda é necessário selecionar uma cobrança.';
      this.showInformation = true;
      return false;
    }

    return true;
  }

  editItem(item: any) {
    console.log(item);
    this.itemSelect = item;
  }

  selectItem(dataItem: any) {
    console.log('cart item selecionado : ' + JSON.stringify(dataItem));
    this.shoppingService.setShoppingItem(dataItem);
  }

  goSalesHome() {
    this.router.navigate(['sales/home']);
  }

  showModalProduct(item: ShoppingItem) {
    this.productService
      .getSaleProduct(this.authService.getStore(), item.idProduct)
      .subscribe((product) => {
        console.log(product);
        let resultProduct: any;
        const dialogRef: DialogRef = this.dialogService.open({
          content: ProductModalComponent,
        });
        const productInfo = dialogRef.content.instance as ProductModalComponent;
        productInfo.product = product;
        productInfo.shoppingItem = item;
        dialogRef.result.subscribe((result) => {
          if (result instanceof DialogCloseResult) {
            console.log('WindowCloseResult', result);
          } else {
            console.log('action', result);
            resultProduct = JSON.stringify(result);
            console.log(resultProduct);
            this.calculateTaxDelivery(true);
            this.messageService.showMessage(JSON.parse(resultProduct).message);
          }
        });
      });
  }

  logout() {
    this.shoppingService.cancelShopping();
    this.authService.logout();
  }

  closeDialogDiscountOrder() {
    this.showDialogDiscountOrder = false;
  }

  confirmDiscountOrder() {
    this.formResumeOrder.patchValue({
      discount: this.formDiscountOrder.get('discountValue').value,
    });
    this.showDialogDiscountOrder = false;
    const discountValue = Number.parseFloat(
      this.formResumeOrder.get('discount').value
    );
    const initialValue = 0;
    const orderValue = this.shoppingItems
      .filter((i) => i.promotion == null || i.promotion === 0)
      .reduce(
        (previousValue, item) => previousValue + item.listPrice * item.quantity,
        initialValue
      );
    let percentOrder = (discountValue / orderValue) * 100;
    console.log('Percentual do pedido: ' + percentOrder);
    // if (this.percentSeller < percentOrder) {
    //   this.openedAuthUser = true;
    //   return;
    // }
    if (discountValue <= 0.01) {
      percentOrder = 0;
    }
    const order: OrderDiscount = {
      id: this.shoppingService.getCart(),
      percentDiscount: percentOrder,
      idUserAuth: this.authService.getUser(),
    };
    this.store.dispatch(new ApplyDiscountOrderAction(order));
    // this.store.dispatch(new LoadShoppingAction(this.shoppingService.getCart())); // Reloader moved to Effect
    this.loadFormOrder();
    this.calculateTaxDelivery(true);
  }

  applyDiscountOrder() {
    const payment = JSON.parse(
      localStorage.getItem('paymentPlan')
    ) as PaymentPlan;
    if (payment == null) {
      this.titleInformation = 'Desconto para o pedido';
      this.messageInformation =
        'Venda sem plano de pagamento informado, desconto não permitido!';
      this.informationDescription =
        'Selecione primeiro um plano de pagamento para aplicar um desconto!';
      this.showInformation = true;
      return;
    }

    this.authService.getUser();
    if (payment.numdias > 30 && !this.authService.isManager()) {
      this.titleInformation = 'Desconto para o pedido';
      this.messageInformation =
        'Plano de pagamento parcelado, desconto não permitido!';
      this.informationDescription =
        'Desconto autorizado apenas para venda a vista ou em 1x no cartão!';
      this.showInformation = true;
      return;
    }

    this.userManager = false; //this.authService.isManager();
    let initialValue = 0;
    const productValue = this.shoppingItems
      .filter((i) => i.promotion == null || i.promotion === 0)
      .reduce(
        (previousValue, item) => previousValue + item.listPrice * item.quantity,
        initialValue
      );
    initialValue = 0;
    const profit = this.shoppingItems
      .filter((i) => i.promotion == null || i.promotion === 0)
      .reduce(
        (previousValue, item) => previousValue + item.cost * item.quantity,
        initialValue
      );
    let discount =
      this.formResumeOrder.get('discount').value != null
        ? Number.parseFloat(this.formResumeOrder.get('discount').value)
        : 0;
    // const productValue = (this.shopping.vlpedido + this.shopping.vldesconto);
    // const profit = (((productValue - this.shopping.vlcustofin)
    //  / productValue) * 100).toFixed(2);
    console.log('CABECALHO DA VENDA: ' + JSON.stringify(this.shopping));
    if (discount === 0) {
      discount = this.shopping.vldesconto;
    }
    console.log(`Total do pedido:  ${productValue}`);
    console.log(`valor de desconto:  ${discount}`);
    const percentProfit = (
      ((productValue - profit) / productValue) *
      100
    ).toFixed(2);
    const percent = Number.parseFloat(
      ((discount / productValue) * 100).toFixed(2)
    );
    const netValue = productValue - discount;
    const netProfit = (((netValue - profit) / netValue) * 100).toFixed(2);
    console.log(`valor profit:  ${profit}`);
    console.log(`valor de percent:  ${percent}`);
    console.log(`valor de netValue:  ${netValue}`);
    console.log(`valor de netProfit:  ${netProfit}`);

    this.formDiscountOrder.patchValue({
      value: Number.parseFloat(productValue.toFixed(2)),
      profit: percentProfit,
      discountValue: discount,
      discount: percent,
      netValue,
      netProfit,
    });
    if (productValue > 0) {
      this.showDialogDiscountOrder = true;
    } else {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation =
        'Não existem itens disponíveis para aplicar desconto !';
      this.informationDescription =
        'Não existem itens adicionados no carrinho ou todos os itens estão em promoção!';
      this.showInformation = true;
      return;
    }
    this.loadFormOrder();
  }

  calcDiscountOrderValue() {
    let initialValue = 0;
    const profit = this.shoppingItems
      .filter((i) => i.promotion == null || i.promotion === 0)
      .reduce(
        (previousValue, item) => previousValue + item.cost * item.quantity,
        initialValue
      );
    initialValue = 0;
    const valorTotal = this.shoppingItems
      .filter((i) => i.promotion == null || i.promotion === 0)
      .reduce(
        (previousValue, item) => previousValue + item.listPrice * item.quantity,
        initialValue
      );
    console.log(JSON.stringify(this.shoppingItems));
    if (valorTotal === 0) {
      return;
    }
    const percent = this.formDiscountOrder.get('discount').value;
    const discountValue = Number.parseFloat(
      (valorTotal * (percent / 100)).toFixed(2)
    );
    const salePrice = Number.parseFloat(
      (valorTotal - discountValue).toFixed(2)
    );
    const netProfit = (((salePrice - profit) / salePrice) * 100).toFixed(2);
    this.formDiscountOrder.patchValue({
      discountValue,
      netValue: salePrice,
      netProfit,
    });
  }

  calcPercentOrderDiscount() {
    const discountValue = this.formDiscountOrder.get('discountValue').value;
    let initialValue = 0;
    const profit = this.shoppingItems
      .filter((i) => i.promotion == null || i.promotion === 0)
      .reduce(
        (previousValue, item) => previousValue + item.cost * item.quantity,
        initialValue
      );
    const valorTotal = this.shoppingItems.reduce((acumulador, item) => {
      return acumulador + item.quantity * item.listPrice;
    }, 0);
    const percent = Number.parseFloat(
      ((discountValue / valorTotal) * 100).toFixed(2)
    );
    const salePrice = Number.parseFloat(
      (valorTotal - discountValue).toFixed(2)
    );
    const netProfit = (((salePrice - profit) / salePrice) * 100).toFixed(2);
    this.formDiscountOrder.patchValue({
      inputDiscount: percent,
      discount: percent,
      discountValue,
      netValue: salePrice,
      netProfit,
    });
  }

  selectModelPreOrder() {
    console.log(
      'selectModelPreOrder' + ' - ' + this.formModelPreOrder.get('model').value
    );
    this.modelPrintPreOrder = this.formModelPreOrder.get('model').value;
    this.openedModelPrintPreOrder = true;
  }

  closeModelPrintPreOrder(action: string) {
    console.log(
      `Dialog result: ${action}` +
      ' - ' +
      this.formModelPreOrder.get('model').value
    );
    this.openedModelPrintPreOrder = false;
    this.modelPrintPreOrder = this.formModelPreOrder.get('model').value;
    if (action === 'Sim') {
      this.openPrintPreOrder();
    }
  }

  closeModelPrintOrder(action: string) {
    this.openedModelPrintOrder = false;
    this.modelPrintOrder = this.formModelOrder.get('model').value;
    if (action === 'Sim') {
      this.openPrintOrder();
    }

    this.titleInformation = 'Gravar pedido de venda';
    this.messageInformation = 'Pedido de venda gerado com sucesso!';
    this.informationDescription = `Número do pedido gerado: ${this.orderNumber} com a posição ${this.orderStatus}`;
    this.showInformationCreateOrder = true;
  }

  closeModelPreCustomer(action: string) {
    console.log(
      `Dialog result: ${action}` + ' - ' + this.formPreCustomer.value
    );
    this.openedPreCustomer = false;
    if (action === 'Sim') {
      if (this.customer !== undefined && this.customer.customerId !== 1) {
        localStorage.setItem('customer', JSON.stringify(this.customer));
        this.updateCart(this.shoppingService.getCart());
        this.updateFormCustomer(this.customer);
      } else {
        localStorage.setItem(
          'preCustomer',
          JSON.stringify(this.formPreCustomer.value)
        );
        this.subscriptionCustomer = this.customerService
          .getCustomerByQuery('customerId', '1')
          .subscribe((data) => {
            if (data.length > 0) {
              this.updateFormCustomer(data[0]);
            }
          });
      }
    }
  }

  // Método para definir se é mobile e ajustar o modal
  checkDevice() {
    this.isMobile = window.innerWidth <= 768; // Define se é mobile

    if (this.isMobile) {
      this.windowWidth = window.innerWidth * 0.9; // 90% da largura da tela
      this.windowHeight = window.innerHeight * 0.8; // 80% da altura da tela
      this.windowTop = (window.innerHeight - this.windowHeight) / 2;
      this.windowLeft = (window.innerWidth - this.windowWidth) / 2;
    } else {
      this.windowWidth = 600;
      this.windowHeight = 500;
      this.windowTop = 100;
      this.windowLeft = (window.innerWidth - this.windowWidth) / 2;
    }
  }

  openPrintPreOrder() {
    // this.urlPrintPreOrder = 'http://localhost:52986//Viewer/{action}?order=' +
    this.urlPrintPreOrder =
      'http://172.35.0.219:8068/Viewer/{action}?order=' +
      this.preOrderNumber +
      '&model=' +
      this.modelPrintPreOrder;
    this.titleInformation = 'Gravar orçamento de venda';
    this.messageInformation = 'Orçamento gerado com sucesso!';
    this.informationDescription = `Número do orçamento gerado: ${this.preOrderNumber}`;
    this.showInformationCreateOrder = true;
    this.openedPrintPreOrder = true;
  }

  openPrintOrder() {
    // this.urlPrintPreOrder = 'http://localhost:52986//Viewer/{action}?order=' +
    this.urlPrintOrder =
      'http://172.35.0.219:8068/Viewer/{action}?orderId=' +
      this.orderNumber +
      '&model=' +
      this.modelPrintOrder;
    this.titleInformation = 'Gravar pedido de venda';
    this.messageInformation = 'Pedido de venda gerado com sucesso!';
    this.informationDescription = `Número do orçamento gerado: ${this.orderNumber}`;
    this.showInformationCreateOrder = true;
    this.openedPrintOrder = true;
    // this.windowState = 'default';
    this.checkDevice();
  }

  async searchCustomer() {
    const document = this.formPreCustomer.get('document').value;
    this.searchCustomerSubscription = this.customerService
      .getCustomerbyCpf(document)
      .subscribe((result) => {
        if (result.data != null) {
          this.formPreCustomer.patchValue({
            document: result.data.cpfCnpj,
            name: result.data.name,
            phone: result.data.cellPhone,
          });
          this.customer = result.data;
        }
      });
  }

  showPreCustomer() {
    let customer: any;
    const dataCustomer = localStorage.getItem('customer');
    customer = dataCustomer !== undefined ? JSON.parse(dataCustomer) : null;
    let preCustomer: any;
    if (localStorage.getItem('preCustomer')) {
      preCustomer = JSON.parse(localStorage.getItem('preCustomer'));
    }
    this.formPreCustomer.reset();
    if (
      customer === undefined ||
      customer === null ||
      customer.customerId === 1
    ) {
      if (preCustomer !== undefined && preCustomer !== null) {
        this.formPreCustomer.patchValue({
          document: preCustomer.document,
          name: preCustomer.name,
          phone: preCustomer.phone,
        });
      }
      this.openedPreCustomer = true;
    } else {
      this.titleInformation = 'Pedido de venda';
      this.messageInformation = 'Pedido / Orçamento já com cliente informado!';
      this.informationDescription =
        'Não é permitido realizar um pré-cadastro com cliente informado no pedido!';
      this.showInformation = true;
      return;
    }
  }

  isPreCustomer() {
    return localStorage.getItem('preCustomer') !== null;
  }

  closeProductsWithoutTax() {
    this.showProductsWithoutTax = false;
  }

  confirmationUser() {
    this.showConfirmUser = true;
  }

  closeConfirmUser() {
    const authUser: AuthUser = {
      email: this.userForm.get('userName').value,
      password: this.userForm.get('password').value,
    };

    this.authService
      .authenticate(authUser)
      .pipe(
        map((response) => {
          if (!response.success) {
            this.titleInformation = 'Autorizar pedido sem taxa de entrega';
            this.messageInformation = 'Usuário ou senha inválidos!';
            this.informationDescription =
              'Não foi possível autenticar este usuário, verifique seu usuario e senha!';
            this.showInformation = true;
            return;
          }

          const userDb = JSON.parse(JSON.stringify(response.data));

          if (userDb.sectorId != userDb.sectorManagerId) {
            console.log(
              `SectorId: ${userDb.sectorId} - SectorManagerId: ${userDb.sectorManagerId}`
            );
            this.titleInformation = 'Autorizar pedido sem taxa de entrega';
            this.messageInformation =
              'Usuário sem permissão para liberar pedido sem taxa de entrega!';
            this.informationDescription =
              'Apenas usuários do setor de GERENTE tem autorização para este processo!';
            this.showConfirmUser = false;
            this.showInformation = true;
            localStorage.removeItem('authorizationTax');
            return;
          }

          localStorage.setItem('authorizationTax', '1');
          const logOrder: LogOrder = {
            idCart: this.shopping.id,
            idUser: this.authService.getUser(),
            action: 'LIBERAR_TAXA_ENTREGA',
            iduserAuth: userDb.id,
            notation: this.userForm.get('notation').value,
          };
          this.shoppingService.createLogShopping(logOrder);
          this.showConfirmUser = false;
          this.createOrder(true);
        }),
        catchError((error) => {
          this.titleInformation = 'Autorizar pedido sem taxa de entrega';
          this.messageInformation = 'Usuário ou senha inválidos!';
          this.informationDescription =
            'Não foi possível autenticar este usuário, verifique seu usuario e senha!';
          this.showConfirmUser = false;
          this.showInformation = true;
          localStorage.removeItem('authorizationTax');
          return of();
        })
      )
      .subscribe();
  }

  calculateTaxDelivery(updateTax: boolean) {
    console.log(JSON.stringify(this.shoppingItems));
    const priorityDelivery = this.formNotes.get('shippingPriority').value;
    const itensDelivery = this.shoppingItems.filter(
      (item) => item.deliveryType == 'EN' || item.deliveryType == 'EF'
    );

    console.log('calculateTaxDelivery: ' + JSON.stringify(itensDelivery));

    if (itensDelivery.length === 0 || priorityDelivery === 'M') {
      this.formResumeOrder.patchValue({
        taxValue: 0,
      });
      this.returnConfirmationTax(true);
      return;
    }

    // Armazena o valor atual antes da chamada
    const currentTaxValue = Number.parseFloat(
      this.formResumeOrder.get('taxValue').value
    );

    const customer = JSON.parse(localStorage.getItem('customer')) as Customer;
    const addressCustomer = JSON.parse(localStorage.getItem('address'));
    const invoiceStore = JSON.parse(localStorage.getItem('invoiceStore'));
    const dataDelivery = JSON.parse(
      localStorage.getItem('dataDelivery')
    ) as OrderDelivery;

    let storeId =
      invoiceStore == null ? this.authService.getStore() : invoiceStore;
    let cityId = 0;
    let ibgeCode = 0;
    const cartId = localStorage.getItem('cart');

    if (addressCustomer != undefined && addressCustomer != null) {
      cityId = addressCustomer.cityCode;
      ibgeCode = addressCustomer.ibgeCode;
    } else {
      cityId = customer.cityId;
      ibgeCode = Number.parseInt(customer.ibgeCode);
    }
    const dataDeliveryTax = {
      cartId: cartId,
      cityId: cityId,
      ibgeCode: ibgeCode,
      priorityDelivery: priorityDelivery,
    };

    console.log('dataDeliveryTax', JSON.stringify(dataDeliveryTax));
    this.shoppingService.calculateDeliveryTax(dataDeliveryTax).subscribe(
      (result) => {
        this.dataDeliveryTax = result;
        console.log(JSON.stringify(this.shopping));
        if (result.length > 0) {
          // (updateTax || this.shopping.vltaxaentrega == undefined || this.shopping.vltaxaentrega == 0)) {
          if (this.shopping.codtabelafrete > 0) {
            const deliveryTaxSelected = result.find(
              (c) => c.id == this.shopping.codtabelafrete
            );
            if (deliveryTaxSelected != null) {
              this.formResumeOrder.patchValue({
                taxValue: deliveryTaxSelected.deliveryValue,
                deliveryTaxId: deliveryTaxSelected.id,
                carrierId: deliveryTaxSelected.carrierId,
              });
            } else {
              this.formResumeOrder.patchValue({
                taxValue: result[0].deliveryValue,
                deliveryTaxId: result[0].id,
                carrierId: result[0].carrierId,
              });
            }
          } else {
            this.formResumeOrder.patchValue({
              taxValue: result[0].deliveryValue,
              deliveryTaxId: result[0].id,
              carrierId: result[0].carrierId,
            });
          }
          this.returnConfirmationTax(true);
        }
      },
      (error) => {
        // Em caso de erro, notifica o usuário e mantém o valor original
        console.error('Erro ao calcular a taxa de entrega:', error);
        this.showErrorMessage(
          'Ocorreu um erro ao calcular a taxa de entrega. Por favor, tente novamente.'
        );
        this.formResumeOrder.patchValue({
          taxValue: currentTaxValue,
        });
        console.error('Erro ao calcular taxa de entrega:', error);
      }
    );
  }

  selectDeliveryTax(data: any) {
    const dataDeliveryTax = data.selectedRows[0].dataItem as DeliveryTaxTable;
    this.formResumeOrder.patchValue({
      taxValue: dataDeliveryTax.deliveryValue,
      deliveryTaxId: dataDeliveryTax.id,
      carrierId: dataDeliveryTax.carrierId,
    });
    this.returnConfirmationTax(true);
    this.showSelectDeliveryTax = false;
  }

  closeAuthPartner(action: boolean) {
    if (!action) {
      this.showAuthPartner = false;
      return;
    }
    const authUser: AuthUser = {
      email: this.userForm.get('userName').value,
      password: this.userForm.get('password').value,
    };

    this.authService
      .authenticate(authUser)
      .pipe(
        map((response) => {
          if (!response.success) {
            this.titleInformation = 'Autorizar parceiro da venda';
            this.messageInformation = 'Usuário ou senha inválidos!';
            this.informationDescription =
              'Não foi possível autenticar este usuário, verifique seu usuario e senha!';
            this.showAuthPartner = false;
            this.showInformation = true;
            localStorage.removeItem('authorizationPartner');
            return;
          }

          const userDb = JSON.parse(JSON.stringify(response.data));

          if (userDb.sectorId != userDb.sectorManagerId) {
            console.log(
              `SectorId: ${userDb.sectorId} - SectorManagerId: ${userDb.sectorManagerId}`
            );
            this.titleInformation = 'Autorizar parceiro da venda';
            this.messageInformation =
              'Usuário sem permissão para liberar parceiro da venda!';
            this.informationDescription =
              'Apenas usuários do setor de GERENTE tem autorização para este processo!';
            this.showAuthPartner = false;
            this.showInformation = true;
            localStorage.removeItem('authorizationPartner');
            return;
          }
          localStorage.setItem('authorizationPartner', '1');
          const logOrder: LogOrder = {
            idCart: this.shopping.id,
            idUser: this.authService.getUser(),
            action: 'AUTORIZAR_PARCEIRO_VENDA',
            iduserAuth: userDb.id,
            notation: '',
          };
          this.shoppingService.createLogShopping(logOrder);
          this.showAuthPartner = false;
          this.createOrder(true);
        }),
        catchError((error) => {
          this.titleInformation = 'Autorizar parceiro da venda';
          this.messageInformation = 'Usuário ou senha inválidos!';
          this.informationDescription =
            'Não foi possível autenticar este usuário, verifique seu usuario e senha!';
          this.showAuthPartner = false;
          this.showInformation = true;
          localStorage.removeItem('authorizationPartner');
          return of();
        })
      )
      .subscribe();
  }

  setStorePlace(storePlace: any) {
    console.log(storePlace);
    this.storePlaceSelected = storePlace;
  }

  closeDeliveryStore(action: boolean) {
    this.showDeliveryStore = false;
    if (action == false) {
      this.isLoadingOrder = false;
      return;
    }
    if (this.storePlaceSelected == null) {
      this.titleInformation = 'Selecionar loja de retirada';
      this.messageInformation =
        'Favor informar a loja que o cliente deseja retirar a mercadoria!';
      this.informationDescription = '';
      this.showInformation = true;
      this.isLoadingOrder = false;
      return;
    }

    this.createOrder(true);
  }

  calculateDeliveryTime() {
    const customer: Customer = JSON.parse(localStorage.getItem('customer'));
    const address: CustomerAddress = JSON.parse(
      localStorage.getItem('address')
    );
    const invoiceStore = JSON.parse(
      localStorage.getItem('invoiceStore')
    ) as StoreERP;
    const cartId = localStorage.getItem('cart');

    const saleDate = new Date();
    const saleYear = saleDate.getFullYear();
    const saleMonth = saleDate.getMonth() + 1;
    const day = saleDate.getDate();
    const stringDate =
      ('00' + day).slice(-2) +
      '-' +
      ('00' + saleMonth).slice(-2) +
      '-' +
      saleYear;
    console.log('Data atual: ' + stringDate);
    let deliveryDays = 0;
    this.shoppingService
      .getDeliveryDays(
        stringDate,
        invoiceStore == null ? this.authService.getStore() : invoiceStore.id,
        address != null
          ? address.placeId
          : customer != null
            ? customer.placeId
            : 0,
        cartId
      )
      .pipe(map((result) => (deliveryDays = result.deliveryDays)))
      .subscribe();
    return deliveryDays;
  }

  @HostListener('window:resize', ['$event'])
  onResize(event?: Event) {
    this.checkDevice();
  }
}
