<template>
  <view class="Mall4j refund-detail">
    <!-- 状态 -->
    <view class="status-box">
      <view class="bg">
        <image src="@/static/images/status-bg.jpg" />
      </view>
      <view class="text">
        <block v-if="platInterSts===platInterStsConstant.APPLY && isUserHandle">
          <view class="status">
            等待平台客服处理
          </view>
          <view class="des">
            请在{{ refundDetail.interventionEndTime }}前补充证据，商家补充凭证可在售后进度中查看
          </view>
        </block>
        <block v-if="platInterSts===platInterStsConstant.APPLY && isPlatHandle">
          <view class="status">
            平台客服处理中
          </view>
          <view class="des">
            平台客服将在{{ refundDetail.platformProcessingEndTime }}前处理
          </view>
        </block>
        <block v-if="platInterSts===platInterStsConstant.AGREE">
          <view class="status">
            进行中
          </view>
          <view class="des">
            平台同意退款，请您耐心等待
          </view>
        </block>
        <block v-if="(platInterSts===platInterStsConstant.APPLY && !isUserHandle && !isPlatHandle) || platInterSts===platInterStsConstant.REJECT">
          <view class="status">
            已关闭
          </view>
          <view class="des">
            平台拒绝退款，退款已关闭
          </view>
        </block>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.APPLY"
          class="status"
        >
          进行中
        </view>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.APPLY"
          class="des"
        >
          您已提交申请，等待商家同意
        </view>
        <!-- 退货退款 -->
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.PROCESSING && applyType===applyTypeConstant.REFUND_AND_RETURNS"
          class="status"
        >
          待处理
        </view>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.PROCESSING && applyType===applyTypeConstant.REFUND_AND_RETURNS"
          class="des"
        >
          商家同意退货，请您填写物流单号
        </view>
        <!-- 仅退款：退款未到帐时 -->
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.PROCESSING && applyType===applyTypeConstant.REFUND"
          class="status"
        >
          进行中
        </view>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.PROCESSING && applyType===applyTypeConstant.REFUND"
          class="des"
        >
          商家同意退款，请您耐心等待
        </view>
        <!-- 仅退款：退款未到帐时 end -->
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.CONSIGNMENT"
          class="status"
        >
          进行中
        </view>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.CONSIGNMENT && applyType===applyTypeConstant.REFUND"
          class="des"
        >
          商家同意退款，请您耐心等待
        </view>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.CONSIGNMENT && applyType===applyTypeConstant.REFUND_AND_RETURNS"
          class="des"
        >
          您已退货，等待卖家收货
        </view>
        <block v-if="returnMoneySts===returnMoneyStsConstant.SUCCESS || platInterSts===platInterStsConstant.REFUND_SUCCEED">
          <view class="status">
            已完成
          </view>
          <view class="des">
            退款已完成，感谢您的支持
          </view>
        </block>

        <block v-if="returnMoneySts===returnMoneyStsConstant.FAIL && closeType===closeTypeConstant.CANCEL">
          <view class="status">
            已取消
          </view>
          <view class="des">
            您已撤销申请，感谢支持
          </view>
        </block>
        <block v-if="platInterSts===platInterStsConstant.NONE && returnMoneySts===returnMoneyStsConstant.FAIL && closeType===closeTypeConstant.DISAGREE">
          <view class="status">
            已拒绝
          </view>
          <view class="des">
            商家已拒绝您的退款申请
          </view>
        </block>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.FAIL && closeType===closeTypeConstant.TIME_OUT"
          class="status"
        >
          已关闭
        </view>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.FAIL && closeType===closeTypeConstant.TIME_OUT"
          class="des"
        >
          您未及时处理，退款已关闭
        </view>
      </view>
    </view>

    <!-- 售后进度 -->
    <view
      class="refund-progress text-arrow"
      @tap="toRefundProgress"
    >
      售后进度
    </view>

    <!-- 退货地址（仅退款时不出现，商家同意退货才出现） -->
    <view
      v-if="applyType===applyTypeConstant.REFUND_AND_RETURNS && returnMoneySts>=returnMoneyStsConstant.PROCESSING"
      class="refund-address"
    >
      <view class="tit">
        寄件地址
      </view>
      <view class="user">
        <view class="name">
          {{ orderRefundAddr.consigneeName }}
        </view>
        <view class="phone">
          {{ orderRefundAddr.consigneeMobile }}
        </view>
      </view>
      <view class="address">
        {{ orderRefundAddr.consigneeAddr }}
      </view>
    </view>

    <!-- 退货物流（填了物流单号之后出现） -->
    <view
      v-if="applyType===applyTypeConstant.REFUND_AND_RETURNS && returnMoneySts===returnMoneyStsConstant.CONSIGNMENT"
      class="refund-logistics"
    >
      <view class="tit">
        退货物流
      </view>
      <view class="logistics">
        <view class="name">
          {{ orderRefundAddr.deliveryName }}
        </view>
        <view class="number">
          {{ orderRefundAddr.deliveryNo }}
        </view>
        <view
          class="change"
          @tap="toReturnLogistics(1)"
        >
          修改
        </view>
      </view>
    </view>

    <!-- 退款信息 -->
    <view class="refund-info">
      <view class="refund-tit">
        退款信息
      </view>
      <view
        v-for="(refundProdItem, prodIndex) in refundDetail.orderItems"
        :key="prodIndex"
        class="prod-info"
      >
        <view class="prod">
          <view class="img">
            <img-show
              :src="refundProdItem.pic"
              img-mode="aspectFit"
            />
          </view>
          <view class="text-box">
            <view class="name">
              {{ refundProdItem.spuName }}
            </view>
            <view class="sku-name">
              {{ refundProdItem.skuName || '' }}
            </view>
            <view class="number">
              申请数量：{{ refundDetail.refundType === 1 ? refundProdItem.count : refundCount }}
            </view>
          </view>
        </view>
        <!-- 组合：多个商品时展示 -->
        <view
          v-if="refundProdItem.comboList && refundProdItem.comboList.length"
          class="gift-prods"
        >
          <view
            v-for="(comboItem, comboItemIndex) in refundProdItem.comboList"
            :key="comboItemIndex"
            class="gift-item"
          >
            <text
              class="name"
            >
              【组合】{{ comboItem.spuName }}{{ comboItem.skuName ? ('&nbsp;&nbsp;' + comboItem.skuName) : '' }}
            </text>
            <text class="num">
              ×{{ comboItem.count }}
            </text>
          </view>
        </view>

        <!-- 赠品：多个商品时展示 -->
        <view
          v-if="
            refundDetail.orderItems.length > 1 &&
              refundProdItem.giveawayList &&
              refundProdItem.giveawayList.length
          "
          class="gift-prods"
        >
          <view
            v-for="(giftItem, giftItemIndex) in refundProdItem.giveawayList"
            :key="giftItemIndex"
            class="gift-item"
          >
            <text
              class="name"
            >
              【赠品】{{ giftItem.spuName }}
            </text>
            <text v-if="giftItem.skuName">
              {{ giftItem.skuName }}
            </text>
            <text class="num">
              ×{{ giftItem.count }}
            </text>
          </view>
        </view>
      </view>
      <!-- 赠品：单个商品时展示 -->
      <block
        v-if="
          refundDetail.orderItems &&
            refundDetail.orderItems.length === 1 &&
            refundDetail.orderItems[0].giveawayList &&
            refundDetail.orderItems[0].giveawayList.length
        "
      >
        <view
          v-for="(item, itemIndex) in refundDetail.orderItems[0].giveawayList"
          :key="itemIndex"
          class="prod-info"
        >
          <view class="prod">
            <view class="img">
              <img-show
                :src="item.pic.indexOf('http') === -1? picDomain + item.pic: item.pic"
                img-mode="aspectFit"
              />
            </view>
            <view class="text-box">
              <view class="name">
                {{ item.spuName }}
              </view>
              <view class="sku-name">
                <text class="sku gift-icon">
                  赠品
                </text>
                <text
                  v-if="item.skuName"
                  class="sku"
                >
                  {{ item.skuName }}
                </text>
                <text class="sku">
                  ×{{ item.count }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </block>
      <view class="refund-item">
        <view class="tit">
          退款编号：
        </view>
        <view class="text">
          {{ refundId }}
        </view>
        <view
          class="copy"
          @tap="copy"
        >
          复制
        </view>
      </view>
      <view class="refund-item">
        <view class="tit">
          申请时间：
        </view>
        <view class="text">
          {{ refundDetail.createTime }}
        </view>
      </view>
      <view class="refund-item">
        <view class="tit">
          退款方式：
        </view>
        <view class="text">
          {{ applyType === applyTypeConstant.REFUND ? '仅退款': '退货退款' }}
        </view>
      </view>
      <view class="refund-item">
        <view class="tit">
          退款金额：
        </view>
        <view class="price">
          <text v-if="refundDetail.refundAmount > 0">
            ￥{{ wxs.parsePrice(refundDetail.refundAmount)[0] }}.{{ wxs.parsePrice(refundDetail.refundAmount)[1] }}
          </text>
          <text v-if="refundDetail.refundAmount > 0 && refundDetail.refundScore > 0">
            +
          </text>
          <text v-if="refundDetail.refundScore > 0">
            {{ refundDetail.refundScore }}
          </text>
          <text
            v-if="refundDetail.refundScore > 0"
            class="score-apart"
          >
            积分
          </text>
        </view>
      </view>
      <view class="refund-item">
        <view class="tit">
          退款原因：
        </view>
        <view class="text">
          {{ refundDetail.buyerReasonValue }}
        </view>
      </view>
      <view class="refund-item">
        <view class="tit">
          退款说明：
        </view>
        <view class="text">
          {{ refundDetail.buyerDesc }}
        </view>
      </view>
      <view
        v-if="imgs && imgs.length"
        class="refund-item"
      >
        <view class="tit">
          退款凭证：
        </view>
        <view class="text">
          <view class="refund-imgs">
            <block
              v-for="(img, index) in imgs"
              :key="index"
            >
              <image
                v-if="img"
                :src="util.addDomain(img)"
                mode="aspectFill"
                :data-cur="img"
                @tap="refundPicPreView"
                @error="handlePicError($event, index)"
              />
              <image
                v-else
                src="@/static/images/def.png"
                mode="aspectFit"
              />
            </block>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部 -->
    <view class="foot-box">
      <view class="btn-box">
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.APPLY || applyType===applyTypeConstant.REFUND_AND_RETURNS && returnMoneySts===returnMoneyStsConstant.PROCESSING"
          class="btn"
          @tap="toContact"
        >
          联系客服
        </view>
        <view
          v-if="returnMoneySts===returnMoneyStsConstant.APPLY || (platInterSts===platInterStsConstant.APPLY && isUserHandle)"
          class="btn"
          @tap="onHandleRepeal"
        >
          撤销申请
        </view>
        <view
          v-if="applyType===applyTypeConstant.REFUND_AND_RETURNS && returnMoneySts===returnMoneyStsConstant.PROCESSING"
          class="btn btn-r"
          @tap="toReturnLogistics('')"
        >
          填写物流
        </view>
        <!-- 卖家拒绝退款时 -->
        <view
          v-if="canApplyPlatInter&&closeType===closeTypeConstant.DISAGREE && platInterSts===platInterStsConstant.NONE"
          class="btn btn-r"
          @tap="onApplyPlayIntervene(1)"
        >
          申请平台介入
        </view>
        <view
          v-if="platInterSts===platInterStsConstant.APPLY && isUserHandle"
          class="btn"
          @tap="onApplyPlayIntervene(2)"
        >
          补充凭证
        </view>
        <view
          v-if="platInterSts===platInterStsConstant.APPLY && isUserHandle"
          class="btn"
          @tap="onToApplyRefund"
        >
          修改申请
        </view>
      </view>
    </view>

    <!-- 售后进度弹窗 -->
    <refundProgress
      v-model="showRefundProgress"
      :refund-detail="refundDetail"
    />

    <!-- 全局确认弹窗 -->
    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-cancel="popCancel"
      @handle-pop-confirm="popConfirm"
    />
  </view>
</template>

<script setup>
import util from '@/utils/util.js'
import { ReturnMoneySts, RefundApplyType, RefundCloseType, PlatInterveneSts } from '@/utils/constant'
import uniCopy from '@/js_sdk/uni-copy'
import refundProgress from '../../components/refund-progress/index.vue'
const wxs = number()
const returnMoneyStsConstant = ReturnMoneySts
const applyTypeConstant = RefundApplyType
const closeTypeConstant = RefundCloseType
const platInterStsConstant = PlatInterveneSts

const refundId = ref('') // 退款编号
onLoad(option => {
  refundId.value = option.refundId
})

onShow(() => {
  getRefundDetail()
})

onUnload(() => {
  intervenEndTimer && clearTimeout(intervenEndTimer)
  intervenFinishTimer && clearTimeout(intervenFinishTimer)
})

onUnmounted(() => {
  if (isShowPreview) {
    uni.closePreviewImage({
      success: () => {
        isShowPreview = false
      }
    })
  }
})

const showPop = ref(false) // 确认弹窗显隐
const popContent = reactive({
  content: '确认要撤销退款申请吗？'
})
let repealType = 0
/**
 * 处理撤销
 */
const onHandleRepeal = () => {
  if (returnMoneySts.value === returnMoneyStsConstant.APPLY) { // 退款申请
    repealType = 1
    popContent.content = '确认要撤销退款申请吗？'
  } else if (platInterSts.value === platInterStsConstant.APPLY) {
    repealType = 2
    popContent.content = '确认要撤销平台介入申请吗？'
  }
  showPop.value = true
}
/**
 * 弹窗确认事件
 */
const popConfirm = () => {
  showPop.value = false
  cancelRefund()
}
/**
 * 弹窗取消事件
 */
const popCancel = () => {
  showPop.value = false
}

/**
 * 跳转到填写退货物流页面
 */
const toReturnLogistics = (isEdit) => {
  if (isEdit) {
    uni.setStorageSync('cloudRefundLogistics', refundDetail.value.orderRefundAddr)
  }
  uni.redirectTo({
    url: '/package-refund/pages/refund-logistics/refund-logistics?refundId=' + refundId.value + '&isEdit=' + isEdit
  })
}
/**
 * 撤销申请
 */
const cancelRefund = () => {
  // 1.撤销退款申请 2.撤销平台介入申请
  let url
  let submitData
  if (repealType === 1) {
    url = '/mall4cloud_order/order_refund/cancel'
    submitData = refundId.value
  } else if (repealType === 2) {
    url = '/mall4cloud_order/order_refund/cancel_platform_intervention'
    submitData = { refundId: refundId.value }
  }
  http.request({
    url,
    method: 'PUT',
    data: submitData
  }).then(() => {
    uni.showToast({
      title: '撤销成功~',
      mask: true,
      icon: 'none'
    })
    getRefundDetail()
  })
}
/**
 * 复制退款编号
 */
const copy = () => {
  uniCopy({
    content: refundId.value,
    success: () => {
      uni.showToast({
        title: '复制成功~',
        icon: 'none'
      })
    },
    error: (e) => {
      uni.showToast({
        title: e,
        icon: 'none',
        duration: 3000
      })
    }
  })
}
/**
 * 获取退款详情
 */
const picDomain = import.meta.env.VITE_APP_RESOURCES_URL
const refundDetail = ref({})
const returnMoneySts = ref(0) // 退款状态
const applyType = ref(0) // 退货退款类型
const closeType = ref(0) // 退款关闭类型
const platInterSts = ref(0) // 平台介入状态
const canApplyPlatInter = ref(false) // 是否可以申请平台介入
const refundCount = ref(0) // 申请退款数量(单件退-退货退款才有)
const isReceived = ref(0) // 商家收货状态
const orderRefundAddr = ref({}) // 退货地址
const imgs = ref([]) // 退款凭证图片
let shopId = null // 店铺id
let orderId = null // 订单编号
const getRefundDetail = () => {
  http.request({
    url: '/mall4cloud_order/order_refund/info',
    method: 'GET',
    data: {
      refundId: refundId.value
    }
  })
    .then(res => {
      imgs.value = []
      if (res.imgUrls) {
        res.imgUrls.split(',').forEach(img => {
          imgs.value.push(picDomain + img)
        })
      }
      refundDetail.value = res
      returnMoneySts.value = res.returnMoneySts
      applyType.value = res.applyType
      closeType.value = res.closeType
      platInterSts.value = res.platformInterventionStatus // 平台介入状态
      canApplyPlatInter.value = res.canApplyRefund // 平台介入状态
      orderRefundAddr.value = res.orderRefundAddr
      refundCount.value = res.refundCount
      shopId = res.shopId
      orderId = res.orderId
      isReceived.value = res.isReceived // 收货状态
      // 处理平台介入时间相关操作
      if (res.platformInterventionStatus === 1) {
        const nowTime = new Date().getTime() // 当前时间
        if (res.interventionEndTime) {
          const endTime = new Date(res.interventionEndTime).getTime() // 添加凭证结束时间
          endTime - nowTime > 0 && intervenEndTimeCountdown()
          if (endTime - nowTime < 0 && res.platformProcessingEndTime) {
            const finishTime = new Date(res.platformProcessingEndTime).getTime() // 平台处理介入结束时间
            finishTime - nowTime > 0 && intervenFinishTimeCountdown()
          }
        }
      }
    })
}

// 添加凭证时间结束倒计时
let intervenEndTimer = null
const isUserHandle = ref(false) // 是否为用户处理介入中
const intervenEndTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(refundDetail.value.interventionEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    isUserHandle.value = true
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenEndTimer = setTimeout(intervenEndTimeCountdown, 1000)
  } else {
    isUserHandle.value = false
    intervenEndTimer && clearTimeout(intervenEndTimer)
    getRefundDetail() // 重新获取详情
  }
}
// 平台介入结束时间倒计时
let intervenFinishTimer = null
const isPlatHandle = ref(false) // 是否为平台处理介入中
const intervenFinishTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(refundDetail.value.platformProcessingEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    isPlatHandle.value = true
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenFinishTimer = setTimeout(intervenFinishTimeCountdown, 1000)
  } else {
    isPlatHandle.value = false
    intervenFinishTimer && clearTimeout(intervenFinishTimer)
    setTimeout(() => {
      getRefundDetail() // 重新获取详情
    }, 2000)
  }
}

