<template>
  <view class="Mall4j order-detail page-order-detail">
    <!-- 订单状态 -->
    <view class="status-box">
      <view class="bg">
        <image :src="statusBG" />
      </view>
      <view class="text">
        <block v-if="status===orderStatusConstant.UNPAY">
          <view class="status">
            等待付款
          </view>
          <view class="des">
            您已拍下商品，请尽快付款
          </view>
        </block>
        <block v-else>
          <view class="status">
            {{ ['','',deliveryType!==2?'等待发货':'待使用','等待收货','','已完成','已取消','待成团','','待付尾款'][status] }}
          </view>
          <view class="des">
            {{ ['','',deliveryType!==2?(updateOrViewDeliveryInfo?'部分商品已发货':'商家还未发货')+'，请您耐心等待':'商品到店，请您尽快到店提货','商品正在运输中，请您耐心等待','','感谢您的购买，欢迎下次光临','您的订单已成功取消','拼团进行中','','您已支付定金，请及时支付尾款'][status] }}
          </view>
        </block>
      </view>
      <view class="icon">
        <image
          v-if="status===orderStatusConstant.UNPAY"
          src="@/package-user/static/images/det-paid.png"
        />
        <!-- 待付款 -->
        <image
          v-if="status===orderStatusConstant.PAYED"
          src="@/package-user/static/images/det-delivered.png"
        />
        <!-- 待发货 -->
        <image
          v-if="status===orderStatusConstant.CONSIGNMENT"
          src="@/package-user/static/images/det-received.png"
        />
        <!-- 带收货 -->
        <image
          v-if="status===orderStatusConstant.SUCCESS"
          src="@/package-user/static/images/det-finish.png"
        />
        <!-- 已完成 -->
        <image
          v-if="status===orderStatusConstant.CANCEL"
          src="@/package-user/static/images/det-cancel.png"
        />
        <!-- 已取消 -->
      </view>
    </view>

    <!-- 物流 虚拟商品(orderMold:1)不展示 -->
    <view
      v-if="(status>=orderStatusConstant.CONSIGNMENT||(status===2 && updateOrViewDeliveryInfo)) && deliveryType !==3 && status!==orderStatusConstant.WAIT_GROUP && updateOrViewDeliveryInfo &&orderMold !== 1"
      class="logistics-box"
      @tap="toLogisticsDetail"
    >
      <view class="icon">
        <image src="@/package-user/static/images/logistics.png" />
      </view>
      <view class="text-arrow">
        查看物流
      </view>
    </view>

    <!-- 地址 虚拟商品(orderMold:1)没有这一项 -->
    <view
      v-if="orderMold !== 1&&deliveryType!==2"
      class="address-box"
    >
      <view class="icon">
        <image src="@/static/images/local.png" />
      </view>
      <view class="text-box">
        <view class="user">
          <view class="name">
            {{ orderAddr.consignee }}
          </view>
          <view class="phone">
            {{ orderAddr.mobile }}
          </view>
        </view>
        <view class="address">
          {{ orderAddr.province + orderAddr.city + orderAddr.area + orderAddr.addr }}
        </view>
      </view>
    </view>

    <!-- 自提订单提货信息（二维码、门店、提货码等） -->
    <view
      v-if="deliveryType===2"
      class="delivery-certificate"
    >
      <!-- 店铺营业等信息 -->
      <view
        v-if="stationInfo"
        class="shop-info"
      >
        <store-item
          :item="stationInfo"
          :is-show-no-stock="false"
        />
      </view>
      <!-- 提货码（二维码、条形码） -->
      <view
        v-if="status<=2 && !showPayBtn"
        class="code"
      >
        <image
          class="qr-code"
          :src="stationQrCode"
        />
        <view class="bar-code">
          <w-barcode :options="barOpations" />
        </view>
      </view>
      <!-- 提货人信息 -->
      <view class="consignee-info">
        <view
          v-if="!(orderType===1 && status===7) && !showPayBtn && status!==6 && status!==9"
          class="info"
        >
          <view class="i-label">
            提 货 码:
          </view>
          <view
            class="i-text station-code"
            :class="{writtenOff:status>2}"
          >
            <view class="code-text">
              {{ codeFormat(stationCode) }} <view
                v-if="status<=2"
                class="copy"
                @tap="copy(stationCode)"
              >
                复制
              </view>
            </view>
            <view :class="[status>2?'used':'be-use']">
              {{ status>2?'已使用':'待使用' }}
            </view>
          </view>
        </view>
        <view class="info">
          <view class="i-label">
            提 货 人:
          </view>
          <view class="i-text">
            {{ stationUserName + ' ' + stationUserMobile }}
          </view>
        </view>
      </view>
    </view>

    <!-- 商品 -->
    <view class="prods-box">
      <view class="shop">
        <view class="icon">
          <image src="@/static/images/shop.png" />
        </view>
        <view
          class="name text-arrow"
          @tap="toShopIndex"
        >
          {{ shopName }}
        </view>
      </view>
      <block
        v-for="(orderItem, prodIdx) in orderItems"
        :key="prodIdx"
      >
        <view
          class="prod-item"
        >
          <view
            class="info"
            @tap="toProdDetail(orderItem.spuId)"
          >
            <view class="prod-img">
              <img-show
                :src="orderItem.pic"
                img-mode="aspectFit"
              />
            </view>
            <view class="text-box">
              <view class="name">
                {{ orderItem.spuName }}
              </view>
              <view class="sku">
                <view
                  v-if="orderItem.skuName"
                  class="sku-text"
                >
                  {{ orderItem.skuName }}
                </view>
                <view
                  v-if="(orderType && orderType < 4) && orderMold !== 1"
                  class="activity-logo"
                >
                  <text v-if="orderType===orderTypeConstant.GROUP">
                    拼团
                  </text>
                  <text v-if="orderType===orderTypeConstant.SECOND">
                    秒杀
                  </text>
                  <text v-if="orderType===orderTypeConstant.SCORE">
                    积分
                  </text>
                </view>
                <!-- 预售 -->
                <view
                  v-if="orderPreSaleInfoVO&&(orderPreSaleInfoVO.preSaleType===0||orderPreSaleInfoVO.preSaleType===1)"
                  class="presale-logo"
                >
                  <view class="activity-logo">
                    预售
                  </view>
                  <view v-if="orderPreSaleInfoVO.preSaleDeliveryType!==-1 && !(status===2||status===3||status===5)">
                    {{ ['付款成功后','尾款支付'][orderPreSaleInfoVO.preSaleType] }}{{ orderPreSaleInfoVO.preSaleDeliveryType }}天开始发货
                  </view>
                  <view v-else>
                    {{ preSaleDeliveryTime }}开始发货
                  </view>
                </view>
              </view>

              <view class="price-box">
                <view class="price">
                  <view
                    v-if="orderType===orderTypeConstant.SCORE"
                    class="symbol"
                  >
                    {{ orderItem.useScore / totalNum }}积分
                  </view>
                  <view
                    v-if="orderType===orderTypeConstant.SCORE && orderItem.price"
                    class="symbol"
                  >
                    +
                  </view>
                  <view
                    v-if="orderType!==orderTypeConstant.SCORE"
                    class="symbol"
                  >
                    ￥
                  </view>
                  <view
                    v-if="orderItem.price"
                    class="big"
                  >
                    {{ wxs.parsePrice(orderItem.price)[0] }}
                  </view>
                  <view
                    v-if="orderItem.price"
                    class="symbol"
                  >
                    .{{ wxs.parsePrice(orderItem.price)[1] }}元
                  </view>
                </view>
                <view class="count">
                  ×{{ orderItem.count }}
                </view>
                <view
                  v-if="status!==orderStatusConstant.UNPAY"
                  class="action"
                >
                  <view
                    v-if="!orderItem.finalRefundId&&orderType!==orderTypeConstant.SCORE && status!==orderStatusConstant.CANCEL && (!orderItem.refundStatus || orderItem.refundStatus===refundStatusConstant.DISAGREE) && canRefund && orderItem.isRefund!==0 && (orderMold !== 1 ||
                      (orderMold === 1 && ((writeOffNum !== 0 && unusedCount) || writeOffNum === 0)))"
                    class="btn"
                    @tap.stop="toApplyRefund(orderItem)"
                  >
                    申请售后
                  </view>
                  <view
                    v-if="orderItem.finalRefundId || (orderItem.refundStatus && orderItem.refundStatus !==refundStatusConstant.DISAGREE)"
                    class="btn"
                    @tap.stop="toRefundDetail(orderItem.finalRefundId)"
                  >
                    查看退款
                  </view>
                </view>
                <!-- 待付款时不显示action,已取消时显示“加购物车”,待发货、待收货、已完成显示“申请售后”和“加购物车” -->
              </view>
            </view>
          </view>

          <!-- 组合：多个商品时展示 -->
          <view
            v-if="orderItem.comboItemList && orderItem.comboItemList.length"
            class="gift-prods"
          >
            <view
              v-for="(comboItem, comboIndex) in orderItem.comboItemList"
              :key="comboIndex"
              class="gift-item"
              @tap="toProdDetail(comboItem.spuId)"
            >
              <text class="name">
                【组合】{{ comboItem.spuName }}{{ comboItem.skuName ? (' ' + comboItem.skuName) : '' }}
              </text>
              <text class="num">
                ×{{ comboItem.count }}
              </text>
            </view>
          </view>

          <!-- 赠品：多个商品时展示 -->
          <view
            v-if="orderItems.length > 1 && orderItem.giveawayList && orderItem.giveawayList.length"
            class="gift-prods"
          >
            <view
              v-for="giftItem in orderItem.giveawayList"
              :key="giftItem.orderItemId"
              class="gift-item"
              @tap="toProdDetail(giftItem.spuId)"
            >
              <text class="name">
                【赠品】{{ giftItem.spuName }}
              </text>
              <text class="num">
                ×{{ giftItem.count }}
              </text>
            </view>
          </view>

          <!-- 预售商品   -->
          <view
            v-if="orderPreSaleInfoVO&&orderPreSaleInfoVO.preSaleType===1"
            class="presale-steps"
          >
            <steps
              :active="orderPreSaleInfoVO.payStatus-1"
              direction="column"
              active-color="#000"
              :options="stepsOptions"
            />
            <view>{{ balanceStartTime }}</view>
          </view>
        </view>

        <!-- 赠品：单个商品时展示 -->
        <view v-if="orderItems.length === 1 && orderItem.giveawayList && orderItem.giveawayList.length">
          <block
            v-for="(item) in orderItem.giveawayList"
            :key="item.orderItemId"
          >
            <view
              class="prod-item"
              @tap="toProdDetail(item.spuId)"
            >
              <view class="info">
                <view class="prod-img">
                  <img-show
                    :src="item.pic"
                    img-mode="aspectFit"
                  />
                </view>
                <view class="text-box">
                  <view class="name">
                    {{ item.spuName }}
                  </view>
                  <view class="sku">
                    <view class="activity-logo">
                      赠品
                    </view>
                    <view
                      v-if="item.skuName"
                      class="sku-text"
                      decode
                    >
                      {{ "&nbsp;&nbsp;" + item.skuName || '' }}
                    </view>
                  </view>
                  <view class="price-box">
                    <view class="count">
                      ×{{ item.count }}
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </block>
        </view>
      </block>
    </view>

    <!-- 订单信息 -->
    <view class="order-info">
      <view class="item-box">
        <view class="item">
          <view class="tit">
            订单编号：
          </view>
          <view class="text">
            {{ orderId }}
          </view>
          <view
            class="copy"
            @tap="copy(orderId)"
          >
            复制
          </view>
        </view>
        <view class="item">
          <view class="tit">
            下单时间：
          </view>
          <view class="text">
            {{ createTime }}
          </view>
        </view>
      </view>
      <view
        v-if="(status!==orderStatusConstant.UNPAY && (status!==orderStatusConstant.CANCEL || payType))||(orderMold === 1 && virtualRemarkList.length > 0)||(orderMold !== 1)"
        class="item-box"
      >
        <view
          v-if="status!==orderStatusConstant.UNPAY && (status!==orderStatusConstant.CANCEL || payType)"
          class="item"
        >
          <view class="tit">
            支付方式：
          </view>
          <view class="text">
            {{ ['积分支付','微信支付','支付宝','微信支付','微信支付','微信支付','支付宝','支付宝','微信支付','余额支付'][payType] }}
          </view>
        </view>
        <!-- 全部留言：虚拟商品 && 留言不为空时显示 -->
        <view
          v-if="orderMold === 1 && virtualRemarkList.length > 0"
          class="item all-msg"
          @tap="showViewMsgPopup"
        >
          <view class="tit">
            全部留言：
          </view>
          <view
            class="text"
            :class="{'pd': isExtraLong}"
          >
            <view
              v-for="(item, index) in virtualRemarkList"
              :key="index"
              class="virtual-item"
            >
              <view class="virtual virt-1">
                {{ item[0] }}
              </view>
              <view class="virtual virt-2">
                {{ item[1] }}
              </view>
            </view>
          </view>
          <view
            v-if="isExtraLong"
            class="more-msg"
          />
        </view>
        <view
          v-if="orderMold !== 1"
          class="item"
        >
          <view class="tit">
            配送方式：
          </view>
          <view class="text">
            {{ ['快递配送','快递配送','用户自提','无需快递','同城配送'][deliveryType] }}
          </view>
        </view>
      </view>
      <view
        v-if="remarks"
        class="item-box"
      >
        <view class="item">
          <view class="tit">
            订单备注：
          </view>
          <view class="text">
            {{ remarks || '' }}
          </view>
        </view>
      </view>
    </view>

    <!--
        虚拟商品-券码列表显隐：
        1、订单状态为status==1“待支付” 时隐藏
        2、订单状态为status==6“已取消”时
          2.1 退款状态为退款成功或部分退款成功（即退款成功）时显示
          2.2 退款状态非退款成功或部分退款成功（即取消支付）时隐藏
        3、订单状态为status==7“拼团中” 时隐藏
        4、writeOffNum!==0 需要核销的虚拟商品 显示
      -->
    <view
      v-if="orderMold === 1 &&
        status !== 1 &&
        status !== 7 &&
        ((status === 6 && (orderItems[0].refundStatus===2 || orderItems[0].refundStatus===3)) || status !== 6) &&
        writeOffNum !== 0"
      class="order-info voucher-code-con"
    >
      <view
        class="item-box tit"
        @tap="toViewWriteOffsRecords"
      >
        <view class="item">
          <!-- 待使用/未使用 (unusedCount待使用的核销券) -->
          <view
            v-if="unusedCount && status !== 6"
            class="txt strong"
          >
            {{ (isExpired?'已过期':'待使用') + '（' + unusedCount + '张' + '）' }}
          </view>
          <!-- 确认收货(已完成) & 没有待核销的券码 -->
          <view
            v-if="status === 5 && !unusedCount"
            class="txt strong"
          >
            {{ '已使用（' + orderItems[0].count + '张）' }}
          </view>
          <!-- 退款成功 -->
          <view
            v-if="status === 6 && orderItems[0].refundStatus"
            class="txt strong"
          >
            {{ '已使用（' + (orderItems[0].count - unusedCount) + '张）' }}
          </view>
        </view>
        <view class="record">
          核销记录
          <view class="text-arrow" />
        </view>
      </view>
      <view class="item-box">
        <view
          class="item"
          @tap="toViewVoucherCodePage"
        >
          <view class="item-left">
            <!-- 有效期限 -->
            <view class="txt weak flex-item">
              <view class="lf">
                有效期限：
              </view>
              <view class="rg">
                <text v-if="writeOffStart && !writeOffEnd">
                  购买后长期有效
                </text>
                <text v-if="writeOffStart && writeOffEnd">
                  {{ writeOffStart + '至' + writeOffEnd }}
                </text>
              </view>
            </view>
            <!-- 核销次数 -->
            <view class="txt weak flex-item">
              <view class="lf">
                核销次数：
              </view>
              <view class="rg">
                <text v-if="writeOffNum === -1">
                  多次核销
                </text>
                <text v-if="writeOffNum === 1">
                  单次核销
                </text>
                <text v-if="writeOffNum === 0">
                  无需核销
                </text>
              </view>
            </view>
          </view>
          <!-- 核销码条码/二维码： 非取消状态 && 仍有待使用的核销券码时显示icon -->
          <view
            v-if="status !== 6 && unusedCount && !(orderItems[0].refundStatus===2||orderItems[0].refundStatus===3)"
            class="item-right"
          >
            <image src="@/package-user/static/images/write-off-code.png" />
          </view>
        </view>
      </view>
      <!-- 券码列表 -->
      <view
        v-if="virtualInfoList && virtualInfoList.length"
        class="item-box voucher-code-list"
      >
        <view
          v-for="(item, index) in virtualInfoList"
          :key="index"
          class="item"
          :class="{'used': item.isWriteOff === 1 || status === 6 || orderItems[0].refundStatus===2||orderItems[0].refundStatus===3 ||isExpired }"
        >
          <view class="code-row">
            <text>券码</text>
            <text v-if="virtualInfoList && virtualInfoList.length > 1">
              {{ index+1 }}
            </text>：
            <text class="code">
              {{ codeFormat(item.writeOffCode) }}
            </text>
          </view>
          <view
            v-if="item.isWriteOff === 1"
            class="tips"
          >
            已使用
          </view>
          <view
            v-else-if="item.isWriteOff === 0 && (orderItems[0].refundStatus===2||orderItems[0].refundStatus===3)"
            class="tips"
          >
            已退款
          </view>
          <view
            v-else-if="isExpired"
            class="tips"
          >
            已过期
          </view>
          <view
            v-else-if="item.isWriteOff === 0 && status !== 6"
            class="copy-btn2"
            @tap="copy(item.writeOffCode)"
          >
            复制
          </view>
        </view>
      </view>
    </view>

    <view class="order-info">
      <view class="item-box">
        <view class="item">
          <view class="tit">
            商品总额：
          </view>
          <view class="price">
            <view v-if="orderType===orderTypeConstant.SCORE">
              {{ orderScore }}积分
            </view>
            <view
              v-if="actualTotal && orderType===orderTypeConstant.SCORE && actualTotal > transfee"
              class="symbol"
            >
              +
            </view>
            <view v-if="productTotalAmount">
              ￥{{ wxs.parsePrice(productTotalAmount)[0] }}.{{ wxs.parsePrice(productTotalAmount)[1] }}
            </view>
          </view>
        </view>
        <view
          v-if="orderMold !== 1 && deliveryType!==2"
          class="item"
        >
          <view class="tit">
            商品运费：
          </view>
          <view class="price">
            ￥{{ wxs.parsePrice(transfee)[0] }}.{{ wxs.parsePrice(transfee)[1] }}
          </view>
        </view>
        <view
          v-if="freeTransfee"
          class="item"
        >
          <view class="tit">
            运费减免：
          </view>
          <view class="price weak">
            ￥{{ wxs.parsePrice(freeTransfee)[0] }}.{{ wxs.parsePrice(freeTransfee)[1] }}
          </view>
        </view>
        <view
          v-if="platformCouponAmount"
          class="item"
        >
          <view class="tit">
            平台优惠券：
          </view>
          <view class="price weak">
            -￥{{ wxs.parsePrice(platformCouponAmount)[0] }}.{{ wxs.parsePrice(platformCouponAmount)[1] }}
          </view>
        </view>
        <view
          v-if="scoreAmount"
          class="item"
        >
          <view class="tit">
            积分抵扣：
          </view>
          <view class="price weak">
            -￥{{ wxs.parsePrice(scoreAmount)[0] }}.{{ wxs.parsePrice(scoreAmount)[1] }}
          </view>
        </view>
        <view
          v-if="memberAmount"
          class="item"
        >
          <view class="tit">
            会员折扣：
          </view>
          <view class="price weak">
            -￥{{ wxs.parsePrice(memberAmount)[0] }}.{{ wxs.parsePrice(memberAmount)[1] }}
          </view>
        </view>
        <view
          v-if="shopCouponMoney"
          class="item"
        >
          <view class="tit">
            店铺优惠券：
          </view>
          <view class="price weak">
            -￥{{ wxs.parsePrice(shopCouponMoney)[0] }}.{{ wxs.parsePrice(shopCouponMoney)[1] }}
          </view>
        </view>
        <view
          v-if="discountMoney"
          class="item"
        >
          <view class="tit">
            促销满减：
          </view>
          <view class="price weak">
            -￥{{ wxs.parsePrice(discountMoney)[0] }}.{{ wxs.parsePrice(discountMoney)[1] }}
          </view>
        </view>
        <view
          v-if="shopComboAmount"
          class="item"
        >
          <view class="tit">
            套餐优惠：
          </view>
          <view class="price weak">
            -￥{{ wxs.parsePrice(shopComboAmount)[0] }}.{{ wxs.parsePrice(shopComboAmount)[1] }}
          </view>
        </view>
        <view
          v-if="(orderType === orderTypeConstant.GROUP || orderType === orderTypeConstant.SECOND)&&shopAmount>0"
          class="item"
        >
          <view class="tit">
            {{ orderType === orderTypeConstant.GROUP?'拼团':'秒杀' }}优惠：
          </view>
          <view class="price weak">
            -￥{{ wxs.parsePrice(shopAmount)[0] }}.{{ wxs.parsePrice(shopAmount)[1] }}
          </view>
        </view>
        <view
          v-if="shopChangeFreeAmount"
          class="item"
        >
          <view class="tit">
            商家改价：
          </view>
          <view
            v-if="shopChangeFreeAmount > 0"
            class="price"
          >
            +￥{{ wxs.parsePrice(shopChangeFreeAmount)[0] }}.{{ wxs.parsePrice(shopChangeFreeAmount)[1] }}
          </view>
          <view
            v-if="shopChangeFreeAmount < 0"
            class="price weak"
          >
            -￥{{ wxs.parsePrice(Math.abs(shopChangeFreeAmount))[0] }}.{{ wxs.parsePrice(Math.abs(shopChangeFreeAmount))[1] }}
          </view>
        </view>
        <template v-if="orderPreSaleInfoVO&&orderPreSaleInfoVO.preSaleType===1">
          <view class="item">
            <view class="tit">
              定金：
            </view>
            <view class="price">
              ￥{{ wxs.parsePrice(orderPreSaleInfoVO.depositAmount)[0] }}.{{ wxs.parsePrice(orderPreSaleInfoVO.depositAmount)[1] }}
            </view>
          </view>
          <view class="item">
            <view class="tit">
              定金膨胀：
            </view>
            <view class="price">
              ￥{{ wxs.parsePrice(orderPreSaleInfoVO.depositExpansionAmount)[0] }}.{{ wxs.parsePrice(orderPreSaleInfoVO.depositExpansionAmount)[1] }}
            </view>
          </view>
          <view class="item">
            <view class="tit">
              尾款：
            </view>
            <view class="price">
              ￥{{ wxs.parsePrice(orderPreSaleInfoVO.balanceAmount)[0] }}.{{ wxs.parsePrice(orderPreSaleInfoVO.balanceAmount)[1] }}
            </view>
          </view>
        </template>

        <view class="item order-price">
          <view class="price-text tit">
            订单总额：
          </view>
          <view class="price">
            <view
              v-if="actualTotal"
              class="symbol"
            >
              ￥
            </view>
            <view
              v-if="actualTotal"
              class="big"
            >
              {{ wxs.parsePrice(actualTotal)[0] }}
            </view>
            <view
              v-if="actualTotal"
              class="symbol"
            >
              .{{ wxs.parsePrice(actualTotal)[1] }}
            </view>
            <view
              v-if="actualTotal && (orderType===orderTypeConstant.SCORE || orderScore)"
              class="symbol"
            >
              +
            </view>
            <view
              v-if="orderType===orderTypeConstant.SCORE || orderScore"
              class="big"
            >
              {{ orderScore }}
            </view>
            <view
              v-if="orderType===orderTypeConstant.SCORE || orderScore"
              class="score-apart"
            >
              积分
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部 -->
    <view
      v-if="btnNum"
      class="foot-box"
    >
      <view class="btn-box">
        <!-- 拼团订单 -->
        <view
          v-if="btnNum > 3"
          class="more-btn"
          @tap="handleMore"
        >
          更多
        </view>
        <div class="operation-box">
          <view
            v-if="showGroupBtn"
            class="btn"
            @tap="toGroupDetail"
          >
            拼团详情
          </view>
          <!-- 待收货时出现 -->
          <view
            v-if="showRefundBtn && btnNum <= 3 && orderMold !==1"
            class="btn"
            @tap="toApplyRefund"
          >
            {{ orderType === orderTypeConstant.NORMAL ? '整单售后' : '申请售后' }}
          </view>
          <!-- 支付后出现 -->
          <view
            v-if="shopCancellBtn"
            class="btn"
            @tap="handleShowPop(1)"
          >
            取消订单
          </view>
          <!-- 待付款时出现 -->
          <view
            class="btn"
            @tap="toContact"
          >
            联系客服
          </view>
          <!-- 待付款时出现 -->
          <view
            v-if="showPayBtn"
            class="btn btn-r"
            @tap="payNow(orderId,actualTotal)"
          >
            立即支付
          </view>
          <!-- 待发货时出现 -->
          <block v-if="orderType!==orderTypeConstant.SCORE && btnNum <= 3">
            <view
              v-if="showInvoiceBtn"
              class="btn"
              @tap="viewIinvoice(orderId, orderInvoiceId)"
            >
              查看发票
            </view>
            <view
              v-if="hideInvoiceBtn && actualTotal"
              class="btn"
              @tap="showInvoicePopup(orderId)"
            >
              申请开票
            </view>
          </block>
          <view
            v-if="showConsigneesBtn"
            class="btn btn-r"
            @tap="handleShowPop(2)"
          >
            确认收货
          </view>
          <view
            v-if="showComment"
            class="btn"
            @tap="wrtieCommnet"
          >
            评价
          </view>
          <!-- 已完成或已取消出现 -->
          <view
            v-if="showDeleteBtn && btnNum <= 3 && returnFunBtn"
            class="btn btn-r"
            @tap="handleShowPop(0)"
          >
            删除订单
          </view>
        </div>
      </view>
    </view>
    <view
      v-if="showMore"
      class="popup"
      :class="{ show: showMore }"
    >
      <view
        class="more-popup-mask"
        @tap="closePopup"
      />
      <view class="more-box">
        <view
          v-if="showRefundBtn && orderMold!==1"
          class="btn"
          @tap="toApplyRefund"
        >
          {{ orderType === orderTypeConstant.NORMAL ? '整单售后' : '申请售后' }}
        </view>
        <view
          v-if="showDeleteBtn && returnFunBtn"
          class="btn btn-r more-box-item"
          @tap="handleShowPop(0)"
        >
          删除订单
        </view>
        <block v-if="orderType!==orderTypeConstant.SCORE">
          <view
            v-if="showInvoiceBtn"
            class="btn"
            @tap="viewIinvoice(orderId, orderInvoiceId)"
          >
            查看发票
          </view>
          <view
            v-if="hideInvoiceBtn && actualTotal"
            class="btn"
            @tap="showInvoicePopup(orderId)"
          >
            申请开票
          </view>
        </block>
      </view>
    </view>
    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-cancel="popCancel"
      @handle-pop-confirm="popConfirm"
    />
    <invoiceEdit
      v-if="isShowInvoicePopup"
      :shop-id="shopId"
      :order-id="invoiceOrderId"
      @close-popup="closePopup"
      @get-data="loadOrderDetail"
    />

    <!-- 查看留言弹窗（虚拟商品） -->
    <view
      class="popup-hide"
      :hidden="!showViewMsg"
    >
      <view class="popup-box virtual-goods-msg-pop">
        <view class="con-tit">
          <view class="tit-text">
            查看留言
          </view>
          <view
            class="close"
            @tap="closeMsgPopup"
          />
        </view>
        <view class="msg-pop-con">
          <view class="msg-list">
            <view
              v-for="(item, index) in virtualRemark"
              :key="index"
              class="msg-item"
            >
              <view class="item-con weak">
                {{ item.name }}
              </view>
              <view class="item-con">
                {{ item.value }}
              </view>
            </view>
          </view>
          <view class="pop-foot">
            <view
              class="foot-btn"
              @tap="closeMsgPopup"
            >
              我知道了
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import number from '@/wxs/number'
import util from '@/utils/util'
import * as locTrans from '@/utils/locTrans.js'
import Qr from '@/utils/wxqrcode.js'
import { OrderStatus, RefundStatus, ProdType, PayType, PayEntry } from '@/utils/constant'
import invoiceEdit from '@/package-user/components/invoice-edit/index.vue'
import storeItem from '@/package-user/components/store-item/index.vue'
import uniCopy from '@/js_sdk/uni-copy'
import Pay from '@/utils/pay'
import moment from 'moment'
import statusBG from '@/static/images/status-bg.jpg'
import wBarcode from '@uni-ui/code-ui/components/w-barcode/index.vue'

