<script>
    import Vue from 'vue';
    import {FormItem} from 'view-design'
    import AsyncValidator from 'async-validator';
    import FunctionComponent from "../../../libs/utils/FunctionComponent";
    const prefixCls = 'ivu-form-item';
    const _FormItem=Vue.extend({
        name:'FormItem',
        extends:FormItem,
        props:{
            validateStatus:{
                type:String
            }
        },
        watch:{
            error: {
                handler(val) {
                    this.validateMessage = val;
                },
                immediate: true
            },
            validateStatus:{
                handler(value){
                    this.validateState = value;
                },
                immediate: true,
            }
        },
        computed:{
            classes () {
                return [
                    `${prefixCls}`,
                    {
                        [`${prefixCls}-required`]: this.required || this.isRequired,
                        [`${prefixCls}-error`]: this.validateState === 'error',
                        [`${prefixCls}-warning`]: this.validateState === 'warning',
                        [`${prefixCls}-success`]: this.validateState === 'success',
                        [`${prefixCls}-validating`]: this.validateState === 'validating'
                    }
                ];
            },
        },
        methods:{
            validate(trigger, callback = function () {}) {
                let rules = this.getFilteredRule(trigger);
                if (!rules || rules.length === 0) {
                    if (!this.required) {
                        callback();
                        return true;
                    }else {
                        rules = [{required: true}];
                    }
                }

                this.validateState = 'validating';

                let descriptor = {};
                descriptor[this.prop] = rules;

                const validator = new AsyncValidator(descriptor);
                let model = {};

                model[this.prop] = this.fieldValue;

                validator.validate(model, { firstFields: true }, errors => {
                    this.validateState = !errors ? 'success' : errors[0].type?errors[0].type:'error';
                    this.validateMessage = errors ? errors[0].message : '';

                    callback(this.validateMessage);
                });
                this.validateDisabled = false;
            }
        }
    });

    export default FunctionComponent(_FormItem,'ht-base-form-item','i');
</script>
