<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]"
      style="background-color: #f1f1f1;"
    >
      <!-- 步驟條 -->
      <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">
        <!-- 登入 or 加入會員 -->
        <div v-if="$auth.loggedIn == false">
          <h2
            class="t18 title-icon-left tw-text-black tw-mb-[15px] xl:tw-mb-[10px] xl:tw-text-[24px]"
          >
            {{ $t("Ordering person") }}
          </h2>
          <div
            class="notice tw-body-3 tw-text-black tw-mb-[20px] tw-hidden xl:tw-block"
          >
            {{
              $t(
                "Please choose to log in or sign up as a member"
              )
            }}
          </div>
          <div
            class="tw-flex tw-justify-between  purchaser-info tw-p-8 tw-mb-[20px] tw-bg-white tw-rounded-xl"
          >
            <div style="width: 25%;">
              <div style="margin-bottom: 15px;">
                <nuxt-link :to="localePath('/user')">
                  <button
                    class="btn_login tw-transition"
                    @click="checkRoute"
                  >
                  登入
                  </button>
                </nuxt-link>
              </div>
              <div>
                <nuxt-link :to="localePath('/user/signUp')">
                  <button
                    class="btn_add"
                    >
                    加入會員
                  </button>
                </nuxt-link>
              </div>
            </div>
            <div style="border-left: 1px solid #e5e5e5; width: 75%; padding-left: 30px;">
              <p class="tw-body-3 tw-text-primary-1 tw-font-bold">加入會員的好處 : </p>
              <ul>
                <li class="tw-body-3 tw-text-black tw-font-bold">訂單進行到哪?加入會員即時掌握進度!</li>
                <li class="tw-body-3 tw-text-black tw-font-bold">輕鬆管理訂單!所有資料保留雲端,紀錄隨手查。</li>
                <li class="tw-body-3 tw-text-black tw-font-bold">您關注的展覽全蒐藏!蒐集自己的展覽資料庫,為展覽盡早做準備。</li>
                <li class="tw-body-3 tw-text-black tw-font-bold">精準提供您需要的展覽資訊及服務優惠。</li>
              </ul>
            </div>
          </div>

        </div>
        <!-- 訂購人資訊 -->
        <OrderPersonInfo
          :countryOptions="countryOptions"
          @orderingPersonInfo="orderingPersonInfo"
          @type="type = $event"
          @individual="individualData = $event"
          @company="companyData = $event"
          @orderingPerson_Validation="getOrderingPerson_validation"
        >
        </OrderPersonInfo>
        <!-- 訂購資訊 -->
        <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
          :class="[orderingPerson_Validation ? 'noFilter' : 'haveFilter']"
          ref="ref_Booking"
          :info="order"
          :content="content"
          :orderingPerson_Validation="orderingPerson_Validation"
          :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 OrderPersonInfo from "@/components/service/OrderingPersonInfo";
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",
  //layout: ['login', 'service'],
  layout: "login",
  // auth: true,
  auth: false,
  components: {
    StepInfo,
    BookingInfoItem,
    PurchaserInfo,
    OrderPersonInfo,
    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: {
        orderPersonInfo: true,
        bookingInfo: false,
        purchaserInfo: false,
        chooseMethod: false,
      },
      orderingPerson_Validation: 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: '',
      personInfo: {},
      updatePersonalInfo: false,
    };
  },
  async created() {
    this.isLoading = true;
    // this.$nextTick(()=>{
    //   this.isLoading = false;
    // });

      this.getOrderingPerson_validation();

    // if (this.$auth.loggedIn) {
      
      let data = this.$route.query;

      this.serviceID = this.$route.params.id;

      //思考可以如何優化
      //高雄
      if(this.serviceID == "fb48072e-2d82-4ec6-9aeb-759df42a9ab0"){

        let selectExhibitionData = data.selectExhibitionData;

        for(let k = 0; k < selectExhibitionData.length; k++) {

          console.log(selectExhibitionData[k])

        }

        console.log('資料檢查', 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.ceil(price);
          this.subTotal = Math.ceil(price);
          this.total = Math.ceil(price*0.05)+Math.ceil(price);
        }
        this.order.order_item = orderItems;
        let title = this.order.title;

        this.order.title = title;
        this.order.service_name = title;
        this.order.selectExhibition = title.slice(1, 19);
        // this.order.selectExhibitionID = selectExhibitionData.ArgumentID;
      }
      else{

        let selectExhibitionData = JSON.parse(decodeURIComponent(data.selectExhibitionData));

        console.log(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.ceil(price);
          this.subTotal = Math.ceil(price);
          this.total = Math.ceil(price*0.05)+Math.ceil(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: {
    checkRoute() {
      console.log(this.$route)
    },
    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,
          //訂購人參數加在這兒
          FirstName: this.personInfo.FirstName,
          LastName: this.personInfo.LastName,
          Email: this.personInfo.Email,
          CountryID: this.personInfo.CountryID,
          Phone: this.personInfo.Phone,
          PhoneCode: this.personInfo.PhoneCode,
          //帳單個人資訊參數
          INVFirstName: this.individualData.first_name,
          INVLastName: this.individualData.last_name,
          INVEmail: this.individualData.email,
          INVICountryID: this.individualData.country,
          INVPhone: this.individualData.phone_number,
          INVPhoneCode: this.individualData.phone_code,
          //帳單公司資訊參數
          INVCompanyName: this.companyData.company_name,
          INVTaxNumber: this.companyData.unified_number,
          INVCountryID: this.companyData.country,
          INVStateName: this.companyData.state_or_province,
          INVCityName: this.companyData.city_,
          INVStreet1: this.companyData.company_address,
          INVZipCode: this.companyData.postal_code,
        }
        this.isLoading = true;
        let jsonData = null;
        let statusCode = 'failed'
        this.$axios.post( `/trending/api/Onsite/Booking`, params)
          .then((response) => {
            //console.log(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.CountryENName + " " + 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);
        });
    },
    //emit回來的訂購人資訊
    orderingPersonInfo(value) {
      this.personInfo = value;
    },
    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));
    // },
    getOrderingPerson_validation(data) {
      this.orderingPerson_Validation = data;
    },
    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%);
}

.btn_login, .btn_add {
  padding: 9px 16px;
  border-radius: 12px;
  border: solid 1px #696969;
  background-color: #fefefe;
  font-family: NotoSansTC;
  font-size: 16px;
  font-weight: bold;
  font-style: normal;
  color: #696969;
}

.btn_login:hover, .btn_add:hover {
  background-color: #696969;
  color: #fefefe;
}

p {
  margin: 0;
}
</style>