<template>
  <view class="Mall4j page-apply-refund">
    <view class="line-prods">
      <view
        v-for="(refundItem, index) in refundItemList"
        :key="index"
        class="item-box"
      >
        <template
          v-for="(combo, comboIndex) in (refundItem.skuComboList ? refundItem.skuComboList : [refundItem])"
          :key="comboIndex"
        >
          <view class="item">
            <view class="img">
              <img-show
                :src="combo.pic"
                img-mode="aspectFit"
              />
            </view>
            <view class="text-box">
              <view class="name">
                {{ combo.spuName }}
              </view>
              <view class="sku">
                {{ combo.skuName || '' }}
              </view>
              <view class="price-box">
                <view class="price">
                  <view class="symbol">
                    ￥
                  </view>
                  <view class="big">
                    {{ wxs.parsePrice(combo.price)[0] }}
                  </view>
                  <view class="symbol">
                    .{{ wxs.parsePrice(combo.price)[1] }}
                  </view>
                </view>
                <view class="number">
                  ×{{ orderMold === 1 && needWriteOffs ? maxRefundPieces : combo.count }}
                </view>
              </view>
            </view>
            <view
              v-if="(applyType === applyTypeConstant.REFUND_AND_RETURNS
                && refundType === refundTypeConstant.SINGLE
                && refundInfo.status > orderStatusConstant.PAYED
                && !orderScore) || (orderMold === 1 && !needWriteOffs)"
              class="number-box"
            >
              <view
                class="minus"
                @tap.stop="changePordNum(-1)"
              />
              <input
                :value="showPordNumer"
                disabled
                class="number"
                maxlength="4"
              >
              <view
                class="plus"
                @tap.stop="changePordNum(1)"
              />
            </view>
          </view>

          <!-- 组合 -->
          <view
            v-if="combo.comboItemList"
            class="gift-prods"
          >
            <view
              v-for="prod in combo.comboItemList"
              :key="prod.orderItemId"
              class="gift-item"
            >
              <text class="name">
                【组合】{{ prod.spuName }}{{ prod.skuName ? ('&nbsp;&nbsp;' + prod.skuName) : '' }}
              </text>
              <text class="num">
                ×{{ prod.count }}
              </text>
            </view>
          </view>

          <!-- 赠品 -->
          <view
            v-if="refundType === 1"
            class="gift-prods"
          >
            <view
              v-for="prod in combo.giveawayList"
              :key="prod.orderItemId"
              class="gift-item"
            >
              <text class="name">
                【赠品】{{ prod.spuName }}
                <text
                  v-if="prod.skuName"
                  decode
                >
                  {{ "&nbsp;&nbsp;" + prod.skuName || '' }}
                </text>
              </text>
              <text class="num">
                ×{{ prod.count }}
              </text>
            </view>
          </view>
        </template>
      </view>

      <view
        v-if="refundItemList.length === 1 && refundType === 2"
        style="margin-top: 30rpx"
      >
        <view
          v-for="(prod, index) in refundItemList[0].giveawayList"
          :key="index"
          class="item"
        >
          <view class="img">
            <img-show
              :src="prod.pic"
              img-mode="aspectFit"
            />
          </view>
          <view class="text-box">
            <view class="name">
              {{ prod.spuName }}
            </view>
            <view
              class="sku"
              decode
            >
              <text class="activity-logo">
                赠品
              </text><text
                v-if="prod.skuName"
                decode
              >
                {{ "&nbsp;&nbsp;" + prod.skuName || '' }}
              </text>
            </view>
            <view class="price-box">
              <view class="price">
                <view class="symbol">
                  ￥
                </view>
                <view class="big">
                  {{ wxs.parsePrice(prod.giveawayAmount)[0] }}
                </view>
                <view class="symbol">
                  .{{ wxs.parsePrice(prod.giveawayAmount)[1] }}
                </view>
              </view>
              <view class="number">
                ×{{ prod.count }}
              </view>
            </view>
          </view>
          <view
            v-if="refundInfo.status !== 2"
            class="number-box"
          >
            <view
              class="remove-btn"
              @tap="removeGiftItem(index)"
            >
              移除
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="refund-box">
      <view class="item">
        <view class="label">
          售后类型
        </view>
        <radio-group
          class="radio-box"
          @change="handleChangeRefundType"
        >
          <label :class="['radio', applyType === applyTypeConstant.REFUND ? 'active' : '']">
            <view class="text">仅退款</view>
            <radio
              color="#fc1b35"
              value="1"
              :checked="applyType === applyTypeConstant.REFUND"
            />
          </label>
          <label
            v-if="orderMold !== 1"
            :class="['radio', applyType === applyTypeConstant.REFUND_AND_RETURNS ? 'active' : '', refundInfo.status === orderStatusConstant.PAYED ? 'failure' : '']"
            @tap="refundTypeTip"
          >
            <view :class="['text']">退货退款</view>
            <radio
              color="#fc1b35"
              value="2"
              :class="refundInfo.status === orderStatusConstant.PAYED ? 'disabled' : ''"
              :checked="applyType === applyTypeConstant.REFUND_AND_RETURNS"
              :disabled="refundInfo.status === orderStatusConstant.PAYED"
            />
          </label>
        </radio-group>
      </view>
      <view
        v-if="refundInfo.status > orderStatusConstant.PAYED"
        class="item"
      >
        <view class="label">
          货物状态
        </view>
        <view
          class="text-arrow"
          @tap="showCargoStatePopup"
        >
          {{ +received === 1 ? '已收货' : '未收货' }}
        </view>
      </view>
      <view class="item">
        <view class="label">
          退款原因
        </view>
        <view
          class="text-arrow"
          @tap="showReasonPopup"
        >
          {{ showReasonList[buyerReason] }}
        </view>
      </view>
      <view class="item">
        <view class="label">
          退款金额
        </view>
        <view
          v-if="!orderScore"
          class="refund-price"
        >
          <view class="symbol">
            ￥
          </view>
          <!-- 禁用状态: 整单退不可用; 待添加:使用积分不可用; 平台分摊金额不可用？ -->
          <input
            v-model="showRefundAmount"
            type="digit"
            class="input"
            :disabled="refundType === refundTypeConstant.ALL || orderScore > 0 || platformCouponAmount > 0 || memberAmount > 0"
            @blur="checkRefundAmount"
          >
        </view>
        <!-- 含积分金额展示 -->
        <view
          v-if="orderScore > 0"
          class="refund-price"
        >
          <text
            v-if="showRefundAmount > 0"
            class="symbol"
            decode
          >
            ￥
          </text>
          <text
            v-if="showRefundAmount > 0"
            class="big-price"
            decode
          >
            {{ showRefundAmount }}
          </text>
          <text
            v-if="showRefundAmount > 0 && orderScore > 0"
            class="symbol"
            decode
          >
            &nbsp;+&nbsp;
          </text>
          <text
            class="big-price"
            decode
          >
            {{ orderScore }}
          </text>
          <text
            class="symbol"
            decode
          >
            &nbsp;积分
          </text>
        </view>
      </view>
      <view class="price-des">
        <text class="max-refund-txt">
          最多可退
        </text>
        <text v-if="totalPrice > 0">
          {{ wxs.parsePrice(totalPrice)[0] }}.{{ wxs.parsePrice(totalPrice)[1] }}元
        </text>
        <text
          v-if="totalPrice > 0 && orderScore > 0"
          decode
        >
          &nbsp;+&nbsp;
        </text>
        <text v-if="orderScore > 0">
          {{ orderScore }}积分
        </text>
      </view>
    </view>
    <view class="refund-explain">
      <view class="label">
        手机号
      </view>
      <input
        v-model="buyerMobile"
        class="phone"
        :placeholder="orderMold === 1 ? '请输入手机号码' : '请输入退货人手机号码'"
        type="number"
        maxlength="11"
      >
      <view class="label">
        退款说明
      </view>
      <Textarea
        v-model:value="buyerDesc"
        class="textarea"
        :placeholder="'补充描述，最多200字'"
        :maxlength="'200'"
      />
      <view class="label">
        退款凭证
      </view>
      <view class="upload-box">
        <imgs-box
          :img-num="3"
          :img-urls="photoFiles"
          @get-image-path="getImgPath"
        />
      </view>
      <view class="upload-des">
        提示：最多可上传3张凭证
      </view>
    </view>
    <view class="btn-box">
      <view
        class="btn"
        @tap="submit"
      >
        提交申请
      </view>
    </view>

    <!-- 货物状态弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowCargoStatePopup }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom cargo-state">
        <view
          v-if="isShowCargoStatePopup"
          class="popup-tit"
        >
          <view class="tit-text">
            选择货物状态
          </view>
          <view
            class="close"
            @tap="closePopup"
          >
            <image src="@/static/images/close.png" />
          </view>
        </view>
        <radio-group
          class="con-box-min"
          @change="handleChangeReceivedStatus"
        >
          <label class="item">
            <view class="text">已收货</view>
            <radio
              color="#fc1b35"
              value="1"
              :checked="currentReceivedStatus === 1"
            />
          </label>
          <label
            v-if="applyType === applyTypeConstant.REFUND && orderMold !== 1"
            class="item"
          >
            <view class="text">未收货</view>
            <radio
              color="#fc1b35"
              value="0"
              :checked="currentReceivedStatus === 0"
            />
          </label>
        </radio-group>
        <view class="btn-box">
          <view
            class="btn"
            @tap="confirmChangeReceivedStatus"
          >
            确定
          </view>
        </view>
      </view>
    </view>

    <!-- 退款理由弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowReasonPopup }"
    >
      <view
        class="popup-mask"
        @tap="closePopup"
      />
      <view class="popup-con-bottom refund-reason">
        <view
          v-if="isShowReasonPopup"
          class="popup-tit"
        >
          <view class="tit-text">
            选择退款原因
          </view>
          <view
            class="close"
            @tap="closePopup"
          >
            <image src="@/static/images/close.png" />
          </view>
        </view>
        <radio-group
          class="con-box-min"
          @change="handleChangeReason"
        >
          <label
            v-for="(reasonItem, reasonIdx) in showReasonList"
            :key="reasonIdx"
            class="item"
          >
            <view class="text">{{ reasonItem }}</view>
            <radio
              color="#fc1b35"
              :value="String(reasonIdx)"
              :checked="reasonIdx === currentSelectReason"
            />
          </label>
        </radio-group>
        <view class="btn-box">
          <view
            class="btn"
            @tap="confirmChangeReason"
          >
            确定
          </view>
        </view>
      </view>
    </view>
    <!-- 确认弹窗 -->
    <confirm-pop
      :show-pop="showPop"
      :show-cancel="showCancel"
      :pop-content="popContent"
      @handle-pop-cancel="popCancel"
      @handle-pop-confirm="popConfirm"
    />
  </view>
