<template>
  <div class="content-page order-preview">
    <q-stepper
      v-model="step"
      ref="stepper"
      color="primary"
      inactive-color="grey-5 "
      class="bg-transparent"
      flat
      animated
    >
      <q-step
        :name="1"
        title="確認訂單"
        icon="settings"
        :done="step > 1"
      ></q-step>

      <q-step
        :name="2"
        title="付款"
        icon="iconfont iconPayment-1"
        :done="step > 2"
      ></q-step>

      <q-step
        :name="3"
        title="訂購完成"
        icon="iconfont iconicon_finish_R"
        :done="step == 3"
      ></q-step>
    </q-stepper>
    <div
      class="row q-pa-md"
      style="min-width: 375px; margin: 0 auto"
      :class="{
        row: $q.screen.width >= 1200 && $q.platform.is.desktop,
        column: $q.screen.width < 1200 || $q.platform.is.mobile,
      }"
      v-if="orderKey && orderKey != '' && trip && price"
    >
      <div class="col">
        <q-form ref="baseUserInfo">
          <q-card flat class="q-pa-md">
          <div
            class="text-subtitle1 text-weight-bolder"
            ref="baseUserInfoTitle"
          >
            訂購人資訊
          </div>
          <q-separator color="grey-2" class="q-my-md" />
            <q-form ref="baseUserInfo">
              <div class="row q-col-gutter-md">
                <div :class="filedWidth">
                  <q-input
                    standout
                    v-model="userInfo.Name"
                    label="名字"
                    ref="name"
                    :rules="[(val) => !!val || '請輸入名字']"
                  />
                </div>
                <div :class="filedWidth">
                  <q-input
                    standout
                    v-model="userInfo.Surname"
                    ref="surname"
                    label="姓氏"
                    :rules="[(val) => !!val || '請輸入姓氏']"
                  />
                </div>
                <div class="row" :class="filedWidth">
                  <q-select
                    style="width: 120px"
                    v-model="userInfo.Country"
                    @input="changeCountry"
                    :options="countrys"
                    emit-value
                    option-label="Name"
                    option-value="ID"
                    map-options
                    label="國家/地區"
                    standout
                  />
                  <q-input
                    class="col q-ml-sm"
                    standout
                    v-model="userInfo.Moblie"
                    label="電話"
                    mask="#"
                    reverse-fill-mask
                    ref="mobile"
                    :rules="[(val) => !!val || '請輸入行動電話']"
                  >
                    <template v-slot:prepend>
                      <div class="text-subtitle2">
                        {{ userInfo.PhoneCountryStr }}
                      </div>
                    </template>
                  </q-input>
                </div>
                <div :class="filedWidth">
                  <q-input
                    standout
                    v-model="userInfo.Mailbox"
                    label="郵箱地址"
                    ref="mailbox"
                    :rules="[
                      (val) =>
                        /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(
                          val
                        ) || '請輸入正確的郵箱地址',
                    ]"
                  />
                </div>
                
              </div>
              <div class="col row justify-end">
                  <q-toggle v-model="isUpdateUserInfo" label="同步更新會員資料" />
              </div>
            </q-form>
          </q-card>
        </q-form>
        
        <q-card flat class="q-pa-md q-my-lg">
          <div class="text-subtitle1 text-weight-bolder q-mb-md">客户資料</div>
          <div class="row">
            <q-img
              :src="trip.CoverImageList.length>0&&trip.CoverImageList[0].Url?trip.CoverImageList[0].Url:''"
              class="rounded-borders"
              spinner-color="grey-3"
              style="width: 80px"
            />
            <div class="q-ml-md col">
              <div class="text-subtitle1 ellipsis">
                {{ trip.Name }} 
                <q-chip
                      style="background: #26a69a1a"
                      size="sm"
                      class="f12 rounded-borders text-secondary"
                      :label="trip.VisaType==1?'个签':trip.VisaType==2?'团签':''"
                    />
                    <template v-if="trip.TypeTagList&&trip.TypeTagList.length>0">
                <template v-for="item in trip.TypeTagList">
                  <q-chip v-if="item.TagTame!=''"
                    style="background: #26a69a1a"
                    size="sm"
                    class="f12 rounded-borders text-secondary"
                    :label="item.TagTame"
                  />
                </template>
              </template>
              <template v-if="trip.ProductTagList&&trip.ProductTagList.length>0">
                  <template v-for="item in trip.ProductTagList">
                    <q-chip v-if="item.TagTame!=''"
                      style="background: #26a69a1a"
                      size="sm"
                      class="f12 rounded-borders text-secondary"
                      :label="item.TagTame"
                    />
                  </template>
              </template>
              <template v-if="trip.FeatureTagList&&trip.FeatureTagList.length>0">
                <template v-for="item in trip.FeatureTagList">
                  <q-chip v-if="item.TagTame!=''"
                    style="background: #26a69a1a"
                    size="sm"
                    class="f12 rounded-borders text-secondary"
                    :label="item.TagTame"
                  />
                </template>
              </template>
              </div>
              <div v-if="trip.SendCityName||trip.ManageDuration" class="text-caption text-grey-6 ellipsis q-mt-sm">
                <span class="text-grey-9">送签地：</span>
                <span>{{ trip.SendCityName }}</span>
                <span v-if="trip.ManageDuration" class="q-pl-lg">收齐资料后需{{ trip.ManageDuration }}个工作日</span>
              </div>
            </div>
          </div>
          <!-- items-center justify-between -->
          <div class="q-mt-md row ">
            <div class="text-grey-9" v-if="trip.VisaValidity">
              <span>有效日期：</span>
              <span>{{ trip.VisaValidity }}</span>
            </div>
            <div class="text-grey-9 q-ml-md">
              <q-icon name="iconfont iconpeople" size="20px" class="q-mr-sm" />
              <span class="q-mr-sm" v-if="chosenObj.AdultPeopleNum > 0"
                >{{ chosenObj.AdultPeopleNum }}人</span
              >
              <span class="q-mr-sm" v-if="chosenObj.ChildPeopleNum>0"
                >兒童 x {{ chosenObj.ChildPeopleNum }}</span
              >
            </div>
          </div>
          <!-- <div class="text-right">
            <q-toggle v-model="isCreateGuest" label="是否預填客户信息" />
          </div> -->
          <q-separator color="grey-2" class="q-my-md" />
          <q-form ref="baseCustomerInfo">
            <!-- <div class="text-subtitle1 text-weight-bolder q-mb-md"
            ref="baseCustomerTitle">客户信息</div>
            <q-separator color="grey-2" class="q-my-md" /> -->
            <div class="row q-col-gutter-md" ref="baseCustomerTitle">
              <div :class="filedWidth">
                <q-input
                  standout
                  v-model="chosenObj.AdultPeopleNum"
                  label="人数"
                  mask="#"
                  reverse-fill-mask
                  ref="AdultPeopleNum"
                  :rules="[(val) => !!val || '請輸入人数']"
                  @input="(e)=>{getValue(e,'AdultPeopleNum')}"
                >
                </q-input>
              </div>
              <!-- <div :class="filedGuestWidth">
                <q-input
                  standout
                  v-model="chosenObj.ChildPeopleNum"
                  label="儿童人数"
                  mask="#"
                  reverse-fill-mask
                  ref="ChildPeopleNum"
                  @input="(e)=>{getValue(e,'AdultPeopleNum')}"
                >
                </q-input>
              </div> -->
              <div :class="filedWidth">
                <q-input
                  standout
                  v-model="chosenObj.EnterCountryTime"
                  label="入境日期"
                  :rules="[(val) => !!val || '請選擇入境日期']"
                >
                  <template v-slot:append>
                    <q-icon name="event" class="cursor-pointer"></q-icon>
                  </template>
                  <q-popup-proxy :offset="[0, 0]" ref="EnterCountryTime">
                    <q-date
                      :options="optionsFn"
                      mask="YYYY-MM-DD"
                      title="入境日期"
                      subtitle="選擇"
                      v-model="chosenObj.EnterCountryTime"
                      @input="getTime(1)"
                    />
                  </q-popup-proxy>
                </q-input>
              </div>
            </div>
            <template v-if="1===0">
              <q-separator color="grey-2" class="q-mb-md" />
              <div
                class="bg-grey-1 rounded-borders q-pa-md q-mt-md guest-item"
                v-for="(x, i) in guests"
                :key="i"
                :ref="`guest${i}Title`"
              >
                <div class="text-subtitle1 q-pb-md text-weight-bold">
                  客户{{ i+1 }}
                </div>
                <q-form :ref="`guest${i}`">
                  <div class="row q-col-gutter-md">
                    <div :class="filedTypeWidth">
                      <q-input
                        standout
                        v-model="x.SurName"
                        label="本國姓"
                        placeholder="例：張"
                        :rules="[(val) => !!val || '請輸本國姓']"
                      />
                    </div>
                    <div :class="filedTypeWidth">
                      <q-input
                        standout
                        v-model="x.Name"
                        label="本國名"
                        placeholder="例：三"
                        :rules="[(val) => !!val || '請輸本國名']"
                      />
                    </div>
                    <div :class="filedTypeWidth">
                      <q-input
                        standout
                        v-model="x.ESurName"
                        label="英文姓"
                        placeholder="例：ZHANG"
                        mask="A"
                        reverse-fill-mask
                        :rules="[(val) => !!val || '請輸英文姓']"
                      />
                    </div>
                    <div :class="filedTypeWidth">
                      <q-input
                        standout
                        v-model="x.EName"
                        label="英文名"
                        placeholder="例：SAN"
                        mask="A"
                        reverse-fill-mask
                        :rules="[(val) => !!val || '請輸英文名']"
                      />
                    </div>
                    <div :class="filedGuestWidth">
                      <q-select
                          label="客户类型"
                          standout
                          map-options
                          option-label="Content"
                          option-value="Code"
                          v-model="x.DutyObj"
                          :options="customerTypes"
                          :rules="[(val) =>!!val || '請选择客户类型']"
                          @input="(e)=>{getValue(e,'Duty',i)}"
                        />
                    </div>
                    <div :class="filedGuestWidth">
                      <q-input
                        standout
                        v-model="x.IdCard"
                        label="证件号"
                        mask="X"
                        reverse-fill-mask
                        :rules="[(val) => !!val || '請輸证件号']"
                      />
                    </div>
                    <div :class="filedGuestWidth">
                      <q-input
                        standout
                        v-model="x.MobilePhone"
                        label="聯絡電話"
                        mask=""
                        reverse-fill-mask
                        placeholder="格式：號碼，例如：25xxxx"
                      />
                    </div>
                  </div>
                </q-form>
              </div>
            </template>
            
            
          </q-form>
        </q-card>
        <q-form ref="baseRecipientInfo">
          <q-card flat class="q-pa-md q-mt-lg">
            <div class="text-subtitle1 text-weight-bolder q-mb-md"
             ref="baseRecipientTitle">收件信息</div>
            <q-separator color="grey-2" class="q-my-md" />
            <div class="row q-col-gutter-md">
              <div :class="filedWidth">
                  <q-input
                    standout
                    v-model="chosenObj.Receiver"
                    label="收件人"
                    ref="Receiver"
                    :rules="[(val) => !!val || '請輸入收件人']"
                  />
                </div>
                <div class="row" :class="filedWidth">
                  <q-select
                        label="國家/地區"
                        standout
                        map-options
                        emit-value
                        option-label="Name"
                        option-value="PhoneCode"
                        v-model="chosenObj.RelationPhoneType"
                        @input="(e)=>{getValue(e,'AreaCode')}"
                        :options="countrys"
                        style="width: 120px"
                        ref="RelationPhoneType"
                      />
                  <q-input
                    class="col q-ml-sm"
                    standout
                    v-model="chosenObj.ReceiverPhone"
                    label="收件人電話"
                    mask="#"
                    reverse-fill-mask
                    ref="ReceiverPhone"
                    :rules="[(val) => !!val || '請輸入收件人電話']"
                  >
                    <template v-slot:prepend>
                      <div class="text-subtitle2" v-if="chosenObj.RelationPhoneType">
                        + {{ chosenObj.RelationPhoneType }}
                      </div>
                    </template>
                  </q-input>
                </div>
                <div :class="filedTypeWidth">
                  <q-select
                        label="省"
                        standout
                        map-options
                        emit-value
                        option-label="Name"
                        option-value="Name"
                        v-model="chosenObj.ReceiverProvince"
                        :options="provinceList"
                        ref="ReceiverProvince"
                        :rules="[(val) =>!!val || '請选择省']"
                        @input="(e)=>{getValue(e,'Province')}"
                      />
                </div>
                <div :class="filedTypeWidth">
                  <q-select
                        label="市"
                        standout
                        map-options
                        emit-value
                        option-label="Name"
                        option-value="Name"
                        v-model="chosenObj.ReceiverCity"
                        :options="cityList"
                        ref="ReceiverCity"
                        :rules="[(val) =>!!val || '請选择市']"
                        @input="(e)=>{getValue(e,'Receiver')}"
                      />
                </div>
                <div class="col-6">
                  <q-input
                    standout
                    v-model="chosenObj.ReceiverAddress"
                    label="收件人地址"
                    mask=""
                    ref="ReceiverAddress"
                    :rules="[(val) => !!val || '請輸入收件人地址']"
                  >
                  </q-input>
                </div>
            </div>
          </q-card>
        </q-form>
          
          <q-card flat class="q-pa-md q-mt-lg">
            
            <div class="text-subtitle1 q-my-md text-weight-bold">
              特殊需求備註：
            </div>
            <q-input
              standout
              v-model="chosenObj.Remark"
              input-style="height:170px;"
              type="textarea"
              placeholder="此欄位僅限資料備註。不在商品規範內的個人需求，不保證提供"
              maxlength="200"
              counter
            />
          </q-card>
        
        <coupon
          v-if="price && price.tcid"
          :product-type="productType"
          :current-price="sumPrice"
          @change="changeDiscountHandler"
        ></coupon>
      </div>
      <div
        class="relative-position"
        :class="{
          'q-ml-lg': !($q.screen.width < 1200 || $q.platform.is.mobile),
          'q-mt-lg  full-width':
            $q.screen.width < 1200 || $q.platform.is.mobile,
        }"
      >
        <div
          class="rounded-borders bg-white q-pa-md"
          style="width: 300px"
          :style="{
            width:
              $q.screen.width < 1200 || $q.platform.is.mobile
                ? 'unset'
                : '300px',
            position: $q.platform.is.mobile ? 'unset' : 'sticky',
            top: $q.platform.is.mobile ? 'unset' : '50px',
          }"
        >
          <div class="text-subtitle1 text-weight-bolder">付款明細</div>
          <div class="row q-mt-md">
            <q-img
              :src="trip.CoverImageList.length>0&&trip.CoverImageList[0].Url?trip.CoverImageList[0].Url:''"
              class="rounded-borders"
              spinner-color="grey-3"
              style="width: 80px"
            />
            <div class="q-ml-md col">
              <div class="text-subtitle1 ellipsis">
                {{ trip.Name }}
              </div>
              <div class="text-caption text-grey-6 ellipsis q-mt-sm">
                {{ trip.VisaType==1?'个签':trip.VisaType==2?'团签':'' }}
              </div>
            </div>
          </div>
          <div class="q-mt-md text-grey-6" v-if="trip.VisaValidity">
            <div class="row">
              <div style="width: 80px">有效日期：</div>
              <div class="q-ml-md">
                {{
                  trip.VisaValidity
                }}
              </div>
            </div>
          </div>
          <q-separator v-if="chosenObj.AdultPeopleNum>0" color="grey-2" class="q-my-md" />
          <div class="text-grey-9">
            <div class="row q-mb-sm" v-if="chosenObj.AdultPeopleNum>0">
              <div class="col">{{chosenObj.AdultPeopleNum}}人</div>
              <div>CNY 
                {{ moneyFormat(trip.VisaB2CPrice, 2) }}
              </div>
            </div>
            <div class="row q-mb-sm" v-if="chosenObj.ChildPeopleNum>0">
              <div class="col">兒童 x {{chosenObj.ChildPeopleNum}}</div>
              <div>
                CNY
                {{
                  moneyFormat(trip.VisaB2CPrice, 2)
                }}
              </div>
            </div>
            <hr
              style="border: none; border-top: 1px dashed #eee !important"
              class="bg-transparent q-mb-sm"
            />
            <div class="row q-mb-sm items-center">
              <div class="col">總金額</div>
              <div class="text-subtitle2 text-weight-bolder text-primary">
                CNY 
                {{ moneyFormat(sumPrice, 2) }}
              </div>
            </div>

            <hr
              style="border: none; border-top: 1px dashed #eee !important"
              class="bg-transparent q-mb-sm"
            />
            <!-- <div class="row q-mb-sm items-center">
              <div class="col">優惠金額</div>
              <div
                class="text-subtitle2 text-weight-bolder text-teal"
                
              >
                CNY - 
                {{ moneyFormat(price.discountPrice, 2) }}
              </div>
              <div class="text-grey-5">暫無優惠</div>
            </div> -->
            <div class="row q-mb-sm items-center">
              <div class="col">支付金額</div>
              <div
                class="text-h6 text-weight-bolder text-primary product-price"
              >
                CNY 
                {{ moneyFormat(sumPrice, 2) }}
              </div>
            </div>
          </div>
          <div class="text-right q-mt-md">
            <q-btn
              unelevated
              color="primary"
              label="立即支付"
              :loading="submiting"
              @click="submitHandler"
            />
          </div>
        </div>
      </div>
    </div>
    <div v-if="!orderKey || orderKey == ''" class="text-center q-my-xl">
      <none-data
        iconType="order"
        title="沒有找到您的訂單信息哦"
        subtitle="趕緊去挑選心儀的旅遊產品吧,三秒後自動跳轉到首頁"
      ></none-data>
    </div>
    <auth></auth>
  </div>
