<template>
  <div class="col-8 col-md-8 col-sm-12 col-xs-12">
    <q-card class="q-ma-sm" elevated bordered>
      <q-card-section>
        <div class="text-h5 text-grey-8 text-bold text-center">Payment Details</div>
      </q-card-section>
      <q-tabs
        v-model="tab"
        dense
        class="text-grey"
        active-color="primary"
        indicator-color="primary"
        align="justify"
        narrow-indicator
      >
        <q-tab name="creditcard" label="Credit Card" />
        <q-tab name="paypal" label="PayPal" />
      </q-tabs>

      <q-separator />

      <q-tab-panels v-model="tab" animated>
        <q-tab-panel name="creditcard">
          <q-form ref="checkoutForm" @submit="checkout" class="q-gutter-md">
            <div class="row">
              <div class="col-12 col-md-6 col-sm-12 col-xs-12 q-pa-xs">
                <q-input
                  outlined
                  dense
                  v-model="form.name"
                  label="Card Holder Name *"
                  placeholder="Enter Card Holder Nam"
                  lazy-rules
                  :rules="[ val => val && val.length > 0 || 'Please type card holder name']"
                />
              </div>
              <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                <q-input
                  outlined
                  dense
                  v-model="form.address"
                  label="Street Address *"
                  placeholder="Enter Street Address"
                  lazy-rules
                  :rules="[ val => val && val.length > 0 || 'Please type address']"
                />
              </div>
              <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                <q-input
                  outlined
                  dense
                  v-model="form.address_2"
                  label="Street Address 2 "
                  placeholder="Enter Street Address 2"
                />
              </div>
            </div>
            <div class="row">
              <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                <q-input
                  outlined
                  dense
                  v-model="form.city"
                  label="City *"
                  placeholder="Type your city name"
                  lazy-rules
                  :rules="[ val => val && val.length > 0 || 'Please type city']"
                />
              </div>
              <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                <q-input
                  outlined
                  dense
                  v-model="form.state"
                  label="State *"
                  lazy-rules
                  :rules="[ val => val && val.length > 0 || 'Please type state']"
                />
              </div>
              <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                <q-input
                  outlined
                  dense
                  number
                  mask="#####"
                  maxlength="5"
                  v-model="form.zip_code"
                  label="Zip Code *"
                  placeholder="Zip code i.e 75600"
                  lazy-rules
                  :rules="validateZipCode"
                />
              </div>
              <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                <q-select
                  clearable
                  dense
                  outlined
                  v-model="form.country"
                  :options="countriesList"
                  emit-value
                  map-options
                  label="Country"
                  lazy-rules
                  :rules="[ val => val && val.length > 0 || 'Please Select Country']"
                />
              </div>
            </div>
            <div class="row">
              <div class="col-12 col-md-5 q-pa-xs">
                <q-input
                  dense
                  outlined
                  v-model="form.email"
                  label="Email Address *"
                  placeholder="Enter Email Address"
                  lazy-rules
                  :rules="validateEmail"
                />
              </div>
              <div class="col-12 col-md-7 q-pa-xs">
                <q-input
                  dense
                  outlined
                  number
                  mask="################"
                  v-model="form.phone"
                  label="Mobile Number *"
                  placeholder="Please enter mobile number"
                  lazy-rules
                  :rules="validateMobileNumber"
                />
              </div>
            </div>
            <div class="row">
              <div class="col-12 col-md-12 q-pa-xs">
                <q-input
                  mask="################"
                  dense
                  outlined
                  number
                  v-model="card.ccNo"
                  label="Credit Card Number (should be 16 digits) *"
                  placeholder="Please enter credit card number 1234 5678 9012 3456"
                  lazy-rules
                  :rules="validateCreditCard"
                />
              </div>
            </div>
            <div class="row">
              <div class="col-12 col-md-4 q-pa-xs">
                <q-input
                  outlined
                  dense
                  number
                  maxlength="2"
                  mask="##"
                  v-model="card.expMonth"
                  label="Expiry Month *"
                  placeholder="Enter Expiry Month"
                  lazy-rules
                  :rules="validateExpMonth"
                />
              </div>
              <div class="col-12 col-md-4 q-pa-xs">
                <q-input
                  outlined
                  dense
                  number
                  maxlength="2"
                  mask="##"
                  v-model="card.expYear"
                  label="Expiration Year *"
                  placeholder="Enter Expiry Year"
                  lazy-rules
                  :rules="validateExpYear"
                />
              </div>
              <div class="col-12 col-md-4 q-pa-xs">
                <q-input
                  outlined
                  dense
                  number
                  maxlength="4"
                  mask="####"
                  v-model="card.cvc"
                  label="CVC Number *"
                  placeholder="Enter CVC Number"
                  lazy-rules
                  :rules="validateCvc"
                />
              </div>
              <div class="col-12">
                <q-btn
                  :loading="isRequestInProgress"
                  color="primary"
                  class="full-width"
                  label="Checkout"
                  type="submit"
                >
                  <template v-slot:loading>
                    <q-spinner-hourglass class="on-left" />processing...
                  </template>
                </q-btn>
              </div>
            </div>
          </q-form>
        </q-tab-panel>

        <!-- <q-tab-panel name="paypal">
            <form @submit.prevent.stop="onSubmit" @reset.prevent.stop="onReset" class="q-gutter-md">
              <div class="row">
                <div class="col-12 col-md-6 col-sm-12 col-xs-12 q-pa-xs">
                  <q-input
                    ref="name"
                    outlined
                    dense
                    v-model="name"
                    label="Card Holder Name *"
                    hint="Card Holder Name must be minimum 2 letters"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Card Holder Name is required']"
                  />
                </div>
                <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                  <q-input
                    ref="street"
                    outlined
                    dense
                    v-model="street"
                    label="Street Name 1 *"
                    hint="Enter street name 1"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Please type street name']"
                  />
                </div>
                <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                  <q-input
                    ref="street"
                    outlined
                    dense
                    v-model="street2"
                    label="Street Name 2 *"
                    hint="Enter street name 2"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Please type street name']"
                  />
                </div>
              </div>
              <div class="row">
                <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                  <q-input
                    ref="city"
                    outlined
                    dense
                    v-model="city"
                    label="City *"
                    hint="Type your city name"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Please type city']"
                  />
                </div>
                <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                  <q-input
                    ref="state"
                    outlined
                    dense
                    v-model="state"
                    label="State *"
                    hint="Type your state name"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Please type state']"
                  />
                </div>
                <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                  <q-input
                    ref="zip"
                    outlined
                    dense
                    type="number"
                    mask="#####"
                    maxlength="5"
                    v-model="zip"
                    label="Zip Code *"
                    hint="Zip code i.e 75600"
                  />
                </div>
                <div class="col-12 col-md-3 col-sm-12 col-xs-12 q-pa-xs">
                  <q-select dense outlined v-model="country" :options="options" label="Country" />
                </div>
              </div>
              <div class="row">
                <div class="col-12 col-md-5 q-pa-xs">
                  <q-input
                    dense
                    outlined
                    v-model="email"
                    label="Email Address *"
                    hint="abc@domain.com"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Please type something']"
                  />
                </div>
                <div class="col-12 col-md-7 q-pa-xs">
                  <q-input
                    mask="(###) ### - ####"
                    dense
                    outlined
                    number
                    v-model="phone"
                    label="Mobile Number (should be 11 digits) *"
                    hint="Please enter mobile number (###) ### - ####"
                    lazy-rules
                    :rules="[ val => val && val.length > 0 || 'Please type phone number']"
                  />
                </div>
              </div>
              <div class="row">
                <div class="col-12">
                  <q-btn color="primary" class="full-width">Submit Order</q-btn>
                </div>
              </div>
            </form>
        </q-tab-panel>-->
      </q-tab-panels>
    </q-card>
  </div>