</template>

<script setup>
import util from '@/utils/util'
import { OrderStatus, RefundType, RefundApplyType } from '@/utils/constant'
import Textarea from '../../components/textarea/index.vue'
import Big from 'big.js'

const wxs = number()
Big.DP = 2
Big.RM = 0

// 各种状态常量
const orderStatusConstant = OrderStatus
const refundTypeConstant = RefundType
const applyTypeConstant = RefundApplyType

const receivedReasonList = ['拍错/多拍/不喜欢', '协商一致退款', '商品破损/少件', '商品与描述不符', '卖家发错货', '质量问题', '其他']
const unReceivedReasonList = ['拍错/多拍/不喜欢', '协商一致退款', '其他']

const isRefundErrorCallBackPop = ref(false) // 是否为申请退款错误回调弹窗
const priceOfRemovedGiveaways = ref(0) // 已被移除的赠品总价

let refundId = 0
onLoad((options) => {
  init() // 初始化页面数据
  refundId = options.refundId || 0
})
/**
 * 修改退款数量
 */
const showPordNumer = ref(0) // 展示的退款数量
const changePordNum = (val) => {
  // 可退总金额
  const actualTotal = new Big(refundItemList.value[0].actualTotal)
  // 可退的最大数量
  const totalCount = refundCount.value
  // 当前想要退的数量
  const currentCount = showPordNumer.value + val
  // 被移除的赠品总数
  const priceOfRemovedGiveawaysCopy = priceOfRemovedGiveaways.value || 0
  if (currentCount > totalCount) {
    uni.showToast({
      title: '退款数量不能大于购买数量',
      icon: 'none'
    })
    return
  }
  if (currentCount < 1) {
    uni.showToast({
      title: '退款数量不能小于1',
      icon: 'none'
    })
    return
  }
  Big.DP = 0
  Big.RM = 0
  const tempAmount = actualTotal.times(currentCount).div(totalCount).minus(priceOfRemovedGiveawaysCopy).valueOf()
  if (tempAmount <= 0) {
    uni.showToast({
      title: '当前数量不可减少',
      icon: 'none',
      duration: 3000
    })
    return
  }
  showPordNumer.value = currentCount
  refundAmount.value = tempAmount
  totalPrice.value = tempAmount
  showRefundAmount.value = Number(tempAmount / 100).toFixed(2)
}
/**
 * 校验金额输入框
 */