const wxs = number()

// 各种状态常量
const orderStatusConstant = reactive(OrderStatus)
const refundStatusConstant = reactive(RefundStatus)
const orderTypeConstant = reactive(ProdType)

const stepsOptions = ref([
  {
    title: '定金(待支付)',
    desc: '￥0.00'
  },
  {
    title: '尾款(未支付)',
    desc: '￥0.00'
  }
])

const orderId = ref('')
/**
 * 生命周期函数--监听页面加载
 */
onLoad((options) => {
  if (options.orderId) {
    orderId.value = options.orderId
  }
  if (Number(options.deliveryType) === 2) {
    // 获取位置权限并请求自提订单详情
    // #ifdef APP-PLUS
    util.getUserAuth(getCurrentLocation)
    // #endif
    // #ifndef APP-PLUS
    getCurrentLocation()
    // #endif
  }
})

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  // 请求订单详情数据
  loadOrderDetail()
})

const codeFormat = computed(() => {
  return function (code) {
    return code.substring(0, 3) + ' ' + code.substring(3, 6) + ' ' + code.substring(6, 9)
  }
})

const showMore = ref(false)
const handleMore = () => {
  showMore.value = true
}

// 发票
const invoiceOrderId = ref(0)
const isShowInvoicePopup = ref(false)
// 发票信息弹窗
const showInvoicePopup = (invoiceOrderIdPar) => {
  invoiceOrderId.value = Number(invoiceOrderIdPar)
  isShowInvoicePopup.value = true
}

