<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,
        }"
      > 
        <div class="col">
          <q-form ref="baseUserInfo">
          <q-card flat class="q-pa-md">
            <div class="text-subtitle1 text-weight-bolder">訂購人資訊</div>
            <q-separator color="grey-2" class="q-my-md" />
            <div class="row q-col-gutter-md">
              <div :class="filedWidth">
                <q-select
                  v-model="userInfo.Country"
                  @input="changeCountry"
                  :options="countrys"
                  emit-value
                  option-label="Name"
                  option-value="ID"
                  map-options
                  label="國家/地區"
                  standout
                />
              </div>
              <div :class="filedWidth">
                <q-input
                  standout
                  v-model="userInfo.Mailbox"
                  label="郵箱地址"
                  :rules="[(val) => /^[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$/.test(val) || '請輸入正確的郵箱地址']"
                  ref="mail"
                />
              </div>
            </div>
          </q-card>
  
          <q-card flat class="q-pa-md q-mt-lg" v-if="details">
            <div class="text-subtitle1 text-weight-bolder q-mb-md">旅客資料</div>
            <div class="row">
              <vue-core-video-players
                v-if="details.videoStr"
                ref="video"
                :src="details.videoStr"
                :title="details.title"
                :muted="true"
                :autoplay="false"
                @play="playHandler"
                @pause="pauseHandler"
                @seeked="seekedChangeHandler"
                @timeupdate="timeChangeHandler"
                logo="../statics/img/transparent_logo.png"
                :loop="false"
                id="trip_video"
                class="rounded-borders"
                style="width: 80px"
              />
              <q-img
                v-else
                :src="details?details.PicPathList[0]:'https://image.kkday.com/v2/image/get/s1.kkday.com/product_138437/20230217083232_t5rcO/jpg'"
                class="rounded-borders"
                spinner-color="grey-3"
                style="width: 80px"
              />
              <div class="q-ml-md col">
                <div class="text-subtitle1 ellipsis">
                  {{details.Name}}
                </div>
                <div class="text-caption text-grey-6 ellipsis q-mt-sm">
                  {{details.Feature}}
                </div>
              </div>
            </div>
            <div class="q-mt-md row">
              <div class="text-grey-9">
                <q-icon name="iconfont iconrili" size="20px" class="q-mr-sm" />
                <span>{{OrderDate.startDate}}</span>
              </div>
              <div class="text-grey-9 q-ml-md" v-if="optionObj">
                <q-icon name="iconfont iconpeople" size="20px" class="q-mr-sm" />
                <span class="q-mr-sm" v-for="(x,i) in optionObj" :key="i"
                  >{{x.TicketName}} x {{ x.Count }}张 </span
                >
                <span class="q-mr-sm"
                  ></span
                >
                <q-icon name="iconfont icontime" size="20px" class="q-mr-xs q-ml-sm" />
                <span class="q-mr-sm">
                  行程時間 1 天
                </span>
              </div>
            </div>
            <div v-if="parameters.MailingState==1" class="rounded-borders bg-blue-1 q-px-lg q-py-sm q-mt-sm">
              自取地址：{{parameters.SelffetchAddress}}
            </div>
            <div v-if="parameters.MailingState==4" class="rounded-borders bg-blue-1 q-px-lg q-py-sm q-mt-sm">
              电子券
            </div>
            <q-separator color="grey-2" class="q-mt-md" />
            
            <div v-if="parameters.MailingState!=4"
              class="bg-grey-1 rounded-borders q-pa-md q-mt-md guest-item"
            >
              <div class="text-subtitle1 q-pb-md text-weight-bold"></div>
              <div class="row q-col-gutter-md">
                <div :class="filedGuestWidth">
                  <q-input
                    standout
                    v-model="parameters.Name"
                    label="本國姓名"
                    placeholder="例：張三"
                    :rules="[(val) => !!val || '請輸本國姓名']"
                    ref="SurName"
                  />
                </div>
                <div :class="filedGuestWidth">
                  <q-input
                    standout
                    v-model="parameters.EName"
                    label="本國姓名(英文)"
                    placeholder="例：zhangsan"
                    :rules="[(val) => !!val || '請輸本國姓名(英文)']"
                    ref="Name"
                    mask="X"
                    reverse-fill-mask
                  />
                </div>
                <div :class="filedGuestWidth">
                  <q-input
                      standout
                      v-model="parameters.Mobile"
                      label="電話"
                      :rules="[(val) => !!val || '請輸正確電話']"
                      ref="Mobile"
                      mask="#"
                      reverse-fill-mask
                  >
                      <template v-slot:prepend>
                      <div class="text-subtitle2">+{{ userInfo.areaCode }}</div>
                      </template>
                  </q-input>
              </div>
              <div :class="filedGuestWidth" v-if="parameters.MailingState==2">
                <q-input
                    standout
                    v-model="parameters.MailingAddress"
                    label="郵寄地址"
                    :rules="[(val) => !!val || '請輸郵寄地址']"
                    ref="MailingAddress"
                ></q-input>
            </div>
              <div :class="filedGuestWidth">
                  <div class="row items-center q-mt-md">
                    <span>選擇性別：</span>
                    <q-radio
                      v-model="parameters.Sex"
                      dense
                      :val="1"
                      label="男"
                      class="q-mr-lg"
                    />
                    <q-radio v-model="parameters.Sex" dense :val="2" label="女" />
                  </div>
                </div>
              </div>
            </div>
            <div class="text-subtitle1 q-my-md text-weight-bold">特殊需求備註：</div>
            <q-input standout v-model="parameters.Remark" input-style="height:170px;" type="textarea"  placeholder="此欄位僅限資料備註。不在商品規範內的個人需求，不保證提供" maxlength="200" counter />
          </q-card>
          </q-form>
          <coupon
          v-if="sumPrice>0"
          :product-type="productType"
          :current-price="sumPrice"
          @change="changeDiscountHandler"
        ></coupon>
        </div>
        
        <div class="relative-position" v-if="details"
          :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">
              <vue-core-video-players
                v-if="details.videoStr"
                ref="video"
                :src="details.videoStr"
                :title="details.title"
                :muted="true"
                :autoplay="false"
                @play="playHandler"
                @pause="pauseHandler"
                @seeked="seekedChangeHandler"
                @timeupdate="timeChangeHandler"
                logo="../statics/img/transparent_logo.png"
                :loop="false"
                id="trip_video"
                class="rounded-borders"
                style="width: 80px"
              />
              <q-img
                v-else
                :src="details?details.PicPathList[0]:'https://image.kkday.com/v2/image/get/s1.kkday.com/product_138437/20230217083232_t5rcO/jpg'"
                class="rounded-borders"
                spinner-color="grey-3"
                style="width: 80px"
              />
              <div class="q-ml-md col">
                <div class="text-subtitle1 ellipsis">
                  {{details.Name}}
                </div>
                <div class="text-caption text-grey-6 ellipsis q-mt-sm">
                  {{details.Feature}}
                </div>
              </div>
            </div>
            <div class="q-mt-md text-grey-6">
              <div class="row">
                <div style="width: 80px">
                  门票日期：</div>
                <div class="q-ml-md">
                  {{parameters.UseDate}}
                </div>
              </div>
            </div>
            <q-separator color="grey-2" class="q-my-md"/>
            <div class="text-grey-9">
              <template v-if="optionObj">
                <div class="row q-mb-sm" v-for="(x,i) in optionObj" :key="i">
                  <template v-if="x.checked">
                    <div class="col">{{x.TicketName}} x {{ x.Count }}</div>
                    <div>{{ moneyFormat(x.originalB2CPrice,2) }}</div>
                  </template>
                </div>
              </template>
              <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" v-if="parameters.MailingState==2&&parameters.MailingMoney>0">
                <div class="col">邮寄费</div>
                <div
                  class="text-subtitle2 text-weight-bolder text-grey-6"
                >
                  CNY  {{ moneyFormat(parameters.MailingMoney,2) }}
                </div>
              </div>
              <div class="row q-mb-sm items-center">
                <div class="col">優惠金額</div>
                <div
                  class="text-subtitle2 text-weight-bolder text-teal"
                  v-if="parameters.DiscountsMoney > 0"
                >
                  CNY - {{ moneyFormat(parameters.DiscountsMoney, 2) }}
                </div>
                <div class="text-grey-5" v-else>暫無優惠</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(parameters.Money, 2) }}
                </div>
              </div>
            </div>
            <div class="text-right q-mt-md" v-if="step!=3">
              <q-btn v-if="step!=3" unelevated color="primary" 
              :loading="loading" :label="step!=3?'立即支付':'已支付'" @click="submit()"
              :disable="step!=3&&loading"/>
              <q-btn v-else unelevated color="primary" label=""/>
            </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 NoneData from "src/components/common/noneData.vue";
  import auth from "src/components/common/auth.vue";
  import { date } from 'quasar'
  import { json } from "body-parser";
  import coupon from 'src/components/common/coupon.vue'
  import ProductTypeEnum from "src/utils/producttypeenum";
  import componentsMap from "src/components/car/Map.vue";
  export default {
    components:{
      coupon,
      componentsMap,
      NoneData,
      auth
    },
    data() {
      return {
        CouponIds: [],
        productType: 4,
        sumPrice: 0,//总金额
        order: null,//订单信息
        orderKey: "",
        optionObj: null,//类型
        details: null,//产品详情
        options: {//音频控件
          currentPage: 0,
          speed: 300,
          itemAnimation: true,
          centeredSlides: true,
          thresholdDistance: 100,
          thresholdTime: 300,
          loopedSlides: 2,
          slidesToScroll: 1,
          loop: true,
        },
        OrderDate: null,//接收产品相关信息
        step: 1,
        userInfo: {
          Country: 0,
          areaCode: "",
          Mailbox: "",
          Mobile: "",
          FullName: ""
        },
        countrys: [],
        areaCodes: [],
        loading: false,
        parameters: {
            OrderId: 0,
            Money: 0.0,
            DiscountsMoney: 0,//优惠金额
            DiscountsIds: '',//优惠券id
            Remark: '',
            MailingState: '',//邮寄状态 1自取 2邮寄
            MailingAddress: '',//MailingState =2 填写邮寄
            MailingMoney: null,
            SelffetchAddress: '',//自取地址
            UseDate:'',//门票日期
            Name:'',
            EName:'',
            Sex: 1,//1男2女
            Birthday: '',
            Mobile:'',
            CouponsId:'',//景点id
            DetailList:[],
            OrderSource: 1,//类型 0 来源B2B 1 来源B2C
        },
        TotalPeople: 0,//总人数
      };
    },
    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,
        };
      },
    },
    created() {},
    mounted() {
      if(this.checkParamsHandler()){
        this.getData()
      }
      
      this.initGuestHandler();
      this.getUserInfoHandler()
    },
    methods: {
      changeDiscountHandler(coupon) {
        if (coupon) {
          this.parameters.DiscountsMoney = coupon.discountMoney;
          this.CouponIds = [coupon.couponId];
          this.parameters.DiscountsIds = this.CouponIds.join(",")
        } else {
          this.parameters.DiscountsMoney = 0;
          this.CouponIds = [];
          this.parameters.DiscountsIds = ''
        }
        this.parameters.Money = this.sumPrice - this.parameters.DiscountsMoney
        this.$forceUpdate();
      },
      // 获取商品详情
      getData() {
        this.$q.loading.show();
        this.apipost(
          "b2c_get_GetTicketCouponsDetail",
          { CouponsId: this.parameters.CouponsId },
          (r) => {
            if (r.data.resultCode == 1) {
              this.details = r.data.data;
              if(this.parameters.MailingState==1){
                  this.parameters.SelffetchAddress = this.details.SelffetchAddress
                  this.parameters.MailingMoney = null
              }else{
                this.parameters.MailingMoney = this.OrderDate.MailingMoney
                this.parameters.SelffetchAddress = ''
              }
            } else {
              this.$q.notify({
                type: "negative",
                message: r.data.message,
                position: "top",
                timeout: 2000, // 以毫秒为单位; 0意味着没有超时
              });
            }
            this.$q.loading.hide();
          },
          null
        );
      },
      checkParamsHandler() {
        try {
          if (this.$route.params && this.$route.params.id) {
            let key = this.$route.params.id;
            let pickuporderScenTickets = localStorage.getItem("pickuporderScenTickets");
            pickuporderScenTickets = pickuporderScenTickets ? JSON.parse(pickuporderScenTickets) : [];
            if (pickuporderScenTickets.length > 0) {
              this.order = pickuporderScenTickets.find((x) => x.key == key);
              if (this.order) {
                this.orderKey = key;
                this.OrderDate = this.order.order
                this.parameters.CouponsId = this.order.order.CouponsId
                this.parameters.MailingState = this.OrderDate.MailingState
                this.parameters.UseDate = this.OrderDate.startDate
                this.getBusTimeDate = this.OrderDate.startDate
                this.parameters.Money = this.OrderDate.sumPrice
                this.optionObj = this.OrderDate.TicketList
                this.parameters.DetailList = []
                this.optionObj.forEach(x=>{
                  if(x.checked){
                    let y = {
                      TicketName: x.TicketName,
                      Unit_Price: x.originalB2CPrice,
                      Num: x.Count,
                      Money: x.originalB2CPrice*x.Count,
                      TicketId: x.Id
                    }
                    this.parameters.DetailList.push(y)
                  }
                })
                this.sumPrice = this.OrderDate.sumPrice
              }
            }
          }
        } catch (error) {
          console.log(error);
        }
        if (this.orderKey == "") {
          setTimeout(() => {
  
          }, 3000);
        }
        return this.orderKey != "";
      },
      async submit() {
        this.$refs.mail.validate()
        if(this.parameters.MailingState!=4){
          this.$refs.SurName.validate()
          this.$refs.Name.validate()
          this.$refs.Mobile.validate()
        }
        
        if(this.parameters.MailingState==2){
          this.$refs.MailingAddress.validate()
        }else{
          this.parameters.MailingAddress = ''
          this.parameters.MailingMoney = 0
        }
        
        let flag = true
        flag = await this.formValidateHandler('baseUserInfo')
        if(!flag){
          let errorObj = this.$refs.baseUserInfo.getValidationComponents().find(x=>x.innerError)
          window.scrollTo(0,errorObj.$el.offsetTop)
        }else{
          this.SetCarOrder()
        }
      },
      async formValidateHandler(formName){
        let temp=this.$refs[formName]
        let formObj = temp instanceof Array ? temp[0] : temp
        return formObj.validate()
      },
      SetCarOrder(){
        this.loading = true
        this.apipost(
          "ticket_post_SetTicketOrder",
          this.parameters,
          (r) => {
            if (r.data.resultCode == 1) {
              this.step = 2
              let ErpOrderId = r.data.data.Id
              this.AddOrderInfo(ErpOrderId)
            }else{
              this.$message.error(r.data.message)
              this.loading = false
            }
        })
      },
      AddOrderInfo(ErpOrderId){
        this.apipost(
          "AddOrderInfo_post",
          {
            SurName: this.parameters.Name?this.parameters.Name:this.userInfo.Surname+this.userInfo.Name,
            Name: '',
            ContactNumber: this.userInfo.Mobile,//	联系电话
            Mailbox: this.userInfo.Mailbox,//邮箱
            GoodsId: this.parameters.CouponsId,//商品id
            GoodsName: this.details.Name,//商品名称
            GoodsPic: this.details.PicPathList[0],//商品图片
            GoodsType: this.productType,
            OrderMake: this.parameters.UseDate,//订单摘要（例如出行时间）
            TotalPrice: this.parameters.Money,//总价格
            PreferentialPrice: this.parameters.DiscountsMoney,//	优惠总金额
            ErpOrderId: ErpOrderId,//erp订单id
            Country: this.userInfo.Country,//国家id
            PlatformTax: 0,//平台税金默认0
            Income: 0,//已收默认0
            Refund: 0,//退款金额默认0
          },
          (r) => {
            if (r.data.resultCode == 1) {
              this.step = 3
              this.$message.success("訂單創建成功")
              this.goPayHandler(r.data.data)
            }else{
              this.$message.error(r.data.message)
            }
            this.loading = false
        })
      },
      goPayHandler(pay){
        let pickuporderScenTickets = localStorage.getItem("pickuporderScenTickets");
        pickuporderScenTickets = pickuporderScenTickets ? JSON.parse(pickuporderScenTickets) : [];
        let i = pickuporderScenTickets.findIndex((x) => x.key == this.orderKey);
        if (i >= 0) {
          pickuporderScenTickets.splice(i, 1);
          localStorage.setItem("pickuporderScenTickets", JSON.stringify(pickuporderScenTickets));
        }
        this.CommonJump("/pay/" + pay.OrderNo, {});
      },
      optionsFn(cd) {
        return (
          cd >=
          date.formatDate(date.addToDate(new Date(), { days: 0 }), "YYYY/MM/DD")
        );
      },
      // 音频
      slideHandler(e) {
        this.options.currentPage = e.currentPage;
        if (
          e.currentPage != 0 &&
          this.$refs.video &&
          this.$refs.video.isPlaying
        ) {
          this.$refs.video.pause();
        }
      },
      playHandler(e) {},
      pauseHandler(e) {},
      timeChangeHandler(e) {
        //console.log(e)
      },
      //
      seekedChangeHandler(e) {
        //console.log(e)
      },
      initGuestHandler() {
       
      },
      // 获取当前用户信息
      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;
              if(r.data.data.Moblie){
                if(this.parameters.MailingState!=4){
                  this.parameters.Mobile = r.data.data.Moblie
                }
                this.userInfo.Mobile = r.data.data.Moblie
              }
            } else {
              this.$user.userInfo = null;
            }
            this.initCountry();
          });
        }
      },
      // 初始化国家
      initCountry() {
        this.apipost("GetCountryInfo_post", {}, (r) => {
          if (r.data.resultCode == 1) {
            this.countrys = r.data.data.countList;
            this.userInfo.Country = this.countrys[0].ID;
    
            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})`;
            });
          }
        });
      },
      changeCountry(id) {
        this.userInfo.areaCode = this.areaCodes.find((x) => x.ID == id).PhoneCode;
      },
    },
  };
  </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,.04) !important;
  }
  .text-h6Detail {
    text-align: center;
    font-size: 18px;
    color: #333;
    font-weight: 700;
    position: relative;
    width:100%;
    height:50px;
  }
  .text-h6Detail i {
    position: absolute;
    right:20px;
    top:10px;
    cursor: pointer;
    font-size:23px;
  }
  </style>
  