<!-- 虚拟商品-查看券码 -->
<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-view-voucher-code">
    <view class="card-vouchers card-model">
      <!-- 券码信息 -->
      <view class="top-half item">
        <view class="prod-name">
          {{ voucherCodeInfo.orderItems[0].spuName }}
        </view>
        <view class="total-num">
          <text class="weak">
            总金额：
          </text>￥{{ wxs.parsePrice(voucherCodeInfo.actualTotal)[0] + '.' + wxs.parsePrice(voucherCodeInfo.actualTotal)[1] }}（{{ voucherCodeInfo.virtualInfoList.length }}张）
        </view>
        <view class="expiry-date">
          <view class="lf weak">
            有效期：
          </view>
          <view class="rg">
            <text v-if="voucherCodeInfo.writeOffStart && !voucherCodeInfo.writeOffEnd">
              购买后长期有效
            </text>
            <text v-if="voucherCodeInfo.writeOffStart && voucherCodeInfo.writeOffEnd">
              {{ voucherCodeInfo.writeOffStart + '至' + voucherCodeInfo.writeOffEnd }}
            </text>
          </view>
        </view>
      </view>
      <!-- 条码 & 二维码 -->
      <view class="bottom-half">
        <!-- 条码 -->
        <view class="bar-code">
          <w-barcode :options="barOpations" />
        </view>
        <!-- <view class="code-number">{{ voucherCodeInfo.orderNumber }}</view> -->
        <view class="tips weak">
          为保障您的权益，未消费前请不要将二维码/条形码提供给商家
        </view>
        <!-- 二维码 -->
        <view class="qr-code">
          <view class="code">
            <image
              :src="orderNumQrCode"
              @longpress="downloadImg(orderNumQrCode)"
            />
          </view>
          <view class="qicode-tips">
            长按二维码保存到相册
          </view>
        </view>
      </view>
    </view>

    <!-- 使用情况 -->
    <view class="code-list">
      <!-- 已过期券码列表 -->
      <view
        v-if="unusedCodeList && unusedCodeList.length && timeLine"
        class="code-item"
      >
        <view class="text">
          已过期（{{ unusedCount }}张）
        </view>
        <view class="text-list">
          <view
            v-for="(unusedItem, unusedIndex) in unusedCodeList"
            :key="unusedIndex"
            class="text"
          >
            券码{{ unusedItem.index }}：{{ codeFormat(unusedItem.writeOffCode) }}
          </view>
        </view>
      </view>
      <!-- 未使用券码列表 -->
      <view
        v-if="unusedCodeList && unusedCodeList.length && !timeLine"
        class="code-item"
      >
        <view class="text">
          待使用（{{ unusedCount }}张）
        </view>
        <view class="text-list">
          <view
            v-for="(unusedItem, unusedIndex) in unusedCodeList"
            :key="unusedIndex"
            class="text"
          >
            券码{{ unusedItem.index }}：{{ codeFormat(unusedItem.writeOffCode) }}
          </view>
        </view>
      </view>
      <!-- 已使用券码列表 -->
      <view
        v-if="usedCodeList && usedCodeList.length"
        class="code-item used"
      >
        <view class="text">
          已使用（{{ usedCodeList.length }}张）
        </view>
        <view class="text-list">
          <view
            v-for="(usedItem, usedIndex) in usedCodeList"
            :key="usedIndex"
            class="text"
          >
            <text class="used-code">
              券码{{ usedItem.index }}：<text class="code">
                {{ codeFormat(usedItem.writeOffCode) }}
              </text>
            </text>
            <text class="right">
              {{ usedItem.writeOffTime }}
            </text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import Qr from '@/utils/wxqrcode.js'
const wxs = number()

const voucherCodeInfo = ref({})
// 条码
const barOpations = reactive({
  height: 150,
  width: 610,
  code: '' // 码值
})

// 未使用总数
const unusedCount = ref(0)
// 未使用列表
const unusedCodeList = ref([])
// 已使用列表
const usedCodeList = ref([])
const timeLine = ref(null)

let getStatusS = null

const codeFormat = computed(() => {
  return function (code) {
    return code.substring(0, 3) + ' ' + code.substring(3, 6) + ' ' + code.substring(6, 9)
  }
})
/**
 * 生命周期函数--监听页面加载
 */