// 关闭弹窗
const closePopup = () => {
  isShowInvoicePopup.value = false
  showMore.value = false
}

const showGroupBtn = ref(false)
const showRefundBtn = ref(false)
const shopCancellBtn = ref(false)
const showPayBtn = ref(false)
const showInvoiceBtn = ref(false)
const hideInvoiceBtn = ref(false)
const showConsigneesBtn = ref(false)
const showComment = ref(false)
const showDeleteBtn = ref(false)
const initBtnStatus = () => {
  showGroupBtn.value = false
  showRefundBtn.value = false
  shopCancellBtn.value = false
  showPayBtn.value = false
  showInvoiceBtn.value = false
  hideInvoiceBtn.value = false
  showConsigneesBtn.value = false
  showComment.value = false
  showDeleteBtn.value = false
  showMore.value = false
}

// 查看发票
const viewIinvoice = (orderIdPar, orderInvoiceIdPar) => {
  uni.navigateTo({
    url: `/package-user/pages/invoice-detail/invoice-detail?orderId=${orderIdPar}&orderInvoiceId=${orderInvoiceIdPar}`
  })
}

// 拼团团队id
const groupTeamId = ref(0)
const orderItems = ref([])
const deliveryType = ref(1) // 配送类型 1:快递 2:自提 3：无需快递 4:同城配送
/**
 * 到拼团详情
 */
