<template>
  <div class="con-box">
    <div class="box-tit" v-if="showApplyRefund">{{$t('applyReturn.applyAfterSales')}}</div>
    <div class="box-tit" v-if="!showApplyRefund">{{$t('applyReturn.viewAfterSales')}}</div>
    <!-- 提交售后申请 -->
    <div :class="['box-content','apply-return', 'apply-box',this.$store.state.locale == 'en'?'en':'']" v-if="showApplyRefund">
      <!-- 退款商品 -->
      <div class="item apply-item apply-prod">
        <div class="tit">{{$t('applyReturn.refundedProducts')}}：</div>
        <div class="goods-box">
          <div class="goods-info">
            <!-- 普通商品 -->
            <div
              v-for="(refundItem, index) in orderItem"
              :key="index"
              class="goods-item">
              <div class="goods-con">
                <div class="goods-img">
                  <img v-if="refundItem.pic" :src="refundItem.pic" alt @error="handlePicError"/>
                  <img v-else src="~/assets/img/def.png" alt />
                </div>
                <div class="goods-text">
                  <div class="name">{{ refundItem.prodName }}</div>
                  <div class="sku">
                    {{ refundItem.skuName }}
                    <span class="num">×{{ refundItem.prodCount }}</span>
                  </div>
                  <!-- <div class="price">￥{{ toPrice(refundItem.price) }}</div> -->
                </div>
              </div>
              <!-- 赠品：整单退款时展示赠品名称和数量 -->
              <div
                v-if="orderRefundParam.refundType == 1 && refundItem.giveawayList && refundItem.giveawayList.length"
                class="gift-name-list">
                <div v-for="item in refundItem.giveawayList" :key="item.orderItemId" class="gift-item" @click="toProdDetail(item.prodId)">
                  <span class="name">{{ '【' + $t('prodDetail.gift') + '】' + item.prodName }}</span>
                  <span class="num">× {{ item.prodCount }}</span>
                </div>
              </div>
              <!-- / 赠品 -->
            </div>
          </div>
          <!-- 赠品：单个退款时展示赠品具体信息 -->
          <div
            v-if="orderRefundParam.refundType == 2 &&
                  giveawayList &&
                  giveawayList.length"
            class="goods-info">
            <div v-for="(prod,index) in giveawayList" :key="prod.orderItemId" class="goods-item giveaways">
              <div class="goods-img">
                <img v-if="prod.pic" :src="prod.pic.indexOf('http') === -1 ? picDomain + prod.pic : prod.pic" @click="toProdDetail(prod.prodId)" />
                <img v-else src="~/assets/img/def.png" alt />
              </div>
              <div class="goods-text">
                <div class="name" @click="toProdDetail(prod.prodId)"> {{ prod.prodName }}</div>
                <div class="sku">
                  <span class="gifts-icon">{{$t('prodDetail.gift')}}</span>
                  <span class="sku-name">{{ prod.skuName }}</span>
                  <span class="num">× {{ prod.prodCount }}</span>
                  <span
                    v-if="orderRefundParam.refundType != 1 && status != 2"
                    class="del-btn"
                    @click="removeGiveaways(prod.orderItemId, index)"
                  >
                    {{$t('prodDetail.removeGiftBtn')}}
                  </span>
                </div>
                <div class="price">￥{{ prod.giveawayAmount }}</div>
              </div>
            </div>
          </div>
          <!-- / 赠品 -->
        </div>
      </div>

      <div class="item">
        <div class="tit">{{$t('applyReturn.serviceType')}}：</div>
        <div
          :class="[
            'apply-item unchecked',
            orderRefundParam.applyType == 1 || status == 2 ? 'active' : '',
          ]"
          @click="returnType(1)"
        >
          {{$t('applyReturn.refundsOnly')}}
        </div>
        <div
          :class="[
            'apply-item unchecked',
            orderRefundParam.applyType == 2 ? 'active' : '',
          ]"
          @click="returnType(2)"
          v-if="status != 2 && orderMold !== 1"
        >
          {{$t('applyReturn.returnsAndRefunds')}}
        </div>
      </div>
      <div class="item" v-if="status != 2">
        <div class="tit">{{$t('applyReturn.cargoStatus')}}：</div>
        <div
          v-if="orderRefundParam.applyType == 1 && !needWriteOffs"
          :class="[
            'apply-item unchecked',
            orderRefundParam.isReceiver == 0 ? 'active' : '',
          ]"
          @click="goodsStatus(0)"
        >
          {{$t('applyReturn.noGoodsReceived')}}
        </div>
        <!-- v-if="orderMold !== 1 || (orderMold === 1 && !needWriteOffs)" -->
        <div
          :class="[
            'apply-item unchecked',
            orderRefundParam.isReceiver == 1 ? 'active' : '',
          ]"
          @click="goodsStatus(1)"
        >
          {{$t('applyReturn.receivedGoods')}}
        </div>
      </div>
      <div :class="['item', showSelectTips ? 'error' : '']">
        <div class="tit"><span class="asterisk">*</span>{{$t('applyReturn.refundReason')}}：</div>
        <div class="retur-reason">
          <div class="reason-tit" @click="selectReason">
            {{
              orderRefundParam.buyerReasonStr
                ? orderRefundParam.buyerReasonStr
                : $t('applyReturn.select')
            }}
          </div>
          <div
            class="reason-select"
            v-if="showReasonOptions && orderRefundParam.isReceiver == 0"
          >
            <!-- 未发货或未收到货退款原因 -->
            <div
              class="s-item"
              v-for="(reason, index) in refundPriReasonArray"
              :key="index"
              :data-reason="reason"
              :data-idx="index"
              @click="returnReason($event)"
            >
              {{ reason }}
            </div>
          </div>
          <div
            class="reason-select"
            v-if="showReasonOptions && orderRefundParam.isReceiver == 1"
          >
            <!-- 已发货退款原因 -->
            <div
              class="s-item"
              v-for="(reason, index) in refundProdReasonArray"
              :key="index"
              :data-reason="reason"
              :data-idx="index"
              @click="returnReason($event)"
            >
              {{ reason }}
            </div>
          </div>
        </div>
        <div class="error-text" v-if="showSelectTips">{{$t('applyReturn.pleaseSelectReason')}}</div>
      </div>
      <!-- 退货数量(无需核销的虚拟商品允许选择数量) -->
      <div
        class="item"
        v-if="
          (orderRefundParam.applyType == 2 &&
          orderRefundParam.refundType == 2 &&
          totalRefundScore == 0) ||
          orderMold == 1
        "
      >
        <div class="tit">{{$t('applyReturn.refundQuantity')}}：</div>
        <div v-if="orderMold == 1 && needWriteOffs && maxRefundPieces" class="counter-box">
          <div class="max-refund-pieces">{{maxRefundPieces}} 件</div>
        </div>
        <div v-else class="counter-box">
          <span
            class="reduce"
            onselectstart="return false"
            @click="changePordNum(-1)"
            >-</span
          >
          <input
            type="text"
            class="prod-num-int"
            v-model="goodsNum"
            readonly="true"
          />
          <span
            class="increase"
            onselectstart="return false"
            @click="changePordNum(+1)"
            >+</span
          >
        </div>
      </div>
      <!-- 退款金额 -->
      <div :class="['item', showAmountTips ? 'error' : '']">
        <div class="tit"><span class="asterisk">*</span>{{$t('applyReturn.refundAmount')}}：</div>
