add.js 13.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
// import WxValidate from '~/utils/WxValidate'

const {
  methods
} = new wx.p.WxValidate()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    buttons: [{
      text: '我知道了',
      extClass: 'btn_cancel'
    }, {
      text: '去兑换',
      extClass: 'btn_primary'
    }],
    repeatButtons: [{
      text: '去修改',
      extClass: 'btn_cancel'
    }, {
      text: '继续添加',
      extClass: 'btn_primary'
    }],
    form: [{
        label: '姓名',
        key: 'bankUserName',
        placeholder: '请输入银行卡预留的姓名',
        maxlength: 10
      },
      {
        label: '手机号',
        key: 'bankPhone',
        placeholder: '请输入银行卡预留的手机号',
        maxlength: 11,
        type: 'number'
      },
      {
        label: '身份证',
        key: 'idCardNo',
        placeholder: '请输入银行卡预留的身份证号',
        maxlength: 18,
        type: 'idcard'
      },
      {
        label: '开户银行',
        key: 'bankName',
        placeholder: '请选择您的开户银行',
        fn: 'click',
        pickerData: [],
        pickerKey: 'bankName'
      },
      {
        label: '银行账户',
        key: 'bankNumber',
        placeholder: '请输入开户银行账户',
        maxlength: 19,
        type: 'number'
      },
      {
        label: '身份证人像面',
        key: 'idCardFront',
        icon: 'emblem',
        upload: true,
      },
      {
        label: '身份证国徽面',
        key: 'idCardBack',
        icon: 'portrait',
        upload: true,
      }
    ],
    repeatShowModal: false,
    btnDisabled: true,
    checkRepeatFlag: 1, //0-不校验,1-校验
    isEnabled: false, //是否上传身份证
    formData: {
      bankUserName: '',
      bankPhone: '',
      idCardNo: '',
      bankName: '',
      bankNumber: '',
      idCardBack: '',
      idCardFront: ''
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    let userInfo = wx.p.storage.get('userInfo')
    this.setData({
      userInfo
    })
    await this.getConfig()
    this.initData()
    this.getBankList()
  },
  onShow() {

  },
  getConfig() {
    return new Promise((resolve) => {
      const {
        channelSource,
        phone,
        merchantId,
        merchantName
      } = this.data.userInfo;
      wx.p.api.withdrawalApi.getConfig({
        channelSource,
        staffPhone: phone,
        merchantId,
        merchantName
      }).then(res => {
        console.log(res)
        if (res.code == 0) {
          this.setData({
            //0-关闭,1-打开
            isEnabled: res.data ? res.data.isEnabled == 0 ? false : true : false
          })
          resolve()
        }

      })
    })

  },
  initData() {
    wx.p.router.getRouterParams().then(params => {
      console.log(params, params)
      this.options = params
      let {
        item
      } = params;
      if (item) {
        this.setData({
          formData: {
            bankUserName: item.bankUserName,
            bankPhone: item.bankPhone,
            idCardNo: item.idCardNo,
            bankName: item.bankName,
            bankNumber: item.bankNumber,
            idCardBack: item.idCardBack,
            idCardFront: item.idCardFront
          },
          isEditBank: true
        })
        wx.setNavigationBarTitle({
          title: '编辑账户'
        })
        this.check()
      }
    })
  },
  repeatConfirm(e) {
    let {
      value
    } = e.detail
    let dialogObj = {
      0: () => {
        this.setData({
          repeatShowModal: false,
          checkRepeatFlag: 1
        })
      },
      1: () => {
        this.setData({
          repeatShowModal: false,
          checkRepeatFlag: 0
        }, () => {
          this.submit()
        })
      }
    }
    dialogObj[value]()
  },
  del(e) {
    const {
      item: {
        key,
      }
    } = e.currentTarget.dataset;
    this.setData({
      [`formData.${key}`]: ''
    })
    this.check()
  },
  // async upload(e) {
  //   const {
  //     item: {
  //       key,
  //     }
  //   } = e.currentTarget.dataset
  //   console.log(e)
  //   const {
  //     tempFiles
  //   } = await wx.chooseMedia({
  //       count: 1,
  //       mediaType: ['image'],
  //       sizeType:['compressed']
  //     }),

  //     [file] = tempFiles,
  //     _this = this
  //   wx.p.wxApi.showLoading('上传中...')
  //   console.log(tempFiles, 'tempFiles')
  //   let fileUrl = file.tempFilePath
  //   let imgType = fileUrl.split('.')[1]
  //   let type = imgType == 'unknown' ? 'jpg' : imgType
  //   try {
  //     wx.getFileSystemManager().readFile({
  //       filePath: fileUrl, //选择图片返回的相对路径
  //       encoding: 'base64', //编码格式
  //       success(_res) {
  //         wx.p.wxApi.showLoading('上传中...')
  //         wx.p.api.common.uploadImg({
  //             file: `${type}@${_res.data}`
  //           })
  //           .then(img => {
  //             wx.p.wxApi.hideLoading()
  //             _this.setData({
  //               [`formData.${key}`]: img
  //             })
  //             _this.check()
  //           })
  //       }
  //     })
  //   } catch (error) {
  //     wx.p.wxApi.showToast(String(JSON.stringify(error)))
  //   }
  // },