const checkRefundAmount = () => {
  if (!showRefundAmount.value) return getRefundAmount(totalPrice.value)
  const val = new Big(showRefundAmount.value).toFixed(2).valueOf()
  if (!val || val < 0.01) return getRefundAmount(totalPrice.value)

  if (val > totalPrice.value / 100) {
    uni.showToast({
      title: '金额不能超出最大可退金额',
      duration: 2000,
      icon: 'none'
    })
    getRefundAmount(totalPrice.value)
    return
  }
  showRefundAmount.value = val
  refundAmount.value = new Big(showRefundAmount.value).times(100).valueOf()
}
/**
 * 提交退款申请
 */
const showPop = ref(false)
const popContent = reactive({
  content: '本次申请的退款商品是本单最后一件商品，退款金额中包含本单运费(如有)，一旦提交申请，本单所有商品的退款申请均不可撤销，是否确认提交'
})
const buyerDesc = ref('')
const buyerMobile = ref('')
const buyerReason = ref(0)
const orderId = ref('')
const orderItemId = ref('')
const received = ref(0) // 是否已收到货
const refundAmount = ref(0)
const refundCount = ref(0)
let submitting = false // 正在提交申请
const submit = util.debounce(() => {
  // 数据校验
  if (parseInt(refundAmount.value) === 0 && parseInt(orderScore.value) === 0) {
    // 如果计算得出退款金额为0，不允许退款
    uni.showToast({
      title: '当前件数可退款金额为0元，无法进行退款操作，请重新选择退款件数',
      icon: 'none'
    })
    return
  }
  // 手机号
  if (!util.checkPhoneNumber(buyerMobile.value)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    })
    return
  }
  // 退款说明
  if (!buyerDesc.value.trim()) {
    uni.showToast({
      title: '请输入退款说明',
      icon: 'none'
    })
    return
  }
  // 输入框金额大于订单最多可退总额（金额+运费）
  if (Number(refundAmount.value) > Number(totalPrice.value)) {
    uni.showToast({
      title: '退款金额超出最大可退金额，请重新输入',
      icon: 'none'
    })
    return
  }
  // 防止重复提交
  if (submitting) return
  submitting = true

  // 退款原因: 未收货时需转换退款原因
  let buyerReasonCopy = buyerReason.value
  buyerReasonCopy = +received.value === 1 ? buyerReasonCopy : +buyerReasonCopy === 2 ? 6 : buyerReasonCopy
  // 处理退款凭证图片
  const imgUrls = []
  if (photoFiles.value.length) {
    photoFiles.value.forEach((imgItem) => {
      imgUrls.push(imgItem.path)
    })
  }
  let refundCount = 0
  refundCount = orderScore.value <= 0 ? (Number(applyType.value) === RefundApplyType.REFUND ? 0 : showPordNumer.value) : refundCount
  if (orderMold.value === 1) {
    refundCount = needWriteOffs.value ? maxRefundPieces.value : showPordNumer.value
  }
  http.request({
    url: refundId ? '/tmerclub_order/order_refund/update_refund' : '/tmerclub_order/order_refund/apply',
    method: refundId ? 'PUT' : 'POST',
    withoutPrompting: true,
    data: {
      refundId,
      applyType: applyType.value,
      buyerDesc: buyerDesc.value,
      buyerMobile: buyerMobile.value,
      buyerReason: buyerReasonCopy,
      imgUrls: imgUrls.join(','),
      orderId: orderId.value,
      orderItemId: orderItemId.value,
      received: received.value,
      refundAmount: Number(refundAmount.value),
      refundCount,
      refundType: refundType.value,
      giveawayItemIds
    }
  })
    .then((res) => {
      // 208:生成退款结算页id
      util.tapLog(6, { pid: 208, bid: res })
      setTimeout(() => {
        submitting = false
        if (refundId) {
          uni.navigateBack()
          return
        }
        uni.redirectTo({
          url: '/package-refund/pages/refund-list/refund-list'
        })
      }, 1000)
    })
    .catch(errMsg => {
      submitting = false
      showCancel.value = false
      popContent.content = errMsg.msg
      showPop.value = true
      isRefundErrorCallBackPop.value = true
    })
})
/**
 * 处理退款数据
 */