</template>
<script>
export default {
  props: ["cart", "cartTotal",'currency','rate'],
  data() {
    return {
      form: {
        token: "",
        name: "",
        address: "",
        address_2: "",
        city: "",
        state: "",
        zip_code: "",
        phone: "",
        email: "",
        country: "",
        rate:1
      },
      card: {
        cvc: "",
        ccNo: "",
        expMonth: "",
        expYear: "",
      },
      countriesList: [],
      isRequestInProgress: false,
      tokenError: false,
      formAlert: null,
      tab: "creditcard"
    };
  },
  computed: {
    country() {
      if (this.form.country) {
        return this.countriesList.find((e) => e.value == this.form.country);
      }
      return null;
    },
    validateMobileNumber() {
      return [
        (val) => {
          if (!val || val.length === 0) {
            return "Please type mobile number";
          }
          return true;
        },
      ];
    },
    validateZipCode() {
      return [
        (val) => {
          if (!val || val.length === 0) {
            return "Please type zip code";
          }
          if (val.length != 5) {
            return "Zip code must be 5 digits";
          }
          return true;
        },
      ];
    },
    validateEmail() {
      const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return [
        (val) => {
          if (!val || val.length === 0) {
            return "Please type email address";
          }
          if (!re.test(String(val).toLowerCase())) {
            return "Please type valid email address";
          }
          return true;
        },
      ];
    },
    validateCreditCard() {
      return [
        (val) => {
          if (!val || val.length === 0) {
            return "Please type credit card number";
          }
          if (val.length != 16) {
            return "Credit card number must be 16 digits";
          }
          return true;
        },
      ];
    },
    validateExpMonth() {
      return [
        (val) => {
          if (!val || val.length === 0) {
            return "Please type credit card expiration month";
          }
          if (val.length != 2) {
            return "Credit card expiration month must be 2 digits";
          }
          if (parseInt(val, 10) > 12) {
            return "Please type a valid month (1-12)";
          }
          return true;
        },
      ];
    },
    validateExpYear() {
      return [
        (val) => {
          if (!val || val.length === 0) {
            return "Please type credit card expiration year";
          }
          if (val.length != 2) {
            return "Credit card expiration year must be 2 digits";
          }
          return true;
        },
      ];
    },
    validateCvc() {
      return [
        (val) => {
          if (!val || val.length === 0) {
            return "Please type credit card cvc";
          }
          if (val.length < 3 || val.length > 4) {
            return "Credit card cvc must be 3 or 4 digits";
          }
          return true;
        },
      ];
    },
  },
  mounted() {
    setTimeout(() => {
      try {
        TCO.loadPubKey();
      } catch (error) {
        console.log(error);
        this.formAlert = this.$q.notify({
          message: "Error",
          type: "error-notify",
          timeout: 0,
          caption: "Paymet gateway is not working.Please contact support",
        });
      }
    }, 2000);

    this.fetchCountriesList();
  },
  methods: {
    checkout() {
      this.isRequestInProgress = true;
      this.$refs.checkoutForm
        .validate()
        .then((success) => {
          if (success) {
            if (this.formAlert) {
              this.formAlert();
            }
            this.tokenRequest();
          } else {
            this.isRequestInProgress = false;
            if (this.formAlert) {
              this.formAlert();
            }
            this.formAlert = this.$q.notify({
              message: "Error",
              type: "error-notify",
              caption: "Please fix the errors in the form and try again...",
            });
          }
        })
        .catch((e) => {
          this.isRequestInProgress = false;
        });
    },
    tokenRequest: function () {
      let ccNo = this.card.ccNo;
      let cvc = this.card.cvc;
      let expMonth = this.card.expMonth;
      let expYear = this.card.expYear;

      // Setup token request arguments
      var args = {
        sellerId: "1543032",
        publishableKey: "F62B7366-50B3-48CA-B804-8E00DEC4762B",
        ccNo: ccNo,
        cvv: cvc,
        expMonth: expMonth,
        expYear: expYear,
      };

      // Make the token request
      TCO.requestToken(this.successCallback, this.errorCallback, args);
    },
    errorCallback: function (data) {
      // Retry the token request if ajax call fails
      this.isRequestInProgress = false;
      console.log(data);
      if (data.errorCode === 200) {
        this.formAlert = this.$q.notify({
          message: "Error",
          type: "error-notify",
          caption: "Request Failed.Please Try Again",
        });
        return;
      } else {
        this.formAlert = this.$q.notify({
          message: "Error",
          type: "error-notify",
          caption: data.errorMsg,
        });

        return;
      }
    },
    successCallback: function (data) {
      this.form.token = data.response.token.token;
      if (this.form.token == "") {
        this.isRequestInProgress = false;
        this.formAlert = this.$q.notify({
          message: "Error",
          type: "error-notify",
          caption: "Card Verification Request Failed.Please Try Again",
        });
        return;
      }
      this.checkoutPaymentOnServer();
    },
    checkoutPaymentOnServer() {
      let cart=[];
      this.cart.forEach((v,i)=>{
        cart.push({
          by: v.by,
          discount: v.discount*this.rate,
          doctype: v.doctype,
          id: v.id,
          name: v.name,
          plan: v.plan,
          plans: v.plans,
          price: v.price*this.rate,
          subscriptionType: v.subscriptionType,
          type: v.type,
        })
      })
      axios
        .post("/checkout", {
          form: this.form,
          cart: cart,
          currency:this.currency
        })
        .then((res) => {
          this.isRequestInProgress = false;
          this.$emit("showThankYou");
        })
        .catch((e) => {
          console.log("error : ", e);
          this.isRequestInProgress = false;
          this.formAlert = this.$q.notify({
            message: "Error",
            type: "error-notify",
            caption:
              "Payment Authorization Failed: Please verify your information and try again, or try another payment method",
          });
        });
    },
    fetchCountriesList() {
      axios.get("/countries/create").then((res) => {
        res.data.forEach((e) => {
          this.countriesList.push({
            id: e.id,
            label: e.name,
            value: e.name,
            calling_code: e.calling_code,
            mobile_digit_count: e.mobile_digit_count,
          });
        });
      });
    },
    xmlToJson(xml) {
      // Create the return object
      var obj = {};

      if (xml.nodeType == 1) {
        // element
        // do attributes
        if (xml.attributes.length > 0) {
          obj["@attributes"] = {};
          for (var j = 0; j < xml.attributes.length; j++) {
            var attribute = xml.attributes.item(j);
            obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
          }
        }
      } else if (xml.nodeType == 3) {
        // text
        obj = xml.nodeValue;
      }

      // do children
      if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {
          var item = xml.childNodes.item(i);
          var nodeName = item.nodeName;
          if (typeof obj[nodeName] == "undefined") {
            obj[nodeName] = xmlToJson(item);
          } else {
            if (typeof obj[nodeName].push == "undefined") {
              var old = obj[nodeName];
              obj[nodeName] = [];
              obj[nodeName].push(old);
            }
            obj[nodeName].push(xmlToJson(item));
          }
        }
      }
      return obj;
    },
  },
  beforeDestroy() {
    if (this.formAlert) {
      this.formAlert();
    }
  },
  watch: {},
};
</script>