const toGroupDetail = () => {
  const spuId = orderItems.value[0].spuId
  uni.navigateTo({
    url: '/package-activities/pages/group-detail/group-detail?orderId=' +
      orderId.value + '&groupTeamId=' + groupTeamId.value + '&spuId=' +
      spuId + '&deliveryType=' + deliveryType.value
  })
}

/**
 * 跳转到发布评价
 */
const wrtieCommnet = () => {
  // 把商品项缓存起来
  const preCommentData = []
  orderItems.value.forEach(el => {
    if ((!el.refundStatus || el.refundStatus === RefundStatus.DISAGREE) && !el.isComm) {
      preCommentData.push({
        spuName: el.spuName,
        pic: el.pic,
        skuName: el.skuName,
        orderItemId: el.orderItemId,
        shopId: el.shopId,
        giveawayList: el.giveawayList
      })
    }
  })
  uni.setStorageSync('cloudOrderItemInfo', preCommentData)
  uni.navigateTo({
    url: '/package-user/pages/pord-comment/pord-comment'
  })
}

/**
 * 查看退款详情
 */
const toRefundDetail = (refundIdPar) => {
  uni.navigateTo({
    url: '/package-refund/pages/refund-detail/refund-detail?refundId=' + refundIdPar
  })
}

/**
 * 跳转到物流详情
 */
