<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('orderDetails.orderDetails')}}</span>
      </div>
      <!-- 订单状态 -->
      <div class="status-process">
        <div class="status-box">
          <div class="order-number">{{$t('orderDetails.orderNumber')}}：{{ orderNumber }}</div>
          <div class="status">
            {{
              [
                '',
                $t('obligation'),
                $t('pendingDelivery'),
                $t('pendingReceipt'),
                $t('pendinEvaluation'),
                $t('completed'),
                $t('canceled'),
                $t('grouping')
              ][orderInfo.status]
            }}
          </div>
          <div
          :class="['invoice-detail',$t('language') === 'zh'?'':'en-width']"
          v-if="((orderInfo.orderInvoiceId && orderInfo.status !== 6) || (orderInfo.orderInvoiceId && (orderInfo.status === 6 && orderInfo.finalRefundId))) && (!orderInfo.refundStatus || orderInfo.refundStatus === 4)" @click="toInvoice(orderNumber)">{{ $t('invoice.viewInvoiceDetail') }}</div>
          <div
            class="description"
            v-if="orderInfo.status == 1 && betweenTime.signs == 1"
          >
            {{$t('orderDetails.remainingTime')}} {{ betweenTime.min + ':' + betweenTime.sec }}
          </div>
          <div class="action" v-if="orderInfo.cancelTime === null">
            <a
              href="javascript:void(0);"
              class="action-a red"
              v-if="orderInfo.status == 1"
              @click="toPayment()"
              >{{$t('orderDetails.payNow')}}</a
            >
            <a
              href="javascript:void(0);"
              class="action-a"
              v-if="orderInfo.status == 1"
              @click="showTips = true"
              >{{$t('orderDetails.cancellation')}}</a
            >
            <!-- <a href="javascript:void(0);" class="action-a btn" v-if="orderInfo.status==2 || orderInfo.status == 3">申请退款</a>
            <a href="javascript:void(0);" class="action-a btn" v-if="orderInfo.status==4">立即评价</a>
            <a href="javascript:void(0);" class="action-a btn" v-if="orderInfo.status==5">再次购买</a>
            <a href="javascript:void(0);" class="action-a btn" v-if="orderInfo.status==5">立即购买</a>-->
          </div>
        </div>
        <div class="process-box">
          <div class="tip">
            {{$t('orderDetails.informationTips')}}
          </div>
          <div class="process">
            <div :class="['item', orderInfo.status >= 1 ? 'active' : '']">
              <div class="img process01"></div>
              <div class="text">{{$t('orderDetails.submitOrder')}}</div>
              <div class="time">{{ orderInfo.createTime }}</div>
            </div>
            <div
              :class="[
                'item',
                orderInfo.status >= 2 && orderInfo.payTime !== null
                  ? 'active'
                  : ''
              ]"
            >
              <div class="img process02"></div>
              <div class="text">{{$t('orderDetails.buyerPayment')}}</div>
              <div class="time">{{ orderInfo.payTime }}</div>
            </div>
            <div
              :class="[
                'item',
                orderInfo.status >= 3 && orderInfo.dvyTime !== null
                  ? 'active'
                  : ''
              ]"
            >
              <div class="img process03"></div>
              <div class="text">{{$t('orderDetails.goodsOut')}}</div>
              <div class="time">{{ orderInfo.dvyTime }}</div>
            </div>
            <div
              :class="[
                'item',
                orderInfo.status >= 3 && orderInfo.dvyTime !== null
                  ? 'active'
                  : ''
              ]"
            >
              <div class="img process04"></div>
              <div class="text">{{$t('orderDetails.waitingForReceipt')}}</div>
              <div class="time">{{ orderInfo.dvyTime }}</div>
            </div>
            <div
              :class="[
                'item',
                orderInfo.status >= 5 && orderInfo.fianllyTime !== null
                  ? 'active'
                  : ''
              ]"
            >
              <div class="img process05"></div>
              <div class="text">{{$t('orderDetails.orderCompletion')}}</div>
              <div class="time">{{ orderInfo.fianllyTime }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- /订单状态 -->
      <!-- 配送信息 -->
      <div class="delivery-box" v-if="deliveryList.length && orderInfo.status !=6">
        <div class="box-tab" v-if="deliveryList.length > 1">
          <div
            :class="indexs === index ? 'item active' : 'item'"
            v-for="(item, index) in deliveryList"
            :key="index"
            @click="onClickTabDelivery(index)"
          >
            {{$t('orderDetails.packages')}}{{ index + 1 }}
          </div>
        </div>
        <div class="box-con" v-if="deliveryExpresse">
          <div class="deliver-msg">
            <div class="d-item">
              <div class="text">{{$t('submitOrder.deliveryMethod')}}：</div>
              <div class="res">{{['',$t('submitOrder.courierDelivery'),$t('orderDetails.buyerPickup'),$t('orderDetails.noExpressDelivery'),$t('orderDetails.sameCityDelivery')][deliveryExpresse.deliveryType]}}</div>
            </div>
            <div class="d-item">
              <div class="text">{{$t('orderDetails.shipmenttime')}}：</div>
              <div class="res">{{ deliveryExpresse.createTime }}</div>
            </div>
            <div class="d-item" v-if="deliveryExpresse.deliveryDto">
              <div class="text">{{$t('orderDetails.courierCompany')}}：</div>
              <div class="res">
                {{ deliveryExpresse.deliveryDto.companyName }}
              </div>
            </div>
            <div class="d-item" v-if="deliveryExpresse.deliveryDto">
              <div class="text">{{$t('orderDetails.waybillNumber')}}：</div>
              <div class="res">
                {{ deliveryExpresse.deliveryDto.dvyFlowId }}
              </div>
            </div>
            <div
              class="d-goods"
              :class="{ over: deliveryExpresse.orderItems.length > 5 }"
            >
              <div
                class="arrow prev"
                @click="prevItem"
                :class="{
                  disable:
                    deliveryExpresse.orderItems.length - 5 <= 0 ||
                    this.offsetCount < 1
                }"
              ></div>
              <div
                class="arrow next"
                @click="nextItem"
                :class="{
                  disable:
                    deliveryExpresse.orderItems.length - 5 <= 0 ||
                    this.offsetCount >= deliveryExpresse.orderItems.length - 5
                }"
              ></div>
              <div class="item-goods">
                <div class="goods-box" ref="carouser">
                  <div
                    class="item"
                    v-for="(orderItem, index) in deliveryExpresse.orderItems"
                    :key="index"
                  >
                    <div class="img">
                      <img v-if="orderItem.pic" :src="orderItem.pic" alt  @error="handlePicError"/>
                      <img v-else src="~/assets/img/def.png" alt />
                      <div class="number">×{{ orderItem.prodCount }}</div>
                    </div>
                    <div class="name">{{ orderItem.prodName }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="logistics" v-if="deliveryExpresse.deliveryType !== 3">
            <div class="l-tit" v-if="deliveryExpresse">
              <span class="text">{{$t('orderDetails.LogisticsInformation')}}：</span>
              <!-- <span
                class="l-state"
                v-if="deliveryExpresse.deliveryDto.state === 0"
                >{{$t('orderDetails.noRecords')}}</span
              >
              <span
                class="l-state"
                v-if="deliveryExpresse.deliveryDto.state === 1"
                >{{$t('orderDetails.received')}}</span
              >
              <span
                class="l-state"
                v-if="deliveryExpresse.deliveryDto.state === 2"
                >{{$t('orderDetails.inTransit')}}</span
              >
              <span
                class="l-state"
                v-if="deliveryExpresse.deliveryDto.state === 3"
                >{{$t('orderDetails.signed')}}</span
              >
              <span
                class="l-state"
                v-if="deliveryExpresse.deliveryDto.state === 201"
                >{{$t('orderDetails.reachCity')}}</span
              >
              <span
                class="l-state"
                v-if="deliveryExpresse.deliveryDto.state === 4"
                >{{$t('orderDetails.faultyPackages')}}</span
              > -->
            </div>
            <div class="logistics-box">
              <div v-if="deliveryExpresse.deliveryDto.traces && deliveryExpresse.deliveryDto.traces.length">
                <div
                  class="item"
                  v-for="(trace, index) in deliveryExpresse.deliveryDto.traces"
                  :key="index"
                >
                  <div class="time">{{ trace.acceptTime }}</div>
                  <div class="text">{{ trace.acceptStation }}</div>
                </div>
              </div>
              <div
                class="item"
                v-if="!deliveryExpresse.deliveryDto.traces || !deliveryExpresse.deliveryDto.traces.length"
              >
                {{$t('orderDetails.logisticsTips1')}}
              </div>
              <div
                class="item"
                v-if="orderInfo.status >= 3 && orderInfo.dvyTime !== null"
              >
                <div class="time">{{ orderInfo.dvyTime }}</div>
                <div class="text">{{$t('orderDetails.logisticsTips2')}}</div>
              </div>
              <div
                class="item"
                v-if="orderInfo.status >= 2 && orderInfo.payTime !== null"
              >
                <div class="time">{{ orderInfo.payTime }}</div>
                <div class="text">{{$t('orderDetails.logisticsTips3')}}</div>
              </div>
              <div :class="['item', orderInfo.status >= 1?'left-line':'']" v-if="orderInfo.status >= 1">
                <div class="time">{{ orderInfo.createTime }}</div>
                <div class="text">{{$t('orderDetails.logisticsTips4')}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- /配送信息 -->
      <!-- 订单信息 -->
      <div class="order-info">
        <!-- 收货信息/自提信息（orderMold=1虚拟商品不展示收货/自提信息） -->
        <div v-if="orderInfo.orderMold !== 1" class="item">
          <div class="tit">{{['', $t('orderDetails.receiptInformation'), $t('orderDetails.selfPickupInformation'), $t('orderDetails.receiptInformation'), $t('orderDetails.receiptInformation')][dvyType]}}</div>
          <div class="con">
            <div class="con-item">
              <span class="item-tit">{{['', $t('orderDetails.receiver'), $t('orderDetails.picker'), $t('orderDetails.receiver'), $t('orderDetails.receiver')][dvyType]}}：</span>
              <span class="item-con">{{dvyType==2?stationUserName:userAddrDto.receiver}}</span>
            </div>
            <div class="con-item">
              <span class="item-tit">{{$t('orderDetails.contactInformation')}}：</span>
              <span class="item-con">{{dvyType==2?stationUserMobile:userAddrDto.mobile}}</span>
            </div>
            <div class="con-item">
              <span class="item-tit">{{['', $t('orderDetails.receiptAddress'), $t('orderDetails.pickupAddress'), $t('orderDetails.receiptAddress'), $t('orderDetails.receiptAddress')][dvyType]}}：</span>
              <span class="item-con">{{dvyType==2?stationAddress:userAddrDto.province+userAddrDto.city+userAddrDto.area+userAddrDto.addr}}</span>
            </div>
          </div>
        </div>
        <!-- 配送信息（orderMold=1虚拟商品不展示配送信息） -->
        <div v-if="orderInfo.orderMold !== 1" class="item">
          <div class="tit">{{$t('orderDetails.deliveryInformation')}}</div>
          <div class="con">
            <div class="con-item">
              <span class="item-tit">{{$t('orderDetails.deliveryMethod')}}：</span>
              <span class="item-con" v-if="dvyType">{{
                [$t('orderDetails.generalDelivery'), $t('orderDetails.buyerPickup'), $t('orderDetails.noExpressDelivery'), $t('orderDetails.sameCityDelivery')][dvyType - 1]
              }}</span>
              <span class="item-con" v-if="!dvyType">{{$t('orderDetails.none')}}</span>
            </div>
            <div class="con-item">
              <span class="item-tit">{{$t('orderDetails.shippingFee')}}：</span>
              <span class="item-con"
                >￥{{ parsePrice(orderInfo.transfee)[0] }}.{{
                  parsePrice(orderInfo.transfee)[1]
                }}</span
              >
            </div>
          </div>
        </div>

        <!--
          虚拟商品-券码列表显隐：
          1、订单状态为status==1“待支付”时隐藏
          2、订单状态为status==6“已取消”时
            2.1 含有退款编号（即退款成功）时显示
            2.2 不含退款编号（即取消支付）时隐藏
          3、订单状态status != 7（status:7拼团中）时显示
          4、writeOffNum!==0 需要核销的虚拟商品才显示
        -->
        <div
          v-if="orderInfo.orderMold === 1 &&
                orderInfo.status != 1 &&
                orderInfo.status != 7 &&
                ((orderInfo.status == 6 && orderInfo.orderItemDtos[0].refundSn) ||orderInfo.status != 6) &&
                orderInfo.writeOffNum !== 0
          "
          class="item virtual-goods-code">
          <!-- 待使用/未使用 (unusedCount待使用的核销券) -->
          <div v-if="unusedCount && orderInfo.status != 6" class="tit">{{$t('orderDetails.toBeUsed')}}（{{unusedCount}}{{$t('orderDetails.sheets')}}）</div>
          <!-- 确认收货(已完成) & 没有待核销的券码 -->
          <div v-if="orderInfo.status == 5  && !unusedCount" class="tit">{{$t('orderDetails.used')}}（{{orderInfo.orderItemDtos[0].prodCount - unusedCount}}{{$t('orderDetails.sheets')}}）</div>
          <!-- 退款成功 -->
          <div v-if="orderInfo.status == 6 && orderInfo.orderItemDtos[0].refundSn" class="tit">{{$t('orderDetails.used')}}（{{orderInfo.orderItemDtos[0].prodCount - unusedCount}}{{$t('orderDetails.sheets')}}）</div>
          <div class="con">
            <!-- 券码列表 -->
            <div v-for="(item,index) in virtualInfoList" :key="index" class="con-item">
              <!-- isWriteOff:0未使用 1已使用 -->
              <div :class="{'used': item.isWriteOff === 1 || orderInfo.status == 6}">
                <div class="item-tit">
                  {{$t('orderDetails.voucherCode')}}<span v-if="virtualInfoList.length > 1">{{index+1}}</span>：
                </div>
                <span class="code">{{item.writeOffCode}}</span>
                <span v-if="item.isWriteOff === 0 && orderInfo.status == 6 && orderInfo.orderItemDtos[0].refundSn" class="grey">({{$t('orderDetails.refunded')}})</span>
              </div>
            </div>
          </div>
        </div>
        <!-- 全部留言（虚拟商品）-->
        <div
          v-if="orderInfo.orderMold === 1
                && virtualRemarks.length"
          class="item all-msg">
          <div class="tit">{{$t('submitOrder.allMessages')}}</div>
          <div class="con">
            <div v-for="(item,index) in virtualRemarks" :key="index" class="con-item">
              <div class="item-tit">{{item.name}}：</div>
              <div class="msg-con">{{item.value}}</div>
            </div>
          </div>
        </div>

        <!-- 付款信息 -->
        <div v-if="orderInfo.status>1 && orderInfo.payType" class="item">
          <div class="tit">{{$t('orderDetails.paymentInformation')}}</div>
          <div class="con">
            <!-- 支付方式 -->
            <div class="con-item">
              <span class="item-tit">{{$t('orderDetails.paymentMethod')}}：</span>
              <!-- <span class="item-con">{{$t('orderDetails.onlinePayment')}}</span> -->
              {{ [$t('payment.pointPay'),$t('payment.wechatPay'),$t('payment.aliPay'),$t('payment.wechatPay'),$t('payment.wechatPay'),$t('payment.wechatPay'),$t('payment.aliPay'),$t('payment.aliPay'),$t('payment.wechatPay'),$t('payment.balancePay')][orderInfo.payType] }}
            </div>
            <!-- 付款时间 -->
            <div class="con-item">
              <span class="item-tit">{{$t('orderDetails.paymentTime')}}：</span>
              <span class="item-con">{{ orderInfo.payTime }}</span>
            </div>
          </div>
        </div>
        <!-- 订单备注 -->
        <div class="item">
          <div class="tit">{{$t('orderDetails.orderRemarks')}}</div>
          <div class="con">
            <div class="con-item">
              <!-- <span class="item-tit">发票类型：</span> -->
              <span class="item-con">{{ orderInfo.remarks }}</span>
            </div>
            <!-- <div class="con-item">
              <span class="item-tit">发票抬头：</span>
              <span class="item-con">个人</span>
            </div>
            <div class="con-item">
              <span class="item-tit">发票内容：</span>
              <span class="item-con">商品明细</span>
            </div>-->
          </div>
        </div>
        <!-- <div class="item">
          <div class="tit">发票信息</div>
          <div class="con">
            <div class="con-item">
              <span class="item-tit">发票类型：</span>
              <span class="item-con">电子普通发票</span>
            </div>
            <div class="con-item">
              <span class="item-tit">发票抬头：</span>
              <span class="item-con">个人</span>
            </div>
            <div class="con-item">
              <span class="item-tit">发票内容：</span>
              <span class="item-con">商品明细</span>
            </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="100" class="tal">{{$t('quantity')}}</th>
                  <th width="140">{{$t('priceOne')}}</th>
                  <th width="140">{{$t('totalAll')}}</th>
                  <th width="140">{{$t('operation')}}</th>
                </tr>
                <tr
                  class="box-tr"
                  v-for="(prod, prodIndex) in orderInfo.orderItemDtos"
                  :key="prodIndex"
                >
                  <td>
                    <div class="goods-info">
                      <a
                        href="javascript:void(0);"
                        @click="toDetail(prod)"
                        class="img"
                      >
                        <img v-if="prod.pic" :src="prod.pic" alt @error="handlePicError"/>
                        <img v-else src="~/assets/img/def.png" alt />
                      </a>
                      <div class="name-sku">
                        <a
                          href="javascript:void(0);"
                          @click="toDetail(prod)"
                          class="name"
                          >{{ prod.prodName }}</a
                        >
                        <span class="sku">{{ prod.skuName }}</span>
                      </div>
                    </div>
                    <!-- 赠品：多件商品时展示 -->
                    <div
                      v-if="orderInfo.orderItemDtos.length > 1 && prod.giveawayList && prod.giveawayList.length"
                      class="gift-info">
                      <div
                        v-for="gitfItem in prod.giveawayList"
                        :key="gitfItem.orderItemId"
                        class="gift-item"
                        @click="toProdDetails(gitfItem.prodId)"
                      >
                        <span class="name">{{  '【' + $t('prodDetail.gift') + '】' + gitfItem.prodName }}</span>
                        <span class="num">×{{ gitfItem.prodCount }}</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>
                  <!-- <td>
                    <div class="status">{{['','待付款','待发货','待收货','待评价','已完成','已取消'][orderInfo.status]}}</div>
                  </td>-->

                  <td>
                    <div class="action">
                      <!-- <a href="javascript:void(0)"
                         @click="payNow(prod.prodId,orderInfo.status)"
                      :class="['action-btn', orderInfo.status>4?'default':'active']">{{['','立即付款','提醒卖家','确认收货','发表评论','再次购买','立即购买'][5]}}</a>-->
                      <!-- 退款条件：拟退款条件，还有未知判定条件 -->
                      <!-- 虚拟商品-申请退款
                        1、canAllRefund允许退款
                        2、orderType==4虚拟商品
                          2.1 需要核销且还有未核销的券码
                          2.2 无需核销
                        3、金额为0且无使用积分时不显示
                      -->
                      <a
                        href="javascript:void(0)"
                        v-if="
                          orderInfo.canAllRefund &&
                          !prod.refundSn &&
                          (prod.actualTotal || (!prod.actualTotal && prod.useScore)) &&
                          orderInfo.orderType != 3 &&
                          orderInfo.orderMold == 1 &&
                          ((orderInfo.writeOffNum != 0 && unusedCount) || orderInfo.writeOffNum == 0)
                        "
                        :class="['action-btn']"
                        @click="toApplyReturn(prod.orderItemId, orderInfo.orderMold == 1 ? 2 : 1)"
                        >{{$t('orderDetails.requestRefund')}}</a
                      >
                      <a
                        href="javascript:void(0)"
                        v-if="
                          (prod.actualTotal || (!prod.actualTotal && prod.useScore)) &&
                          orderInfo.canRefund &&
                          !prod.refundSn &&
                          orderInfo.orderType != 3 &&
                          orderInfo.orderMold != 1
                        "
                        :class="['action-btn']"
                        @click="toApplyReturn(prod.orderItemId, 2)"
                        >{{$t('orderDetails.requestRefund')}}</a
                      >
                      <a
                        href="javascript:void(0)"
                        v-if="prod.refundSn"
                        :class="['action-btn']"
                        @click="
                          toViewRefund(
                            prod.refundSn,
                            2,
                            prod.orderItemId,
                            prod.returnMoneySts
                          )
                        "
                        >{{$t('orderDetails.viewRefund')}}</a
                      >
                      <a
                        href="javascript:void(0)"
                        v-if="orderInfo.status === 4"
                        :class="['action-btn']"
                        >{{$t('orderDetails.evaluation')}}</a
                      >
                      <a
                        href="javascript:void(0)"
                        v-if="(orderInfo.status > 4 || orderInfo.cancelTime !==null) && orderInfo.status != 7"
                        @click="toProdDetail(prod.prodId)"
                        :class="['action-btn']"
                      >{{$t('orderDetails.repurchase')}}</a>
                      <!-- @click="orderRoute(prod.prodId)" -->
                    </div>
                  </td>
                </tr>

              </tbody>

              <!-- 赠品：单个商品时展示 -->
              <tbody v-if="giveawayList && giveawayList.length">
                <tr
                  class="box-tr"
                  v-for="prod in giveawayList"
                  :key="prod.orderItemId"
                >
                  <td>
                    <div class="goods-info">
                      <nuxt-link
                        :to="'/detail/' + prod.prodId"
                        class="img"
                      >
                        <img v-if="prod.pic" :src="prod.pic.indexOf('http') === -1 ? picDomain + prod.pic : prod.pic" alt @error="handlePicError"  />
                        <img v-else src="~/assets/img/def.png" alt />
                      </nuxt-link>
                      <div class="name-sku">
                        <nuxt-link :to="'/detail/' + prod.prodId"
                          class="name"
                          >{{ prod.prodName }}</nuxt-link
                        >
                        <div class="sku">
                          <span class="gift-icon">{{ $t('prodDetail.gift')}}</span>
                          <span>{{ prod.skuName }}</span>
                        </div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <div class="goods-number">×{{ prod.prodCount }}</div>
                  </td>
                  <td>
                    <span class="price">-</span>
                  </td>
                  <td>
                    <span class="price">-</span>
                  </td>

                  <td>
                  </td>
                </tr>
                <!-- / 赠品 -->
              </tbody>
            </table>
            <div class="total-return">
              <!-- 申请退款 -->
              <!-- 金额为0且无使用积分时不显示 -->
              <a
                href="javascript:void(0)"
                v-if="
                  orderInfo.canRefund &&
                    orderInfo.canAllRefund &&
                    !orderInfo.orderItemDtos.refundSn &&
                    orderInfo.orderType != 3
                    && orderInfo.orderMold != 1
                    && ((orderInfo.orderScore && !orderInfo.actualTotal) || orderInfo.actualTotal)
                "
                class="action-btn"
                @click="toApplyReturn(orderInfo.orderItemDtos.orderItemId, 1)"
                >{{$t('orderDetails.refundsEntireOrders')}}</a
              >
              <!-- <a
                href="javascript:void(0)"
                v-if="!orderInfo.canRefund && !orderInfo.canAllRefund && orderInfo.orderItemDtos[0].refundSn && orderInfo.orderItemDtos.length == 1"
                class="action-btn"
                @click="toViewRefund(orderInfo.orderItemDtos[0].refundSn,1,orderInfo.orderItemDtos[0].orderItemId,orderInfo.orderItemDtos[0].returnMoneySts)"
              >查看退款</a>-->
            </div>
          </div>

          <!-- 商品总额与优惠明细 -->
          <div class="goods-total">
            <!-- 商品总额 -->
            <div class="item">
              <span class="tit">{{$t('orderDetails.totalMerchandise')}}：</span>
              <span class="price"
                >￥{{ parsePrice(orderInfo.total)[0] }}.{{
                  parsePrice(orderInfo.total)[1]
                }}</span
              >
            </div>
            <!-- 商品运费 -->
            <div v-if="orderInfo.orderMold !== 1" class="item">
              <span class="tit">{{$t('orderDetails.productShipping')}}：</span>
              <span class="price"
                ><span v-if="orderInfo.transfee && orderInfo.status === 2 && orderInfo.isRefunding" style="margin-right: 8px;">
                  <el-popover
                    placement="top-start"
                    width="200"
                    trigger="hover"
                    :content="$t('applyReturn.refundBeforeShippingTips')">
                    <i class="el-icon-warning" slot="reference"></i>
                  </el-popover></span
                >￥{{ parsePrice(orderInfo.transfee)[0] }}.{{
                  parsePrice(orderInfo.transfee)[1]
                }}
               </span
              >
            </div>
            <!-- 运费减免 -->
            <div v-if="orderInfo.platformFreeFreightAmount" class="item">
              <span class="tit">{{$t('orderDetails.shippingDiscount')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.platformFreeFreightAmount)[0] }}.{{
                  parsePrice(orderInfo.platformFreeFreightAmount)[1]
                }}</span
              >
            </div>
            <!-- 平台优惠券 -->
            <div v-if="orderInfo.platformCouponAmount" class="item">
              <span class="tit">{{$t('submitOrder.platformCoupons')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.platformCouponAmount)[0] }}.{{
                  parsePrice(orderInfo.platformCouponAmount)[1]
                }}</span
              >
            </div>
            <!-- 积分抵扣 -->
            <div v-if="orderInfo.scoreAmount" class="item">
              <span class="tit">{{$t('submitOrder.pointsCredit')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.scoreAmount)[0] }}.{{
                  parsePrice(orderInfo.scoreAmount)[1]
                }}</span
              >
            </div>
            <!-- 会员折扣 -->
            <div v-if="orderInfo.memberAmount" class="item">
              <span class="tit">{{$t('submitOrder.memberDiscount')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.memberAmount)[0] }}.{{
                  parsePrice(orderInfo.memberAmount)[1]
                }}</span
              >
            </div>
            <!-- 店铺优惠券 -->
            <div v-if="orderInfo.shopCouponMoney" class="item">
              <span class="tit">{{$t('orderDetails.storeCoupons')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.shopCouponMoney)[0] }}.{{
                  parsePrice(orderInfo.shopCouponMoney)[1]
                }}</span
              >
            </div>
            <!-- 促销满减 -->
            <div v-if="orderInfo.discountMoney" class="item">
              <span class="tit">{{$t('submitOrder.promotionalSale')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.discountMoney)[0] }}.{{
                  parsePrice(orderInfo.discountMoney)[1]
                }}</span
              >
            </div>
            <!-- 套餐减免 -->
            <div v-if="orderInfo.shopComboAmount" class="item">
              <span class="tit">{{$t('submitOrder.packageOffer')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.shopComboAmount)[0] }}.{{
                  parsePrice(orderInfo.shopComboAmount)[1]
                }}</span
              >
            </div>
            <!-- 拼团/秒杀 -->
            <div v-if="orderInfo.orderType && orderInfo.orderType!=3 && orderInfo.shopAmount" class="item">
              <span class="tit">{{orderInfo.orderType === 1 ? $t('index.group') : $t('index.spike')}}{{$t('cart.offers')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.shopAmount)[0] }}.{{
                  parsePrice(orderInfo.shopAmount)[1]
                }}</span
              >
            </div>
            <!-- 商家改价(只允许减价) -->
            <div v-if="orderInfo.shopChangeFreeAmount" class="item">
              <span class="tit">{{$t('orderDetails.merchantsModifyPrices')}}：</span>
              <span class="price gray"
                >- ￥{{ parsePrice(orderInfo.shopChangeFreeAmount)[0] }}.{{
                  parsePrice(orderInfo.shopChangeFreeAmount)[1]
                }}</span>
            </div>

            <!-- 商品总优惠 -->
            <!-- <div class="item">
              <span class="tit">{{$t('orderDetails.productOffer')}}：</span>
              <span class="price"
                >-￥{{ parsePrice(orderInfo.reduceAmount)[0] }}.{{
                  parsePrice(orderInfo.reduceAmount)[1]
                }}</span
              >
            </div> -->
            <!-- 应付金额/实付金额 -->
            <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>
          <!-- 商品总额与优惠明细 end -->

          <!-- 提示弹窗 -->
          <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>
  </div>
