export default {
  data () {
    return {
      rules: {}
    }
  },
  methods: {
    // 设置某个字段必填项
    setRequired (key) {
      if (!this.rules[key]) {
        this.$set(this.rules, key, [])
      }

      // 检查是否已存在必填规则
      const hasRequired = this.rules[key].some(rule => rule.required)
      if (!hasRequired) {
        const targetItem = this.formItems.find(item => item.model === key || `${item.name}${item.model}` === key)

        this.rules[key].push({
          required: true,
          message: `${targetItem?.name || '该字段'}不能为空`,
          trigger: 'blur'
        })

        // 触发表单重新验证
        this.$nextTick(() => {
          this.$refs.selectForm.validateField(key)
        })
      }
    },

    // 移除某个字段必填项
    removeRequired (key) {
      if (this.rules[key]) {
        // 过滤掉必填规则
        this.rules[key] = this.rules[key].filter(rule => !rule.required)
        // 清除验证状态
        this.$nextTick(() => {
          this.$refs.selectForm.clearValidate(key)
        })
        console.log('移除必填项', this.rules[key])
        this.$forceUpdate()
      }
    },
  }
}
