<template>
  <div
    class="tw-px-[15px] tw-mb-[60px] xl:tw-px-[60px] xl:tw-max-w-screen-xl xl:tw-mx-auto xl:tw-grid xl:tw-grid-cols-[822px_auto] xl:tw-gap-[30px]"
  >
    <section
      class="section section-one tw-my-[40px] md:tw-my-[50px] xl:tw-col-span-2"
    >
      <StepInfo :step_active="step"></StepInfo>
    </section>
    <section class="section section-two">
      <h2
        class="t18 title-icon-left tw-text-black tw-mb-[15px] xl:tw-mb-[10px] xl:tw-text-[24px]"
      >
        {{ $t("Booking Info") }}
      </h2>
      <div
        class="notice tw-body-3 tw-text-black tw-mb-[20px] tw-hidden xl:tw-block"
      >
        {{
          $t(
            "Please enter your info carefully. Once submitted it cannot be changed."
          )
        }}
      </div>
      <BookingInfoItem
        v-for="(item, index) in order"
        :key="index"
        :info="item"
        :content="content"
        :questions="content.booking_questions"
        :contact.sync="userContactList"
        :active="activeLabel"
        @changeActiveLabel="activeLabel = $event"
        @contact="contactData = $event"
        @answer="answerData = $event"
        @bookingDetail_validation="getBookingDetail_validation"
      >
      </BookingInfoItem>
      <h2
        class="t18 title-icon-left tw-text-black tw-mb-[15px] lg:tw-mb-[8px] xl:tw-text-[24px] xl:tw-mt-[60px]"
      >
        {{ $t("Complete Payment") }}
      </h2>
      <div
        class="notice tw-body-3 tw-text-black tw-mb-[20px] tw-hidden xl:tw-block"
      >
        {{
          $t(
            "Please enter your info carefully. Once submitted it cannot be changed."
          )
        }}
      </div>

      <PurchaserInfo
        :class="[bookingDetail_Validation ? 'noFilter' : 'haveFilter']"
        ref="purchaserInfo"
        :userCompanyList="userCompanyList"
        :countryOptions="countryOptions"
        :infoType="type"
        :bookingDetail_Validation="bookingDetail_Validation"
        @type="type = $event"
        @active="companyActiveLabel = $event"
        @individual="individualData = $event"
        @company="companyData = $event"
        @purchaserInfo_validation="getPurchaserInfo_validation"
      ></PurchaserInfo>
      <ChooseMethod
        :class="[purchaserInfo_Validation ? 'noFilter' : 'haveFilter']"
        :orderNo="orderNo"
        :purchaserInfo_Validation="purchaserInfo_Validation"
        @paymentType="paymentData.payment_type = $event"
        @update="updateToken($event)"
      >
      </ChooseMethod>
      <Invoice v-if="language == 'zh-tw'"></Invoice>
      <PcTotalPrice
        :subTotal="subTotal"
        :currency="currency"
        v-on:payNowClick="payNow()"
      ></PcTotalPrice>
    </section>
    <section class="section section-three">
      <PriceInfo
        v-for="(item, index) in order"
        :key="index"
        :info="item"
        :currency="currency"
      ></PriceInfo>
      <TotalPrice
        :subTotal="subTotal"
        :currency="currency"
        v-on:payNowClick="payNow()"
      ></TotalPrice>
    </section>
    <AddContactModal @update="updateContactList"></AddContactModal>
    <EditContactModal
      ref="EditContactModal"
      :contact.sync="userContactList[this.activeLabel - 1]"
      @update="getContactList"
    ></EditContactModal>
    <AddCompanyModal
      :selectList.sync="countryOptions"
      @update="updateCompanyList()"
    >
    </AddCompanyModal>
    <EditCompanyModal
      :selectList.sync="countryOptions"
      :company.sync="userCompanyList[companyActiveLabel - 1]"
      @update="getCompanyList()"
    ></EditCompanyModal>
  </div>
</template>
<script>
import StepInfo from "@/components/service/StepInfo";
import BookingInfoItem from "@/components/service/BookingInfoItem";
import PurchaserInfo from "@/components/service/PurchaserInfo";
import ChooseMethod from "@/components/service/ChooseMethod";
import PriceInfo from "@/components/service/PriceInfo";
import TotalPrice from "@/components/service/TotalPrice";
import PcTotalPrice from "@/components/service/PcTotalPrice";
import elementInput from "@/components/newComponent/form/ElementInput";
import AddContactModal from "@/components/newComponent/modal/AddContactModal";
import EditContactModal from "@/components/newComponent/modal/EditContactModal";
import AddCompanyModal from "@/components/newComponent/modal/AddCompanyModal";
import EditCompanyModal from "@/components/newComponent/modal/EditCompanyModal";
import Invoice from "@/components/service/Invoice.vue";