</template>

<script>
import util from '~/plugins/util'
import { picDomain } from '~/plugins/config.js'
import big from '~/plugins/big.min.js'
export default {
  data () {
    return {
      // 图片地址
      picDomain: picDomain,
      orderNumber: '',
      orderInfo: {},
      userAddrDto: {},
      showTips: false,
      betweenTime: { day: '', hou: '', min: '', sec: '' }, // 订单支付倒计时
      timer: '', // 定时器
      indexs: 0,
      deliveryList: [],  //  包裹集合
      deliveryExpresse: null,  //  包裹信息
      offsetCount: 0,  //  偏移数

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

      // 虚拟商品
      virtualRemarks: [], // 全部留言列表
      unusedCount: 0, // 待使用的核销券
      virtualInfoList: [], // 券码列表

      giveawayList: [] // 赠品列表
    }
  },
  created () {
    this.orderNumber = this.$route.query.orderNumber
  },
  mounted () {
    // 设置网页标题
    document.title = this.$i18n.t('orderDetails.orderDetails')
    this.getOrderDetail()
    // console.log(this.deliveryExpresse.deliveryDto.traces.length)
  },
  watch: {
    deliveryExpresse: function (newVal, oldVal) {
      this.$nextTick(() => {
        this.offsetCount = 0  //初始化变量
        if (this.deliveryExpresse && this.$refs.carouser) {
          this.$refs.carouser.style.left = '0px'
        }
      })
    }
  },
  methods: {

    /**
     * 获取支付订单详情
     */
    getOrderDet () {
      this.$axios.get('/p/order/getOrderPayInfoByOrderNumber', {
        params: {
          orderNumbers: this.orderNumber
        }
      }).then(({ data }) => {
        this.payOrderInfo = data
        this.betweenTimestamp = util.betweenTimestamp(new Date().getTime(), util.dateToTimestamp(data.endTime))
        if (this.betweenTimestamp > 0) {
          this.betweenTime = util.betweenTime(this.betweenTimestamp)
          this.countdown()
        } else {
        }
      })
    },

    /**
     * 倒计时
     */
    countdown () {
      this.betweenTimestamp = this.betweenTimestamp - 1000
      this.betweenTime = util.betweenTime(this.betweenTimestamp)
      if(Number(this.betweenTime.day === 0) && Number(this.betweenTime.hou === 0) && Number(this.betweenTime.min === 0) && Number(this.betweenTime.sec === 0)){
        clearTimeout(this.timer)
        history.go(0)
      }
      this.timer = setTimeout(() => {
        this.countdown()
      }, 1000)
    },

    handlePicError(e){
      e.target.src=require('../assets/img/def.png')
    },

    /**
     * 跳转详情页
     */
    toDetail(prod) {
      if (this.orderInfo.orderType == 2 && !this.orderInfo.seckillId) {
        this.$message.warning(this.$i18n.t('spike.currentSecondsAreOver'))
        return
      }
      this.$router.push({ path: (this.orderInfo.orderType == 3 ? '/member-center/integral-det/': this.orderInfo.orderType == 2 ? '/secdetail/' : '/detail/') + (this.orderInfo.orderType == 2 ? this.orderInfo.seckillId : prod.prodId) });
    },

    /**
     * 获取订单详情
     */
    getOrderDetail () {
      this.$axios.get('/p/myOrder/orderDetail', {
        params: {
          orderNumber: this.$route.query.orderNumber
        }
      }).then(({ data }) => {
        // isRefunding: 是否有订单项正在退款
        data.isRefunding = data.orderItemDtos.findIndex(el=> el.refundSn && el.returnMoneySts && el.returnMoneySts != 5) > -1
        if (data.status == 1) {
          // 订单待支付则获取待支付订单详情
          this.getOrderDet()
        }
        this.dvyType = data.dvyType
        this.orderInfo = data
        // 官方自营店判断
        this.orderInfo.shopId===null?this.orderInfo.shopId=0:this.orderInfo.shopId
        this.userAddrDto = data.userAddrDto  //地址Dto
        if(this.orderInfo.status >= 3) {
          this.getDeliveryDet()
        }
        if (this.dvyType == 2) {
          this.getStationDetail()
        }
        // 虚拟商品
        if (data.orderMold === 1) {
          // 留言列表（过滤没有填写的留言）
          const virtualRemarks = data.virtualRemark ? JSON.parse(data.virtualRemark) : []
          let remark = []
          if (virtualRemarks && virtualRemarks.length) {
            remark = virtualRemarks.filter(el => el.value)
          }
          this.virtualRemarks = remark || []

          this.virtualInfoList = data.virtualInfoList || []

          // 计算待使用券码总数
          if (this.virtualInfoList && this.virtualInfoList.length) {
            let unusedCount = 0
            this.virtualInfoList.forEach(el => {
              if (el.isWriteOff === 0) {
                unusedCount = unusedCount + 1
              }
            })
            this.unusedCount = unusedCount
          }
        }
        // 赠品
        this.giveawayList = []
        if (this.orderInfo.orderItemDtos && this.orderInfo.orderItemDtos.length === 1) {
          this.giveawayList = this.orderInfo.orderItemDtos[0].giveawayList
        }
      })
    },

    // 获取自提点信息
    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 }) => {
        if (data.length && data[0].deliveryDto && data[0].deliveryDto.traces) {
         data[0].deliveryDto.traces.reverse()
        }
        this.deliveryList = data //包裹集合信息
        this.deliveryExpresse = data[0] //包裹信息
      })
    },

    // 点击包裹tab事件
    onClickTabDelivery (index) {
      this.indexs = index
      this.getDeliveryDtoById()
    },

    // 获取指定包裹的物流信息
    getDeliveryDtoById() {
      this.$axios.get('/p/myDelivery/deliveryOrder/' +  this.deliveryList[this.indexs].orderDeliveryId).then(({ data }) => {
        if (data.deliveryDto && data.deliveryDto.traces) {
          data.deliveryDto.traces.reverse()
        }
        this.deliveryExpresse = data
      })
    },

    // 商品切换
    prevItem () {
      var len = this.deliveryExpresse.orderItems.length
      if (len - 5 > 0) {
        if (this.offsetCount > 0) {
          this.offsetCount--
          this.$refs.carouser.style.left = '-' + (70 * this.offsetCount) + 'px'
        } else {
          return false
        }
      } else if (len - 5 <= 0) {
        return false
      } else {
        return false
      }
    },

    nextItem () {
      var len = this.deliveryExpresse.orderItems.length
      if (len - 5 > 0) {
        if (this.offsetCount < len - 5) {
          this.offsetCount++
          this.$refs.carouser.style.left = '-' + (70 * this.offsetCount) + 'px'
        } else if (len - 5 <= 0) {
          return false
        } else {
          return false
        }
      } else {
        return false
      }
    },
    /**
     * 跳转店铺页面
     */
    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' })
    },
    /**
    * 跳转到商品详情页
    */
    toProdDetails (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) {
      const platformFreeFreightAmount = this.orderInfo.platformFreeFreightAmount
      const transfee = platformFreeFreightAmount
                       ? Number.parseFloat(new big(platformFreeFreightAmount).minus(this.orderInfo.transfee)).valueOf()
                       : 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(".");
    },
    /**
     * 查看发票
     */
    toInvoice(orderNumber) {
      this.$router.push({
        path: '/invoice-detail',
        query: {
          orderNumber,
          orderInvoiceId: this.orderInfo.orderInvoiceId
        }
      })
    }
  },

  beforeDestroy () {
    clearTimeout(this.timer)
  }
}
</script>

<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;
}
.en-width {
  width:120px !important;
}
</style>
