zyPayPopup.js 7.17 KB
// packageEquity/pages/carQuotation/components/zyPayPopup/zyPayPopup.js
const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/dj-car-boutique-work-wechat/'
import api from '~/api/api.js'
Component({
  /**
   * 组件的属性列表
   */
  options: {
    styleIsolation: 'shared', // 自定义覆盖vant样式 
  },
  properties: {
    show: {
      type: Boolean,
      observer: function(n) {
        if (n) {
          let sysInfo = wx.getSystemInfoSync()
          // sysInfo.environment 1 企业微信打开 0微信打开
          // sysInfo.platform === 'windows' || sysInfo.platform === 'mac' || sysInfo.platform === 'linux' 是否pc端打开
          this.setData({
            envName: sysInfo.environment ? 1 : 0,
            envPlat: sysInfo.platform === 'windows' || sysInfo.platform === 'mac' || sysInfo.platform === 'linux' ? 1 : 0
          })
        }
      }
    },
    isListShow: Boolean
  },

  /**
   * 组件的初始数据
   */
  data: {
    IMG_URL,
    showChangeFileType: false,
    fileList: []
  },

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

  /**
   * 组件的方法列表
   */
  methods: {
    noScroll() { },
    selectUplaodType() {
      this.setData({
        showChangeFileType: true
      })
    },
    uploadImages() {
      let _this = this
      let { fileList } = _this.data
      wx.chooseImage({
        count: 9 - fileList?.length,
        success(res) {
          _this.setData({
            loadingFlag: true
          })
          const uploadImages = async (tempFilePaths) => {
            try {
              for (const val of tempFilePaths) {
                const imgType = val.split('.')[1]
                const type = imgType === 'unknown' ? 'jpg' : imgType
                const _res = await new Promise((resolve, reject) => {
                  wx.getFileSystemManager().readFile({
                    filePath: val, // 选择图片返回的相对路径
                    encoding: 'base64', // 编码格式
                    success: resolve,
                    fail: reject
                  })
                })
                const img = await api.uploadImg({
                  file: `${type}@${_res.data}`
                })
                const { code, data, message } = img
                if (code == 0) {
                  fileList.push({ url: data })
                  _this.setData({
                    fileList,
                    showChangeFileType: false,
                    fileType: 'image'
                  })
                } else {
                  wx.$util.showToast(message)
                }
              }
            } catch (error) {
              wx.$util.showToast("上传失败,请重试")
            } finally {
              _this.setData({
                loadingFlag: false
              })
            }
          }
          uploadImages(res?.tempFilePaths)
        }
      })
    },

    // 图片预览
    previewImage(e) {
      let { url, index } = e.currentTarget.dataset
      let imageUrl = url?.map(v => { return v.url})
      wx.previewImage({
        urls: imageUrl,
        current: imageUrl[index]
      })
    },
  
    async uploadPDFs() {
      let { envPlat, envName } = this.data
      if (envPlat == 1 || envName == 1) { // 企微或在pc端打开登录小程序使用跳转h5上传方式
        this.setData({
          showChangeFileType: false,
          show: false
        })
        const { zyWebViewUrl } = await wx.$util.getMockData()
        let path = `${zyWebViewUrl}/#/zyUpload`
        return wx.navigateTo({
          url: `/pages/webView/webView?url=${encodeURIComponent(path)}`,
          events: {
            webViewMessage: (data) => {
              if (data == 'cancel') { // 稍后补录
                return this.close('', 2)
              } else { // 确认上传
                this.setData({
                  fileList: [data]
                }) 
                this.confirm('', 2)
              }
            }
          }
        })
      } else { // 移动端微信打开使用打开微信会话选择文件方式
        let _this = this
        let { fileList } = _this.data
        wx.chooseMessageFile({
          count: 1,
          type: 'file',
          extension: ['pdf'],
          success(res) {
            // 正确获取选择的文件
            let tempFile = res.tempFiles[0]
            let fileName = tempFile.name // 获取文件名
            let fileType = fileName.split('.').pop() // 获取文件扩展名
            // 读取文件
            if (fileType != 'pdf') return wx.$util.showToast('只可上传pdf类型文件')
            _this.setData({
              loadingFlag: true
            })
            wx.getFileSystemManager().readFile({
              filePath: tempFile.path, // 使用正确的路径
              encoding: 'base64',
              success(_res) {
                // 调用上传接口
                api.uploadPdfAPI({
                  file: `${fileType}@${_res.data}` // 处理文件类型
                }).then(img => {
                  _this.setData({
                    loadingFlag: false
                  })
                  let { code, data, message } = img;
        
                  if (code == 0) {
                    fileList.push({ url: data, fileName: fileName }); // 添加到文件列表
                    _this.setData({
                      fileList,
                      showChangeFileType: false,
                      fileType: 'pdf' // 设置文件类型为 pdf
                    });
                  } else {
                    wx.$util.showToast(message);
                  }
                });
              },
              fail(err) {
                _this.setData({
                  loadingFlag: false
                })
                console.error('读取文件失败', err);
              }
            });
          },
          fail(err) {
            console.error('选择文件失败', err);
          }
        })
      }
    },
    deleteFile(e) {
      let { index } = e.currentTarget.dataset
      let { fileList } = this.data
      fileList.splice(index, 1)
      this.setData({fileList})
    },
    closeChangeUploadType() {
      this.setData({showChangeFileType: false})
    },
    close(e, pageBackNum) {
      // pageBackNum 从h5返回页面层级数
      let { isListShow } = this.data
      if (isListShow) return this.setData({show: false, fileList: []})
      let thisPage = wx.$router.getPageInstance(pageBackNum || 1)
      thisPage.setData({
        ['orderInfo.zyPayUrl']: '',
        confirmStatus: false
      })
      thisPage.handleSecondConfirm('cancel')
    },
    confirm(e, pageBackNum) {
      // pageBackNum 从h5返回页面层级数
      let { fileList, isListShow } = this.data
      let thisPage = wx.$router.getPageInstance(pageBackNum || 1)
      if (fileList.length) {
        if (isListShow) {
          this.triggerEvent('confirm', {zyPayUrl: fileList.map(item => item.url)})
        } else {
          thisPage.setData({
            ['orderInfo.zyPayUrl']: fileList.map(item => item.url)?.join(','),
            confirmStatus: false
          })
          thisPage.handleSecondConfirm()
        }
      } else {
        wx.$util.showToast('请上传延保协议')
      }
    }
  }
})