<template>
  <div style="margin-bottom: 20px">
    <b-row>
      <b-col>
        <b-row>
          <b-col md="9">
            <div class="row">
              <b-tabs
                class="col-md-12"
                @activate-tab="changePaymentMethod"
                content-class="mt-3"
                v-model="tabIndex"
              >
                <b-tab v-if="isSalesconsultant && !isPromotherInOtherOrder">
                  <template v-slot:title>
                    <b-form-radio
                      v-model="paymentMethod"
                      name="some-radios"
                      value="CREDIT_CARD"
                    >Cartão de Crédito</b-form-radio>
                  </template>
                  <credit-card-payment ref="creditCard" />
                </b-tab>

                <b-tab>
                  <template v-slot:title>
                    <b-form-radio
                      v-model="paymentMethod"
                      name="some-radios"
                      value="BILLET"
                    >Boleto Bancário</b-form-radio>
                  </template>

                  <p class="p-3">Seu Boleto Bancário será enviado dentro da Caixa.</p>
                </b-tab>
              </b-tabs>
            </div>

            <b-row class="actions">
              <b-col md="6" class="text-right">
                <b-button class="btn radius-theme go-to-back" @click="gotToBack">
                  <font-awesome-icon class="icon" icon="shopping-basket" />Voltar para o meu pedido
                </b-button>
              </b-col>
              <b-col md="6" class="text-left" v-if="paymentMethod == 'CREDIT_CARD'">
                <b-button
                  :disabled="loading"
                  class="btn btn-success radius-theme"
                  @click="payOrder"
                >
                  <b-spinner v-if="loading" type="grow" label="Spinning"></b-spinner>
                  <font-awesome-icon v-else class="icon" icon="dollar-sign" />Efeturar pagamento
                </b-button>
              </b-col>
              <b-col md="6" class="text-left" v-else>
                <b-button
                  :disabled="loading"
                  class="btn btn-success radius-theme"
                  @click="payWithBilletOrder"
                >
                  <b-spinner v-if="loading" type="grow" label="Spinning"></b-spinner>
                  <font-awesome-icon v-else class="icon" icon="save" />Salvar pedido
                </b-button>
              </b-col>
            </b-row>
          </b-col>

          <b-col class="show-list-order-products default-card" md="3">
            <b-row class="header">
              <b-col class="d-flex modal-text-color ml-2" cols="8">
                <div class="d-flex align-self-center justify-content-center rounded-div mr-2 mt-1">
                  <font-awesome-icon icon="shopping-basket" class="align-self-center" />
                </div>
                <div class="pt-1 text-left">
                  <div class="inline-block akkurat-regular min-header-text">Confira</div>
                  <div class="akkurat-bold max-header-text">Seu pedido</div>
                </div>
              </b-col>
            </b-row>

            <div class="list">
              <b-row v-for="product in orderProducts" :key="product.id">
                <b-col class="text-right" sm="2">
                  <img src="@/assets/PR_1.png" alt="foto_do_produto" height="45px" />
                </b-col>

                <b-col sm="10" class="text-left">
                  <span
                    class="name-product akkurat-bold-italic"
                  >{{product.product_per_campaign.product.name}}</span>
                  <br />
                  <span
                    class="details-product-order akkurat-light-regular"
                  >Qtd: {{product.quantity}} | R$ {{product.to_pay | formatCoin}}</span>
                </b-col>
              </b-row>
            </div>
            <hr color="#979797" />
            <b-row class="total-container">
              <b-col sm="6" class="text-left">
                <strong>Total:</strong>
              </b-col>
              <b-col sm="6" class="text-rigth">R$ {{total | formatCoin}}</b-col>
            </b-row>
          </b-col>
        </b-row>
      </b-col>
    </b-row>
    <modalRoulette />
  </div>
</template>