const showReasonList = ref([])
const transfee = ref(0)
const showRefundAmount = ref(0)
const actualTotal = ref(0)
const refundType = ref(RefundType.ALL) // 退款类型:  1整单退款; 2单件退款
const refundInfo = ref({})
const refundItemList = ref([]) // 所有的退款商品项
const maxRefundPieces = ref(0) // 最大可退款件数（虚拟商品：需要核销时展示）
const needWriteOffs = ref(false) // 是否需要核销
const orderMold = ref(0) // 订单模式 1虚拟商品订单
let giveawayItemIds = []
const orderScore = ref(0) // 订单使用的积分
const platformCouponAmount = ref(0) // 平台优惠券优惠金额
const memberAmount = ref(0) // 会员折扣

const init = () => {
  // 从缓存获取退款信息
  const refundInfoCopy = uni.getStorageSync('cloudRefundInfo')
  refundInfo.value = refundInfoCopy
  orderId.value = refundInfoCopy.orderId
  refundItemList.value = refundInfoCopy.orderItems
  actualTotal.value = refundInfoCopy.actualTotal
  transfee.value = refundInfoCopy.transfee
  refundType.value = +refundInfoCopy.refundType
  orderItemId.value = refundInfoCopy.refundType === RefundType.ALL ? 0 : refundInfoCopy.orderItems[0].orderItemId
  refundCount.value = refundInfoCopy.refundType === RefundType.ALL ? 0 : refundInfoCopy.orderItems[0].count
  showPordNumer.value = refundInfoCopy.refundType === RefundType.ALL ? 0 : refundInfoCopy.orderItems[0].count
  buyerMobile.value = refundInfoCopy.mobile
  if (refundType.value === 2) { // 单个
    // 赠品ids
    giveawayItemIds = refundItemList.value[0].giveawayList?.map(el => el && el.orderItemId)
  }
  if (refundType.value === 1) { // 整单退款
    refundItemList.value.forEach(el => {
      if (el.giveawayList && el.giveawayList.length) {
        // 赠品ids
        giveawayItemIds = giveawayItemIds.concat(el.giveawayList.map(el => el && el.orderItemId))
      }
    })
  }
  // 订单使用的积分
  orderScore.value = refundInfoCopy.orderScore
  platformCouponAmount.value = refundInfoCopy.platformCouponAmount
  memberAmount.value = refundInfoCopy.memberAmount
  // 设置默认展示的退款原因
  showReasonList.value = +received.value === 1 ? receivedReasonList : unReceivedReasonList
  // 订单模式 1虚拟商品订单
  orderMold.value = refundInfoCopy.orderMold ? Number(refundInfoCopy.orderMold) : 0
  // 虚拟商品
  if (orderMold.value === 1) {
    // needWriteOffs是否需要核销
    needWriteOffs.value = refundInfoCopy.needWriteOffs
    received.value = 1
    currentReceivedStatus.value = 1
    // 最大可退件数（需要核销）
    if (needWriteOffs.value) {
      maxRefundPieces.value = refundInfoCopy.maxRefundPieces ? Number(refundInfoCopy.maxRefundPieces) : 0
    }
  }
  // 计算退款金额
  getRefundAmount()
}
/**
 * 计算退款金额
 */
