<template>
  <div :class="['order-detail',this.$store.state.locale == 'en'?'order-detail-en':'']">
    <div class="content">
      <div class="crumbs">
        <a class="item-a" @click="userCenter()">{{$t('orderDetails.personalCenter')}}</a>
        <span class="arrow">></span>
        <span class="item-span">{{ $t('invoice.InvoiceDetails') }}</span>
      </div>
      <!-- /发票状态 -->
      <div class="info-box">
        <!-- 发票信息 -->
        <div class="invoice-info">
          <div class="item">
            <div class="tit">{{ $t('invoice.orderInfo') }}</div>
            <div class="con">
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.orderStatus') }}：</span>
                <span class="item-con">{{ [
                  '',
                  $t('obligation'),
                  $t('pendingDelivery'),
                  $t('pendingReceipt'),
                  $t('pendinEvaluation'),
                  $t('completed'),
                  $t('canceled'),
                  $t('grouping'),
                ][orderInfo.status] }}</span>
                <!-- <span class="item-con">{{ [ '', '待付款', '待发货', '待收货', '待评价', '已完成', '已取消', '拼团中' ][2] }}</span> -->
              </div>
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.orderNumber') }}：</span>
                <span class="item-con">{{ invoiceInfo.orderNumber }}</span>
                <!-- <span class="item-con">12312312412</span> -->
              </div>
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.orderCreateTime') }}：</span>
                <span class="item-con">
                  {{ orderInfo.createTime }}
                </span>
                <!-- <span class="item-con">
                  12131242131241
                </span> -->
              </div>
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.invoiceType') }}：</span>
                <span v-if="invoiceInfo.invoiceType === 1" class="item-con">
                  {{ $t('invoice.generalInvoice') }}
                </span>
                <!-- <span class="item-con">
                  普通电子发票
                </span> -->
              </div>
            </div>
          </div>
          <div class="item">
            <div class="tit">{{ $t('invoice.invoiceInfo') }}</div>
            <div class="con">
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.invoiceStatus') }}：</span>
                <span v-if="invoiceInfo.invoiceState === 2" class="item-con invoice-status">
                  {{ $t('invoice.invoiced') }}
                </span>
                <span v-if="invoiceInfo.invoiceState === 1" class="item-con invoice-status">
                  {{ $t('invoice.application') }}
                </span>
              </div>
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.invoiceContent') }}：</span>
                <span v-if="invoiceInfo.invoiceContext === 1" class="item-con">{{ $t('invoice.productDetails') }}</span>
                <!-- <span class="item-con">商品明细</span> -->
              </div>
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.invoiceTitle') }}：</span>
                <span class="item-con">{{ invoiceInfo.headerName || $t('invoice.personal') }}</span>
                <!-- <span class="item-con">'个人'</span> -->
              </div>
               <!-- v-if="invoiceInfo.headerType === 1" -->
              <div v-if="invoiceInfo.headerType === 1" class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.TaxpayerIDNumber') }}：</span>
                <span class="item-con">{{ invoiceInfo.invoiceTaxNumber}}</span>
              </div>
            </div>
          </div>
          <div class="item">
            <div class="tit">{{ $t('invoice.invoiceDownload') }}</div>
            <div class="con">
               <!-- v-if="invoiceInfo.invoiceState === 2" -->
              <div class="con-item"  v-if="invoiceInfo.uploadTime">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.uploadTime') }}：</span>
                <span class="item-con">
                  {{ invoiceInfo.uploadTime || '' }}
                </span>
              </div>
              <div class="con-item">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.invoiceExchange') }}：</span>
                <span class="item-con invoice-update" @click="showAddOrUpdateDialog(invoiceInfo.orderInvoiceId)">{{ $t('invoice.updateInvoice') }}</span>
              </div>
               <!-- v-if="invoiceInfo.invoiceState === 2" -->
              <div class="con-item"  v-if="filePath">
                <span class="item-tit" :class="{'invoice-en': $t('language') === 'en' }">{{ $t('invoice.invoiceDownload') }}：</span>
                <div class="item-con download" :style="{color: textColor}" @click="invoiceDownload" @mouseenter="HoverDownload" @mouseleave="HoverDownloadSelect">
                  <!-- <img src="~/assets/images/invoice-download-select.png" alt=""> -->
                  <img :src="downloadIcon" alt="">
                  {{ $t('invoice.viewInvoice') }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- /发票信息 -->
      </div>
      <!-- 商品信息 -->
      <div class="goods-box">
        <div class="goods-con">
          <div class="shop">
            <span class="name">{{$t('chat.stores')}}：</span>
            <a
              href="javascript:void(0)"
              @click="toShopPage(orderInfo.shopId)"
              class="name"
              >{{ orderInfo.shopName }}</a
            >
          </div>
          <div class="order-table">
            <table cellspacing="0" cellpadding="0" class="box">
              <tbody>
                <tr class="box-tit">
                  <th>{{$t('products')}}</th>
                  <th width="145" class="tal">{{$t('quantity')}}</th>
                  <th width="185">{{$t('priceOne')}}</th>
                  <th width="185">{{$t('totalAll')}}</th>
                </tr>
                <tr
                  class="box-tr"
                  v-for="(prod, prodIndex) in orderInfo.orderItemDtos"
                  :key="prodIndex"
                >
                  <td>
                    <div class="goods-info">
                      <nuxt-link
                        :to="
                          (orderInfo.orderType == 3
                            ? '/member-center/integral-det/'
                            : orderInfo.orderType == 2 ? '/secdetail/' : '/detail/') + (orderInfo.orderType==2? orderInfo.seckillId : prod.prodId)
                        "
                        class="img"
                      >
                        <img v-if="prod.pic" :src="prod.pic" alt />
                        <img v-else src="~/assets/img/def.png" alt />
                      </nuxt-link>
                      <div class="name-sku">
                        <nuxt-link
                          :to="
                            (orderInfo.orderType == 3
                              ? '/member-center/integral-det/'
                              : orderInfo.orderType == 2 ? '/secdetail/' : '/detail/') + (orderInfo.orderType==2? orderInfo.seckillId : prod.prodId)
                          "
                          class="name"
                          >{{ prod.prodName }}</nuxt-link
                        >
                        <span class="sku">{{ prod.skuName }}</span>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="goods-number">×{{ prod.prodCount }}</div>
                  </td>
                  <td>
                    <span class="price"
                      >￥{{ parsePrice(prod.price)[0] }}.{{
                        parsePrice(prod.price)[1]
                      }}</span
                    >
                  </td>
                  <td>
                    <span class="price"
                      >￥{{ parsePrice(prod.productTotalAmount)[0] }}.{{
                        parsePrice(prod.productTotalAmount)[1]
                      }}</span
                    >
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="goods-total">
            <div class="item">
              <span class="tit">{{
                orderInfo.status == 1 ? $t('orderDetails.amountPayable') : $t('orderDetails.actualAmount')
              }}</span>
              <span class="price big">
                <span v-if="orderInfo.actualTotal"
                  >￥{{ parsePrice(orderInfo.actualTotal)[0] }}.{{
                    parsePrice(orderInfo.actualTotal)[1]
                  }}</span
                >
                <span v-if="orderInfo.actualTotal && orderInfo.orderScore"
                  >+</span
                >
                <span v-if="orderInfo.orderScore"
                  >{{ orderInfo.orderScore }} {{$t('orderDetails.points')}}</span
                >
              </span>
            </div>
          </div>
          <!-- /商品信息 -->
          <!-- 提示弹窗 -->
          <div class="popup-mask" v-if="showTips"></div>
          <div class="popup-box" v-if="showTips">
            <div class="tit">
              <div class="text">{{$t('tips')}}</div>
              <div class="close" @click="showTips = 0"></div>
            </div>
            <div class="con">
              <div class="tip">
                <div class="tip-icon warning"></div>
                <div class="tip-info">
                  <div class="result">{{$t('orderDetails.confirmCancellation')}}</div>
                  <div class="date">{{$t('orderDetails.confirmCancellationTips')}}</div>
                  <div class="btns">
                    <a
                      href="javascript:void(0);"
                      class="btn-r"
                      @click="cancelOrder"
                      >{{$t('determine')}}</a
                    >
                    <a
                      href="javascript:void(0);"
                      class="btn-g"
                      @click="showTips = 0"
                      >{{$t('cancel')}}</a
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- /商品信息 -->
      <div class="questions-info">
        <div class="title">{{ $t('invoice.questions') }}：</div>
        <div class="text">1、{{ $t('invoice.questions1') }}</div>
        <div class="text">2、{{ $t('invoice.questions2') }}</div>
        <div class="text">3、{{ $t('invoice.questions3') }}</div>
        <div class="text">4、{{ $t('invoice.questions4') }}</div>
        <div class="text">5、{{ $t('invoice.questions5') }}</div>
      </div>
    </div>
    <addOrEditInvoice
      v-if="showInvoiceAdd"
      ref="invoiceAddOrUpdate"
      @toggleAddrPop="refreshChange"
      @updateData="refreshChange"
      @hidePop="hidePop"
    />
  </div>
</template>

<script>
import config from '~/plugins/config'
import addOrEditInvoice from '~/components/add-or-edit-invoice'
import big from '~/plugins/big.min.js'

export default {
  components: {
    addOrEditInvoice
  },
  data () {
    return {
      orderNumber: '',
      orderInfo: {},
      showTips: false,
      offsetCount: 0,  //  偏移数

      isLastProd: false,  //最后一款商品
      irrevocable: false,  //不可撤销
      sum: [],  //本单已申请单个退款的商品数组
      dvyType: 1, //配送类型 1:快递 2:自提 3：无需快递
      stationUserName: '', //自提人名字
      stationUserMobile: '', //自提人手机号
      stationAddress: '',  //自提地址

      showInvoiceAdd: false,
      invoiceInfo: {},
      downloadIcon: require('~/assets/images/invoice-download.png'),
      textColor: '#333333',

      resourcesUrl: config.picDomain,
      filePath: '',

      orderInvoiceId: '',
      unusedCount: 0
    }
  },
  created () {
    this.orderNumber = this.$route.query.orderNumber
    this.orderInvoiceId = this.$route.query.orderInvoiceId
  },
  mounted () {
    // 设置网页标题
    document.title = this.$i18n.t('invoice.InvoiceDetails')
    this.getOrderDetail()
    this.getInvoiceDetail()
    // console.log(this.deliveryExpresse.deliveryDto.traces.length)
  },
  methods: {

    /**
     * 发票下载
     */
    invoiceDownload() {
      window.open(this.resourcesUrl + this.filePath, '_blank')
    },
    /**
     * 鼠标移入事件
     */
    HoverDownload() {
      this.textColor = '#DF241A'
      this.downloadIcon = require('~/assets/images/invoice-download-select.png')
    },
    /**
     * 鼠标移出事件
     */
    HoverDownloadSelect() {
      this.textColor = '#333333'
      this.downloadIcon = require('~/assets/images/invoice-download.png')
    },
    showAddOrUpdateDialog(orderInvoiceId) {
      this.showInvoiceAdd = true
      const param = {
        headerName: this.invoiceInfo.headerName,
        headerType: this.invoiceInfo.headerType,
        invoiceContext: this.invoiceInfo.invoiceContext,
        invoiceState: this.invoiceInfo.invoiceState,
        invoiceTaxNumber: this.invoiceInfo.invoiceTaxNumber,
        invoiceType: this.invoiceInfo.invoiceType
      }
      this.$nextTick(() => {
        this.$refs.invoiceAddOrUpdate.init(1, param, this.invoiceInfo.orderNumber, this.invoiceInfo.shopId, orderInvoiceId)
      })
    },
    /**
     * 刷新回调
     */
    refreshChange(visible) {
      this.showInvoiceAdd = visible
      this.getInvoiceDetail()
    },
    hidePop(visible) {
      this.showInvoiceAdd = visible
    },
    /**
     * 获取发票详情
     */
    getInvoiceDetail() {
      this.$axios.get('/p/orderInvoice/info/'+this.orderInvoiceId)
        .then(({ data }) => {
          this.invoiceInfo = data
          this.getInvoiceFile()
        })
    },
    getInvoiceFile() {
      if(this.invoiceInfo.fileId) {
        this.$axios.get('/p/file/get_file_by_id?fileId=' + this.invoiceInfo.fileId)
          .then(({ data }) => {
            this.filePath = data.filePath
          })
      }
    },

    /**
     * 获取订单详情
     */
    getOrderDetail () {
      this.$axios.get('/p/myOrder/orderDetail', {
        params: {
          orderNumber: this.$route.query.orderNumber
        }
      }).then(({ data }) => {
        this.dvyType = data.dvyType
        this.orderInfo = data
        // 官方自营店判断
        this.orderInfo.shopId===null?this.orderInfo.shopId=0:this.orderInfo.shopId
        if(this.orderInfo.status >= 3) {
          this.getDeliveryDet()
        }
        if (this.dvyType == 2) {
          this.getStationDetail()
        }
        let virtualInfoList = data.virtualInfoList || []
        // 计算待使用券码总数
        if (virtualInfoList.length) {
          let unusedCount = 0
          virtualInfoList.forEach(el => {
            if (el.isWriteOff === 0) {
              unusedCount = unusedCount + 1
            }
          })
          this.unusedCount = unusedCount
        }
      })
    },

    // 获取自提点信息
    getStationDetail () {
      this.$axios.get('/p/myStationOrder/stationDetail', {
        params: {
          orderNumber: this.$route.query.orderNumber
        }
      }).then(({ data }) => {
        this.stationUserName = data.stationUserName //自提人的名字
        this.stationUserMobile = data.stationUserMobile //自提人的手机
        this.stationAddress = data.stationAddress //自提点的地址
      })
    },

    // 获取物流详情
    getDeliveryDet () {
      this.$axios.get('/p/myDelivery/orderInfo/' + this.orderNumber).then(({ data }) => {
        this.deliveryList = data //包裹集合信息
        this.deliveryExpresse = data[0] //包裹信息
      })
    },

    // 点击包裹tab事件
    onClickTabDelivery (delivery, index) {
      this.deliveryExpresse = delivery
      this.indexs = index
    },
    /**
     * 跳转店铺页面
     */
    toShopPage (shopId) {
      if(shopId===0){
        this.$router.push({ path: '/member-center/integral-mall' })
        return
        }
      this.$router.push({ path: '/shopIndex?sid=' + shopId })
    },
    /**
     * 跳转到个人中心
     */
    userCenter () {
      this.$router.push({ path: '/user-center' })
    },
    /**
    * 跳转到商品详情页
    */
    // toProdDetail (prodId) {
    //   this.$router.push({ path: '/detail/' + prodId })
    // },
    toProdDetail (prodId) {
      if (this.orderInfo.orderType == 3) {
        this.$router.push({ path: '/member-center/integral-det/' + prodId })
      } else {
        this.$router.push({ path: '/detail/' + prodId })
      }
    },
    /**
     * 根据订单状态跳转
     */
    // orderRoute (prodId) {
    //   this.toProdDetail(prodId)
    // },

    /**
     * 是否最后一个商品在执行单个商品退款事件
     */
    applyLastProdRefund: function () {
      if (this.orderInfo.status == 2) { //待发货状态下
        if (this.orderInfo.orderItemDtos.length > 1) {  //如果商品列表长度大于1
          let sum = []
          // 遍历商品list
          this.orderInfo.orderItemDtos.forEach((el, index) => {
            if (el.refundSn) { //如果拥有退款单号
              sum.push(el)
              this.sum = sum
            }
          })
          if (this.sum.length == this.orderInfo.orderItemDtos.length - 1) {
            // 如果拥有退款单号的商品数组长度等于商品列表数据长度-1，那么点击的这件商品就是最后一个订单项
            this.isLastProd = true
          }
        }
      }
    },

    /**
     * 申请退款
     */
    toApplyReturn (orderItemId, refundType) {  //refundType退款单类型（1:整单退款,2:单个物品退
      const platformFreeFreightAmount = this.orderInfo.platformFreeFreightAmount
      const transfee = platformFreeFreightAmount
                       ? Number.parseFloat(new big(platformFreeFreightAmount).minus(this.orderInfo.transfee)).valueOf()
                       : this.orderInfo.transfee
      if (this.orderInfo.status == 2) {  //待发货
        if (refundType == 2) {  //单个退款
          this.applyLastProdRefund()  //是否最后一个订单项申请退款
          let orderItem = []
          this.orderInfo.orderItemDtos.forEach((el, index) => {
            el.isLastProd = this.isLastProd
            if (el.orderItemId == orderItemId) {  //如果当前的订单项id和点击传入的订单项id一致
              //保存数据
              orderItem.push(el)
            }
          })
          let refundProdObj = {}
          if (this.orderInfo.orderItemDtos.length == 1) {
            refundProdObj.isOnlyProd = true
          } else {
            refundProdObj.isOnlyProd = false
          }
          refundProdObj.refundType = refundType
          refundProdObj.orderItem = orderItem
          refundProdObj.buyerMobile = this.dvyType === 2 ? this.stationUserMobile : this.orderInfo.userAddrDto ? this.orderInfo.userAddrDto.mobile : ''
          localStorage.setItem('refundProdObj', JSON.stringify(refundProdObj))  //将整个订单项保存
        } else if (refundType == 1) {  //整单退款
          let refundProdObj = {}
          refundProdObj.orderItem = this.orderInfo.orderItemDtos
          refundProdObj.refundType = refundType
          refundProdObj.actualTotal = this.orderInfo.actualTotal
          refundProdObj.buyerMobile = this.dvyType === 2 ? this.stationUserMobile : this.orderInfo.userAddrDto ? this.orderInfo.userAddrDto.mobile : ''
          localStorage.setItem('refundProdObj', JSON.stringify(refundProdObj))  //将整个订单所有项保存
        }
        this.$router.push({
          path: '/user-center/apply-return',
          query: {
            orderNumber: this.orderNumber,
            transfee: transfee,
            status: this.orderInfo.status,
            // actualTotal: this.orderInfo.actualTotal,
            refundType: refundType,
          }
        })
      } else if (this.orderInfo.status != 2) {
        if (refundType == 2) {  //单个退
          let orderItem = []
          this.orderInfo.orderItemDtos.forEach((el, index) => {
            if (el.orderItemId == orderItemId) {  //如果当前的订单项id和点击传入的订单项id一致
              //保存数据
              orderItem.push(el)
            }
          })
          let refundProdObj = {}
          refundProdObj.orderItem = orderItem
          // 虚拟商品
          if (this.orderInfo.orderMold == 1) {
            // 1.无需核销：允许用户选择退款数量（writeOffNum 0无需核销 -1多次核销 1单次核销）
            refundProdObj.needWriteOffs = this.orderInfo.writeOffNum !== 0
            // 2.需要核销：展示最大可退款件数，不允许选择（最大可退款件数 = 待使用的核销券数）
            refundProdObj.maxRefundPieces = this.unusedCount
          }
          refundProdObj.buyerMobile = this.dvyType === 2 ? this.stationUserMobile : this.orderInfo.userAddrDto ? this.orderInfo.userAddrDto.mobile : ''
          localStorage.setItem('refundProdObj', JSON.stringify(refundProdObj))  //将整个订单项保存
        } else if (refundType == 1) {  //整单退款
          let refundProdObj = {}
          refundProdObj.orderItem = this.orderInfo.orderItemDtos
          refundProdObj.actualTotal = this.orderInfo.actualTotal
          refundProdObj.orderType = this.orderInfo.orderType
          refundProdObj.buyerMobile = this.dvyType === 2 ? this.stationUserMobile : this.orderInfo.userAddrDto ? this.orderInfo.userAddrDto.mobile : ''
          localStorage.setItem('refundProdObj', JSON.stringify(refundProdObj))  //将整个订单所有项保存
        }
        this.$router.push({
          path: '/user-center/apply-return',
          query: {
            orderNumber: this.orderNumber,
            status: this.orderInfo.status,
            transfee: transfee,
            isLastProd: this.isLastProd,
            orderItemId: orderItemId, // 订单项id
            // actualTotal: this.orderInfo.actualTotal,
            refundType: refundType,
            orderMold: this.orderInfo.orderMold
          }
        })
      }
    },
    /**
     * 查看退款
     */
    toViewRefund (refundSn, refundType, orderItemId, returnMoneySts) {
      let transfee = this.orderInfo.transfee
      // returnMoneySts处理退款状态:(1.买家申请 2.卖家接受 3.买家发货 4.卖家收货 5.退款成功 6.买家撤回申请 7.商家拒绝 -1.退款关闭)
      if (returnMoneySts < 4 && returnMoneySts != -1) {
        if (refundType == 2) {  //单个退款
          this.orderInfo.orderItemDtos.forEach((el, index) => {
            if (el.orderItemId == orderItemId) {  //如果当前的订单项id和点击传入的订单项id一致
              //保存数据
              let orderItem = []
              orderItem.push(el)
              localStorage.setItem('orderItem', JSON.stringify(orderItem))  //将整个订单项保存
            }
          })
        } else if (refundType == 1) {  //整单退款
          localStorage.setItem('orderItem', JSON.stringify(this.orderInfo.orderItemDtos))  //将整个订单所有项保存
        }
        this.toApplyReturn(orderItemId, refundType)  //申请售后
        //申请售后（详情）页
        this.$router.push({ path: '/user-center/apply-return?refundSn=' + refundSn + '&transfee=' + transfee + '&orderNumber=' + this.orderNumber })
      } else {
        //退款详情页
        this.$router.push({ path: '/return-detail?refundSn=' + refundSn + '&transfee=' + transfee })
      }
    },

    /**
     * 立即支付
     */
    toPayment () {
      sessionStorage.setItem("pay_total", this.orderInfo.actualTotal)
      sessionStorage.setItem("pay_orderNumber", this.orderNumber)
      // this.$router.push({ path: '/payment' })
      //点击立即支付时再次请求判断订单状态
      this.$axios.get('/p/order/getOrderPayInfoByOrderNumber', {
        params: {
          orderNumbers: this.orderNumber
        }
      }).then(({ data }) => {
        //H5其它端取消订单时对订单状态加判断
        if (data.status != 1) {
          this.$message({
            message: this.$i18n.t('orderDetails.orderChanged'),
            type: 'warning',
            duration: 1000
          })
          setTimeout(() => {
            window.location.reload();  //刷新页面
          }, 1000)
        } else {
          this.$router.push({ path: '/payment' })
        }
      })
    },

    /**
     * 取消订单
     */
    cancelOrder () {
      this.showTips = false
      this.$axios.put('/p/myOrder/cancel/' + this.orderNumber).then(({ data }) => {
        this.$message({
          type: 'success',
          message: this.$i18n.t('orderDetails.orderCancelled'),
          duration: 1000
        })
        this.$router.push({ path: '/user-center/uc-order' })
      })
    },

    /**
     * 价格处理
     */
    parsePrice: (value) => {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },
  }
}
</script>

<style scoped src='~/assets/css/invoice-detail.css'></style>
<style soped src='~/assets/css/order-detail.css'></style>
<style scoped src='~/assets/css/user-center.css'></style>
<style>
.bg-fix {
  background-color: #f9f9f9 !important;
}
</style>
