<template>
  <div class="submit-order">
    <div class="content">
      <div class="step-box">
        <div class="left">
          <span class="img"></span>
          <span class="text">{{$t('submitOrder.submitOrder')}}</span>
        </div>
        <div class="steps">
          <div class="item">
            <div class="number">step 01.</div>
            <div class="text">{{$t('submitOrder.selectProductToBuy')}}</div>
          </div>
          <div class="item active">
            <div class="number">step 02.</div>
            <div class="text">{{$t('submitOrder.confirmOrderInformation')}}</div>
          </div>
          <div class="item">
            <div class="number">step 03.</div>
            <div class="text">{{$t('submitOrder.payToCompleteTheOrder')}}</div>
          </div>
        </div>
      </div>
      <div class="submit-con">
        <!-- 收货地址 -->
        <div v-if="orderInfo.mold !== 1" class="submit-box">
          <div class="tit">
            <span class="text">{{$t('address.receivingAddress')}}</span>
            <!-- <span class="action">显示全部地址</span> -->
          </div>
          <div class="con address-box">
            <div
              :class="['item', address.commonAddr?'default-address':'',selectedAddrId==address.addrId?'active':'']"
              v-for="address in addressList"
              :key="address.addrId"
              @click="changeAddress(address.addrId)"
            >
              <div class="name-phone">
                <span class="name">{{address.receiver}}</span>
                <span class="phone">{{address.mobile}}</span>
                <span
                  class="set-default"
                  v-if="!address.commonAddr"
                  @click="setDefaultAddr(address.addrId)"
                >{{$t('address.setDefault')}}</span>
                <span class="default-tag" v-if="address.commonAddr">{{$t('address.default')}}</span>
              </div>
              <div
                class="address-detail"
              >{{address.province+address.city+address.area+address.addr}}</div>
              <div class="del-edit">
                <span class="edit" @click.stop="editAddr(address.addrId)"></span>
                <span class="del" @click.stop="toggleDelAddr(true,address.addrId)"></span>
              </div>
            </div>
            <div
              class="item add-address"
              @click="toggleAddrPop(true)"
              v-if="addressList.length < 10"
            >
              <div class="add-box">
                <div class="img">+</div>
                <div class="text">{{$t('address.addAddress')}}</div>
              </div>
            </div>
          </div>
          <div class="popup-mask" v-if="showDelAddr"></div>
          <div class="fix-transform-blur">
            <div class="popup-box" v-if="showDelAddr">
              <div class="tit" style="padding:10px;">
                <div class="text">{{$t('tips')}}</div>
                <div class="close" @click="toggleDelAddr(false)"></div>
              </div>
              <div class="con">
                <div class="tip">
                  <div class="tip-icon warning"></div>
                  <div class="tip-info">
                    <div class="result">{{$t('address.deleteShippingAddress')}}</div>
                    <div class="date">{{$t('address.deleteShippingTips')}}</div>
                    <div class="btns">
                      <a href="javascript:void(0);" @click="delAddr()" class="btn-r">{{$t('delete')}}</a>
                      <a href="javascript:void(0);" @click="toggleDelAddr(flase)" class="btn-g">{{$t('cancel')}}</a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 收货地址 -->
        <!-- 支付方式 -->
        <div class="submit-box">
          <div class="tit">
            <span class="text">{{$t('commonFoot.paymentMethod')}}</span>
          </div>
          <div class="con pay-way">
            <div class="item active">{{$t('submitOrder.payOnline')}}</div>
            <!-- <div class="item">货到付款</div>
            <div class="item">线下支付</div>-->
          </div>
        </div>
        <!-- 支付方式 -->
        <!-- 配送方式 -->
        <div v-if="orderInfo.mold !== 1" class="submit-box">
          <div class="tit">
            <span class="text">{{$t('submitOrder.deliveryMethod')}}</span>
          </div>
          <div class="con delivery-way">
            <div class="item active">{{$t('submitOrder.courierDelivery')}}</div>
            <!-- <div class="item">到店自提</div> -->
            <!-- <div class="description">（该商品不支持自提）</div> -->
          </div>
        </div>
        <!-- /配送方式 -->
        <!-- 全部留言（虚拟商品） -->
        <!-- <div v-if="orderInfo.mold === 1 && orderInfo.virtualRemarkList.length" class="submit-box all-msg-row">
          <div class="tit">
            <span class="text">{{$t('submitOrder.allMessages')}}</span>
          </div>
          <div class="con">
            <div v-for="(item,index) in orderInfo.virtualRemarkList" :key="index" class="msg-item">
              <span v-if="item.isRequired" class="red-stress">*</span>
              <input
                v-model="item.value"
                class="msg-int-item"
                type="text"
                :placeholder="$t('submitOrder.pleaseEnter') + `${item.name}`"
                @blur="handleInputBlur(item.value, index)"
                 maxlength="20"
              >
            </div>
          </div>
        </div> -->
        <!-- 全部留言（虚拟商品）/ -->
        <!-- 商品信息 -->
        <div class="submit-box goods-info">
          <div class="tit">
            <span class="text">{{$t('applyReturn.productInformation')}}</span>
          </div>
          <div class="goods-msg">
            <div class="msg-tab">
              <div class="img">&nbsp;</div>
              <div class="info">{{$t('products')}}</div>
              <div class="unit-price">{{$t('priceOne')}}</div>
              <div class="freight">{{$t('submitOrder.shippingFee')}}</div>
              <div class="number">{{$t('quantity')}}</div>
              <div class="total">{{$t('subtotal')}}</div>
            </div>
            <div class="msg-con">
              <!-- 店铺 -->
              <div class="shop-msg">
                <nuxt-link
                  :to="'/shopIndex?sid=' + shopCartItem.shopId"
                  class="shop-name"
                  >{{$t('index.shop')}}：{{ shopCartItem.shopName }}</nuxt-link
                >
                <span class="self" v-if="shopCartItem.shopId == 1">{{$t('prodDetail.selfEmployed')}}</span>
              </div>
              <!-- 店铺中的商品 -->

              <div class="goods-box">
                <div class="prod-row">
                  <div class="img">
                    <div class="img-box" @click="toProdDetail(shopCartItem.seckillId)">
                      <img :src="shopCartItem.pic" alt />
                    </div>
                  </div>
                  <div class="info">
                    <div class="name" @click="toProdDetail(shopCartItem.seckillId)">{{shopCartItem.prodName}}</div>
                    <span class="sku">{{shopCartItem.skuName}}</span>
                  </div>
                  <div
                    class="unit-price"
                  >￥{{parsePrice(shopCartItem.price)[0]}}.{{parsePrice(shopCartItem.price)[1]}}</div>
                  <div
                    class="freight"
                  >￥{{parsePrice(orderInfo.transfee)[0]}}.{{parsePrice(orderInfo.transfee)[1]}}</div>
                  <div class="number">{{shopCartItem.prodCount}}</div>
                  <div
                    class="total"
                  >￥{{parsePrice(shopCartItem.productTotalAmount)[0]}}.{{parsePrice(shopCartItem.productTotalAmount)[1]}}</div>
                </div>
                <!-- 虚拟商品留言 start -->
                <div
                  v-if="orderInfo.virtualRemarkList && orderInfo.virtualRemarkList.length"
                  class="virtual-goods-msg"
                >
                  <div :class="['msg-tit',$t('language')=='en' ? 'msg-tit-en' : '']">
                    <span class="text">{{ $t('submitOrder.userMessage') }}：</span>
                  </div>
                  <div>
                    <div v-for="(msgItem,msgIndex) in orderInfo.virtualRemarkList" :key="msgIndex" class="msg-item">
                      <span v-if="msgItem.isRequired" class="red-stress">*</span>
                      <input
                        v-model="msgItem.value"
                        class="msg-int-item"
                        type="text"
                        :placeholder="$t('submitOrder.pleaseEnter') + `${msgItem.name}`"
                        @blur="handleInputBlur(msgItem.value, msgIndex)"
                        maxlength="20"
                      >
                    </div>
                  </div>
                </div>
                  <!-- 虚拟商品留言 end -->
              </div>

              <div class="remake-box">
                {{$t('submitOrder.messageToMerchant')}}：
                <input type="text" maxlength="100" class="text" v-model="remarks" :placeholder="$t('submitOrder.numberLength100')" />
                <!-- 发票 -->
                <div class="invoice-title">{{ $t('invoice.invoiceInfo') }}</div>
                <div v-if="shopCartItem.invoiceDataFrom" class="invoice-box">
                  <div v-if="shopCartItem.invoiceDataFrom.invoiceType === 1" class="invoice-box-item invoice-type">{{ $t('invoice.generalInvoice') }}</div>
                  <div v-if="shopCartItem.invoiceDataFrom.invoiceType === 2 || !shopCartItem.invoiceDataFrom" class="invoice-box-item invoice-type">{{ $t('invoice.noInvoice') }}</div>
                  <div v-if="shopCartItem.invoiceDataFrom.invoiceType === 1" class="invoice-box-item invoice-unit">{{ shopCartItem.invoiceDataFrom.headerName || $t('invoice.personal') }}</div>
                  <div v-if="shopCartItem.invoiceDataFrom.invoiceType === 1" class="invoice-box-item invoice-contents">{{ $t('invoice.productDetails') }}</div>
                  <div class="invoice-box-item invoice-operation" @click="showAddOrUpdateDialog(0,shopCartItem,shopCartItem.shopId)">{{ $t('invoice.update') }}</div>
                </div>
                <div v-else class="invoice-box">
                  <div class="invoice-box-item invoice-type">{{ $t('invoice.noInvoice') }}</div>
                  <div class="invoice-box-item invoice-operation" @click="showAddOrUpdateDialog(0,shopCartItem,shopCartItem.shopId)">{{ $t('invoice.update') }}</div>
                </div>
                <!-- 发票 -->
              </div>
              <!-- /留言 -->
            </div>
          </div>
        </div>
      </div>
      <div class="submit-bottom">
        <div class="statistic-box">
          <div class="item">
            <div class="tit">
              <span class="number">{{orderInfo.totalCount}}</span>{{$t('submitOrder.totalItems')}}：
            </div>
            <div class="con">￥{{parsePrice(orderInfo.total)[0]}}.{{parsePrice(orderInfo.total)[1]}}</div>
          </div>
          <!-- 应付运费 -->
          <div v-if="orderInfo.mold !== 1" class="item">
            <div class="tit">{{$t('submitOrder.freightPayable')}}：</div>
            <div
              class="con"
            >￥{{parsePrice(orderInfo.transfee)[0]}}.{{parsePrice(orderInfo.transfee)[1]}}</div>
          </div>
          <!-- 秒杀优惠 -->
          <div v-if="orderInfo.seckillReduce > 0" class="item">
            <div class="tit">{{$t('submitOrder.seckillReduce')}}：</div>
            <div
              class="con bright"
            >-￥{{parsePrice(orderInfo.seckillReduce)[0]}}.{{parsePrice(orderInfo.seckillReduce)[1]}}</div>
          </div>
        </div>

        <div class="detail-box">
          <div class="item">
            <div class="tit">{{$t('submitOrder.totalPayable')}}：</div>
            <div
              class="con"
            >￥{{parsePrice(orderInfo.actualTotal)[0]}}.{{parsePrice(orderInfo.actualTotal)[1]}}</div>
          </div>
          <div class="item" v-if="currentAddr.addrId">
            <span
              class="text"
            >{{$t('submitOrder.sendTo')}}：{{currentAddr.province+' '+currentAddr.city +' '+currentAddr.area+' '+currentAddr.addr}}</span>
            <span class="text">{{$t('submitOrder.consignee')}}：{{currentAddr.receiver}} {{currentAddr.mobile}}</span>
          </div>
        </div>
        <div class="btn-box">
          <a href="javascript:void(0)" class="btn" @click="submitOrder">{{$t('submitOrder.submitOrder')}}</a>
        </div>
      </div>
    </div>
    <!-- 地址弹窗 -->
    <AddressPop
      :editAddrId="editAddrId"
      v-if="showAddrPop"
      @getAddrList="getAddrList"
      @toggleAddrPop="toggleAddrPop"
    />
    <!-- /地址弹窗 -->
    <!-- 发票弹窗 -->
    <addOrEditInvoice
      v-if="showInvoiceAdd"
      ref="invoiceAddOrUpdate"
      @toggleAddrPop="refreshChange"
      @getInvoiceData="getInvoiceData"
      @hidePop="hideInvoicePop"
    />
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import bus from '~/plugins/bus'
import AddressPop from '~/components/add-or-edit-address'
import addOrEditInvoice from '~/components/add-or-edit-invoice'
import loginPopupVue from '../../components/login-popup.vue'
export default {
  components: {
    AddressPop,
    addOrEditInvoice
  },
  data () {
    return {
      addressList: [],
      selectedAddrId: 0,
      orderInfo: {},
      shopCartItem: {},
      currentAddr: {}, // 当前选择的地址
      showAddrPop: false, // 地址弹窗显隐
      editAddrId: 0, // 要修改的地址id
      showDelAddr: false,

      orderPath: '', // 秒杀订单路径
      secKillObj: {}, // 秒杀订单数据

      remarks: '',
      loading: {},
      seckillOrderNumber: '',
      pollingTimes: 0,
      seckillOrderStsTimer: '',

      // 发票弹窗
      showInvoiceAdd: false,
      invoiceId: '',
      invoiceDataFrom: '',
      seckillId: this.$route.query.seckillId
    }
  },
  created () {
    this.getAddrList()
  },
  mounted () {
    this.secKillObj = JSON.parse(sessionStorage.getItem('secKillObj'))
    this.getSecOrderPath()
  },
  methods: {
    /**
     * 跳转商品详情
     */
    toProdDetail() {
      this.$axios.get('/seckill/prod', {
        params: {
          seckillId: this.seckillId
        }
      }).then(({ data }) => {
        if (data) {
          this.$router.push({ path: '/secdetail/' + this.seckillId })
        } else {
          this.$router.push({ path: '/detail/' + this.shopCartItem.prodId })
        }
      })
    },

    showAddOrUpdateDialog(st, shopCartItem, shopId) {
      this.showInvoiceAdd = true
      const param = shopCartItem.invoiceDataFrom ? shopCartItem.invoiceDataFrom : ''
      this.$nextTick(() => {
        this.$refs.invoiceAddOrUpdate.init(st, param, '', shopId)
      })
    },
    /**
     * 刷新回调
     */
    refreshChange(visible) {
      this.showInvoiceAdd = visible
      // this.getUserAddr()
    },
    /**
     * 发票信息
     */
    getInvoiceData(invoiceDataFrom) {
      if(invoiceDataFrom.headerType === 2) {
        delete invoiceDataFrom.invoiceTaxNumber
      }
      if (this.shopCartItem.shopId === invoiceDataFrom.shopId) {
        this.shopCartItem.invoiceDataFrom = invoiceDataFrom
      }
      this.showInvoiceAdd = false
    },
    hideInvoicePop(visible) {
      this.showInvoiceAdd = visible
    },
    /**
     * 获取地址列表
     */
    getAddrList () {
      this.$axios.get('/p/address/list').then(({ data }) => {
        this.addressList = data
      })
      if (this.orderPath && (this.selectedAddrId || this.selectedAddrId==0)) {
        this.confirmSecOrder(this.orderPath)
      }
    },

    /**
     * 选择地址
     */
    changeAddress (addrId) {
      this.addressList.forEach(element => {
        if (element.addrId == addrId) {
          this.currentAddr = element
        }
      });
      this.selectedAddrId = addrId
      this.confirmSecOrder(this.orderPath)
    },

    /**
     * 设置为默认地址
     */
    setDefaultAddr (addrId) {
      this.$axios.put('/p/address/defaultAddr/' + addrId).then(({ data }) => {
        this.$message({
          message: data,
          type: 'success',
          duration: 1000
        })
        this.getAddrList()
      })
    },
    /**
     * 显示/隐藏确认删除弹窗
     */
    toggleDelAddr (sts, addrId) {
      this.showDelAddr = sts
      this.editAddrId = addrId
    },
    /**
     * 显示/隐藏地址弹窗
     */
    toggleAddrPop (sts) {
      if (Cookie.get('token')) {
        this.showAddrPop = sts
        this.editAddrId = 0
      } else {
        bus.$emit("showLogin", true)
        this.showAddrPop = false
      }
    },

    /**
     * 修改地址 (弹窗传地址id)
     */
    editAddr (addrId) {
      if (Cookie.get('token')) {
        this.showAddrPop = true
        this.editAddrId = addrId
      } else {
        bus.$emit("showLogin", true)
        this.showAddrPop = false
      }
    },
    /**
     * 删除地址
     */
    delAddr () {
      if (this.editAddrId == this.selectedAddrId) {
        this.secKillObj.addrId = 0
        this.selectedAddrId = 0
      }
      this.$axios.delete('/p/address/deleteAddr/' + this.editAddrId).then(({ data }) => {
        this.$message({
          message: data,
          type: 'success',
          duration: 1000
        })
        this.toggleDelAddr(false)
        this.getAddrList()
      })
    },
    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },


    /**
     * 获取 orderPath
     */
    getSecOrderPath () {
      this.$axios.get('/p/seckill/orderPath').then(({ data }) => {
        this.orderPath = data
        this.confirmSecOrder(data)
      })
    },

    /**
     * 确认秒杀订单
     */
    confirmSecOrder (orderPath) {
      var confirmParam = this.secKillObj
      if (this.selectedAddrId || this.selectedAddrId == 0) {
        confirmParam.addrId = this.selectedAddrId
      }
      this.$axios.post(`/p/seckill/${orderPath}/confirm`, confirmParam).then(({ data }) => {
        this.orderInfo = data
        this.shopCartItem = data.shopCartItem
        if (data.userAddr) {
          this.currentAddr = data.userAddr
          this.selectedAddrId = data.userAddr.addrId
        }
      })
    },

    /**
     * 留言输入框失焦
     */
    handleInputBlur (value, index) {
      if (!value) {
        return
      }
      if (!value.trim()) {
        this.orderInfo.virtualRemarkList[index].value = value.trim()
        return
      }
    },

    /**
     * 提交订单
     */
    submitOrder () {
      if (this.orderInfo.mold !== 1 && !this.addressList.length) {
        this.$message({
          message: this.$t('submitOrder.pleaseAddTheAddressFirst'),
          type: 'warning',
          duration: 1000
        })
        this.showAddrPop = true
        return
      }
      if (this.orderInfo.mold !== 1 && this.selectedAddrId == 0) {
        this.$message({
          message: this.$t('submitOrder.pleaseAddTheAddressFirst'),
          type: 'warning',
          duration: 1000
        })
        document.body.scrollTop = document.documentElement.scrollTop = 0
        return
      }
      // 虚拟商品留言必填项校验
      if (
        this.orderInfo.mold === 1 &&
        this.orderInfo.virtualRemarkList.length &&
        this.orderInfo.virtualRemarkList.find(el => el.isRequired && !el.value)
      ) {
        this.$message({
          message: this.$t('submitOrder.messageCannotBeEmpty'),
          type: 'warning',
          duration: 2500
        })
        return
      }
      // 显示秒杀loading
      this.seckillLoading()
      // 提交秒杀订单
      var orderShopParam = {
        remarks: this.remarks,
        shopId: this.shopCartItem.shopId,
        orderInvoice: orderInvoiceDTO,
        virtualRemarkList: this.orderInfo.virtualRemarkList
      }
      let orderInvoiceDTO = null // invoiceDataFrom
      if (this.shopCartItem.invoiceDataFrom && this.shopCartItem.invoiceDataFrom.invoiceType === 1) {
        orderInvoiceDTO = this.shopCartItem.invoiceDataFrom
      }
      this.$axios.post(`/p/seckill/${this.orderPath}/submit`, orderShopParam).then(({data})=> {
        this.seckillOrderNumber = data.orderNumbers
        // 轮询秒杀订单提交状态
        setTimeout(this.checkSeckillOrderSubmitStatus,3000)
      }).catch(() => {
        // 关闭秒杀loading
        this.loading.close();
        this.$router.go(-1)
      })
    },

    /**
     *  轮询秒杀订单提交状态
     */
    checkSeckillOrderSubmitStatus() {
      if (this.pollingTimes < 10) {
        this.$axios.get('/p/seckill/createOrderStatus',  {
          params : {
            orderNumber: this.seckillOrderNumber
          }
        }).then(({ data }) => {
          if (data) {
            clearTimeout(this.seckillOrderStsTimer)
            this.loading.close()
            sessionStorage.setItem("pay_total", this.shopCartItem.actualTotal)
            sessionStorage.setItem("pay_orderNumber", this.seckillOrderNumber)
            sessionStorage.setItem('pay_mold', this.orderInfo.mold)
            this.$router.push({
              path: '/payment'
            })
          } else {
            this.pollingTimes++
            this.seckillOrderStsTimer = setTimeout(this.checkSeckillOrderSubmitStatus, 3000)
          }
        })
      } else {
        this.loading.close()
        this.$message.warning(this.$t('submitOrder.secFailTips'))
      }
    },


    /**
     * 秒杀loading
     */
    seckillLoading () {
      const loading = this.$loading({
        lock: true,
        text: this.$t('submitOrder.inTheMadRushToBuy'),
        background: 'rgba(255, 255, 255, 0.8)'
      });
      this.loading = loading

    },
  },

}
</script>

<style scoped src='~/assets/css/submit-order.css'></style>
<style scoped>
.fix-transform-blur {
  z-index: 10000;
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -40%);
}
.seckill-loading {
  color: #fff;
}
.submit-order .submit-box {
  border-bottom: 1px solid #eee !important;
}
</style>
