VinSecDialog.js 3.32 KB
// packageEquity/pages/carQuotation/components/VinSecDialog/VinSecDialog.js
import { validateVin } from '~/utils/vinVaildate'
import { ImgUrl } from '~/config'
const IMG_URL = ImgUrl + '/'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    showVinDialog: Boolean,
    secFormData: Object
  },

  /**
   * 组件的初始数据
   */
  data: {
    IMG_URL,
    vinFormat: '',
    formData: {
      carVin: ''
    },
    disable: true,
    that: this,
    beforeClose: null,
    vinValid:true
  },

  lifetimes: {
    attached() {
      let { carVin } = this.data.secFormData
      const vinValue = carVin || ''
      this.setData({
        'formData.carVin': vinValue,
        vinFormat: vinValue ? vinValue.replace(/(.{4})/g, "$1 ") : ''
      })
    }
  },

  /**
   * 数据监听器
   */
  observers: {
    'formData.carVin': function(carVin) {
      // 当 carVin 值发生变化时,会触发这个函数
      console.log('carVin 值变化了:', carVin)
      if (carVin.length === 17) {
        validateVin(carVin).then(res => {
          let { valid } = res.data.data
          console.log("upperVinRes", valid)
          // 保存 valid 值到组件 data 中
          this.setData({
            vinValid: valid
          })
        }).catch(() => {
          console.log("upperVinErr", carVin)
          // 校验失败时,设置为 false
          this.setData({
            vinValid: false
          })
        })
      }
      // 在这里可以执行你需要的逻辑
      // 例如:格式化显示、验证、触发事件等
      
      // 如果需要格式化显示,可以更新 vinFormat
      // this.setData({
      //   vinFormat: carVin ? carVin.replace(/(.{4})/g, "$1 ") : ''
      // })
      
      // 你可以在这里添加其他监听逻辑,例如:
      // - 实时验证车架号格式
      // - 触发自定义事件通知父组件
      // - 更新其他相关的数据状态
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleInput(e) {
      let inputValue = e.detail.toUpperCase()
      this.setData({
        'formData.carVin': inputValue
      })
    },
    changeVal(e) {
      let { attr, val } = e.target.dataset
      this.setData({
        [attr]: false
      })
    },
    dialogClost(type) {
      this.setData({
        beforeClose: (action) =>
          new Promise((resolve) => {
            if (action === 'confirm') {
              // 点击确定,根据传入的状态判断是否取消
              resolve(type)
            } else if (action === 'cancel') {
              // 取消则直接关闭
              resolve(true)
            }
          }),
      })
    },
    onClose() {
      this.triggerEvent('onClose')
    },
    onConfirm(e) {
      let { carVin } = this.data.formData
      let { vinValid } = this.data
      console.log("onConfirm",vinValid);
      console.log("onConfirm",carVin);
      if (!carVin || !(/^[a-zA-Z0-9]{17}$/.test(carVin))) {
        wx.$util.showToast('请输入 17 位有效字符(支持大写 A-H/J-N/P-Z、0-9)')
        return this.dialogClost(false) 
      }
      if(!vinValid) {
        console.log("表单校验不通过");
        return this.dialogClost(false) // 表单校验不通过
      } else {
        this.triggerEvent('onConfirm', { carVin: carVin })
        this.dialogClost(true) // 表单校验通过
      }
    }
  }
})