<template>
  <div>
    <get-sales-consultant v-if="!isSalesConsultant || isPromoter" />

    <create-header />

    <b-row>
      <b-col md="9">
        <b-row>
          <b-col md="6">
            <search-product
              ref="searchProduct"
              :campaignId="campaignId"
              :disabled="campaignId == 0"
              v-model="productSelected"
            />
          </b-col>

          <b-col md="3" class="product-qty">
            <label class="label-qty" for="product-qty">Quantidade:</label>
            <input-qty
              :product="productSelected"
              :disabled="!productSelected"
              v-model=" qtyProduct"
            />
          </b-col>
          <b-col md="3" class="col-add-to-order">
            <label for="btn-add">&nbsp; _</label>
            <b-button
              id="btn-add"
              :disabled="!productSelected"
              @click="addProductToOrder"
              variant="primary"
              class="text-light"
            >
              <font-awesome-icon class="icon text-light" icon="shopping-basket" />Adicionar
            </b-button>
          </b-col>

          <b-col md="12">
            <order-products></order-products>
            <b-alert
              v-if="campaignId == 0"
              variant="danger"
              show
            >Sem campanha ativa para envio de Pedido</b-alert>
          </b-col>
        </b-row>
        <b-row>
          <b-col md="12" class="text-center go-to-payment">
            <b-button
              class="btn btn-primary radius-theme"
              @click="closeOrder"
              :disabled="campaignId == 0"
            >
              <font-awesome-icon class="icon" icon="shopping-basket" />Ir para pagamento
            </b-button>
          </b-col>
        </b-row>
      </b-col>

      <b-col md="3">
        <right-bar v-if="campaignId > 0"></right-bar>
      </b-col>
    </b-row>

    <show-last-time-offers-modal />
    <alert-limit-exceeded-modal />
    <alertQuantityLimitPerOrder />
    <alertStockLimit />
  </div>
</template>

<script>
import orderService from "@/services/resources/OrderService";

import createHeader from "./order-create/header";
import orderProducts from "./order-create/orderProducts";
import rightBar from "./order-create/rightBar";
import inputQty from "@/components/shared-components/inputs/inputQuantity";
import searchProduct from "./order-create/searchProduct";
import showLastTimeOffersModal from "@/components/modals/Order/showLastTimeOffers";
import alertLimitExceededModal from "@/components/modals/Order/alertLimitExceeded";
import alertQuantityLimitPerOrder from "@/components/modals/Order/alertQuantityLimitPerOrder"
import alertStockLimit from "@/components/modals/Order/alertStockLimit"
import getSalesConsultant from "@/components/orders/order-create/getSalesConsultant";
const OrderService = orderService.build();

export default {
  components: {
    createHeader,
    rightBar,
    orderProducts,
    inputQty,
    searchProduct,
    showLastTimeOffersModal,
    alertLimitExceededModal,
    getSalesConsultant,
    alertQuantityLimitPerOrder,
    alertStockLimit
  },
  data: () => {
    return {
      productSelected: null,
      qtyProduct: 1,
      suggestedProducts: [],
      saveOrderInterval: null
    };
  },
  computed: {
    campaignId() {
      let calendar = this.$store.state.orderCreate.calendar;

      if (calendar) {
        return calendar.campaign.id;
      }

      return 0;
    },
    sumSubTotal() {
      return this.$store.getters.getSumSubTotal;
    },
    isManagerSalesConsultant() {
      return this.$store.getters.isManagerSalesConsultant;
    },
    isSalesConsultant() {
      return this.$store.getters.isSalesConsultant;
    },
    isPromoter() {
      return this.$store.getters.isPromoter;
    }
  },
  watch: {
    sumSubTotal(newSumSubTotal) {
      if (
        newSumSubTotal > this.$store.state.orderCreate.credit_limit &&
        this.$store.state.orderCreate.payment_method === "BILLET"
      ) {
        this.$modal.show("alert-limit-exceeded");
      }
    }
  },
  methods: {
    closeOrder() {
        //this.saveOrder();
      if (this.$store.getters.getLastTimeOffers.length > 0) {
        this.$modal.show("show-last-time-offers");
        return;
      }

      this.$router.push({ name: "Checkout" });
    },

    addProductToOrder() {
      this.$store.dispatch("updateOrder", {
        product_per_campaign: this.productSelected,
        quantity: this.qtyProduct
      });

      this.qtyProduct = 1;

      this.productSelected = null;
      this.$refs.searchProduct.clear();
    },
    saveOrder() {
      this.$store.dispatch("saveOrder").catch(err => {
        vm.$fire({
          title: "Falha ao salvar Pedido",
          type: "error"
        });
      });
    },
    autoSaveOrder() {
      var vm = this;

      this.saveOrderInterval = window.setInterval(() => {
        vm.saveOrder();
      }, 30000);
    }
  },
  created() {
    var vm = this;
    if (this.$store.state.orderCreate.salesConsultantId > 0) {
      return;
    }

    if (this.isSalesConsultant && !this.isPromoter) {
      this.$store.dispatch("initOrderCreate").catch(err => {
        let resp = JSON.parse(err.response.data);
        vm.$fire({
          title: "Não é possível criar um pedido",
          text: resp.msg,
          type: "error"
        });
      });
    }

    this.$store.dispatch("setSalesConsultantIdOrderCreate");
  },
  mounted() {
   // this.autoSaveOrder();
  },
  beforeDestroy() {
    //clearInterval(this.saveOrderInterval);
  }
};
</script>


<style scoped lang="scss">
@import "@/assets/css/main.scss";
@import "@/assets/css/cards.scss";

.go-to-payment {
  margin-bottom: 20px;

  .btn {
    padding-right: 30px;
    .icon {
      margin-right: 30px;
    }
  }
}
.product-qty {
  label {
    display: block;
    text-align: left;
  }
}

.col-add-to-order {
  label {
    display: block;
    opacity: 0;
  }
  button {
    position: relative;
    display: block;
    width: 100%;
    border-radius: 20px;
    .icon {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      margin: auto 0 auto 4px;
      width: 32px;
      height: 32px;
      border-radius: 50%;
      padding: 6px;
    }
  }
}
</style>