const totalPrice = ref(0)
const getRefundAmount = (totalAmount) => {
  const refundInfoCopy = refundInfo.value // 整个退款信息
  const refundTypeCopy = refundType.value // 退款类型 1整单  2单个物品
  // 订单总额(包含运费)
  const actualTotal = new Big(refundInfoCopy.actualTotal)
  // 实际运费
  const transfee = new Big(refundInfoCopy.transfee || 0).minus(new Big(refundInfoCopy.freeTransfee || 0))

  // 虚拟商品&需要核销：根据最多可退件数，计算最大可退金额
  if (orderMold.value === 1 && needWriteOffs.value) {
    const prodCount = refundInfoCopy.orderItems[0].count
    refundAmount.value = actualTotal.times(maxRefundPieces.value).div(prodCount).valueOf()
    totalPrice.value = refundAmount.value
    showRefundAmount.value = (totalPrice.value / 100).toFixed(2)
    return
  }

  // 用户可退金额 = 订单总额 - 实际支付运费金额
  if (refundInfoCopy.status === OrderStatus.PAYED) {
    // 待发货
    if (refundInfoCopy.status === OrderStatus.PAYED) {
      refundAmount.value = actualTotal.valueOf()
      totalPrice.value = actualTotal.valueOf()
      showRefundAmount.value = actualTotal.div(100).toFixed(2)
      // console.log(`${refundTypeCopy === RefundType.ALL ? '整单' : '单个'}退-最大可退金额: `, refundAmount.value)
    }
  } else {
    // 已发货- 都不退运费
    refundAmount.value = totalAmount > 0 ? totalAmount : refundTypeCopy === RefundType.ALL ? actualTotal.minus(transfee).valueOf() : actualTotal.times(showPordNumer.value).div(refundCount.value).valueOf()
    totalPrice.value = refundAmount.value
    showRefundAmount.value = (totalPrice.value / 100).toFixed(2)
  }
  transfee.value = parseFloat(typeof (transfee) === 'object' ? transfee.valueOf() : transfee)
}
/**
 * 更改退款理由
 */
