<template>
  <form class="el-form" :class="[
    type ? 'el-form--type-' + type : '',
    labelPosition ? 'el-form--label-' + labelPosition : '',
    { 
      'el-form--inline': inline ,
      'is-readonly': readonly
    }
  ]">
    <slot></slot>
  </form>
</template>
<script>
  import objectAssign from 'bml-workstand-ui/src/utils/merge';

  export default {
    name: 'BmlForm',

    componentName: 'BmlForm',

    provide() {
      return {
        bmlForm: this
      };
    },

    props: {
      model: Object,
      rules: Object,
      labelPosition: String,
      labelWidth: String,
      labelSuffix: {
        type: String,
        default: ''
      },
      inline: Boolean,
      inlineMessage: {
        type: Boolean,
        default: true
      },
      statusIcon: Boolean,
      showMessage: {
        type: Boolean,
        default: true
      },
      size: String,
      disabled: Boolean,
      readonly: Boolean,
      type: String,
      validateOnRuleChange: {
        type: Boolean,
        default: true
      },
      hideRequiredAsterisk: {
        type: Boolean,
        default: false
      }
    },
    watch: {
      rules() {
        // remove then add event listeners on form-item after form rules change
        this.formFields.forEach(field => {
          field.removeValidateEvents();
          field.addValidateEvents();
        });

        if (this.validateOnRuleChange) {
          this.validate(() => {});
        }
      }
    },
    computed: {
      autoLabelWidth() {
        if (!this.potentialLabelWidthArr.length) return 0;
        const max = Math.max(...this.potentialLabelWidthArr);
        return max ? `${max}px` : '';
      }
    },
    data() {
      return {
        formFields: [],
        potentialLabelWidthArr: [] // use this array to calculate auto width
      };
    },
    created() {
      this.$on('el.form.addField', (field) => {
        if (field) {
          this.formFields.push(field);
        }
      });
      /* istanbul ignore next */
      this.$on('el.form.removeField', (field) => {
        if (field.prop) {
          this.formFields.splice(this.formFields.indexOf(field), 1);
        }
      });
    },
    methods: {
      resetFields() {
        if (!this.model) {
          console.warn('[Bml Warn][Form]model is required for resetFields to work.');
          return;
        }
        this.formFields.forEach(field => {
          field.resetField();
        });
      },
      clearValidate(props = []) {
        const validFields = props.length
          ? (typeof props === 'string'
            ? this.formFields.filter(field => props === field.prop)
            : this.formFields.filter(field => props.indexOf(field.prop) > -1)
          ) : this.formFields;
        validFields.forEach(field => {
          field.clearValidate();
        });
      },
      validate(callback) {
        if (!this.model) {
          console.warn('[Bml Warn][Form]model is required for validate to work!');
          return;
        }

        let promise;
        // if no callback, return promise
        if (typeof callback !== 'function' && window.Promise) {
          promise = new window.Promise((resolve, reject) => {
            callback = function(valid) {
              valid ? resolve(valid) : reject(valid);
            };
          });
        }

        let valid = true;
        let count = 0;
        // 如果需要验证的fields为空，调用验证时立刻返回callback
        if (this.formFields.length === 0 && callback) {
          callback(true);
        }
        let invalidFields = {};
        this.formFields.forEach(field => {
          field.validate('', (message, field) => {
            if (message) {
              valid = false;
            }
            invalidFields = objectAssign({}, invalidFields, field);
            if (typeof callback === 'function' && ++count === this.formFields.length) {
              callback(valid, invalidFields);
            }
          });
        });

        if (promise) {
          return promise;
        }
      },
      validateFields(props,cb){
        if (!this.model) {
          console.warn('[Bml Warn][Form]model is required for validate to work!');
          return;
        }

        let promise;
        // if no callback, return promise
        if (typeof cb !== 'function' && window.Promise) {
          promise = new window.Promise((resolve, reject) => {
            cb = function(valid) {
              valid ? resolve(valid) : reject(valid);
            };
          });
        }

        // 根据校验属性列表取得相应字段
        let validFields = this.formFields.filter(field => props.indexOf(field.prop) !== -1);
        console.log(validFields);

        let valid = true;
        let count = 0;
        // 如果需要验证的fields为空，调用验证时立刻返回callback
        if (validFields.length === 0 && cb) {
          cb(true);
        }
        
        let invalidFields = {};
        validFields.forEach(field => {
          field.validate('', (message, field) => {
            if (message) {
              valid = false;
            }
            invalidFields = objectAssign({}, invalidFields, field);
            if (typeof cb === 'function' && ++count === validFields.length) {
              cb(valid, invalidFields);
            }
          });
        });

        if (promise) {
          return promise;
        }
      },
      validateField(props, cb) {
        props = [].concat(props);
        const validFields = this.formFields.filter(field => props.indexOf(field.prop) !== -1);
        if (!validFields.length) {
          console.warn('[Bml Warn]please pass correct props!');
          return;
        }

        validFields.forEach(field => {
          field.validate('', cb);
        });
      },
      getLabelWidthIndex(width) {
        const index = this.potentialLabelWidthArr.indexOf(width);
        // it's impossible
        if (index === -1) {
          throw new Error('[BmlForm]unpected width ', width);
        }
        return index;
      },
      registerLabelWidth(val, oldVal) {
        if (val && oldVal) {
          const index = this.getLabelWidthIndex(oldVal);
          this.potentialLabelWidthArr.splice(index, 1, val);
        } else if (val) {
          this.potentialLabelWidthArr.push(val);
        }
      },
      deregisterLabelWidth(val) {
        const index = this.getLabelWidthIndex(val);
        this.potentialLabelWidthArr.splice(index, 1);
      }
    }
  };
</script>