</template>

<script>
import coupon from "../../components/common/coupon.vue";
import NoneData from "src/components/common/noneData.vue";
import auth from "src/components/common/auth.vue";
import { date } from "quasar";
import ProductTypeEnum from "../../utils/producttypeenum";
import EnumHelper from "../../utils/enumhelper";
export default {
  components: {
    coupon,
    NoneData,
    auth,
  },

  data() {
    return {
      step: 1,
      userInfo: {
        lastName: "",
        firstName: "",
        Surname: '',
        Country: 0,
      },
      chosenObj: {
        IsNeedInvoice: 0,//	是否需要发票 ，0-默认	
        InvoiceName: '',//	发票名称		
        InvoiceType: 0,//	发票类型1-个人，2-企业，3-非企业性单位
        // InvoiceTypeObj:'',	
        DutyParagraph: '',//	税号		
        Receiver: '',//	收件人		
        ReceiverPhone: '',//	收件人电话		
        ReceiverProvince: '',//	收件人省		
        ReceiverProvinceId: '',
        // ReceiverProvinceObj: '',
        ReceiverCity: '',//	收件人市
        ReceiverCityObj: '',
        ReceiverAddress: '',//	收件人地址
        ReceiverCity: '',//	收件人市		
        ReceiverAddress: '',//	收件人地址		
        RelationPhoneType: 2,//	手机号码归属国家
        // RelationPhoneTypeObj: '',
        EnterCountryTime: '',//	入境时间
        AdultPeopleNum: null,
        ChildPeopleNum: null,
        Remark: '',
        PeopleNum: 0,
      },
      isUpdateUserInfo: false,
      countrys: [],
      areaCodes: [],
      guest: {
        MobilePhone:'',//旅客的手机号码
        SurName:'',//旅客中文姓
        Name:'',//旅客中文名
        ESurName:'',//旅客英文姓
        EName:'',//旅客英文名
        Duty:'',//客户类型
        IdCard: '',//证件号
      },
      guests: [],
      disableSign: false,
      orderKey: "",
      order: {},
      trip: null,
      price: null,
      unionCity: null,
      sumPrice: 0,
      submiting: false,
      CouponIds: [],
      productType: 0,
      isCreateGuest:false,
      InvoiceTypes:[
        {label:'个人',value:1},
        {label:'企业',value:2},
        {label:'非企业性单位',value:3}
      ],
      areaCode:[],
      provinceList: [],
      cityList: [],
      customerTypes: [],
    };
  },
  computed: {
    filedWidth() {
      return {
        "col-12": this.$q.screen.width < 1200,
        "col-6": this.$q.screen.width >= 1200,
      };
    },
    filedGuestWidth() {
      return {
        "col-12": this.$q.screen.width < 1200,
        "col-4": this.$q.screen.width >= 1200,
      };
    },
    filedTypeWidth() {
      return {
        "col-6": this.$q.screen.width < 1200,
        "col-3": this.$q.screen.width >= 1200,
      };
    },
  },
  created() {
    if (this.checkParamsHandler()) {
      this.initGuestHandler()
      this.getTripData();
      this.getUserInfoHandler();
    }
    this.GetSelectData()
  },
  mounted() {
    if (localStorage.b2bUser) {
      var b2bUser = JSON.parse(window.localStorage.getItem('b2bUser'))
      if (b2bUser) {
        
      }
    }
  },
  methods: {
    optionsFn(cd) {
      return (
        cd >=
        date.formatDate(date.addToDate(new Date(), { days: this.trip.BookAdvance?this.trip.BookAdvance:7 }), "YYYY/MM/DD")
      );
    },
    getTime(type) {
      if(type==1) this.$refs.EnterCountryTime.hide()
      if(type==2) this.$refs.qDateProxy7.hide()
      if(type==3) this.$refs.qDateProxy8.hide()
    },
    getValue(e,type,i) {
      if(type=='Invoice') this.chosenObj.InvoiceType = e.value
      // if(type=='AreaCode') this.chosenObj.RelationPhoneType = e.PhoneCode
      if(type=='Province') {
        this.provinceList.filter(item=>{
          if(item.Name==e) {
            this.chosenObj.ReceiverProvinceId = item.ID
          } 
        })
        this.getCity()
      }
      // if(type=='Receiver') this.chosenObj.ReceiverCity = e.ID
      if(type=='Duty') this.guests[i].Duty = e.Code
      if(type=='AdultPeopleNum') {
        let AdultPeopleNum = this.chosenObj.AdultPeopleNum?this.chosenObj.AdultPeopleNum:0
        let ChildPeopleNum = this.chosenObj.ChildPeopleNum?this.chosenObj.ChildPeopleNum:0
        this.chosenObj.PeopleNum = Number(AdultPeopleNum)+Number(ChildPeopleNum)
        let People = 0
        if(this.chosenObj.PeopleNum>this.guests.length){
          People = this.chosenObj.PeopleNum-this.guests.length
          for (let j = 0; j < People; j++) {
            this.guests.push(JSON.parse(JSON.stringify(this.guest)))
          }
        }
        if(this.guests.length>this.chosenObj.PeopleNum){
          People = this.guests.length-this.chosenObj.PeopleNum
          for (let j = 0; j < People; j++) {
            let index = this.guests.length-1
            this.guests.splice(index,1)
          }
        }
        if(this.chosenObj.PeopleNum==0) this.guests = []
        this.calcMoney()
      }
    },
    GetSelectData() {
      // this.apipost(
      //   "dict_post_Destination_GetPhoneCodeListExt",
      //   {},
      //   (res) => {
      //     if (res.data.resultCode == 1) {
      //       this.areaCode = res.data.data
      //     } else {
      //       this.$message.error(res.data.message);
      //     }
      //   },
      //   (err) => {
          
      //   }
      // );
      // this.apipost('dict_get_GetDictValueCommonList', {
      //   "Key":"SK_CRM_DutyType"
      // }, res => {
      //   if (res.data.resultCode == 1) {
      //     this.customerTypes = res.data.data
      //   }
      // }, err => {})
      this.apipost('dict_post_Destination_GetChildList', {
        Id: 2,
        "level": 1
      }, res => {
        if (res.data.resultCode == 1) {
          this.provinceList = res.data.data
        }
      }, err => {})
    },
    //市
    getCity() {
      this.apipost('dict_post_Destination_GetChildList', {
        Id: this.chosenObj.ReceiverProvinceId,
        "level": 2
      }, res => {
        if (res.data.resultCode == 1) {
          this.cityList = res.data.data;
        }
      }, err => {})
    },
    // 区
    getRegion() {
      this.apipost('app_customer_GetChildList', {
        Id: this.userInfo.CityObj.ID,
        "level": 3
      }, res => {
        if (res.data.resultCode == 1) {
          this.regionList = res.data.data;
        }
      }, err => {})
    },
    async submitHandler() {
      let flag = true;
      flag = await this.formValidateHandler("baseUserInfo");
      if (!flag) {
        this.goScrollToForm("baseUserInfoTitle");
      } else {
        flag = await this.formValidateHandler("baseCustomerInfo");
        if (!flag) {
          this.goScrollToForm(`baseCustomerTitle`);
          return
          // for (let i = 0; i < this.guests.length; i++) {
          //   flag = await this.formValidateHandler("guest" + i);
          //   if (!flag) {
          //     this.goScrollToForm(`guest${i}Title`);
          //     return
          //   }
          // }
          
        }else{
          flag = await this.formValidateHandler("baseRecipientInfo");
          if (!flag) {
            this.goScrollToForm("baseRecipientTitle");
            return
          }
        }
        // if(flag&&this.chosenObj.PeopleNum==0) return this.$message.error("请输入成人或者儿童人数！");
        
        if (flag) {
          this.submiting = true;
          this.submitOrderHandler();
          return;
        }
      }
      this.submiting = false;
    },
    submitOrderHandler() {
      let msg = {
        Id: 0,
        VisaId: this.order.order.Pid,
        AdultPeopleNum: this.chosenObj.AdultPeopleNum,//大人
        ChildPeopleNum: this.chosenObj.ChildPeopleNum,//小孩
        TotalPrice: this.sumPrice,//总价
        CustomerId: 0,//客户id
        CreateBy: 0,//销售
        OrderSource: 3,//1-ERP,2-B2B订单，3-B2C订单，4wap 5同业  6支付宝
        EnterCountryTime: this.chosenObj.EnterCountryTime,//入境时间
        GuestList: [],//this.guests
        VisaOrderRelation:{
          RelationName: this.userInfo.Surname + this.userInfo.Name,//	联系名称	
          RelationPhone: this.userInfo.Moblie,//	电话	
          RelationEmail: this.userInfo.Mailbox,//	邮箱		
          IsNeedInvoice: this.chosenObj.IsNeedInvoice,//	是否需要发票 ，0-默认	
          InvoiceName: this.chosenObj.InvoiceName,//	发票名称		
          InvoiceType: this.chosenObj.InvoiceType,//	发票类型1-个人，2-企业，3-非企业性单位	
          DutyParagraph: this.chosenObj.DutyParagraph,//	税号		
          Receiver: this.chosenObj.Receiver,//	收件人		
          ReceiverPhone: this.chosenObj.ReceiverPhone,//	收件人电话		
          ReceiverProvince: this.chosenObj.ReceiverProvince,//	收件人省		
          ReceiverCity: this.chosenObj.ReceiverCity,//	收件人市		
          ReceiverAddress: this.chosenObj.ReceiverAddress,//	收件人地址		
          RelationPhoneType: this.chosenObj.RelationPhoneType,//	手机号码归属国家
        },
        OrderForm: 1,//1电脑端
        ClientType: 2,//客户类型 1同业 2直客
        Remark: this.chosenObj.Remark,
      };
      console.log(msg,'-------')
      // return
      this.apipost(
        "b2b_get_SetB2BVisaOrder",
        msg,
        (res) => {
          if (res.data.resultCode == 1) {
            console.log(res,'-------下单')
            if (this.isUpdateUserInfo) {
              this.setUserInfoHandler();
            }
            // if (this.isCreateGuest) {
            //   this.uploadGuests(0, res.data.data.OrderId);
            // } else {
            //   this.submitB2COrderHandler(res.data.data.OrderId);
            // }
            this.submitB2COrderHandler(res.data.data.airOrderId);
          } else {
            this.$message.error(res.data.message);
          }
          this.submiting = false;
        },
        (err) => {
          this.submiting = false;
        }
      );
    },
    uploadGuests(i, orderId) {
      let currentGuest = this.guests[i];
      currentGuest.OrderId = orderId;
      currentGuest.TCID = this.order.order.tcid;
      this.apipost(
        "sellorder_post_SetTravelGuestInfo_V2",
        currentGuest,
        (r) => {
          if (i < this.guests.length - 1) {
            i++;
            this.uploadGuests(i, orderId);
          } else {
            this.submitB2COrderHandler(orderId);
          }
        }
      );
    },
    submitB2COrderHandler(orderId) {
      let guestInfo = `${this.chosenObj.AdultPeopleNum} 人; `;
      if (this.chosenObj.ChildPeopleNum > 0) {
        guestInfo += `兒童x${this.chosenObj.ChildPeopleNum}; `;
      }
      let msg = {
        SurName: this.userInfo.Surname,
        Name: this.userInfo.Name,
        ContactNumber:
          this.userInfo.PhoneCountryStr + " " + this.userInfo.Moblie,
        Mailbox: this.userInfo.Mailbox,
        GoodsId: this.order.order.Pid,
        GoodsName: this.trip.Name,
        GoodsPic: this.trip.CoverImageList.length>0&&this.trip.CoverImageList[0].Url?this.trip.CoverImageList[0].Url:'',
        GoodsType: this.productType,//产品类型
        OrderMake: `${guestInfo} ${this.chosenObj.EnterCountryTime}入境`,// 摘要
        TotalPrice: this.sumPrice,
        PreferentialPrice: 0,//this.price.discountPrice 优惠总金额
        ErpOrderId: orderId,
        Country: this.userInfo.Country,
        PlatformTax: 0,
        Income: 0,
        Refund: 0,
      };
      this.apipost("AddOrderInfo_post", msg, (r) => {
        if (r.data.resultCode == 1) {
          this.$message.success("訂單創建成功");
          this.goPayHandler(r.data.data);
        } else {
          this.$message.error(r.data.message);
        }
      });
    },
    getProductTypeHandler() {
      return (
        this.price.teamType == 0
          ? ProductTypeEnum.TEAM_TRIP
          : this.price.teamType == 2
          ? ProductTypeEnum.ONE_DAY
          : ProductTypeEnum.UNIT_TRIP
      ).value;
    },
    goPayHandler(pay) {
      let lineVisas = localStorage.getItem("lineVisas");
      lineVisas = lineVisas ? JSON.parse(lineVisas) : [];
      let i = lineVisas.findIndex((x) => x.key == this.orderKey);
      if (i >= 0) {
        lineVisas.splice(i, 1);
        localStorage.setItem("lineVisas", JSON.stringify(lineVisas));
      }
      this.CommonJump("/pay/" + pay.OrderNo, {});
    },
    GUID() {
      return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, function (c) {
        var r = (Math.random() * 16) | 0,
          v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
      });
    },
    async formValidateHandler(formName) {
      let temp = this.$refs[formName];
      let formObj = temp instanceof Array ? temp[0] : temp;
      return formObj.validate();
    },
    goScrollToForm(formName) {
      let temp = this.$refs[formName];
      let formObj = temp instanceof Array ? temp[0] : temp;
      window.scrollTo(0, formObj.offsetTop);
    },
    checkParamsHandler() {
      try {
        if (this.$route.params && this.$route.params.id) {
          let key = this.$route.params.id;
          let lineVisas = localStorage.getItem("lineVisas");
          lineVisas = lineVisas ? JSON.parse(lineVisas) : [];
          if (lineVisas.length > 0) {
            this.order = lineVisas.find((x) => x.key == key);
            if (this.order) {
              this.orderKey = key;
            }
          }
        }
      } catch (error) {
        console.log(error);
      }
      if (this.orderKey == "") {
        setTimeout(() => {
          location.href = location.origin;
        }, 3000);
      }
      return this.orderKey != "";
    },
    changeDiscountHandler(coupon) {
      if (coupon) {
        this.price.discountPrice = coupon.discountMoney;
        this.CouponIds = [coupon.couponId];
      } else {
        this.price.discountPrice = 0;
        this.CouponIds = [];
      }
      this.calcMoney();
      this.$forceUpdate();
    },
    calcMoney() {
      let money = this.chosenObj.PeopleNum * this.trip.VisaB2CPrice;
      this.sumPrice = money;
    },
    changeRoomHandler() {
      let currentSign = this.guests.filter((x) => x.IsSignRoom);
      this.disableSign = currentSign == this.chosenObj.df;
    },
    initGuestHandler() {
      
    },
    initCountry() {
      this.apipost("GetCountryInfo_post", {}, (r) => {
        this.countrys = r.data.data.phoneCountList;
        if(!this.userInfo.Country){
          this.userInfo.Country = this.countrys[0].ID;
          this.userInfo.PhoneCountryStr = '+'+this.countrys[0].PhoneCode
        }
        
        this.chosenObj.RelationPhoneType = this.countrys[0].PhoneCode;
        this.areaCodes = r.data.data.phoneCountList;
        this.changeCountry(this.userInfo.Country);
        this.areaCodes.forEach((x) => {
          let temp = this.countrys.find((y) => y.ID == x.ID);
          x.EnName = `${temp.EnName}(${x.PhoneCode})`;
        });
        this.userInfo.Country =
          this.userInfo.Country == 0
            ? this.countrys[0].ID
            : this.userInfo.Country;
        this.changeCountry(this.userInfo.Country);
      });
    },
    changeCountry(id) {
      this.userInfo.PhoneCountry = this.areaCodes.find(
        (x) => x.ID == id
      ).PhoneCode;
      this.userInfo.PhoneCountryStr = "+" + this.userInfo.PhoneCountry;
    },
    getUserInfoHandler() {
      let u = this.$user.userInfo;
      if (u) {
        this.apipost("GetCustomerInfo_post", { Id: u.id }, (r) => {
          if (r.data.resultCode == 1) {
            this.userInfo = r.data.data
            console.log(this.userInfo,'-----')
            Object.assign(this.userInfo, r.data.data)
          } else {
            this.$user.userInfo = null;
          }
          this.initCountry();
        });
      }
    },
    setUserInfoHandler() {
      this.apipost("UpdateUserInfo_post", this.userInfo, (r) => {
        console.log(r,'-----同步会员接口');
      });
    },
    getTripData() {
      this.$q.loading.show();
      let msg = {
        Pid: this.order.order.Pid,
      };
      this.apipost(
        "b2c_get_GetB2CVisaProductInfo",
        msg,
        (r) => {
          if (r.data.resultCode == 1) {
            this.trip = r.data.data;
            this.price = this.trip.VisaProductInfo;
            // this.price.realPrice = this.price.originalB2CPrice;
            // if (
            //   this.order.order.startCityId &&
            //   this.order.order.startCityId != this.trip.startCityId
            // ) {
            //   this.unionCity = this.price.unionCityList.find(
            //     (x) => x.cityId == this.order.order.startCityId
            //   );
            //   if (
            //     this.unionCity.backFlight &&
            //     this.unionCity.backFlight.addPrice
            //   ) {
            //     this.price.originalB2CPrice +=
            //       this.unionCity.backFlight.addPrice;
            //   }
            //   if (this.unionCity.goFlight && this.unionCity.goFlight.addPrice) {
            //     this.price.originalB2CPrice += this.unionCity.goFlight.addPrice;
            //   }
            // }
            this.calcMoney();
            this.productType = 15//this.getProductTypeHandler();
          } else {
            this.$q.notify({
              type: "negative",
              message: r.data.message,
              position: "top",
              timeout: 2000, // 以毫秒为单位; 0意味着没有超时
            });
          }
          this.$q.loading.hide();
        },
        null
      );
    },
  },
};
</script>
<style>
.order-preview .q-stepper__content {
  display: none !important;
}
.order-preview .q-toggle__track {
  height: 0.7em;
  border-radius: 0.35em;
  opacity: 0.38;
  width: 50px;
}
.order-preview .q-toggle__thumb {
  top: 0.42em;
  left: 0.45em;
  width: 0.5em;
  height: 0.5em;
  transition: left 0.22s ease-in-out;
  user-select: none;
  z-index: 0;
}
.order-preview .q-toggle__inner--truthy .q-toggle__thumb {
  left: 0.94em;
}
.order-preview .q-toggle__inner {
  width: 1.9em;
}
.order-preview .q-toggle__label {
  margin-top: 12px;
}
.guest-item:hover {
  background: rgba(241, 65, 108, 0.04) !important;
}
</style>
