OrderPopup.js 6.8 KB
// components/OrderPopup/OrderPopup.js
import api from '~/api/api.js'
Component({
  /**
   * 组件的属性列表
   */
  options: {
    styleIsolation: 'shared', // 自定义覆盖vant样式 
  },
  properties: {
    show: Boolean,
    orderType: {
      type: String,
      observer: function (n) {
      }
    },
    resetTransNo: String,
    resetOrder: Boolean,
    orderInfo: Object
  },

  /**
   * 组件的初始数据
   */
  data: {
    textareaValue: '',
    routerBack: null,
    outTradeNo: '',
    payVoucherList: []
  },

  /** 组件生命周期 */
  lifetimes: {
    attached: function () {
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    async tryClear4logCacheOnce() {
      // 某些调试/日志组件会把日志写到 USER_DATA_PATH/4log,文件过大时会触发
      // writeFile:fail the maximum size of the file storage limit is exceeded
      // 进而导致选图/上传等流程异常。这里做一次兜底清理,不影响正常业务。
      if (this.__cleared4logOnce) return
      this.__cleared4logOnce = true
      const fs = wx.getFileSystemManager()
      const baseDir = `${wx.env.USER_DATA_PATH}/4log`

      const safeReaddir = dirPath =>
        new Promise(resolve => {
          fs.readdir({
            dirPath,
            success: res => resolve(res?.files || []),
            fail: () => resolve([])
          })
        })

      const safeUnlink = filePath =>
        new Promise(resolve => {
          fs.unlink({
            filePath,
            complete: () => resolve()
          })
        })

      const files = await safeReaddir(baseDir)
      if (!files.length) return
      // 只删除该目录下的文件(不递归删子目录,避免误删)
      await Promise.all(
        files.map(name => safeUnlink(`${baseDir}/${name}`))
      )
    },
    noScroll() { },
    close() {
      let thisPage = wx.$router.getPageInstance()
      let { routerBack } = this.data
      if (routerBack) {
        wx.navigateBack()
        return
      }
      this.setData({
        show: false
      })
      // 点击关闭 情况门店付款数据
      thisPage.setData({
        showPopup: false,
        // ['orderInfo.transactionNo']: '',
        // ['orderInfo.tradeNo']: '',
        ['orderInfo.paymentDocList']: []
      })
    },
    input(e) {
      let { value } = e.detail
      let val = value.replace(/[\u4E00-\u9FA5]/g, '')
      this.setData({
        outTradeNo: val
      })
    },
    // 上传付款凭证
    async upLoad(event) {
      let _this = this
      let { payVoucherList } = _this.data
      const { file } = event.detail
      let tempFiles = file?.url
      if (!tempFiles) return wx.$util.showToast('请选择图片')

      let imgType = tempFiles.split('.')[1]
      let type = imgType == 'unknown' ? 'jpg' : imgType

      const fs = wx.getFileSystemManager()
      const readBase64 = () =>
        new Promise((resolve, reject) => {
          fs.readFile({
            filePath: tempFiles,
            encoding: 'base64',
            success: res => resolve(res?.data),
            fail: err => reject(err)
          })
        })

      try {
        wx.$util.showLoading('上传中...')
        const base64 = await readBase64()
        const img = await api.uploadImg({
          file: `${type}@${base64}`
        })
        wx.$util.hideLoading()
        const { code, data, message } = img || {}
        if (code == 0) {
          payVoucherList.push({ url: data })
          _this.setData({ payVoucherList })
        } else {
          wx.$util.showToast(message || '上传失败')
        }
      } catch (err) {
        wx.$util.hideLoading()
        const msg = err?.errMsg || ''
        // 本地存储满:尝试清理日志缓存后重试一次
        if (msg.includes('maximum size of the file storage limit is exceeded')) {
          await this.tryClear4logCacheOnce()
          try {
            wx.$util.showLoading('上传中...')
            const base64 = await readBase64()
            const img = await api.uploadImg({
              file: `${type}@${base64}`
            })
            wx.$util.hideLoading()
            const { code, data, message } = img || {}
            if (code == 0) {
              payVoucherList.push({ url: data })
              _this.setData({ payVoucherList })
              return
            }
            wx.$util.showToast(message || '上传失败')
            return
          } catch (err2) {
            wx.$util.hideLoading()
          }
        }
        wx.$util.showToast(msg || '读取图片失败,请稍后重试')
      }
    },
    // 删除上传
    deletePayVoucher(e) {
      let { index } = e?.detail
      let _this = this
      let { payVoucherList } = _this.data
      payVoucherList.splice(index, 1)
      this.setData({
        payVoucherList
      })
    },
    changeOrderSource(e) {
      console.log(e)
      let { index } = e.currentTarget.dataset
      let { orderTypeList } = this.data
      orderTypeList.map(i => (i.active = false))
      orderTypeList[index].active = true
      this.setData({
        orderTypeList
      })
    },
    confirm(e) {
      let { outTradeNo, payVoucherList, resetOrder, orderInfo } = this.data
      // debugger
      // console.log(wx.$router)
      let thisPage = wx.$router.getPageInstance()
      if (resetOrder) return this.newResetOrder()
      if (orderInfo.outTradeNo) return this.ResetOrder()
      if (payVoucherList.length && outTradeNo) {
        thisPage.setData({
          ['orderInfo.transactionNo']: outTradeNo,
          ['orderInfo.tradeNo']: outTradeNo,
          ['orderInfo.paymentDocList']: payVoucherList.map(item => item.url)
        })
        console.log(thisPage.handleSecondConfirm);
        thisPage.handleSecondConfirm()
      } else {
        wx.$util.showToast('交易流水号或付款凭证不能为空!')
      }
    },
    // 标记错误订单&补录订单
    newResetOrder() {
      let { resetTransNo, payVoucherList } = this.data
      let thisPage = wx.$router.getPageInstance()
      // debugger
      if (payVoucherList.length && resetTransNo) {
        thisPage.setData({
          ['orderInfo.transactionNo']: resetTransNo,
          ['orderInfo.tradeNo']: resetTransNo,
          ['orderInfo.paymentDocList']: payVoucherList.map(item => item.url)
        })
        thisPage.handleSecondConfirm()
      } else {
        wx.$util.showToast('交易流水号或付款凭证不能为空!')
      }
    },
    // 多流水补录
    ResetOrder() {
      let { payVoucherList } = this.data
      if (payVoucherList.length) {
        let thisPage = wx.$router.getPageInstance()
        thisPage.setData({
          ['orderInfo.paymentDocList']: payVoucherList.map(item => item.url)
        })
        // console.log(thisPage.handleSecondConfirm);
        thisPage.handleSecondConfirm()
      } else {
        wx.$util.showToast('付款凭证不能为空!')
      }
    }
  }
})