const currentSelectReason = ref(0)
const handleChangeReason = (e) => {
  currentSelectReason.value = Number(e.detail.value)
}
/**
 * 确认修改退款理由
 */
const confirmChangeReason = () => {
  buyerReason.value = currentSelectReason.value
  isShowReasonPopup.value = false
}
/**
 * 更改售后类型
 */
const applyType = ref(RefundApplyType.REFUND) // 申请类型:  1仅退款; 2退货退款
const currentReceivedStatus = ref(0)
const handleChangeRefundType = (event) => {
  priceOfRemovedGiveaways.value = 0
  applyType.value = Number(event.detail.value)
  // 退货退款不展示“未收货”
  received.value = 0 // 默认
  currentReceivedStatus.value = 0 // 默认
  buyerReason.value = 0 // 退款原因
  currentSelectReason.value = 0 // 退款原因
  if (applyType.value === 2) {
    received.value = 1
    currentReceivedStatus.value = 1
  }
  showReasonList.value = +received.value === 1 ? receivedReasonList : unReceivedReasonList
  init()
}
/**
 * 售后类型切换不可用
 */
const refundTypeTip = () => {
  if (refundInfo.value.status === OrderStatus.PAYED) {
    uni.showToast({
      title: '订单未发货无法使用该退款方式',
      icon: 'none'
    })
  }
}
/**
 * 更改收货状态
 */