const toLogisticsDetail = () => {
  uni.navigateTo({
    url: '/pages/logistics-detail/logistics-detail?orderId=' + orderId.value
  })
}

const status = ref(0)
/**
 * 立即支付
 */
const payNow = (orderIdPar, actualTotalPar) => {
  const payStatus = status.value === orderStatusConstant.PENDING_FINAL_PAYMENT ? '&pay_status=9' : '' // 预售订单
  if (actualTotalPar) {
    uni.navigateTo({
      url: '/package-activities/pages/payment/payment?orderIds=' + orderIdPar + payStatus
    })
  } else {
    surePay(orderIdPar + '', 0) // 0-积分支付
  }
}

// dvyType: dvyType,
// 确认支付
const surePay = (orderIdsPar, payTypePar) => {
  const paymentData = {
    payType: 0,
    orderIds: orderIdsPar,
    isPurePoints: orderIdsPar,
    payEntry: PayEntry.ORDER
  }
  if (payTypePar === PayType.SCOREPAY) {
    uni.showModal({
      title: '提示',
      content: '确认进行支付吗？',
      success: (res) => {
        if (res.confirm) {
          Pay.toOrderPay(paymentData)
        } else if (res.cancel) {
          uni.showToast({
            title: '取消支付',
            icon: 'none',
            duration: 1500
          })
        }
      }
    })
  }
}

const showPop = ref(false)
/**
 * 订单操作按钮
 * @param {number} operTypePar 0:取消订单; 1删除订单; 2确认收货
 */
const orderOperation = (operTypePar) => {
  let url = ''
  let reqMethod = ''
  if (operTypePar === 0) {
    url = '/tmerclub_order/my_order/'
    reqMethod = 'DELETE'
  } else if (operTypePar === 1) {
    url = '/tmerclub_order/my_order/cancel/'
    reqMethod = 'PUT'
  } else if (operTypePar === 2) {
    url = '/tmerclub_order/my_order/receipt/'
    reqMethod = 'PUT'
  }
  url = url + orderId.value
  http.request({
    url,
    method: reqMethod
  }).then(() => {
    showPop.value = false
    uni.showToast({
      title: '操作成功',
      duration: 2000,
      mask: true,
      icon: 'none'
    })
    setTimeout(() => {
      if (operTypePar) {
        loadOrderDetail()
      } else {
        const pages = getCurrentPages()
        const prePage = pages[pages.length - 2]
        // 如果上一页是订单列表页，则返回上一页
        if (prePage?.route === 'package-user/pages/order/order') {
          uni.navigateBack(1)
        } else { // 否则跳转到订单列表页
          uni.redirectTo({
            url: '/package-user/pages/order/order?orderStatus=0'
          })
        }
      }
    }, 1000)
  })
}

/**
 * 跳转商品详情
 */
const toProdDetail = (spuIdPar) => {
  if (orderType.value === orderTypeConstant.SCORE) {
    uni.navigateTo({
      url: '/package-activities/pages/score-prod-detail/score-prod-detail?spuId=' + spuIdPar
    })
  } else {
    uni.navigateTo({
      url: '/pages/detail/detail?spuId=' + spuIdPar
    })
  }
}

const btnNum = ref(1)// 订单部分商品处于退款不能删除订单
const returnFunBtn = ref(true)
const shopId = ref(0)
const actualTotal = ref(0)
const orderAddr = ref({})
const remarks = ref('')
const createTime = ref('')
const productTotalAmount = ref(0)
const transfee = ref(0)
const freeTransfee = ref(0)
const reduceAmount = ref(0)
const orderType = ref(0)
const shopName = ref('')
const canRefund = ref(true)
const canAllRefund = ref(true)
const payType = ref(0)
const orderScore = ref(0)
const totalNum = ref(1)
const isComm = ref(0)
// 当前订单可退金额
const canRefundAmount = ref(0)
// 优惠明细
const platformCouponAmount = ref(0) // 平台优惠券优惠金额
const scoreAmount = ref(0) // 积分抵扣
const shopAmount = ref(0) // 店铺优惠总额(包括秒杀/团购优惠)
const shopCouponMoney = ref(0) // 店铺优惠券
const discountMoney = ref(0) // 促销满减
const shopComboAmount = ref(0) // 套餐优惠
const memberAmount = ref(0) // 会员折扣
const shopChangeFreeAmount = ref(0) // 商家改价
// 是否更新物流信息
const updateOrViewDeliveryInfo = ref(0)
const orderInvoiceId = ref(null)
const orderMold = ref(1) // 订单类型 1虚拟商品
const virtualRemark = ref([]) // 留言
const writeOffNum = ref(null) // 核销次数 -1.多次核销 0.无需核销 1.单次核销
const writeOffStart = ref(null)
const writeOffEnd = ref(null)
const virtualInfoList = ref([]) // 券码
const orderPreSaleInfoVO = ref(null) // 预售信息
const preSaleDeliveryTime = ref(null)
const balanceStartTime = ref(null)
const isExpired = ref(null) // 判断有无超过有效时间
// 是否展示评价按钮
let showCommentBtn = false
/**
 * 加载订单数据
 */