<script>
import CreditCardPayment from "@/components/shared-components/CreditCardPayment";
import { validationDate, validationCPF } from "@/utils/validation";
import modalRoulette from "@/components/modals/Order/RouletteIncentive";
export default {
  name: "checkout",
  components: {
    CreditCardPayment,
    modalRoulette
  },
  computed: {
    orderProducts() {
      return this.$store.getters.getOrder();
    },
    total() {
      return this.$store.getters.getTotalToPay;
    },
    isSalesconsultant() {
      return this.$store.getters.isSalesConsultant;
    },
    isPromotherInOtherOrder() {
      return this.$store.getters.isPromotherInOtherOrder;
    },
    paymentMethod: {
      get() {
        return this.$store.state.orderCreate.payment_method;
      },
      set(value) {}
    },
   computedOrder(){
      return  this.$store.state.orderCreate;
    }
  },
  data: () => {
    return {
      pagSeguro: {
        hash: null,
        brand: null,
        creditCardToken: null
      },
      tabIndex: 0,
      loading: false,
      resultSaveOrder: null
    };
  },
  methods: {
    changePaymentMethod(newTab, prevTab, event) {
      let methods = ["CREDIT_CARD", "BILLET"];

      var method = methods[newTab];

      if (
        this.$store.getters.getMinOrderAmount >
          this.$store.state.orderCreate.credit_limit &&
        method === "BILLET"
      ) {
        this.$fire({
          title: "Limite de crédito excedido!",
          text: "Sua compra pode ser finalizada apenas com cartão de crédito.",
          type: "warning"
        });
        this.$store.dispatch("setPaymentMethod", {
          payment_method: "CREDIT_CARD"
        });
        event.preventDefault();
        this.tabIndex = 0;
        console.log("change" + this.tabIndex);
        return;
      }
      this.$store.dispatch("setPaymentMethod", { payment_method: method });
    },

    gotToBack() {
      this.$router.push({ name: "Digitar Pedido" });
    },
    async payOrder() {
      //useing Credit card
      try {
        var vm = this;
        this.loading = true;
        if (!validationDate(this.$store.state.pagSeguro.birthDate)) {
          this.$fire({
            title: "",
            type: "error",
            text: "Data de Nascimento inválida"
          });

          throw "Data de Nascimento inválida";
        } else if (!validationCPF(this.$store.state.pagSeguro.cpf)) {
          this.$fire({
            title: "",
            type: "error",
            text: "CPF Inválido"
          });

          throw "CPF Inválido";
        }

        let resp = await this.$refs.creditCard.setToken();
        let payOrderPagSeguro = await this.$store
          .dispatch("PayOrderWithCreditCard")
          .catch(err => {
            const resp = JSON.parse(err.response.data);

            vm.$fire({
              title: "Erro ao enviar pedido",
              type: "error",
              text: resp.msg
            });

            throw resp.msg;
          });
        
        await this.$fire({
            title: "Pedido salvo com sucesso",
            type: "success"
          });

        this.loading = false;
        this.$router.push({ name: "Digitar Pedido" });

        if (this.$store.getters.isSalesConsultant) {
          this.$router.push({ name: "Meus Pedidos" });
        } else {
          this.$store.dispatch("resetOrderCreate");
        }
      } catch (error) {
        this.loading = false;
        console.error(error);
      }
    },
    async payWithBilletOrder() {
      if (
        this.$store.getters.getMinOrderAmount >
          this.$store.state.orderCreate.credit_limit &&
        this.$store.state.orderCreate.payment_method === "BILLET"
      ) {
        this.$fire({
          title: "Limite de crédito excedido!",
          text: "Sua compra pode ser finalizada apenas com cartão de crédito.",
          type: "warning"
        });
        return;
      }

      try {
        var vm = this;
        this.loading = true;
        await this.$store.commit("setStatus", "CLOSED");
        await this.saveOrder();
        

        if (this.$store.getters.isSalesConsultant) {
          await this.$fire({
            title: "Pedido salvo com sucesso",
            type: "success"
          });
          this.loading = false;
          this.$store.dispatch("resetOrderCreate");
          this.$router.push({ name: "Meus Pedidos" });
        } else {
         
          await this.$fire({
            title: "O pedido "+this.computedOrder.orderId+" da consultora "+this.computedOrder.salesConsultant.code+" foi criado com sucesso em " +
            this.$options.filters.formatDateTimeDDMMAAAA( this.resultSaveOrder.data.updated_at),
            type: "success"
          });
          this.loading = false; 
          this.$store.dispatch("resetOrderCreate");
          this.$router.push({ name: "Digitar Pedido" });
        }
      } catch (err) {
        console.log(err)
        vm.loading = false;
      }
    },
    async saveOrder() {
      var vm = this;
      await this.$store.dispatch("saveOrder").then( resp => vm.resultSaveOrder = resp )
      .catch(err => {
        const resp = JSON.parse(err.response.data);
        console.log(resp);
        vm.$fire({
          title: "Erro ao enviar pedido",
          type: "error",
          text: resp.msg
        });

        throw resp.msg;
      });
    }
  },
  created() {
    this.$store.dispatch("initPagSeguro");
  },
  async mounted() {
   // this.saveOrder();
    this.$modal.show("show-roulette-incentive");

    if (
      this.$store.getters.getNeedMinOrderToClass >
      this.$store.getters.getMinOrderAmount
    ) {
      await this.$fire({
        title: "Você ainda não atingiu o pedido mínimo.",
        text: "Continue a digitar seu pedido.",
        icon: "warning"
      });

      this.$router.push({ name: "Digitar Pedido" });
    }

    if (
      this.$store.getters.getMinOrderAmount >
        this.$store.state.orderCreate.credit_limit &&
      this.$store.state.orderCreate.payment_method === "BILLET"
    ) {
      this.$fire({
        title: "Limite de crédito excedido!",
        text: "Sua compra pode ser finalizada apenas com cartão de crédito.",
        type: "warning"
      });
    }
    this.tabIndex =
      this.$store.state.orderCreate.payment_method === "BILLET" ? 1 : 0;
  }
};
</script>

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

