<script>
import { rules as ruleList } from '../utils/registRules';
export default {
  functional: true,
  render(h, content) {
    const parent = content.parent;
    const { form, value, tagName, controlKey, option = {} } = content.props;
    const { layout = {}, formItem = {}, component = {} } = option;
    // 特殊处理的属性
    let { rules = [] } = option;
    let usedRules = [];
    // 对rules预处理
    for (const item of rules) {
      if (typeof item === 'string') {
        // 如果注册的校验列表中没有该校验规则，舍弃
        if (ruleList[item]) usedRules.push(ruleList[item]);
      } else {
        // 区分函数校验和一般校验
        if (item.validator) {
          usedRules.push({
            ...item,
            validator: (rule, value2, callback) => {
              item.validator(rule, value, callback, form);
            }
          });
        } else {
          usedRules.push(item);
        }
      }
    }
    // 不加这一行，校验不会触发，暂时不清楚原因
    // 加入一个空的校验规则，保证不会影响校验结果
    // BUG
    usedRules.push({
      validator: (rules, value, callback) => {
        callback();
      }
    });
    // 需要根据组件类型渲染
    // 不能直接h('el-col', layout)，会报错，数据监听的问题
    return h(
      'el-col',
      {
        props: { ...layout.props },
        attrs: { ...layout.attrs },
        style: { ...layout.style },
        class: { ...layout.class }
      },
      [
        h(
          'el-form-item',
          {
            props: { ...formItem.props },
            attrs: {
              ...formItem.attrs,
              prop: controlKey,
              rules: usedRules
            },
            style: { ...formItem.style },
            class: { ...formItem.class }
          },
          [
            h(tagName, {
              props: { ...component.props },
              attrs: {
                value: value,
                ...component.attrs
              },
              style: {
                ...component.style
              },
              class: { ...component.class },
              on: {
                input: parent.valueChange
              }
            })
          ]
        )
      ]
    );
  }
};
</script>