// eslint-disable-next-line max-lines-per-function
const loadOrderDetail = () => {
  btnNum.value = 1
  http.request({
    url: '/tmerclub_order/my_order/order_detail',
    method: 'GET',
    data: {
      orderId: orderId.value
    }
    // eslint-disable-next-line max-lines-per-function
  }).then((res) => {
    initBtnStatus()
    // 是否显示确认收货按钮
    let showConfirmReceipt = true
    let len = 0
    res.orderItems.forEach(orderItem => {
      if (orderItem.refundStatus === 1 && orderItem.refundStatus !== -1 && orderItem.refundStatus !== 5) {
        showConfirmReceipt = false
      }
      if (!orderItem.refundStatus || (orderItem.refundStatus === RefundStatus.PARTIAL_SUCCESS || orderItem.refundStatus === RefundStatus.DISAGREE)) {
        len = len + 1
      }
      // 订单部分商品处于退款不能删除订单
      if (orderItem.refundStatus === 1) {
        returnFunBtn.value = false
      }
    })
    showCommentBtn = len === res.orderItems.length
    actualTotal.value = res.actualTotal
    orderAddr.value = res.orderAddr
    remarks.value = res.remarks
    orderItems.value = res.orderItems
    createTime.value = res.createTime
    status.value = res.status
    productTotalAmount.value = res.total
    transfee.value = res.transfee
    orderType.value = res.orderType
    totalNum.value = res.totalNum
    shopName.value = res.shopName
    canRefund.value = res.canRefund
    canAllRefund.value = res.canAllRefund
    payType.value = res.payType
    deliveryType.value = res.deliveryType // 配送类型 1:快递 2:自提 3：无需快递
    orderScore.value = res.orderScore // 整单使用积分
    shopId.value = res.shopId
    groupTeamId.value = res.groupTeamId || ''
    isComm.value = res.orderItems[0].isComm
    canRefundAmount.value = res.canRefundAmount
    // 优惠明细
    reduceAmount.value = res.reduceAmount // 优惠总额
    platformCouponAmount.value = res.platformCouponAmount // 平台优惠券优惠金额
    freeTransfee.value = res.freeFreightAmount || res.platformFreeFreightAmount // 运费减免
    scoreAmount.value = res.scoreAmount // 积分抵扣
    shopAmount.value = res.shopAmount // 店铺优惠总额
    shopCouponMoney.value = res.shopCouponMoney // 店铺优惠券
    discountMoney.value = res.discountMoney // 促销满减
    shopComboAmount.value = res.shopComboAmount // 套餐优惠
    memberAmount.value = res.memberAmount // 会员折扣
    shopChangeFreeAmount.value = res.shopChangeFreeAmount // 商家改价
    updateOrViewDeliveryInfo.value = res.updateOrViewDeliveryInfo
    orderInvoiceId.value = res.orderInvoiceId // 发票id
    const finalRefundId = res.finalRefundId
    orderMold.value = res.orderMold // 虚拟商品订单
    if (res.orderMold === 1) {
      virtualRemark.value = res.orderItems[0].virtualRemark ? (JSON.parse(res.orderItems[0].virtualRemark) ? JSON.parse(res.orderItems[0].virtualRemark) : []) : [] // 虚拟商品的用户留言

      writeOffNum.value = res.writeOffNum // 核销次数 -1多次 0无需核销 1单次核销
      writeOffStart.value = res.writeOffStart // 核销有效期开始时间
      writeOffEnd.value = res.writeOffEnd // 核销有效期结束时间（仅有开始时间没有结束时间标识长期有效）
      virtualInfoList.value = res.virtualInfoList // 券码
      if (res.writeOffEnd) {
        const writeOffEndTime = new Date(res.writeOffEnd).getTime()
        const nowTime = new Date().getTime()
        if (nowTime > writeOffEndTime) {
          isExpired.value = true
        }
      }
    }

    // 预售
    orderPreSaleInfoVO.value = res.orderPreSaleInfoVO//  预售信息
    const orderPreSaleInfoVOPar = orderPreSaleInfoVO.value
    if (orderPreSaleInfoVOPar && (orderPreSaleInfoVOPar.preSaleType === 1 || orderPreSaleInfoVOPar.preSaleType === 0)) {
      preSaleDeliveryTime.value = moment(new Date(orderPreSaleInfoVOPar.preSaleDeliveryTime ? orderPreSaleInfoVOPar.preSaleDeliveryTime.replace(/-/g, '/') : null)).format('M[月]D[日]')
    }
    if (orderPreSaleInfoVOPar && orderPreSaleInfoVOPar.preSaleType === 1) {
      // 尾款开始开始
      const balanceStartTimePar = new Date(orderPreSaleInfoVOPar.balanceStartTime ? orderPreSaleInfoVOPar.balanceStartTime.replace(/-/g, '/') : null).getTime() // 结束时间（时间戳）
      // 尾款结束时间
      const balanceEndTime = new Date(orderPreSaleInfoVOPar.balanceEndTime ? orderPreSaleInfoVOPar.balanceEndTime.replace(/-/g, '/') : null).getTime()
      const nowTime = Date.now()// 现在时间（时间戳）

      const isbalanceStartTime = (balanceStartTimePar - nowTime) // 距离开始的毫秒数
      const isbalanceEndTime = (balanceEndTime - nowTime) // 距离结束的毫秒数

      if (isbalanceStartTime > 0) {
        balanceStartTime.value = moment(new Date(orderPreSaleInfoVOPar.balanceStartTime ? orderPreSaleInfoVOPar.balanceStartTime.replace(/-/g, '/') : null)).format('M[月]D[日] HH:mm:ss [开始支付尾款]')
      } else {
        balanceStartTime.value = moment(new Date(orderPreSaleInfoVOPar.balanceEndTime ? orderPreSaleInfoVOPar.balanceEndTime.replace(/-/g, '/') : null)).format('M[月]D[日] HH:mm:ss [尾款停止支付]')
      }

      const stepsOptionsPar = [
        { title: '定金(待支付)', desc: '￥' + (orderPreSaleInfoVOPar.depositAmount / 100).toFixed(2) },
        { title: '尾款(未支付)', desc: '￥' + (orderPreSaleInfoVOPar.balanceAmount / 100).toFixed(2) }
      ]

      switch (orderPreSaleInfoVOPar.payStatus) {
        case 1:
          stepsOptionsPar[0].title = '定金(已支付)'
          if (isbalanceStartTime > 0) {
            stepsOptionsPar[1].title = '尾款(未开始)'
          } else if (isbalanceStartTime <= 0 && isbalanceEndTime >= 0) {
            stepsOptionsPar[1].title = '尾款(待付款)'
          } else if (isbalanceEndTime < 0) {
            stepsOptionsPar[1].title = '尾款(超时未付款)'
          }
          break
        case 2:
          stepsOptionsPar[0].title = '定金(已支付)'
          stepsOptionsPar[1].title = '尾款(已支付)'
          break
        default:
          break
      }
      stepsOptions.value = stepsOptionsPar
    }
    const statusPar = status.value
    if (orderType.value === orderTypeConstant.GROUP && statusPar >= orderStatusConstant.PAYED && statusPar !== orderStatusConstant.CANCEL) {
      btnNum.value++
      showGroupBtn.value = true
    }
    if (statusPar > orderStatusConstant.UNPAY && statusPar !== orderStatusConstant.CANCEL && canAllRefund.value && orderType.value !== orderTypeConstant.SCORE) {
      btnNum.value++
      showRefundBtn.value = true
    }
    if (statusPar === orderStatusConstant.UNPAY) {
      btnNum.value++
      shopCancellBtn.value = true
    }
    if (statusPar === orderStatusConstant.UNPAY || (statusPar === orderStatusConstant.PENDING_FINAL_PAYMENT && stepsOptions.value[1].title === '尾款(待付款)')) {
      btnNum.value++
      showPayBtn.value = true
    }
    if (((orderInvoiceId.value && statusPar !== 6) || (orderInvoiceId.value && (statusPar === 6 && finalRefundId))) && orderType.value !== orderTypeConstant.SCORE) {
      btnNum.value++
      showInvoiceBtn.value = true
    }
    if (!orderInvoiceId.value && (statusPar !== 6) && orderType.value !== orderTypeConstant.SCORE) {
      btnNum.value++
      hideInvoiceBtn.value = true
    }
    if (statusPar === orderStatusConstant.CONSIGNMENT && showConfirmReceipt) {
      btnNum.value++
      showConsigneesBtn.value = true
    }
    if (statusPar === orderStatusConstant.SUCCESS && !isComm && showCommentBtn && orderType.value !== orderTypeConstant.SCORE) {
      btnNum.value++
      showComment.value = true
    }
    if (statusPar === orderStatusConstant.CANCEL || statusPar === orderStatusConstant.SUCCESS) {
      btnNum.value++
      showDeleteBtn.value = true
    }
    if (orderMold.value === 1) {
      // 虚拟商品留言处理
      handlevirtualRemark()
      // 虚拟商品-待使用的券总数
      handleUnusedVirtualCode(res.virtualInfoList)
    }
  })
}

