<template>
  <view class="Mall4j page-plat-intervene">
    <view class="refund-explain">
      <view class="label">
        {{ pageType===1?'申请理由':'凭证说明' }}
      </view>
      <textarea
        v-model="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"
      >
        {{ pageType === 1 ? '提交申请' : '提交' }}
      </view>
    </view>
  </view>
</template>

<script setup>
import util from '@/utils/util'

const pageType = ref(1) // 1.申请介入 2.补充凭证
let refundDetail
onLoad((options) => {
  refundDetail = JSON.parse(uni.getStorageSync('cloudRefundDetail'))
  pageType.value = +options.pageType
  uni.setNavigationBarTitle({
    title: pageType.value === 1 ? '申请客服介入' : '补充凭证'
  })
})

const buyerDesc = ref('')
let isSubmit = false // 正在提交申请
const submit = util.debounce(() => {
  // 处理退款凭证图片
  const imgUrls = []
  if (photoFiles.value.length) {
    photoFiles.value.forEach((imgItem) => {
      imgUrls.push(imgItem.path)
    })
  }

  if (!buyerDesc.value.trim()) {
    const tempTxt = pageType.value === 1 ? '申请理由' : '凭证说明'
    uni.showToast({
      title: tempTxt + '不能为空',
      icon: 'none'
    })
    return
  }
  if (!imgUrls.length) {
    uni.showToast({
      title: '请上传凭证',
      icon: 'none'
    })
    return
  }

  let url = '/mall4cloud_order/order_refund/apply_platform_intervention' // 申请平台客服介入
  if (pageType.value === 2) {
    url = '/mall4cloud_order/order_refund_intervention/save_intervention_voucher' // 补充凭证
  }
  // 防止重复提交
  if (isSubmit) return
  isSubmit = true
  http.request({
    url,
    method: 'PUT',
    data: {
      refundId: refundDetail.refundId,
      sysType: 0,
      refundSts: refundDetail.refundStatus,
      voucherDesc: buyerDesc.value,
      imgUrls: imgUrls.join(',')
    }
  }).then(() => {
    uni.showToast({
      title: pageType.value === 1 ? '申请成功' : '提交成功',
      icon: 'none'
    })
    setTimeout(() => {
      isSubmit = false
      uni.navigateBack({
        delta: 1
      })
    }, 1000)
  }).catch(() => {
    isSubmit = false
  })
}, 600)

/**
 * 获取上传图片组件返回的图片路径
 * @param {String} urls 图片组件返回路径数组
 */
const photoFiles = ref([])
const getImgPath = (urls) => {
  if (urls) {
    photoFiles.value = urls
  }
}

</script>

<style scoped lang="scss">
  @use './plat-intervene.scss';
</style>