.show-list-order-products {
  .header {
    color: #3e3e3e;
    margin-top: 10px;
    .rounded-div {
      background-color: #edc52680;
    }
    svg {
      color: #edc526;
    }
    .modal-text-color {
      margin-left: 0px !important;
    }
    .min-header-text {
      letter-spacing: 0.2px;
      font-size: 9px;
    }

    .max-header-text {
      letter-spacing: 0.4px;
      font-size: 16px;
    }
  }

  .list {
    margin-top: 15px;
    overflow-y: auto;
    overflow-x: hidden;
    max-height: 200px;

    &::-webkit-scrollbar-track {
      background: #ffffff 0% 0% no-repeat padding-box;
      border: 0.5px solid #707070;
      border-radius: 2px;
    }

    &::-webkit-scrollbar {
      width: 4px;
      background: #ffffff 0% 0% no-repeat padding-box;
      border: 0.5px solid #707070;
      border-radius: 2px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #707070;
      border: 0.5px solid #707070;
      border-radius: 2px;
    }

    .name-product {
      font: Bold Italic 12px/15px BressayW01;
      letter-spacing: 0px;
      color: #3e3e3e;
    }
    .details-product-order {
      text-align: left;
      font-size: 12px;
      letter-spacing: 0px;
      color: #2c2c2c;
    }
  }

  .total-container {
    margin-top: 10px;
    margin-bottom: 10px;
  }
}

.actions {
  margin-bottom: 20px;
  margin-top: 20px;
  .btn {
    padding-right: 30px;

    .icon {
      margin-right: 30px;
    }
  }

  .go-to-back {
    background-color: #275389;
    border-color: #275389;
    box-shadow: none;
    &:active {
      background-color: #164b8c !important;
      border-color: #164b8c !important;
    }
  }
}

.tab-content {
  margin-top: 0px !important;
}
.nav-tabs .nav-link.active,
.nav-tabs .nav-item.show .nav-link {
  background-color: #fff !important;
}

.nav .nav-tabs {
  position: relative;
}

li.nav-item:nth-child(1) {
  width: 50%;
}
.presentation {
  li.nav-item:nth-child(2) {
    border-left: solid 9px #ededed;

    width: 50%;
  }
}

.li.nav-item {
  text-align: left;
}
.presentation {
  .nav-link {
    background-color: #fff !important;
    background: $theme-color-white;
    border: none !important;
    border-radius: 0px $middle-border-radius 0px 0px;
  }
}

.tab-content {
  background: $theme-color-white;
  box-shadow: $box-shadow;
  border-radius: $middle-border-radius;
}
.tab-pane {
  padding: 20px 20px;
  background-color: #fff;
}
</style>