<!-- 标志11111 -->

        <a
          class="unalterable"
          v-if="
            orderItem.platformShareReduce > 0 ||
            totalRefundScore > 0 ||
            orderRefundParam.refundType == 1 &&
            orderMold !== 1
          "
          :title="$t('applyReturn.refundAmountModified')"
        >
          <span v-if="actualTotal && actualTotal > 0">￥{{ actualTotal }}</span>
          <span v-if="actualTotal > 0 && totalRefundScore > 0">+</span>
          <span v-if="totalRefundScore && totalRefundScore > 0">{{
            totalRefundScore + $t('applyReturn.points')
          }}</span>
        </a>
        <div class="return-price" v-else>
          <span class="prefix">￥</span>
          <input
            type="text"
            class="text"
            v-model.number="actualTotal"
            maxlength="20"
            :placeholder="$t('applyReturn.pleaseEnterAmount')"
            @blur="resetActualTotal"
          />
          <span class="return-score" v-if="totalRefundScore"
            >+ {{ totalRefundScore }} {{$t('applyReturn.points')}}</span
          >
        </div>
        <div class="price-des">
          {{$t('applyReturn.maximumRefundable')}}
          <!-- 整单退款包含运费 -->
          <span v-if="refundAmount && refundAmount > 0"
            >￥{{ refundType === 1 ? actualTotal : refundAmount }}</span
          >
          <span v-if="refundAmount > 0 && totalRefundScore > 0">+</span>
          <span v-if="totalRefundScore && totalRefundScore > 0">{{
            totalRefundScore + $t('applyReturn.points')
          }}</span>
          <span v-if="showTransfee && transfee > 0">
            <el-popover
              placement="top-start"
              title=""
              width="200"
              trigger="hover"
              :content="$t('applyReturn.refundBeforeShippingTips')">
              <i class="el-icon-warning" slot="reference"></i>
            </el-popover>
          </span>
        </div>
        <div class="error-text" v-if="showAmountTips">{{$t('applyReturn.correctRefundAmount')}}</div>
      </div>
      <div :class="['item', showMobileTips ? 'error' : '']">
        <div class="tit"><span class="asterisk">*</span>{{$t('applyReturn.mobileNumber')}}：</div>
        <div class="fillin-mobilenumber">
          <input
            type="text"
            class="text mobilenum"
            maxlength="11"
            :placeholder="$t('applyReturn.mobileNumberTips')"
            @blur="resetMobileNumber"
            v-model="orderRefundParam.buyerMobile"
          />
        </div>
        <div class="error-text" v-if="showMobileTips">{{$t('applyReturn.correctPhoneNumber')}}</div>
      </div>
      <div :class="['item', showBuyerDescErrTips ? 'error' : '']">
        <div class="tit"><span class="asterisk">*</span>{{$t('applyReturn.refundInstructions')}}：</div>
        <textarea
          class="shop-description"
          :placeholder="$t('applyReturn.refundInstructionsTips')"
          v-model="orderRefundParam.buyerDesc"
          maxlength="200"
          @blur="checkBuyerDesc"
        ></textarea>
        <div v-if="showBuyerDescErrTips" class="error-text">{{$t('applyReturn.refundInstructionsTips')}}</div>
      </div>
      <div class="item">
        <div class="tit">{{$t('applyReturn.refundVoucher')}}：</div>
        <div>
          <mul-pic-upload v-model="orderRefundParam.photoFiles" :limit="5" />
          <div class="img-des">（ {{$t('applyReturn.uploadFiveVouchers')}} ）</div>
        </div>
      </div>
      <div class="item">
        <div class="tit">&nbsp;</div>
        <a href="javascript:void(0);" class="btn" @click="applyRefund"
          >{{$t('applyReturn.SubmitRequest')}}</a
        >
      </div>
    </div>
    <!-- /提交售后申请 -->

    <!-- 等待商家处理&&填写运单号 -->
    <div class="box-content apply-return applied-box" v-if="!showApplyRefund">
      <!-- 等待商家处理 -->
      <div class="return-wait" v-if="WaitProcessing">
        <div class="return-state">
          <div class="state">{{$t('applyReturn.applicationTips1')}}</div>
          <!-- <div class="rest-time">剩余时间：<span class="time">23时59分</span></div> -->
        </div>
        <div class="return-tip">
          <div class="tip-item" v-if="orderRefundParam.applyType !== 1">
            {{$t('applyReturn.applicationTips2')}}
          </div>
          <div class="tip-item">
            {{$t('applyReturn.applicationTips3')}}
          </div>
          <div class="tip-item" v-if="orderRefundParam.applyType !== 1">
            {{$t('applyReturn.applicationTips4')}}
          </div>
        </div>
        <div class="return-btn">
          <a
            href="javascript:void(0);"
            class="btn-r"
            @click="cancelApply"
            v-if="returnDetail.isCancel"
            >{{$t('applyReturn.applicationTips5')}}</a
          >
          <!--
            修改退款金额：
            1、仅退款(applyTyp:1)：买家申请(returnMoneySts:1)状态下可以修改
            2、退货退款(applyTyp:2)：买家申请(returnMoneySts:1) ||
                                    卖家处理(returnMoneySts:2) ||
                                    买家发货(returnMoneySts:3)
                                    状态下可以修改
            3、整单退款(refundType:1)：不可修改
            4、isUsedPlatformReduce 是否使用了平台优惠 （是 则不可修改）
          -->
          <a
            v-if="returnDetail.refundType !== 1 &&
                  ((returnDetail.applyType == 1 &&
                  returnDetail.returnMoneySts == 1) ||
                  (returnDetail.applyType == 2 &&
                  (returnDetail.returnMoneySts == 1 ||
                  returnDetail.returnMoneySts == 2 ||
                  returnDetail.returnMoneySts == 3)))  &&
                  !isUsedPlatformReduce"
            href="javascript:void(0);"
            class="btn-r" @click="modifyRefundAmount">{{$t('applyReturn.modifyRefundAmount')}}</a>
        </div>
      </div>

      <!-- 填写运单号 -->
      <div class="return-wait" v-if="fillInLogistics">
        <div class="return-state">
          <div class="state" v-if="returnDetail.returnMoneySts == 2">
            {{$t('applyReturn.applicationTips6')}}
          </div>
          <div class="state" v-if="returnDetail.returnMoneySts == 3">
            {{$t('applyReturn.applicationTips7')}}
          </div>

          <!-- <div class="rest-time">剩余时间：<span class="time">23时59分</span></div> -->
        </div>
        <div class="return-tip">
          <div class="tip-item">
            {{$t('applyReturn.applicationTips8')}}
          </div>
          <div class="tip-item">
            {{$t('applyReturn.applicationTips9')}}
          </div>
        </div>
        <div class="shop-info">
          <div class="shop-name">
            {{$t('applyReturn.consignee')}}：
            <span class="name">{{
              returnDetail.refundDelivery.receiverName
            }}</span>
            <span class="phone">{{
              returnDetail.refundDelivery.receiverMobile
            }}</span>
          </div>
          <div class="shop-address">
            {{ returnDetail.refundDelivery.receiverAddr }}
          </div>
          <div class="shop-address">
            {{ returnDetail.refundDelivery.senderRemarks }}
          </div>
        </div>
        <div class="return-btn" v-if="returnDetail.returnMoneySts == 2">
          <!-- 填写运单号：
          <input type="text"
                  v-model="logisticsNumber"
          class="return-number">-->
          <a href="javascript:void(0);" class="btn-r" @click="writeLogisticsMsg"
            >{{$t('applyReturn.fillLogisticsInformation')}}</a
          >
        </div>
        <div class="return-btn" v-if="returnDetail.returnMoneySts == 3">
          <a href="javascript:void(0);" class="btn-r" @click="writeLogisticsMsg"
            >{{$t('applyReturn.modifyLogisticsInformation')}}</a
          >
        </div>
      </div>

      <!-- 已同意但未发放退款 (仅退款)-->
      <div class="return-wait" v-if="returnDetail.returnMoneySts == 2 && returnDetail.applyType == 1">
        <div class="return-state">
          <div class="state">
            {{$t('applyReturn.applicationTips6-1')}}
          </div>
        </div>
        <div class="return-tip">
          <div class="tip-item">
            {{$t('applyReturn.applicationTips6-1-1')}}
          </div>
        </div>
      </div>

      <!-- 退款详情 -->
      <div class="return-detail">
        <div class="detail-tit">{{$t('applyReturn.refundDetails')}}</div>
        <div class="item prod-con-box">
          <div class="tit">{{$t('applyReturn.refundedProducts')}}：</div>
          <div>
            <div v-for="(refundProd, index) in prodList"
                 :key="index"
                 class="prod-item"
            >
              <!-- 普通商品详情 -->
              <div class="goods-info"
                  :class="{'pointer': refundProd.giveawayOrderItemId}"
                  @click="toProdDetail(refundProd.prodId)">
                <div class="goods-img">
                  <img v-if="refundProd.pic" :src="refundProd.pic.indexOf('http') == -1 ? picDomain + refundProd.pic : refundProd.pic" alt  @error="handlePicError"/>
                  <img v-else src="~/assets/img/def.png" alt />
                </div>
                <div class="goods-text">
                  <div class="name">{{ refundProd.prodName }}</div>
                  <div class="sku">
                    <span v-if="refundProd.giveawayOrderItemId" class="gift-icon">{{$t('prodDetail.gift')}}</span>
                    <span>{{ refundProd.skuName }}</span>
                  </div>
                  <div class="price-con">
                    <span v-if="refundProd.giveawayOrderItemId" class="pri">￥{{ toPrice(refundProd.giveawayAmount) }}</span>
                    <span v-if="!refundProd.giveawayOrderItemId" class="pri">￥{{ toPrice(refundProd.price) }}</span>&nbsp;&nbsp;
                    <span>×{{ returnDetail.refundType === 1 ? refundProd.prodCount : returnDetail.goodsNum }}</span>
                  </div>
                </div>
              </div>
              <!-- 赠品 -->
              <div v-if="returnDetail.orderItems.length > 1 &&
                         refundProd.giveawayList &&
                         refundProd.giveawayList.length"
                   class="gift-prod">
                <div
                  v-for="giftItem in refundProd.giveawayList"
                  :key="giftItem.orderItemId"
                  class="gift-item"
                  @click="toProdDetail(giftItem.prodId)"
                >
                  <span class="name">【{{$t('prodDetail.gift')}}】{{ giftItem.prodName }}</span>
                  <span class="num">×{{ giftItem.prodCount }}</span>
                </div>
              </div>
              <!-- / 赠品 -->
            </div>
          </div>
        </div>
        <div class="detail-con">
          <div class="det-box">
            <div class="item">
              <div class="tit">{{$t('applyReturn.merchantName')}}：</div>
              <div class="return-text">{{ returnDetail.shopName }}</div>
            </div>
            <div class="item">
              <div class="tit">{{$t('applyReturn.cargoStatus')}}：</div>
              <div v-if="isReceiverOfCach" class="return-text">
                {{ [$t('applyReturn.noGoodsReceived'), $t('applyReturn.receivedGoods')][isReceiverOfCach?isReceiverOfCach:0] }}
              </div>
              <div v-else class="return-text">
                {{ returnDetail.isReceiver? $t('applyReturn.receivedGoods') : $t('applyReturn.noGoodsReceived') }}
              </div>
            </div>
            <div class="item">
              <div class="tit">{{$t('applyReturn.orderNumber')}}：</div>
              <div class="return-text">{{ returnDetail.orderNumber }}</div>
            </div>
            <div class="item">
              <div class="tit">{{$t('applyReturn.refundAmount')}}：</div>
              <!-- <div class="return-text">￥{{toPrice(returnDetail.refundAmount)}}</div> -->
              <div class="return-text">
                <span v-if="returnDetail.orderAmount"
                  >￥{{ toPrice(returnDetail.refundAmount) }}</span
                >
                <span
                  v-if="returnDetail.refundScore && returnDetail.orderAmount"
                  >+</span
                >
                <span v-if="returnDetail.refundScore"
                  >{{ returnDetail.refundScore }} {{$t('applyReturn.points')}}</span
                >
              </div>
            </div>
            <!-- <div class="item">
              <div class="tit">商品单价：</div>
              <div class="return-text">￥{{(returnDetail.orderItems[0].price).toFixed(2)}}</div>
            </div>
            <div class="item">
              <div class="tit">商品数量：</div>
              <div class="return-text">{{returnDetail.orderItems[0].prodCount}}件</div>
            </div>-->
            <div class="item">
              <div class="tit">{{$t('applyReturn.applicationNumber')}}：</div>
              <div class="return-text">{{ returnDetail.goodsNum }}{{$t('items')}}</div>
            </div>
            <div class="item error">
              <div class="tit">{{$t('applyReturn.refundReason')}}：</div>
              <div class="return-text">
                {{ refundReasonArray[returnDetail.buyerReason] }}
              </div>
            </div>
          </div>
          <div class="det-box">
            <div class="item">
              <div class="tit">{{$t('applyReturn.refundNumber')}}：</div>
              <div class="return-text">{{ refundSn }}</div>
            </div>
            <div class="item">
              <div class="tit">{{$t('applyReturn.refundType')}}：</div>
              <div class="return-text">
                {{ ['', $t('applyReturn.refundsOnly'), $t('applyReturn.returnsAndRefunds')][returnDetail.applyType] }}
              </div>
            </div>
            <div class="item error">
              <div class="tit">{{$t('applyReturn.transactionTime')}}：</div>
              <div class="return-text">{{ returnDetail.orderPayTime }}</div>
            </div>
            <div class="item">
              <div class="tit">{{$t('applyReturn.courierPostage')}}：</div>
              <div class="return-text">￥{{ toPrice(transfee) }}</div>
            </div>
            <div class="item">
              <div class="tit">{{$t('applyReturn.totalOrderPrice')}}：</div>
              <!-- <div class="return-text">￥{{toPrice(returnDetail.orderAmount)}}</div> -->
              <div class="return-text">
                <span v-if="returnDetail.orderAmount"
                  >￥{{ returnDetail.orderAmount }}</span
                >
                <span
                  v-if="returnDetail.refundScore && returnDetail.orderAmount"
                  >+</span
                >
                <span v-if="returnDetail.refundScore"
                  >{{ returnDetail.refundScore }} {{$t('applyReturn.points')}}</span
                >
              </div>
            </div>
            <div class="item">
              <div class="tit">{{$t('applyReturn.refundInstructions')}}：</div>
              <div class="return-text">{{ returnDetail.buyerDesc }}</div>
            </div>
          </div>
        </div>
        <div class="item" v-if="photoFiles.length">
          <div class="tit">{{$t('applyReturn.refundVoucher')}}：</div>
          <el-image class="ref-img" :key="pic" :src="pic" v-for="pic in photoFiles" :preview-src-list="photoFiles"></el-image>
        </div>
      </div>
    </div>
    <!-- /等待商家处理&&填写运单号 -->



    <!-- 弹窗 -->
    <div class="popup-mask" v-if="false"></div>
    <div class="popup-box" v-if="false">
      <div class="tit">
        <div class="text">{{$t('tips')}}</div>
        <div class="close"></div>
      </div>
      <div class="con">
        <div class="tip">
          <div class="tip-icon success"></div>
          <div class="tip-info">
            <div class="result">{{$t('applyReturn.applicationTips10')}}</div>
            <div class="date">{{$t('applyReturn.applicationTips11')}}</div>
            <div class="btns">
              <a href="javascript:void(0);" class="btn">
                {{$t('applyReturn.ViewAfterSalesDetails')}}
                <span class="arrow">&gt;&gt;</span>
              </a>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /弹窗 -->

    <!-- 修改退款金额弹窗 -->
    <div class="popup-mask" v-if="isModifyRefundAmount"></div>
    <div class="popup-box" v-if="isModifyRefundAmount">
      <div class="tit">
        <div class="text">{{$t('applyReturn.modifyRefundAmount')}}</div>
        <div class="close" @click="isModifyRefundAmount = false"></div>
      </div>
      <div class="con modify-amount">
        <div class="int-box">
          <input
            v-model="modifyAmount"
            type="text"
            class="int"
            :placeholder="this.$t('applyReturn.pleaseEnterAmount')"
            @blur="handleAmountInput"
            @focus="handleAmountInput"
          >
          <div v-if="!refundAmountError" class="max-amount">
            {{$t('applyReturn.maximumRefundable')}}￥{{maxRefundAmount}}
          </div>
          <div v-if="refundAmountError" class="error">
            {{ modifyAmount && Number.parseFloat(modifyAmount) > Number.parseFloat(maxRefundAmount)
              ? `${$t('applyReturn.maximumRefundable')}￥${maxRefundAmount}，${$t('applyReturn.reEnter')}`
              : $t('applyReturn.pleaseEnterAmount')}}
          </div>
        </div>
        <div class="foot-btn">
          <span class="confirm" @click="requestModify">{{$t('login.confirmChanges')}}</span>
        </div>
      </div>
    </div>
    <!-- / 修改退款金额弹窗 -->

    <!-- 物流信息弹框 -->
    <writeLogisticsInfo
      v-if="showAdd"
      @toggleAddrPop="refreshChange"
      :refundSn="refundSn"
      :orderNumber="orderRefundParam.orderNumber"
      :refundDelivery="returnDetail.refundDelivery"
      :returnMoneySts="returnDetail.returnMoneySts"
    ></writeLogisticsInfo>
  </div>