onLoad(() => {
  voucherCodeInfo.value = uni.getStorageSync('cloudVoucherCodeInfo')
  // 计算未使用券总数
  if (voucherCodeInfo.value.virtualInfoList.length) {
    let _unusedCount = 0
    const _unusedCodeList = []
    const _usedCodeList = []
    voucherCodeInfo.value.virtualInfoList.forEach((el, index) => {
      el.index = index + 1
      if (el.isWriteOff === 0) {
        _unusedCount = _unusedCount + 1
        _unusedCodeList.push(el)
      } else if (el.isWriteOff === 1) {
        _usedCodeList.push(el)
      }
    })
    unusedCount.value = _unusedCount
    unusedCodeList.value = _unusedCodeList
    usedCodeList.value = _usedCodeList
  }

  // 计算有无过期
  if (voucherCodeInfo.value.writeOffEnd) {
    const writeOffEndTime = new Date(voucherCodeInfo.value.writeOffEnd).getTime()
    const nowTime = new Date().getTime()
    if (nowTime > writeOffEndTime) {
      timeLine.value = true
    }
  }
  barOpations.code = voucherCodeInfo.value.orderNumber
  getQrcode(voucherCodeInfo.value.orderNumber)
})

onShow(() => {
  clearGetStatus()
  getStatus()
})

onHide(() => {
  clearGetStatus()
})
const orderNumQrCode = ref('')
const getQrcode = (code) => {
  orderNumQrCode.value = Qr.createQrCodeImg(code)
}
const clearGetStatus = () => {
  if (getStatusS) {
    clearInterval(getStatusS)
  }
}

// 获取订单核销状态
const getStatus = () => {
  const params = {
    url: '/mall4cloud_order/my_order/get_order_status',
    method: 'GET',
    selfLoading: true,
    data: {
      orderId: voucherCodeInfo.value.orderNumber
    }
  }
  getStatusS = setInterval(() => {
    http.request(params).then((res) => {
      let unusedCount = 0
      if (res.virtualInfoList && res.virtualInfoList.length) {
        res.virtualInfoList.forEach((el) => {
          if (el.isWriteOff === 0) {
            unusedCount = unusedCount + 1
          }
        })
      }
      if (res.status === 5 && unusedCount === 0) {
        clearInterval(getStatusS)
        uni.navigateBack({
          delta: 1
        })
      }
    })
  }, 1000)
}
/**
 * 保存图片至相册
 */
const downloadImg = (qrcodeImg) => {
  uni.showLoading({
    // #ifndef MP-TOUTIAO
    mask: true
    // #endif
  })
  // #ifdef APP-PLUS
  const bitmap = new plus.nativeObj.Bitmap('test')
  bitmap.loadBase64Data(
    qrcodeImg,
    () => {
      const url = '_doc/' + new Date() + '.png' // url建议用时间戳命名方式
      bitmap.save(
        url,
        {
          overwrite: true
        },
        () => {
          uni.saveImageToPhotosAlbum({
            filePath: url,
            success: () => {
              uni.hideLoading()
              uni.showToast({
                title: '已保存至相册'
              })
              bitmap.clear()
            }
          })
        },
        () => {
          uni.hideLoading()
          // alert('保存失败1111', JSON.stringify(e))
          bitmap.clear()
        }
      )
    },
    () => {
      // alert('保存失败2222', JSON.stringify(e))
      uni.hideLoading()
      bitmap.clear()
    }
  )
  // #endif
  // #ifdef MP-WEIXIN
  wx.getImageInfo({
    src: qrcodeImg,
    success: (res) => {
      const path = res.path
      wx.saveImageToPhotosAlbum({
        filePath: path,
        // eslint-disable-next-line no-unused-vars
        success: (res) => {
          // console.log('保存图片成功res:', res)
          wx.showToast({
            title: '已保存至相册'
          })
        },
        // eslint-disable-next-line no-unused-vars, n/handle-callback-err
        fail: (err) => {
          uni.hideLoading()
          // console.log('保存图片失败err:', err)

          // 获取授权信息
          wx.getSetting({
            success (res) {
              if (!res.authSetting['scope.writePhotosAlbum']) {
                wx.showModal({
                  title: '提示',
                  content: '保存失败，请授权相关访问权限',
                  success (res) {
                    if (res.confirm) {
                      // console.log('用户点击确定')
                      // 打开授权设置
                      wx.openSetting({
                        // eslint-disable-next-line no-unused-vars
                        success (res) {
                          // console.log(res.authSetting)
                        }
                      })
                    } else if (res.cancel) {
                      // console.log('用户点击取消')
                    }
                  }
                })
              }
            }
          })
        }
      })
    },
    // eslint-disable-next-line no-unused-vars, n/handle-callback-err
    fail: (err) => {
      // console.log('获取图片信息失败err:', err)
      uni.hideLoading()
    }
  })
  // #endif
}

/**
   * 生命周期函数--监听页面卸载
   */
onUnload(() => {
  clearGetStatus()
  uni.removeStorageSync('cloudVoucherCodeInfo')
})

</script>

<style lang="scss" scoped>
@use "./voucher-code.scss";
</style>