export default {
  name: "service",
  layout: "service",
  auth: true,
  components: {
    StepInfo,
    BookingInfoItem,
    PurchaserInfo,
    ChooseMethod,
    PriceInfo,
    TotalPrice,
    PcTotalPrice,
    elementInput,
    Invoice,
    AddContactModal,
    EditContactModal,
    AddCompanyModal,
    EditCompanyModal,
  },
  data() {
    return {
      apiUrl: process.env.SERVICE_CONSOLE,
      devECPayUrl: "https://dev-lambda.showeasy.com",
      language: this.$i18n.locale,
      step: "2",
      orderNo: this.$route.params.id,
      order: null,
      serviceId: "",
      currency: "",
      type: "Individual",
      individualData: {},
      companyData: {},
      contactData: {},
      paymentData: {},
      answerData: [],
      content: {
        preview_image: "",
        country: null,
        city: null,
        name: "",
        highlights: "",
        details: "",
        cancellation_policy: "",
        saved: false,
        confirmation_time: 24,
        supplier: null,
        available_sections: null,
        timeStatus: "",
        dateStatus: "",
        times: [],
        start: "",
        end: "",
        faq: null,
        packages: [],
        additionalServices: [],
        booking_questions: [],
      },
      subTotal: 0,
      activeLabel: 0,
      companyActiveLabel: 0,
      userContactList: [],
      userCompanyList: [],
      countryOptions: [],
      contact: [],
      method: "",
      payToken: "",
      three_d_url: "",
      validation: {
        bookingInfo: false,
        purchaserInfo: false,
        chooseMethod: false,
      },
      bookingDetail_Validation: false,
      purchaserInfo_Validation: false,
    };
  },
  async created() {
    if (this.$auth.loggedIn) {
      // await this.getContactList();
      // await this.getActiveLength();
      // await this.getOrder();
      // await this.getServiceData();
      // await this.getPackages();
      // await this.getAdditionalServices();
      // await this.getCountries();
      // await this.getCompanyList();
    }
  },
  mounted() {},
  methods: {
    async getContactList() {
      await this.$axios
        .get(
          `/member/contacts?jwt=${
            this.$auth.$storage.getUniversal("jwt").token
          }`
        )
        .then((result) => {
          this.userContactList = result.data.contacts;
          return result.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async updateContactList() {
      await this.$axios
        .get(
          `/member/contacts?jwt=${
            this.$auth.$storage.getUniversal("jwt").token
          }`
        )
        .then((result) => {
          this.userContactList = result.data.contacts;
          this.activeLabel = this.userContactList.length;
          return result.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async getOrder() {
      await this.$axios
        .get(
          `/order/${this.$route.params.id}?jwt=${
            this.$auth.$storage.getUniversal("jwt").token
          }`
        )
        .then((res) => {
          this.order = res.data;
          for (let index in this.order[0].order_item) {
            this.subTotal += this.order[0].order_item[index].item_amount;
          }
          for (let index in this.order[0].order_as) {
            this.subTotal += this.order[0].order_as[index].as_amount;
          }
          this.serviceId = this.order[0].service_id;
          this.currency = this.order[0].currency;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async getServiceData() {
      await this.$axios
        .get(
          `${this.apiUrl}/user-services/content?service_id=${this.serviceId}&lang_code=${this.$i18n.localeProperties["langQuery"]}&currency=${this.currency}`
        )
        .then((res) => {
          this.content.preview_image = res.data.preview_image;
          this.content.name = res.data.name;
          this.content.country = res.data.country;
          this.content.city = res.data.city;
          this.content.highlights = res.data.highlights;
          this.content.details = res.data.details;
          this.content.cancellation_policy = res.data.cancellation_policy;
          this.content.supplier = res.data.supplier;
          this.content.available_sections = res.data.available_sections;
          this.content.times = res.data.available_sections.times;
          this.content.timeStatus = res.data.available_sections.time_status;
          this.content.dateStatus = res.data.available_sections.date_status;
          this.content.start = res.data.available_sections.start;
          this.content.end = res.data.available_sections.end;
          this.content.payment_currency = res.data.payment_currency;
          this.content.booking_questions = res.data.booking_questions;
        })
        .catch((error) => console.log(error));
    },
    async getPackages() {
      let orderPackageId = this.order[0].order_item[0].package_id
        ? this.order[0].order_item[0].package_id
        : "";
      await this.$axios
        .get(
          `${this.apiUrl}/user-services/packages?service_id=${this.serviceId}&lang_code=${this.$i18n.localeProperties["langQuery"]}&currency=${this.currency}`
        )
        .then((res) => {
          this.content.packages = res.data;
          let packageObject =
            this.content.packages[
              this.content.packages.findIndex(
                (item) => item.package_id === orderPackageId
              )
            ];
          for (let i in packageObject.questions) {
            packageObject.questions[i].required =
              packageObject.questions[i].required_ans;
            this.content.booking_questions.push(packageObject.questions[i]);
          }
        })
        .catch((error) => console.log(error));
    },
    async getAdditionalServices() {
      await this.$axios
        .get(
          `${this.apiUrl}/user-services/additional?service_id=${this.serviceId}&lang_code=${this.$i18n.localeProperties["langQuery"]}&currency=${this.currency}`
        )
        .then((res) => {
          this.content.additionalServices =
            res.data.services == [] ? null : res.data;
          if (this.order[0].order_as.length > 0) {
            for (let i in this.content.additionalServices[0].questions) {
              this.content.additionalServices[0].questions[i].required =
                this.content.additionalServices[0].questions[i].required_ans;
              this.content.booking_questions.push(
                this.content.additionalServices[0].questions[i]
              );
            }
          }
        })
        .catch((error) => console.log(error));
    },
    async payNow() {
      let vm = this;
      if (this.paymentData.payment_type == "Credit Card") {
        try {
          ECPay.getPayToken(function (paymentInfo, errMsg) {
            //console.log("response => getPayToken(paymentInfo, errMsg):", paymentInfo, errMsg);
            if (errMsg != null) {
              vm.ErrHandle(errMsg);
              return;
            }
            vm.payToken = paymentInfo.PayToken;
            vm.updateOrder(Object);
            return true;
          });
        } catch (err) {
          this.ErrHandle(err);
        }
      } else {
        vm.updateOrder(Object);
      }
    },
    async getCountries() {
      await this.$axios
        .get(`/users/countries?lang=${this.$i18n.locale.replace("-", "")}`)
        .then((result) => {
          this.countryOptions = result.data.result;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async getCompanyList() {
      await this.$axios
        .get(
          `/member/company?jwt=${this.$auth.$storage.getUniversal("jwt").token}`
        )
        .then((result) => {
          this.userCompanyList = result.data.data;
          Array.from(this.userCompanyList).forEach((item) => {
            let id = item.company_country;
            let countryName = this.countryOptions.filter(
              (item) => item.id === id || null
            );
            item.company_country_name = countryName[0].name ?? 0;
          });
          return result.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    updateCompanyList() {
      this.$axios
        .get(
          `/member/company?jwt=${this.$auth.$storage.getUniversal("jwt").token}`
        )
        .then((result) => {
          this.userCompanyList = result.data.data;
          this.companyActiveLabel = this.userCompanyList.length;
          this.Company.company_name =
            result.data.data[this.activeLabel].company_name;
          this.Company.company_tax_no =
            result.data.data[this.activeLabel].company_tax_no;
          this.Company.company_address1 =
            result.data.data[this.activeLabel].company_address1;
          this.Company.company_address2 =
            result.data.data[this.activeLabel].company_address2;
          this.Company.company_city =
            result.data.data[this.activeLabel].company_city;
          this.Company.company_state =
            result.data.data[this.activeLabel].company_state;
          this.Company.company_country =
            result.data.data[this.activeLabel].company_country_name;
          this.Company.company_zipcode =
            result.data.data[this.activeLabel].company_zipcode;
          return result.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    updateOrder() {
      let Object = {
        order_id: this.order[0].order_id,
        total: this.subTotal,
        amount: this.subTotal,
        discount: 0,
        contact: [this.contactData],
        answer: this.answerData,
      };
      if (this.type == "Individual") {
        Object.purchase_personal = this.individualData;
      } else {
        Object.purchase_company = this.companyData;
      }
      Object.payment = [this.paymentData];
      Object.payment[0].payment_index = 0;
      Object.payment[0].amount = this.subTotal;
      this.$axios
        .put(
          `/order/${this.$route.params.id}?jwt=${
            this.$auth.$storage.getUniversal("jwt").token || ""
          }`,
          Object
        )
        .then((res) => {
          if (res.status == "200") {
            if (this.paymentData.payment_type == "Credit Card") {
              this.createPayment();
            } else {
              this.$router.push(
                this.localePath("/service/done/" + this.$route.params.id)
              );
            }
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getActiveLength() {
      this.activeLabel = this.userContactList.length > 0 ? 1 : 0;
    },
    updateToken(token) {
      this.payToken = token;
    },
    createPayment() {
      this.$axios
        .post(`${this.devECPayUrl}/payment/ecpay/create-payment`, {
          pay_token: this.payToken,
          payment_flow: "ecpay",
          product_order_no: this.orderNo,
        })
        .then((response) => {
          if (response.data.status_code === 200) {
            window.location.assign(response.data.three_d_url);
          }
        })
        .catch((error) => console.log(error));
    },
    getBookingDetail_validation(data) {
      this.bookingDetail_Validation = data;
    },
    getPurchaserInfo_validation(data) {
      this.purchaserInfo_Validation = data;
    },
  },
};
</script>
<style lang="scss" scoped>
.noFilter {
  pointer-events: auto;
  cursor: auto;
}

.haveFilter {
  cursor: not-allowed;
  pointer-events: none;
  filter: opacity(50%);
}
</style>