</template>

<script>
import MulPicUpload from '~/components/mul-pic-upload'
import writeLogisticsInfo from '~/components/write-logistics-info'
import util from '~/plugins/util.js'
import big from '~/plugins/big.min.js'
import { _debounce } from "~/plugins/util"
import { picDomain } from '~/plugins/config.js'

export default {
  components: {
    MulPicUpload,
    writeLogisticsInfo
  },
  data () {
    return {
      picDomain: picDomain,
      showApplyRefund: false, //填写申请显隐
      WaitProcessing: false, //等待商家处理显隐
      fillInLogistics: false,  //填写物流显隐
      //  退款原因（已收到货）
      // refundProdReasonArray: ['拍错/多拍/不喜欢', '协商一致退款', '商品破损/少件', '商品与描述不符', '卖家发错货', '质量问题', '其他'],
      // 退款原因（未收到货）
      // refundPriReasonArray: ['拍错/多拍/不喜欢', '协商一致退款', '其他'],
      // 退款原因（总）
      // refundReasonArray: ['拍错/多拍/不喜欢', '协商一致退款', '商品破损/少件', '商品与描述不符', '卖家发错货', '质量问题', '其他', '', '拼团失败'],
      refundProdObj: {}, // 订单数据
      orderItem: [],  //订单项
      transfee: this.$route.query.transfee,  //运费
      status: this.$route.query.status,  //订单状态 1:待付款 2:待发货 3:待收货 4:待评价 5:成功 6:失败
      actualTotal: this.$route.query.actualTotal,  //实际总额
      refundAmount: 0, //（最多可退）退款金额
      // 申请售后数据
      orderRefundParam: {
        orderNumber: this.$route.query.orderNumber,  //订单编号
        applyType: 1,  //申请类型(1:仅退款 2退款退货)
        isReceiver: 0,  //货物状态(1:已收到货 0:未收到货)
        buyerReason: '',  //申请原因(下拉选择)
        buyerMobile: '',  //手机号
        buyerDesc: '',  //备注说明
        photoFiles: '', //凭证图片列表
        refundType: this.$route.query.refundType,  //退款单类型（1:整单退款,2:单个物品退
        orderItemId: this.$route.query.orderItemId,  //订单项ID（单个物品退款时使用）
        giveawayItemIds: [] // 赠品id数组
      },
      showSelectTips: true,  //退款原因错误提示显隐
      showAmountTips: false,  //退款金额错误提示显隐
      showMobileTips: false, //手机号码错误提示显隐
      // showBuyerDescTips: false,  //退款说明提示显隐

      //等待商家处理
      returnDetail: {},  //退款详情信息
      refundSn: this.$route.query.refundSn, //退款单号
      photoFiles: [],  //退款详情图片展示
      logisticsNumber: '',  //是否有物流单号

      showAdd: false,

      showReasonOptions: false,  //退款原因选项

      goodsNum: 1,  //计数器数量

      showTransfee: false,  //是否显示含运费提示

      isOnlyProd: false, //是否仅一个商品项（可退运费）

      totalRefundAmount: 0, // 可退总金额（含可退运费）

      // 缓存中的货物状态
      isReceiverOfCach: null,

      // 当前商品信息
      orderItemProdInfo: [],

      // 订单模型 1虚拟商品订单
      orderMold: 0,
      // 是否需要核销
      needWriteOffs: false,
      // 最大可退款件数（虚拟商品：需要核销时展示）
      maxRefundPieces: 0,

      // 退款说明错误提示
      showBuyerDescErrTips: false,

      // 实际支付总积分
      totalRefundScore: 0,

      // 赠品列表
      giveawayList: [],
      // 被移除的赠品总额
      priceOfRemovedGiveaways: 0,

      prodList: [],

      isModifyRefundAmount: false, // 修改金额弹窗
      modifyAmount: '', // 修改金额
      refundAmountError: false,
      // 退款项中是否使用了平台优惠 (使用了则不能修改退款金额)
      isUsedPlatformReduce: false,
      refundType: 0,
      maxRefundAmount: 0
    }
  },
  computed: {
    //  退款原因（已收到货）
      refundProdReasonArray: function(){
        return [this.$i18n.t('applyReturn.refundReason1'), this.$i18n.t('applyReturn.refundReason2'), this.$i18n.t('applyReturn.refundReason3'), this.$i18n.t('applyReturn.refundReason4'), this.$i18n.t('applyReturn.refundReason5'), this.$i18n.t('applyReturn.refundReason6'), this.$i18n.t('applyReturn.refundReason7')]
      },
      // 退款原因（未收到货）
      refundPriReasonArray: function(){
        return [this.$i18n.t('applyReturn.refundReason1'), this.$i18n.t('applyReturn.refundReason2'), this.$i18n.t('applyReturn.refundReason7')]
      },
      // 退款原因（总）
      refundReasonArray: function(){
        return [this.$i18n.t('applyReturn.refundReason1'), this.$i18n.t('applyReturn.refundReason2'), this.$i18n.t('applyReturn.refundReason3'), this.$i18n.t('applyReturn.refundReason4'), this.$i18n.t('applyReturn.refundReason5'), this.$i18n.t('applyReturn.refundReason6'), this.$i18n.t('applyReturn.refundReason7'), '', this.$i18n.t('applyReturn.refundReason8')]
      }
  },
  mounted () {
    // 是否为虚拟商品订单
    this.orderMold = this.$route.query.orderMold ? Number(this.$route.query.orderMold) : 0
    // 从缓存中获取退款详情展示的货物状态
    this.isReceiverOfCach = localStorage.getItem('isReceiverOfCach');
    //从缓存中拿到订单项
    this.refundProdObj = JSON.parse(localStorage.getItem('refundProdObj') || '{}')
    this.orderItem = this.refundProdObj.orderItem //商品item
    this.isLastProd = this.orderItem[0].isLastProd // 是否最后一项
    this.isOnlyProd = this.refundProdObj.isOnlyProd // 是否仅一个商品项（可退运费）
    this.refundType = this.refundProdObj.refundType
    this.goodsNum = this.orderItem[0].prodCount  //商品数量
    //订单项id
    this.orderRefundParam.orderItemId = this.refundProdObj.orderItem[0].orderItemId
    this.orderRefundParam.buyerMobile = this.refundProdObj.buyerMobile

    if (!this.returnDetail.refundSn && !this.refundSn) {  //退款编号为空时
      this.showApplyRefund = true //填写申请
    }
    //等待商家处理（修改和撤销按钮页）退款订单详情
    if (this.refundSn || !this.showApplyRefund) {
      this.getReturnDetail()
    }

    // 订单类型 0普通 1团购 2秒杀 3积分
    this.orderType = this.refundProdObj.orderType ? Number(this.refundProdObj.orderType) : 0
    // 虚拟商品
    if (this.orderMold == 1) {
      // needWriteOffs是否需要核销
      this.needWriteOffs = this.refundProdObj.needWriteOffs
      // 最大可退件数（需要核销）
      if(this.needWriteOffs) {
        this.orderRefundParam.isReceiver = 1 // 核销不存在未收到货
        this.maxRefundPieces = this.refundProdObj.maxRefundPieces ? Number(this.refundProdObj.maxRefundPieces) : 0
      }
    }

    // this.getRefundAmount()  //计算金额输入框初始默认价格

    // 获取订单项商品数据（国际化时需要改变）
    this.queryProdInfo()
    // 设置网页标题
    document.title = this.$i18n.t('applyReturn.applyAfterSales')
  },
  methods: {
    /**
     * 加载默认图片
     */
    handlePicError(e){
       e.target.src=require('@/assets/img/def.png')
    },
    /**
     * 商品信息
     */
    queryProdInfo() {
      this.$axios.get('/p/myOrder/orderDetail', {
        params: {
          orderNumber: this.$route.query.orderNumber
        }
      }).then(({ data }) => {
        this.giveawayList = []
        this.orderItem = []
        // 要退的赠品商品项id数组
        this.orderRefundParam.giveawayItemIds = []
        // 单个退&有订单项id
        if (this.orderRefundParam.refundType == 2 &&
            this.orderRefundParam.orderItemId) {
          // 单个商品项
          const item = data.orderItemDtos.find(el => el.orderItemId === this.orderRefundParam.orderItemId) || null
          this.orderItem = item ? this.orderItem.concat(item) : []
          // 赠品列表
          this.giveawayList = this.orderItem[0].giveawayList ? this.orderItem[0].giveawayList : []
          // 赠品ids
          this.orderRefundParam.giveawayItemIds = this.giveawayList.map(el => el && el.orderItemId)
        } else {
          // 整单商品项
          this.orderItem = data.orderItemDtos
          // 收集每个订单项赠品列表里的赠品id
          this.orderItem.forEach(el => {
            if (el.giveawayList && el.giveawayList.length) {
              this.orderRefundParam.giveawayItemIds = this.orderRefundParam.giveawayItemIds.concat(el.giveawayList.map(el => el && el.orderItemId))
            }
          })
        }
        //计算金额输入框初始默认价格
        this.getRefundAmount()
      })
    },

    /**
     * 点击移除（赠品）按钮重新计算可退总额
     */
    removeGiveaways (orderItemId, index) {
      // 赠品价值
      const giveawayAmount = this.giveawayList[index].giveawayAmount
      this.$confirm(`${ this.$i18n.t('prodDetail.removeGiftTip1') + giveawayAmount + this.$i18n.t('prodDetail.removeGiftTip2')}`, this.$i18n.t('chat.tips'), {
        confirmButtonText: this.$i18n.t('chat.confirm'),
        cancelButtonText: this.$i18n.t('chat.cancel'),
        type: 'warning'
      }).then(() => {
        // 实际总额
        const actualTotal = new big(this.orderItem[0].actualTotal)
        // 商品总件数
        const prodCount = this.orderItem[0].prodCount
        // 当前退款件数
        const goodsNum = this.goodsNum
        // 已被移除的赠品总价
        const priceOfRemovedGiveaways = this.priceOfRemovedGiveaways
        // 当前最大可退款金额 = 订单实际总额/商品总件数*当前退款件数-已被移除的赠品总价
        const curRefundAmount = actualTotal.div(prodCount).times(goodsNum).minus(priceOfRemovedGiveaways)

        // 可退金额 = 当前最大可退款金额 - 当前点击移除的赠品价值
        const totalAmount = Number.parseFloat(curRefundAmount.minus(giveawayAmount).valueOf())

        // 当减去当前要移除的赠品价格所得值<=0时，不允许移除
        if (giveawayAmount > 0 && totalAmount <= 0) {
          this.$message({
            message: this.$i18n.t('prodDetail.removeGiftTip3'),
            type: 'warning',
            duration: 2000,
            onClose: () => {
            }
          })
          return
        }

        // 已被移除的赠品总价
        this.priceOfRemovedGiveaways = new big(giveawayAmount).plus(this.priceOfRemovedGiveaways).valueOf() || 0

        // 移除
        this.giveawayList.splice(index, 1)
        this.orderRefundParam.giveawayItemIds.splice(index, 1)

        // 计算退款金额
        this.getRefundAmount(totalAmount)
      }).catch(() => {

      })
    },

    /**
     * 处理价格样式
     */
    toPrice (val) {
      var val = Number(val)
      if (!val) {
        val = 0;
      }
      return (val.toFixed(2))
    },

    /**
     * 计算金额输入框初始默认价格
     */
    getRefundAmount (totalAmount) {
      var newTransfee = new big(this.transfee)
      var totalRefundScore = 0 //  totalRefundScore: 实际所有积分即可退换的所有积分
      this.orderItem.forEach(prodItem => {
        totalRefundScore += prodItem.useScore
      })
      this.totalRefundScore = totalRefundScore

      // 虚拟商品&需要核销：根据最多可退件数，计算最大可退金额
      if (this.orderMold === 1 && this.needWriteOffs) {
        const prodCount = this.orderItem[0].prodCount
        const actualTotal = this.orderItem[0].actualTotal
        this.actualTotal = new big(actualTotal).times(this.maxRefundPieces).div(prodCount).valueOf()
        // 最多可退
        this.refundAmount = this.actualTotal
        // 记录可退款总金额
        this.totalRefundAmount = this.actualTotal
        return
      }

      // refundType退款单类型：1.整单退款,2.单个物品退
      if (this.orderRefundParam.refundType == 1) {  //整单退款
        this.actualTotal = this.refundProdObj.actualTotal
        var newActualTotal = new big(this.actualTotal)
        if (this.status == 2 && this.transfee) {  //待发货且有运费
          this.refundAmount = newActualTotal.minus(newTransfee).valueOf()
          this.showTransfee = true
        } else {
          this.actualTotal = this.refundAmount = newActualTotal.minus(newTransfee).valueOf()
          this.showTransfee = false
        }
      } else if (this.orderRefundParam.refundType == 2) {  //单个退
        this.actualTotal = totalAmount > 0 ? totalAmount : this.refundProdObj.orderItem[0].actualTotal
        var newActualTotal = new big(this.actualTotal)
        this.refundAmount = this.actualTotal
        if (this.status == 2 && this.transfee && (this.isLastProd || this.isOnlyProd)) { // 待发货&&有运费&&(最后一个商品项||仅一个商品项)
          this.actualTotal = newActualTotal.valueOf()
          this.showTransfee = true
        } else {
          this.showTransfee = false
        }
      }

      // 记录可退款总金额
      this.totalRefundAmount = this.actualTotal

    },

    /**
     * 改变商品数量重新计算价格（数量加减）
     */
    changePordNum: function (changeNum) {
      let actualTotal = this.orderItem[0].actualTotal  //商品原始总额（不含运费）
      var prodCount = this.orderItem[0].prodCount  //商品原始总数
      var goodsNum = this.goodsNum + changeNum // 计数器商品总数
       // 被移除的赠品总数
      const priceOfRemovedGiveaways = this.priceOfRemovedGiveaways || 0
      if (goodsNum < 1) {
        this.$message({
          message: this.$i18n.t('applyReturn.returnedGoods'),
          type: 'error',
          duration: 1000
        })
        return
      }
      if (goodsNum > prodCount) {
        this.$message({
          message: this.$i18n.t('applyReturn.refundReason9'),
          type: 'error',
          duration: 1500
        })
        return
      }
      big.DP = 2
      big.RM = 0
      // 当前最大可退款金额 = 实际总额/商品总数*当前退款数量-已被移除的赠品总价
      let amount = new big(actualTotal).times(goodsNum).div(prodCount).minus(priceOfRemovedGiveaways).valueOf()
      if (amount <= 0) {
        this.$message({
          message: this.$i18n.t('applyReturn.canotReduce'),
          type: 'error',
          duration: 1500
        })
        return
      }

      this.goodsNum = goodsNum
      this.actualTotal = amount
      // 最多可退
      this.refundAmount = this.actualTotal
      this.totalRefundAmount = this.actualTotal
    },

    /**
     * 退款方式选择
     */
    returnType (applyType) {
      applyType == 1 ? this.orderRefundParam.applyType = 1 : this.orderRefundParam.applyType = 2
      if (applyType == 2) {
        this.orderRefundParam.isReceiver = 1
      }
    },
    /**
     * 货物状态选择
     */
    goodsStatus (isReceiver) {
      isReceiver == 1 ? this.orderRefundParam.isReceiver = 1 : this.orderRefundParam.isReceiver = 0
      this.orderRefundParam.buyerReason = ''
      this.orderRefundParam.buyerReasonStr = ''
    },
    /**
     * 输入手机号input框过滤
     */
    resetMobileNumber () {  //失去焦点时
      if (!util.checkPhoneNumber(this.orderRefundParam.buyerMobile)) {
        this.showMobileTips = true
      }
      else {
        this.showMobileTips = false
      }
    },
    /**
     * 退款原因选项列表
     */
    selectReason () {
      this.showReasonOptions = true
    },

        /**
     * 取消退款原因选项列表
     */
    hideSelectReason () {
      this.showReasonOptions = false
    },


    /**
     * 退款原因选择
     */
    returnReason (e) {
      this.orderRefundParam.buyerReason = e.target.dataset.idx
      this.orderRefundParam.buyerReasonStr = e.target.dataset.reason
      this.showSelectTips = false
      this.showReasonOptions = false
    },

    checkBuyerDesc () {
      this.showBuyerDescErrTips = false
      if (!this.orderRefundParam.buyerDesc.trim()) {
        this.orderRefundParam.buyerDesc = ''
        this.showBuyerDescErrTips = true
      }
    },

    // 失焦时校验金额是否输入正确
    resetActualTotal () {
      // 正则限制：正数（小数点后可以保留2位）
      let refundAmountReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
      this.showAmountTips = false

      // 虚拟商品
      if (this.orderMold == 1 && (!refundAmountReg.test(this.actualTotal) || this.actualTotal < 0.01 || this.actualTotal > this.totalRefundAmount)) {
        this.showAmountTips = true
        return
      }

      // 积分为空时，输入框内容不为正数/小于0.01/大于最大退款数，就显示错误提示语
      if (!this.totalRefundScore && (!refundAmountReg.test(this.actualTotal) || this.actualTotal < 0.01 || this.actualTotal > this.totalRefundAmount)) {
        this.showAmountTips = true
      }
    },

    /**
     * 提交售后申请
     */
    applyRefund: _debounce(function () {
      this.orderRefundParam.goodsNum = this.goodsNum
      this.orderRefundParam.refundAmount = parseFloat(this.actualTotal) || 0
      // 检查数据完整性
      this.orderRefundParam.refundAmount = parseFloat(this.actualTotal) || 0
      // 正则限制：正数（小数点后可以保留20位）
      let refundAmountReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,20})?$/
      if (!this.orderRefundParam.buyerReason) {  //退款原因
        this.showSelectTips = true
        return
      }
      else if (!this.totalRefundScore && (!refundAmountReg.test(this.actualTotal) || this.actualTotal < 0.01 || this.actualTotal > this.totalRefundAmount)) {
        this.showAmountTips = true
        return
      }
      if (!util.checkPhoneNumber(this.orderRefundParam.buyerMobile)) {
        // 手机号
        this.showMobileTips = true
      } else if (!this.orderRefundParam.buyerDesc.trim()) {
        // 退款说明
        this.showBuyerDescErrTips = true
      }  else {
        if (this.orderRefundParam.isReceiver == 0) { // 未收到货
          // 未收到货需要转换一下原因
          this.orderRefundParam.buyerReason == 2 ? this.orderRefundParam.buyerReason = 6 : 0
        }
        // 整单退款移除 数量 和 订单项id
        if (this.orderRefundParam.refundType == 1) {
          this.orderRefundParam.orderItemId = undefined
          this.orderRefundParam.goodsNum = undefined
        }
        // 虚拟商品-需要核销，传最大可退货数量
        if (this.orderMold == 1 && this.needWriteOffs) {
          this.orderRefundParam.goodsNum = this.maxRefundPieces
        }
        this.applyOrderRefund(this.orderRefundParam)
      }
    }, 1000),

    // 请求申请退款接口
    applyOrderRefund (orderRefundParam) {
      // 清除缓存中的货物状态
      localStorage.removeItem("isReceiverOfCach");
      this.$axios.post('/p/orderRefund/apply', orderRefundParam)
        .then(({ data }) => {
          this.refundSn = data   //退款编号
          // 将货物状态放进缓存
          localStorage.setItem('isReceiverOfCach',orderRefundParam.isReceiver);
          this.$message({
            message: this.$i18n.t('applyReturn.applicationSuccessful'),
            duration: 1000,
            type: 'success'
          });
          setTimeout(() => {
            this.showApplyRefund = false
            this.$router.push({ path: '/order-detail?orderNumber=' + orderRefundParam.orderNumber })
          }, 1000)
        })
    },


    /**
     * 请求退款详情信息
     */
    getReturnDetail () {
      this.$axios.get('/p/orderRefund/info?refundSn=' + this.refundSn)
        .then(({ data }) => {
          let isUsedPlatformReduce = false
          data.orderItems.forEach(orderItem => {
            if (orderItem.platformShareReduce && !isUsedPlatformReduce) {
              isUsedPlatformReduce = true
            }
          })
          this.maxRefundAmount = data.maxRefundAmount
          this.isUsedPlatformReduce = isUsedPlatformReduce
          this.returnDetail = data
          //详情页图片显示
          if (this.returnDetail.photoFiles) {
            this.photoFiles = (this.returnDetail.photoFiles).split(",");
          }
          if (this.refundSn && this.returnDetail.returnMoneySts == 1) {  //有退款编号且退款状态为1"买家申请"时
            this.WaitProcessing = true  //等待处理
          }
          if (this.refundSn && (this.returnDetail.returnMoneySts == 2 || this.returnDetail.returnMoneySts == 3) && this.returnDetail.applyType == 2) {  //退款状态为2"卖家接受"且退款类型为2“退货退款”时
            this.fillInLogistics = true
          }
          this.prodList = data.orderItems
          const orderItems = data.orderItems
          // 单个商品 && 有赠品时：
          if (orderItems.length === 1 && orderItems[0].giveawayList && orderItems[0].giveawayList.length) {
            this.prodList = [...orderItems, ...orderItems[0].giveawayList]
          }
        })
    },

    /**
     * 撤销申请
     */
    cancelApply () {
      this.$confirm(this.$i18n.t('applyReturn.refundReason11'), this.$i18n.t('applyReturn.tips'), {
        confirmButtonText: this.$t('determine'),
        cancelButtonText: this.$t('cancel'),
        type: 'warning'
      }).then(() => {
        this.$axios.put('/p/orderRefund/cancel', this.refundSn)
          .then(({ data }) => {
            this.$message({
              message: this.$i18n.t('applyReturn.refundReason12'),
              duration: 1000,
              type: 'success'
            });
            setTimeout(() => {
              this.$router.push({ path: '/user-center/uc-return' })
            }, 2000)
          })
      }).catch(() => {
      });
    },

    /**
     * 填写 || 修改物流信息
     */
    writeLogisticsMsg () {
      this.showAdd = true
    },
    /**
    * 刷新回调
    */
    refreshChange (visible) {
      this.showAdd = visible
    },

    /**
     * 跳转商品详情
     */
    toProdDetail (prodId) {
      if (prodId) {
        this.$router.push({ path: `/detail/${prodId}` })
      }
    },

    /**
     * 修改退款金额
     */
    modifyRefundAmount() {
      this.modifyAmount = ''
      this.refundAmountError = false
      this.isModifyRefundAmount = true
    },
    handleAmountInput() {
      this.refundAmountError = false
      if (!this.modifyAmount || !this.modifyAmount.trim()) {
        this.modifyAmount = this.modifyAmount.trim()
        return
      }
      this.modifyAmount = this.checkInput(this.modifyAmount)
    },
    checkInput (num) {
      if (num) {
        var tmpVal = num.replace(/[^\d^\\.]/g, '')
        var reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
        if (!reg.test(tmpVal)) {
          tmpVal = tmpVal + ''
          tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
          var n = (tmpVal.split('.')).length - 1
          if (n > 1) {
            tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
          }
        }
        return tmpVal
      } else {
        return ''
      }
    },
    requestModify() {
      if (!this.modifyAmount || !this.modifyAmount.trim() || this.modifyAmount <= 0) {
        this.refundAmountError = true
        this.modifyAmount = this.modifyAmount.trim()
        return
      }
      if (Number.parseFloat(this.modifyAmount) > Number.parseFloat(this.maxRefundAmount)) {
        this.refundAmountError = true
        return
      }
      const param = {
        refundAmount: this.modifyAmount,
        refundSn: this.refundSn
      }
      this.$axios.put('/p/orderRefund/updateRefundAmount', param)
        .then(({ data }) => {
          this.$message({
            message: this.$t('applyReturn.modifiedSuccessfully'),
            type: 'success',
            duration: 1000
          })
          this.isModifyRefundAmount = false
          this.refundAmountError = false
          this.refundAmount = ''
          this.getReturnDetail()
        })
    }

  },
}
</script>

<style scoped src='~/assets/css/apply-return.css'></style>
<style scoped src='~/assets/css/user-center.css'></style>
<style scoped src='~/assets/css/uc-edit.css'></style>
<style>
.pic-upload .pic-uploader-component {
  display: block;
  width: 100%;
  height: 100%;
}
.pic-upload .pic-uploader-component .el-upload {
  display: block !important;
}
.el-upload--picture-card {
  line-height: 160px;
}
.apply-return .el-icon-plus {
  width: inherit !important;
  height: inherit !important;
  line-height: inherit !important;
}
textarea.shop-description {
  font-family: arial;
}
.item .ref-img {
  width: 100px;
  height: 100px;
  padding: 3px;
  margin-right: 10px;
}
</style>