const unusedCount = ref(0) // 待使用的核销券
// 虚拟商品-待使用的券总数
const handleUnusedVirtualCode = (list) => {
  if (list && list.length) {
    let unusedCountPar = 0
    list.forEach(el => {
      if (el.isWriteOff === 0) {
        unusedCountPar = unusedCountPar + 1
      }
    })
    unusedCount.value = unusedCountPar
  }
}

/**
 * 获取当前地理位置
 */
const getCurrentLocation = () => {
  uni.showLoading()
  uni.getLocation({
    type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回国测局坐标，可用于 uni.openLocation 的坐标，app平台高德SDK仅支持返回gcj02
    altitude: true,
    isHighAccuracy: true,
    highAccuracyExpireTime: 3500,
    success: (res) => {
      uni.hideLoading()
      if (res) {
        confirmLocation(res)
      }
    },
    fail: () => {
      uni.showToast({
        title: '获取定位失败！',
        icon: 'none',
        duration: 1500
      })
      lat = ''
      lng = ''
      loadStationDetail()
    },
    complete: () => {
      uni.hideLoading()
    }
  })
}

let lat = null
let lng = null
/**
 * 转换经纬度
 * @param locationRes 当前定位信息
 */
const confirmLocation = (locationRes) => {
  let locationObj
  // #ifdef APP-PLUS || MP-WEIXIN
  locationObj = locTrans.gcj02tobd09(locTrans.wgs84togcj02(locationRes))
  // #endif

  // #ifdef H5
  locationObj = locTrans.gcj02tobd09(locationRes)
  // #endif

  lat = locationObj.latitude
  lng = locationObj.longitude
  loadStationDetail()
}

// 自提信息
const stationInfo = ref(null)
const stationUserName = ref('')
const stationUserMobile = ref('')
const stationCode = ref('')

const barOpations = reactive({
  height: 44,
  width: 250,
  code: '', // 码值
  orient: 'vertical'
})

/**
 * 加载订单详情自提信息
 */
const loadStationDetail = () => {
  http.request({
    url: '/tmerclub_order/my_station_order/station_detail',
    method: 'GET',
    data: {
      orderId: orderId.value,
      lat,
      lng
    }
  }).then((res) => {
    stationCode.value = res.stationCode // 提货码
    stationUserMobile.value = res.stationUserMobile // 自提人的手机
    stationUserName.value = res.stationUserName // 自提人的名字
    const timeInfo = {}
    let distance
    if (!res.distance) {
      distance = '0 km'
    } else {
      distance = parseFloat(res.distance) >= 1000 ? (parseFloat(res.distance) / 1000).toFixed(2) + 'km' : parseFloat(res.distance) + 'm'
    }
    const stationTimeInfo = JSON.parse(res.timeInfo)
    const start = moment(new Date(stationTimeInfo.shopTime[0])).format('HH:mm')
    const end = moment(new Date(stationTimeInfo.shopTime[1])).format('HH:mm')
    timeInfo.startTime = start
    timeInfo.endTime = end
    const operationState = getOperationState(stationTimeInfo.shopTime[0], stationTimeInfo.shopTime[1])
    stationInfo.value = {
      ...res,
      stationName: res.stationName,
      mobile: res.stationPhone,
      operationState,
      timeInfo,
      distanceCont: distance,
      stationAddress: res.stationAddress,
      imgUrl: res.stationImgUrl
    }
    if (stationCode.value) {
      barOpations.code = stationCode.value
      getQrcode(stationCode.value)
    }
  })
}

// 获取营业状态
const getOperationState = (startTime, endTime) => {
  const timeS = new Date(startTime)
  const timeE = new Date(endTime)
  const timeSH = timeS.getHours()
  const timeSM = timeS.getMinutes()
  const timeEH = timeE.getHours()
  const timeEM = timeE.getMinutes()
  const nowHours = new Date().getHours()
  const nowMinutes = new Date().getMinutes()
  // 营业状态
  let operationState = 0
  if (nowHours >= timeSH && nowHours <= timeEH) {
    operationState = 1
    if (nowHours === timeSH && nowMinutes < timeSM) {
      operationState = 0
    }
    if (nowHours === timeEH && nowMinutes > timeEM) {
      operationState = 0
    }
  }
  return operationState
}

// 二维码相关
const stationQrCode = ref('')
/**
 * 生成二维码
 */
const getQrcode = (stationCode) => {
  stationQrCode.value = Qr.createQrCodeImg(stationCode)
}

// 虚拟商品留言是否超长
const isExtraLong = ref(true)
const virtualRemarkList = ref([]) // 整理后的留言列表
// 虚拟商品-留言列表处理
const handlevirtualRemark = () => {
  virtualRemark.value.push({})
  if (virtualRemark.value && virtualRemark.value.length) {
    // 过滤掉没有填写的留言
    virtualRemark.value = virtualRemark.value.filter(el => el.value)
    const virtualRemarkListPar = []
    let virtualRemarks
    // 如果留言总数大于3条，先展示前一条（完整留言在弹窗中展示）
    if (virtualRemark.value.length > 3) {
      const list = JSON.parse(JSON.stringify(virtualRemark.value))
      virtualRemarks = list.splice(0, 1)
      isExtraLong.value = true
    } else {
      virtualRemarks = virtualRemark.value
      isExtraLong.value = false
    }
    // 全部留言拼接
    virtualRemarks.forEach((el) => {
      virtualRemarkListPar.push([el.name, el.value])
    })
    virtualRemarkList.value = virtualRemarkListPar
  }
}