async upload(e) {
  const {
    item: {
      key,
    }
  } = e.currentTarget.dataset
  console.log(e)
  const {
    tempFiles
  } = await wx.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sizeType: ['compressed']
  })

  const [file] = tempFiles
  const _this = this
  
  wx.p.wxApi.showLoading('上传中...')
  console.log(tempFiles, 'tempFiles')
  
  let fileUrl = file.tempFilePath
  let imgType = fileUrl.split('.')[1]
  let type = imgType == 'unknown' ? 'jpg' : imgType
  
  try {
    // 读取图片文件并检查大小
    const fileInfo = wx.getFileSystemManager().statSync(fileUrl)
    const fileSize = fileInfo.size // 文件大小(字节)
    const maxSize = 300 * 1024 // 300KB
    
    // 如果文件大于300KB,需要进一步压缩
    if (fileSize > maxSize) {
      // 使用canvas压缩图片
      const compressedBase64 = await this.compressImage(fileUrl, maxSize)
      console.log(compressedBase64)
      wx.p.wxApi.showLoading('上传中...')
      wx.p.api.common.uploadImg({
        file: `${type}@${compressedBase64}`
      }).then(img => {
        wx.p.wxApi.hideLoading()
        _this.setData({
          [`formData.${key}`]: img
        })
        _this.check()
      })
    } else {
      // 文件小于300KB,直接上传
      wx.getFileSystemManager().readFile({
        filePath: fileUrl,
        encoding: 'base64',
        success(_res) {
          wx.p.wxApi.showLoading('上传中...')
          wx.p.api.common.uploadImg({
            file: `${type}@${_res.data}`
          }).then(img => {
            wx.p.wxApi.hideLoading()
            _this.setData({
              [`formData.${key}`]: img
            })
            _this.check()
          })
        }
      })
    }
  } catch (error) {
    wx.p.wxApi.hideLoading()
    wx.p.wxApi.showToast('图片处理失败')
    console.error(error)
  }
},