/**
 * 联系客服
 */
const toContact = () => {
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url: '/package-user/pages/my-chat/my-chat?shopid=' + shopId + '&orderNumber=' + orderId
    })
  })
}
/**
 * 申请平台介入|补充凭证
 * @params {Number} type 跳转页面类型 1:申请 2:补充凭证
 */
const onApplyPlayIntervene = (type) => {
  uni.setStorageSync('cloudRefundDetail', JSON.stringify(refundDetail.value))
  uni.navigateTo({
    url: `/package-refund/pages/plat-intervene/plat-intervene?pageType=${type}`
  })
}

// 修改申请售后
let isApplyRefundFlag = false
const onToApplyRefund = () => {
  if (isApplyRefundFlag) return
  isApplyRefundFlag = true
  http.request({
    url: '/mall4cloud_order/my_order/order_detail',
    method: 'GET',
    data: {
      orderId
    }
  }).then((res) => {
    const refundInfo = {}
    refundInfo.orderId = orderId
    refundInfo.transfee = res.transfee
    refundInfo.freeTransfee = res.freeFreightAmount || res.platformFreeFreightAmount // 运费减免
    refundInfo.status = res.status
    refundInfo.canRefundAmount = res.canRefundAmount
    refundInfo.mobile = refundDetail.value.buyerMobile
    refundInfo.orderMold = res.orderMold || 0
    refundInfo.refundType = refundDetail.value.refundType // 退款类型
    // 整单退款
    if (refundInfo.refundType === 1) {
      refundInfo.actualTotal = res.actualTotal
      refundInfo.orderItems = res.orderItems
      refundInfo.canRefundTransfee = res.status === OrderStatus.PAYED ? !refundInfo.freeTransfee : false
      refundInfo.orderScore = res.orderScore
    } else if (refundInfo.refundType === 2) {
      const curProdOrder = res.orderItems.find(item => item.spuId === refundDetail.value.orderItems[0].spuId)
      // 单件退
      refundInfo.actualTotal = curProdOrder.actualTotal
      refundInfo.orderItems = [JSON.parse(JSON.stringify(curProdOrder))]
      refundInfo.orderScore = curProdOrder.useScore || 0
      // 虚拟商品
      if (refundInfo.orderMold === 1) {
        // 1.无需核销：允许用户选择退款数量（writeOffNum 0无需核销 -1多次核销 1单次核销）
        refundInfo.needWriteOffs = res.writeOffNum !== 0
        // 2.需要核销：展示最大可退款件数，不允许选择（最大可退款件数 = 待使用的核销券数）
        refundInfo.maxRefundPieces = res.virtualInfoList?.filter(it => it.isWriteOff === 0).length || 0
      }
    }
    uni.setStorageSync('cloudRefundInfo', refundInfo)
    uni.navigateTo({
      url: '/package-refund/pages/apply-refund/apply-refund?refundId=' + refundId.value
    })
    isApplyRefundFlag = false
  })
}

/**
 * 售后进度
 */
const showRefundProgress = ref(false) // 售后进度弹窗显隐
const toRefundProgress = () => {
  showRefundProgress.value = true
}

/**
 * 图片错误显示默认图片
 */
// eslint-disable-next-line no-unused-vars
const handlePicError = (event, index) => {
  // 替换默认图
  imgs.value = imgs.map((item, idx) => idx === index ? null : item)
}

let isShowPreview = false
/**
 * 退款凭证 图片点击预览
 */
const refundPicPreView = (e) => {
  const current = e.currentTarget.dataset.cur
  uni.previewImage({
    current,
    urls: imgs.value,
    success: () => {
      isShowPreview = true
    }
  })
}
</script>

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