const handleChangeReceivedStatus = (e) => {
  currentReceivedStatus.value = Number(e.detail.value)
}
/**
 * 确认修改收货状态
 */
const confirmChangeReceivedStatus = () => {
  received.value = currentReceivedStatus.value
  buyerReason.value = 0
  currentSelectReason.value = 0
  showReasonList.value = +received.value === 1 ? receivedReasonList : unReceivedReasonList
  isShowCargoStatePopup.value = false
}
/**
 * 获取上传图片组件返回的图片路径
 * @param {String} urls 图片组件返回路径数组
 */
const photoFiles = ref([])
const getImgPath = (urls) => {
  if (urls) {
    photoFiles.value = urls
  }
}
/**
 * 弹窗取消
 */
const popCancel = () => {
  showPop.value = false
}
/**
 * 弹窗确认
 */
const showCancel = ref(true)
const reqParams = {}
const popConfirm = () => {
  if (!showCancel.value) {
    showCancel.value = true
  } else {
    http.request(reqParams)
  }
  showPop.value = false
  if (isRefundErrorCallBackPop.value) {
    uni.navigateBack({
      delta: 1
    })
    isRefundErrorCallBackPop.value = false
  }
}
/**
 * 货物状态弹窗
 */
const isShowCargoStatePopup = ref(false) // 货物状态弹窗
const showCargoStatePopup = () => {
  isShowCargoStatePopup.value = true
}
/**
 * 退款理由弹窗
 */
const isShowReasonPopup = ref(false) // 退款理由弹窗
const showReasonPopup = () => {
  isShowReasonPopup.value = true
}
/**
 * 关闭弹窗
 */
const closePopup = () => {
  isShowCargoStatePopup.value = false
  isShowReasonPopup.value = false
  currentSelectReason.value = buyerReason.value
  currentReceivedStatus.value = received.value
}
/**
 * 移除赠品
 */
const removeGiftItem = (index) => {
  // plus+ minus- times* div/
  // 赠品价值
  const giveawayAmount = refundItemList.value[0].giveawayList[index].giveawayAmount
  uni.showModal({
    title: '提示',
    // 移除赠品后退款金额将减去赠品价格xxx
    content: `移除赠品后退款金额将减去赠品价格￥${wxs.parsePrice(giveawayAmount)[0]}.${wxs.parsePrice(giveawayAmount)[1]}，是否确定移除？`,
    confirmText: '确定',
    cancelText: '取消',
    success: (successRes) => {
      if (successRes.confirm) {
        // 订单实际总额
        const actualTotal = new Big(refundItemList.value[0].actualTotal)
        // 商品总件数
        const prodCount = refundItemList.value[0].count
        // 当前退款件数
        const showPordNumerCopy = showPordNumer.value
        // 已被移除的赠品总价
        const priceOfRemovedGiveawaysCopy = priceOfRemovedGiveaways.value || 0
        // 当前最大可退款金额 = 订单实际总额/商品总件数*当前退款件数-已被移除的赠品总价
        const curRefundAmount = actualTotal.div(prodCount).times(showPordNumerCopy).minus(priceOfRemovedGiveawaysCopy)

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

        // 当减去当前要移除的赠品价格所得值<=0时，不允许移除
        if (giveawayAmount > 0 && totalAmount <= 0) {
          uni.showToast({
            title: '赠品金额大于订单当前可退金额，不可移除',
            icon: 'none',
            duration: 3000
          })
          return
        }

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

        // 移除
        refundItemList.value[0].giveawayList.splice(index, 1)
        giveawayItemIds.splice(index, 1)

        // 计算退款金额
        actualTotal.value = totalAmount
        getRefundAmount(totalAmount)
      }
    }
  })
}
</script>

<style scoped lang="scss">
@use "@/popup.scss";
@use './apply-refund.scss';
</style>
