<template>
  <client-only>
  <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("Ordering information") }}
      </h2>
      <div
        class="notice tw-body-3 tw-text-black tw-mb-[20px] tw-hidden xl:tw-block"
      >
        {{
          $t(
            "Please confirm whether the information is filled in correctly. Once the information is sent, it cannot be changed"
          )
        }}
      </div>
      <BookingInfoItem
        ref="ref_Booking"
        :info="order"
        :content="content"
        :questions="questionList"
        @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"
        :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"
        :payTypes="payTypes"
        :chooseMethod="chooseMethod"
        :purchaserInfo_Validation="purchaserInfo_Validation"
        @paymentType="payment_type = $event"
        @update="updateToken($event)"
      >
      </ChooseMethod>
      <!-- <Invoice v-if="language == 'zh-tw'"></Invoice> -->
      <PcTotalPrice
        :subTotal="total"
        :currency="currency"
        v-on:payNowClick="payNow()"
      ></PcTotalPrice>
    </section>
    <section class="section section-three">
      <PriceInfo
        :info="order"
        :currency="currency"
      ></PriceInfo>
      <TotalPrice
        :subTotal="subTotal"
        :total="total"
        :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> -->
    <loading :isLoading="isLoading"></loading>
  </div></client-only>
</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";
// import ElementInputNew from "@/components/newComponent/form/ElementInputNew";
import loading from "@/components/newComponent/loading/loading.vue";