// 压缩图片的方法
compressImage(filePath, maxSize) {
  return new Promise((resolve, reject) => {
    wx.getImageInfo({
      src: filePath,
      success(res) {
        // 创建画布
        const canvas = wx.createOffscreenCanvas({
          type: '2d',
          width: res.width,
          height: res.height
        });
        
        // 创建图片对象
        const img = canvas.createImage();
        
        img.onload = () => {
          // 计算压缩比例
          let ratio = 1;
          if (res.width > 1000 || res.height > 1000) {
            ratio = Math.min(1000 / res.width, 1000 / res.height);
          }
          
          const canvasWidth = res.width * ratio;
          const canvasHeight = res.height * ratio;
          
          // 调整画布大小
          canvas.width = canvasWidth;
          canvas.height = canvasHeight;
          
          const ctx = canvas.getContext('2d');
          // 绘制图片
          ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);
          
          // 逐步降低质量直到满足大小要求
          let quality = 0.9;
          const tryCompress = () => {
            try {
              const dataURL = canvas.toDataURL('image/jpeg', quality);
              const base64Data = dataURL.replace(/^data:image\/\w+;base64,/, '');
              const byteLength = base64Data.replace(/[^A-Za-z0-9+/]/g, '').length * 0.75;
              
              if (byteLength <= maxSize || quality <= 0.1) {
                // 满足大小要求或质量已降到最低
                resolve(base64Data);
              } else {
                // 继续降低质量
                quality -= 0.1;
                tryCompress();
              }
            } catch (err) {
              reject(err);
            }
          };
          
          tryCompress();
        };
        
        img.onerror = (err) => {
          reject(err);
        };
        
        // 设置图片源
        img.src = filePath;
      },
      fail(err) {
        reject(err);
      }
    });
  });
},
  async getBankList() {
    const {
      bankList
    } = await wx.p.api.systemApi.getMockData(), {
        form
      } = this.data,
      index = form.findIndex(e => e.key == 'bankName');

    this.setData({
      [`form[${index}].pickerData`]: bankList
    })
  },
  bindInput(e) {
    const {
      item: {
        key,
      }
    } = e.currentTarget.dataset
    this.setData({
      [`formData.${key}`]: e.detail.value.replace(/\s/g, '')
    })
    this.check()
  },
  bindPickerChange(e) {
    const {
      value
    } = e.detail, {
        item: {
          key,
          pickerKey,
          pickerData
        }
      } = e.currentTarget.dataset,
      val = pickerData[value][pickerKey]
    this.setData({
      [`formData.${key}`]: val
    })
    this.check()
  },
  check() {
    const {
      formData,
      isEnabled
    } = this.data
    let btnDisabled = false
    //配置是否开启身份证
    if (!isEnabled) {
      delete formData.idCardBack
      delete formData.idCardFront
    }
    try {
      for (const key in formData) {
        if (!formData[key]) throw true
      }
    } catch (error) {
      btnDisabled = error
    }
    this.setData({
      btnDisabled
    })
  },
  dialogClose() {
    wx.p.router.back()
    // wx.p.router.go('/packageIndex/pages/bankAccount/list/list', {
    //   score: this.options.score
    // })
  },
  bindButton(e) {
    let {
      value
    } = e.detail;
    let dialogObj = {
      0: () => {
        this.dialogClose()
      },
      1: () => {
        this.dialogConfirm()
      }
    }
    dialogObj[value]()
  },
  dialogConfirm() {
    const {
      score
    } = this.options;

    wx.p.router.redirectTo('/packageIndex/pages/integral/withdrawal/withdrawal', {
      score
    })
    this.setData({
      showModal: false
    })
  },
  async submit() {

    const {
      formData,
      userInfo: {
        phone,
        channelSource,
        merchantId,
        merchantName
      },
      checkRepeatFlag
    } = this.data, {
        item
      } = this.options,
      validateKeys = ['bankPhone', 'idCardNo','bankNumber']
    try {
      validateKeys.map(e => {
        if (e == 'bankPhone' && !methods.tel(formData[e])) throw '手机号'
        if (e == 'idCardNo' && !methods.idcard(formData[e])) throw '身份证'
        if (e == 'bankNumber' && !methods.digits(formData[e])) throw '银行账户'
      })
    } catch (error) {
      return wx.p.wxApi.showToast(`请输入正确的${error}`)
    }
    if (item && item.id) formData.id = item.id
    formData.checkRepeatFlag = checkRepeatFlag
    formData.staffPhone = phone
    formData.channelSource = channelSource
    formData.merchantId = merchantId
    formData.merchantName = merchantName
    try {
      const {
        code,
        message,
        data
      } = await wx.p.api.withdrawalApi.insetorupdateStaffBank(formData)
      if (code == '0') {
        //返回类型:0:失败,1:成功,2:提示 建议您不要添加同一个人的多张卡片,避免提现时个人税务汇算累积
        let resultObj = {
          0: () => {
            this.setData({
              showModal: true,
              success: 'fail',
              dialogText: `原因:${message}`
            })
          },
          1: () => {
            this.setData({
              showModal: true,
              success: 'success',
              dialogText: item ? '您的银行账户修改成功!' : '您的银行账户添加成功!'
            })
          },
          2: () => {
            this.setData({
              repeatShowModal: true
            })
          }
        }
        resultObj[data]()

      } else {
        this.setData({
          showModal: true,
          success: 'fail',
          dialogText: `原因:${message}`
        })
        wx.p.sentry.reportError(`添加账户异常:${message}`, {
          ...formData,
          message
        });
        // wx.$api.showToast(message)
      }
    } catch (err) {
      wx.p.sentry.reportError(`添加账户异常:${err.message}`, {
        ...formData,
        err
      });
    }

  }
})