// 查看全部留言弹窗
const showViewMsg = ref(false)
// 查看用户留言弹窗
const showViewMsgPopup = () => {
  if (isExtraLong.value) {
    showViewMsg.value = true
  }
}

const closeMsgPopup = () => {
  showViewMsg.value = false
}

/**
 * 联系客服
 */
const toContact = () => {
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url: '/package-user/pages/my-chat/my-chat?shopid=' + shopId.value + '&orderNumber=' + orderId.value
    })
  })
}

/**
 * 复制订单号
 */
const copy = (item) => {
  uniCopy({
    content: item,
    success: () => {
      uni.showToast({
        title: '复制成功~',
        icon: 'none'
      })
    },
    error: (e) => {
      uni.showToast({
        title: e,
        icon: 'none',
        duration: 3000
      })
    }
  })
}

/**
 * 跳转店铺首页
 */
const toShopIndex = () => {
  if (orderType.value === orderTypeConstant.SCORE) {
    uni.navigateTo({
      url: '/package-activities/pages/integral-mall/integral-mall'
    })
    return
  }
  getShopInfo(shopId.value)
}

/**
* 获取店铺信息
*/
const getShopInfo = (shopIdPar) => {
  http.request({
    url: '/tmerclub_admin/ua/shop_detail/head_info',
    method: 'GET',
    data: {
      shopId: shopIdPar,
      imgType: 0 // 图片类型：0.app(h5) 1.pc
    }
  }).then((res) => {
    uni.setStorageSync('cloudShopInfo', res)
    uni.redirectTo({
      url: res.renovationId ? '/package-shop/shop-page/feature-index/feature-index?shopId=' + res.shopId +
        '&renovationId=' + res.renovationId : '/package-shop/shop-page/shop-index/shop-index?shopId=' + shopIdPar
    })
  })
}

/**
 * 申请退款按钮
 * @param {Object} singleRefundItem 退款的订单项(单个), null则为整单退款
 */
const toApplyRefund = util.debounce((singleRefundItem) => {
  // canRefundTransfee 是否可退运费
  const refundInfo = {}
  refundInfo.orderId = orderId.value
  refundInfo.transfee = transfee.value
  refundInfo.freeTransfee = freeTransfee.value
  refundInfo.status = status.value
  refundInfo.canRefundAmount = canRefundAmount.value
  refundInfo.mobile = orderAddr.value ? orderAddr.value.mobile : ''
  refundInfo.orderMold = orderMold.value || 0
  refundInfo.platformCouponAmount = platformCouponAmount.value
  refundInfo.memberAmount = memberAmount.value

  // 整单退款
  if (!singleRefundItem.orderItemId) {
    refundInfo.actualTotal = actualTotal.value
    refundInfo.orderItems = orderItems.value
    refundInfo.refundType = 1
    refundInfo.canRefundTransfee = status.value === OrderStatus.PAYED ? !freeTransfee.value : false
    refundInfo.orderScore = orderScore.value
  } else {
    // 单件退
    refundInfo.refundType = 2
    refundInfo.actualTotal = singleRefundItem.actualTotal
    const orderItemsPar = []
    orderItemsPar.push(singleRefundItem)
    refundInfo.orderItems = JSON.parse(JSON.stringify(orderItemsPar))
    refundInfo.orderScore = singleRefundItem.useScore
    // 虚拟商品
    if (orderMold.value === 1) {
      // 1.无需核销：允许用户选择退款数量（writeOffNum 0无需核销 -1多次核销 1单次核销）
      refundInfo.needWriteOffs = writeOffNum.value !== 0
      // 2.需要核销：展示最大可退款件数，不允许选择（最大可退款件数 = 待使用的核销券数）
      refundInfo.maxRefundPieces = unusedCount.value
    }
    // 订单状态为 PAYED(待发货)，且运费未经减免(freeTransfee为0)，且该退款项为最后一项或唯一一项; 则可退运费
    if (status.value === OrderStatus.PAYED) {
      if (orderItemsPar.length > 1) {
        // 待发货-商品项长度大于1
        let hadApplyCounts = 0
        // 遍历数组
        orderItemsPar.forEach((orderItem) => {
          if (orderItem.finalRefundId && orderItem.refundStatus && orderItem.refundStatus !== RefundStatus.DISAGREE) {
            hadApplyCounts++
          }
        })
        // 该项为最后一个商品项则可退款
        refundInfo.canRefundTransfee = (orderItems.value.length - hadApplyCounts === 1) && !freeTransfee.value
        refundInfo.isLastProd = orderItems.value.length - hadApplyCounts === 1
      } else {
        // 待发货-只有一个商品项 若无平台减免则退运费
        refundInfo.canRefundTransfee = !freeTransfee.value
      }
    } else {
      // 单件退-已发货  不退运费
      refundInfo.canRefundTransfee = false
    }
  }
  uni.setStorageSync('cloudRefundInfo', refundInfo)
  uni.navigateTo({
    url: '/package-refund/pages/apply-refund/apply-refund'
  })
}, 600)

/**
 * 弹窗取消事件
 */
const popCancel = () => {
  showPop.value = false
}

let operType = null
/**
 * 弹窗确认事件 - 操作订单
 */
const popConfirm = () => {
  orderOperation(operType)
}

const popContent = ref({})
/**
 * 显示订单操作弹窗
 * @param {number} operTypePar 0:删除订单; 1取消订单; 2确认收货
 */
const handleShowPop = async (operTypePar) => {
  operType = operTypePar
  // 设置弹窗内容文本
  if (operType === 0) {
    popContent.value.title = '是否删除该订单'
    popContent.value.content = '订单删除后将无法恢复，请谨慎操作'
  } else if (operType === 1) {
    popContent.value.title = '是否取消该订单'
    popContent.value.content = '订单取消后将无法恢复，请谨慎操作'
  } else {
    popContent.value.title = '我已收到货？'
    popContent.value.content = '确认收货后将改变订单状态'
    // 确认收货前检查
    const wxConfirmFlag = await util.orderReceiptCheck(orderId.value, loadOrderDetail)
    if (wxConfirmFlag) return
  }
  showPop.value = true
}

/**
 * 查看券码（虚拟商品）
 */
const toViewVoucherCodePage = () => {
  if (isExpired.value) {
    uni.showToast({
      title: '券码已过期',
      icon: 'none'
    })
    return
  }
  if (!unusedCount.value) {
    uni.showToast({
      title: '券码已使用',
      icon: 'none'
    })
    return
  }
  if (orderItems.value[0].refundStatus === 2 || orderItems.value[0].refundStatus === 3) {
    uni.showToast({
      title: '订单已退款',
      icon: 'none'
    })
    return
  }
  const voucherCodeInfo = {
    // 订单编号
    orderNumber: orderId.value,
    // 商品信息
    orderItems: orderItems.value,
    // 实付金额
    actualTotal: actualTotal.value,
    // 虚拟商品-券码列表
    virtualInfoList: virtualInfoList.value,
    // 虚拟商品-有效期
    writeOffStart: writeOffStart.value,
    writeOffEnd: writeOffEnd.value
  }
  uni.setStorageSync('cloudVoucherCodeInfo', voucherCodeInfo)
  uni.navigateTo({
    url: '/package-user/pages/voucher-code/voucher-code'
  })
}

const toViewWriteOffsRecords = () => {
  uni.navigateTo({
    // writeOffMultipleCount: 核销次数
    url: '/package-user/pages/write-offs-records/write-offs-records?orderId=' +
      orderId.value + '&writeOffMultipleCount=' + virtualInfoList.value[0].writeOffMultipleCount
  })
}
</script>

<style lang="scss" scoped>
@use "order-detail";
</style>
<style lang="scss" scoped>
@use "../../../popup";
</style>