export default {
  name: "checkout",
  layout: "service",
  auth: true,
  components: {
    StepInfo,
    BookingInfoItem,
    PurchaserInfo,
    ChooseMethod,
    PriceInfo,
    TotalPrice,
    PcTotalPrice,
    elementInput,
    Invoice,
    loading,
    // AddContactModal,
    // EditContactModal,
    // AddCompanyModal,
    // EditCompanyModal,
    // ElementInputNew,
  },
  data() {
    return {
      isLoading: false,
      serviceID: '',
      apiUrl: process.env.SERVICE_CONSOLE,
      devECPayUrl: "https://dev-lambda.showeasy.com",
      language: this.$i18n.locale,
      step: "2",
      orderNo: this.$route.params.id,
      order: {
        title: '',
        detail: '',
        preview_image: '',
        date: '',
        quantity: '',
        total: 0,
        service_name: '',
        package_name: '',
        package_name: '',
        customer_plan_name: '',
        service_date: '',
        service_time: '',
        selectExhibition: '',
        selectExhibitionID: '',
        order_as: [],
        order_item: []
      },
      serviceId: "",
      currency: "NTD",
      type: "Company",
      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,
      total: 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,
      chooseMethod: "",
      payTypes: [],
      questionList: [{
        id: "question01",
        name: this.$t("Mobilization date"),
        type: "DateText",
        validation: true,
        value: '',
        requiredFlag: '1'
      },{
        id: "question02",
        name: this.$t("Mobilization time"),
        type: "TimeText",
        validation: true,
        value: '',
        requiredFlag: '1'
      },{
        id: "question03",
        name: this.$t("Exit date"),
        type: "DateText",
        validation: true,
        value: '',
        requiredFlag: '1'
      },{
        id: "question04",
        name: this.$t("Exit time"),
        type: "TimeText",
        validation: true,
        value: '',
        requiredFlag: '1'
      }],
      payment_type: '',
    };
  },
  async created() {
    this.isLoading = true;
    if (this.$auth.loggedIn) {
      let data = this.$route.query;
      this.serviceID = this.$route.params.id;
      let selectExhibitionData = JSON.parse(decodeURIComponent(data.selectExhibitionData));
      let selectExhibitionServiceData = JSON.parse(decodeURIComponent(data.selectExhibitionServiceData));
      let quantityData = JSON.parse(decodeURIComponent(data.quantityData));
      this.currency = decodeURIComponent(data.currencyName);
      // let pickupServiceData = JSON.parse(data.pickupServiceData);
      this.order.preview_image = decodeURIComponent(data.previewFile);
      this.order.title = decodeURIComponent(data.title);
      let serviceItems = "";
      let orderItems = [];
      if(selectExhibitionServiceData && selectExhibitionServiceData.length>0){
        for(let i=0;i<selectExhibitionServiceData.length;i++){
          let tmpData = selectExhibitionServiceData[i];
          let target = tmpData.selectServiceItems;
          let itemTypes = "";
          if(target && target.length>0){
            for(let j=0;j<target.length;j++){
              if(target[j].name!=""){
                if(j>0){
                  itemTypes +=",";
                }
                itemTypes += target[j].name;
              }
            }
          }
          let item = "["+ tmpData.selectPackape.name +","+tmpData.length+"*"+tmpData.width+"*"+tmpData.height+"cm,"+tmpData.weight+"kg,"+itemTypes+"] x"+tmpData.quantity;
          orderItems.push(item);
        }
      }
      for(let n=0;n<quantityData.selectList.length;n++){
          let name = quantityData.selectList[n].name;
          let num = quantityData.selectList[n].number;
          let maxWeight = quantityData.selectList[n].maxWeight;
          let size = quantityData.selectList[n].size;
          if(num>0){
            let item = "["+ name +" "+ this.$t("Ton truck")+","+this.$t("Maximum load")+" "+maxWeight+","+this.$t("Car size")+" "+size+"] x"+num;
            orderItems.push(item);
          }
      }
      for(let n=0;n<quantityData.truckList.length;n++){
          let name = quantityData.truckList[n].name;
          let num = quantityData.truckList[n].number;
          if(num>0){
            let item = "["+ name +" "+this.$t("Ton lift tailgate truck")+"] x"+num;
            orderItems.push(item);
          }
      }
      if(data.totalPrice!=undefined && data.totalPrice!=""){
        let price = Number(data.totalPrice);
        this.order.total = Math.round(price);
        this.subTotal = Math.round(price);
        this.total = Math.round(price*0.05 + price);
      }
      this.order.order_item = orderItems;
      let title = this.order.title;
      this.order.title = title;
      this.order.service_name = title;
      this.order.selectExhibition = selectExhibitionData.selectPackape.name;
      this.order.selectExhibitionID = selectExhibitionData.selectPackape.id;
      // await this.getContactList();
      // await this.getActiveLength();
      // await this.getOrder();
      // await this.getServiceData();
      // await this.getPackages();
      await this.getOrderQuestions();
      await this.getCountries();
      await this.getPayTypes();
      // await this.getCompanyList();
      this.$nextTick(()=>{
        this.isLoading = false;
      });
      
    }
  },
  mounted() {},
  methods: {
    getQuestionList(){
      this.questionList = [{
        id: "question01",
        name: this.$t("Mobilization date"),
        type: "DateText",
        validation: true,
        value: '',
        requiredFlag: '1'
      },{
        id: "question02",
        name: this.$t("Mobilization time"),
        type: "TimeText",
        validation: true,
        value: '',
        requiredFlag: '1'
      },{
        id: "question03",
        name: this.$t("Exit date"),
        type: "DateText",
        validation: true,
        value: '',
        requiredFlag: '1'
      },{
        id: "question04",
        name: this.$t("Exit time"),
        type: "TimeText",
        validation: true,
        value: '',
        requiredFlag: '1'
      }];
    },
    // async getContactList() {
    //   await this.$axios
    //     .get(`/trending/api/Members/Contacts`)
    //     .then((response) => {
    //       if(response && response.data && response.data.DATA && response.data.DATA.rel){
    //         let data = response.data.DATA.rel
    //         if(data.length>0){
    //           this.userContactList = data.map((item) => {
    //             return {
    //               first_name: item.FirstName,
    //               last_name: item.LastName,
    //               email: item.Email,
    //               phone_number: item.PhoneCountryCode +"-"+ item.PhoneNo
    //             };
    //           });
    //         }
    //       }
    //     })
    //     .catch((err) => {
    //       console.log(err);
    //     });
    // },
    // async updateContactList() {
    //   const patchData = {};
    //   await this.$axios
    //     .post(`/trending/api/Members/Contacts`,patchData)
    //     .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(`/trending/api/Onsite/Info?Lang=${this.$i18n.localeProperties["langQuery"]}&ServiceID=${this.$route.params.id}`)
        .then((response) => {
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data){
              // this.content.service_name = data.ServiceName;
              // this.content.package_name = data.Features;
              // this.content.package_name = data.Details;
              // this.content.customer_plan_name = data.CancelPolicy;
              // this.content.specification_name = data.FQAs;
              // this.content.quantity = data.ConfirmDays;
              // this.content.service_date = "2023-02-13";
              // this.content.service_time = "02:00:12";
              // this.content.booking_questions = data.FQAs;

              // 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 = 0;
            }
          }
        })
        .catch((error) => console.log(error));
    },
    async getPayTypes() {
      await this.$axios
        .get(`/trending/api/Onsite/PayTypes?Lang=${this.$i18n.localeProperties["langQuery"]}&ServiceID=${this.$route.params.id}`)
        .then((response) => {
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data.length>0){
              this.chooseMethod = data[0].ArgumentID;
              this.payTypes = data.map((item)=>{
                return {
                  id: item.ArgumentID,
                  name: item.ArgumentValue,
                }
              });
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    async getOrderQuestions() {
      await this.$axios
        .get(`/trending/api/Onsite/OrderQuestions?Lang=${this.$i18n.localeProperties["langQuery"]}&ServiceID=${this.$route.params.id}`)
        .then((response) => {
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel;
            this.getQuestionList();
            if(data.length>0){
              let list = data.map((item)=>{
                return {
                  id: item.QuestionID,
                  name: item.SurveyName,
                  type: item.AnswerType,
                  validation: true,
                  value: '',
                  requiredFlag: item.RequiredFlag
                }
              });
              this.questionList = this.questionList.concat(list);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    payNow() {
      let isPass1 = this.$refs.ref_Booking.getValidation();//this.bookingDetail_Validation;
      let isPass2 = true;
      this.$refs.purchaserInfo.updatePurchaserInfo(true);//this.purchaserInfo_Validation;
      isPass2 = this.purchaserInfo_Validation;
      if(isPass1 && isPass2){
        let vm = this;
        let answerList = [];
        let serviceDateS = "";
        let serviceDateE = "";
        if(this.answerData.length>2){
          serviceDateS = this.answerData[0].value.replaceAll(".","/") +" "+ this.answerData[1].value;
          serviceDateE = this.answerData[2].value.replaceAll(".","/") +" "+ this.answerData[3].value;
          answerList = this.answerData.map((item)=>{
            return item.name +":"+item.value;
          });
        }
        if(this.payment_type==null || this.payment_type==""){
          return false;
        }
        let params = {
          LangType: this.$i18n.localeProperties["langQuery"],
          ExhibitionID: this.order.selectExhibitionID,
          CurrencyID: this.$store.getters.getCurrency,
          PayType: this.payment_type,
          ServiceID: this.serviceID,
          TotalPrice: this.total + "",
          SubTotal: this.subTotal +"",
          BookingItem: this.order.order_item,
          OrderQuestion: answerList,
          ServiceDateS: serviceDateS,
          ServiceDateE: serviceDateE,
        }
        this.isLoading = true;
        let jsonData = null;
        let statusCode = 'failed'
        this.$axios.post( `/trending/api/Onsite/Booking`, params)
          .then((response) => {
            this.isLoading = false;
            if(response && response.response && response.response.status==504){
              statusCode = 'failed'
            }else{
              if(response && response.data && response.data.DATA && response.data.DATA.rel){
                statusCode = 'success'
                let data = response.data.DATA.rel;
                if(data){
                  jsonData = data;
                }
              }else{
                statusCode = 'failed'
              }
            }
            this.$router.push(
              { 
                path: this.localePath("/service/done/" + this.$route.params.id), 
                //携带需要传递的参数
                query: {
                  data: encodeURIComponent(JSON.stringify(jsonData)),
                  status: statusCode,
                } 
              });
          })
          .catch((err) => {
            this.isLoading = false;
            this.$router.push(
            { 
              path: this.localePath("/service/done/" + this.$route.params.id), 
              //携带需要传递的参数
              query: {
                data: encodeURIComponent(JSON.stringify(jsonData)),
                status: statusCode
              } 
            });
            console.log(err);
          });
        }
    },
    async getCountries() {
      await this.$axios
        .get(`/trending/api/Onsite/Countries?Lang=${this.$i18n.localeProperties["langQuery"]}`)
        .then((response) => {
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data.length>0){
              this.countryOptions = data.map((item)=>{
                return {
                  id: item.CountryID,
                  name: item.CountryName
                }
              });
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getCompanyList() {
      this.$axios
        .get(
          `/trending/api/Members/Companies?Lang=${this.$i18n.localeProperties["langQuery"]}`
        )
        .then((response) => {
          if(response && response.data && response.data.DATA && response.data.DATA.rel){
            let data = response.data.DATA.rel
            if(data.length>0){
              this.userCompanyList = data.map((item) => {
                return {
                  company_name: item.CompanyName,
                  company_tax_no: item.TaxNumber,
                  company_address1: item.Street1,
                  company_address2: item.Street2,
                  company_city: item.CityName,
                  company_state: item.StateName,
                  company_country_name: item.Country.Country,
                  company_zipcode: item.ZipCode,
                  company_country: item.Country.CountryID,
                };
              });
              // 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() {
      const patchData = {};
      this.$axios
        .post(
          `/trending/api/Members/Company`,patchData
        )
        .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>
