<template>
  <tbody>
    <tr v-if="isSalesConsultant">
      <td>{{order.id}}</td>
      <td>{{order.campaign.name}}</td>
      <td>{{ (order.campaign_benchmarking_range != null)? order.campaign_benchmarking_range.name : ""}}</td>
      <td>{{order.created_at | formatDateTimeDDMMAAAA}}</td>
      <td style="white-space: nowrap;">{{ totalItens(order.itens)}}</td>
      <td style="white-space: nowrap;">R$ {{amountCatalog(order.itens) | formatCoin}}</td>
      <td style="white-space: nowrap;">R$ {{parseFloat(order.amount_total) | formatCoin}}</td>
      <td style="white-space: nowrap;">R$ {{amountCatalog(order.itens) - parseFloat(order.amount_total)| formatCoin}}</td>
      <td>{{STATUS_PEDIDO[order.status]}}</td>
      <td>
        <font-awesome-icon :icon="PAYMENT_METHOD[order.payment_method]" />
      </td>
      <td>
        <a v-if="loadingLink != order.id" href="#" @click.prevent="print(order.id)">
          <font-awesome-icon icon="print" />
        </a>
        <b-spinner v-else type="grow" label="Loading..."></b-spinner>
      </td>
       <td>
        <a
          v-if="deletingOrder != order.id && (order.status == 'TYPED' || order.status=='CLOSED' && order.payment_method == 'BILLET')"
          v-b-popover.hover="'Excluir pedido'"
          href="#"
          @click.prevent="deleteOrder(order.id)"
        >
          <font-awesome-icon icon="trash" />
        </a>
        <b-spinner v-else-if="deletingOrder == order.id" type="grow" label="Loading..."></b-spinner>
      </td>
    </tr>
    <tr v-else>
      <td>{{order.id}}</td>
      <td>{{order.campaign.name}}</td>

      <td>Grupo*</td>
      <td>{{order.sales_consultant.sector.division.region.name}}</td>
      <td style="white-space: nowrap;">{{order.sales_consultant.sector.division.name}}</td>
      <td>{{order.sales_consultant.sector.name}}</td>
      <td>{{order.sales_consultant.code}}</td>
      <td style="white-space: nowrap;">{{order.sales_consultant.name}}</td>
      <td>{{ (order.campaign_benchmarking_range != null)? order.campaign_benchmarking_range.name : ""}}</td>
      <td>{{order.created_at | formatDateTimeDDMMAAAA}}</td>
      <td style="white-space: nowrap;">{{ totalItens(order.itens)}}</td>
      <td style="white-space: nowrap;">R$ {{amountCatalog(order.itens) | formatCoin}}</td>
      <td style="white-space: nowrap;">R$ {{parseFloat(order.amount_total) | formatCoin}}</td>
      <td style="white-space: nowrap;">R$ {{amountCatalog(order.itens) - parseFloat(order.amount_total)| formatCoin}}</td>
      <td>{{STATUS_PEDIDO[order.status]}}</td>
      <td>
        <font-awesome-icon :icon="PAYMENT_METHOD[order.payment_method]" />
      </td>
      <td>
        <a v-if="loadingLink != order.id" v-b-popover.hover="'Detalhar'" href="#" @click.prevent="print(order.id)">
          <font-awesome-icon icon="print" />
        </a>
        <b-spinner v-else type="grow" label="Loading..."></b-spinner>
      </td>
      <td>
        <a
          v-if="deletingOrder != order.id && (order.status == 'TYPED' || order.status=='CLOSED' && order.payment_method == 'BILLET')"
          v-b-popover.hover="'Excluir pedido'"
          href="#"
          @click.prevent="deleteOrder(order.id)"
        >
          <font-awesome-icon icon="trash" />
        </a>
        <b-spinner v-else-if="deletingOrder == order.id" type="grow" label="Loading..."></b-spinner>
      </td>
    </tr>
  </tbody>
</template>

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

const service = impressService.build();

const PAYMENT_METHOD = {
  CREDIT_CARD: "credit-card",
  BILLET: "barcode"
};

const STATUS_PEDIDO = {
  TYPED: "Aberto",
  CLOSED: "Fechado",
  AWAITING_ANALYSIS: "Em análise",
  AWAITING_PAYMENT: "Aguardando Pgto",
  PROCESSING: "Em processamento",
  AWAITING_NF: "Aguardando NF",
  TRANSPORT: "Em transporte",
  DELIVERED: "Entregue"
};

export default {
  name: "orders-info-card",
  props: {
    order: {
      type: Object
    }
  },
  data: () => {
    return {
      PAYMENT_METHOD,
      STATUS_PEDIDO,
      loadingLink: 0,
      deletingOrder: 0
    };
  },
  computed: {
    isSalesConsultant() {
      return this.$store.getters.isSalesConsultant;
    }
  },
  methods: {
    amountCatalog(itens) {
      let total = itens.reduce(
        (total, current) =>
          total + (current.pivot.unitary_value * current.pivot.quantity || 0),
        0
      );

      return parseFloat(total);
    },
    totalItens(itens) {
      var total = 0;

      itens.forEach(item => (total += item.pivot.quantity));

      return total;
    },
    print(id) {
      var vm = this;
      this.loadingLink = id;
      service
        .getLink({
          view: "Order",
          id: id
        })
        .then(resp => {
          window.open(
            process.env.VUE_APP_API_HOST + "/api/impress/" + resp.resource,
            "_blank"
          );
          vm.loadingLink = 0;
        })
        .catch(err => {
          vm.loadingLink = 0;
        });
    },
    async deleteOrder(orderId) {
      var vm = this;
      var confirm = false;
      let serviceOrder = orderService.build();

     await this.$fire({
       title: "Excluir Pedido "+orderId,
        text: "Você realmente deseja realizar essa operação?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "Sim, excluir!",
        cancelButtonText: 'Cancelar',
      }).then(result => {
        if (result.value) {
         
         confirm = true;
        }
      });

if(!confirm){

  return;
}

      vm.deletingOrder = orderId;
      await serviceOrder
        .destroy({ id: orderId })
        .then(resp => {
          vm.$fire({
            title: "Pedido deletado com sucesso",
            type: "success"
          });
          vm.deletingOrder = 0;
          vm.$emit('deleted');
        })
        .catch(err => {
          vm.deletingOrder = 0;

           let resp = JSON.parse(err.response.data);
          vm.$fire({
            title: "Falha ao deletar pedido.",
            text: resp.msg,
            type: "error"
          });
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.product-card {
  border-radius: 5px;
  background: white;
  height: 49px;
  box-shadow: 0px 0px 4px #00000022;
}

.product-name {
  font-size: 0.9em;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ref-tag {
  font-size: 0.8em;
  color: #5a5a5a;
  letter-spacing: 0.35px;
}

.min-text {
  font-size: 0.625rem;
}
</style>
