<template>
    <view :class="extClass">
        <slot></slot>
    </view>
</template>

<script>
exports.__esModule = true;
exports.default = void 0;
var _formValidator = _interopRequireDefault(__webpack_require__(5));
var _object = __webpack_require__(0);
function _interopRequireDefault(obj) {
    return obj && obj.__esModule
        ? obj
        : {
              default: obj
          };
}
function linked(target) {
    if (target.data.prop) {
        this.formItems[target.data.prop] = target;
    }
    if (target.setInForm) {
        target.setInForm();
    }
    if (!this.firstItem) {
        this.firstItem = target;
    }
}
function unlinked(target) {
    if (target.data.prop) {
        delete this.formItems[target.data.prop];
    }
}
export default {
    unicomGroup: ['checkbox-group'],
    data() {
        return {
            errors: {},
            formItems: {},
            firstItem: null,
            newRules: ''
        };
    },
    props: {
        models: {
            type: Object,
            default: () => ({})
        },
        rules: {
            // 格式是[{name, rules: {}}]
            type: Array,

            default: () => []
        },
        extClass: {
            type: String,
            default: ''
        }
    },
    relations: {
        '../cell/cell': {
            type: 'descendant',
            linked,
            unlinked
        },
        '../checkbox-group/checkbox-group': {
            type: 'descendant',
            linked,
            unlinked
        }
    },
    mounted() {
        // 处理小程序 attached 生命周期
        this.attached();
    },
    methods: {
        attached() {
            this.initRules();
            this.formValidator = new _formValidator.default(this.models, this.newRules);
        },

        initRules(rules) {
            const newRules = {};
            (rules || this.rules).forEach((rule) => {
                if (rule.name && rule.rules) {
                    newRules[rule.name] = rule.rules || [];
                }
            });
            this.setData({
                newRules
            });
            return newRules;
        },

        modelChangeFun(newVal, oldVal) {
            if (!this.isInit) {
                this.isInit = true;
                return newVal;
            } // 这个必须在前面

            this.formValidator.setModel(newVal);
            this.isInit = true;
            const diffObj = (0, _object.diffObject)(oldVal, newVal);
            if (diffObj) {
                let isValid = true;
                const errors = [];
                const errorMap = {};
                Object.keys(diffObj).forEach((k) => {
                    this.formValidator.validateField(k, diffObj[k], function (isValided, error) {
                        if (error && error[k]) {
                            errors.push(error[k]);
                            errorMap[k] = error[k];
                        }
                        isValid = isValided;
                    });
                });
                this.showErrorsFun(diffObj, errorMap);
                this.$emit(isValid ? 'success' : 'fail', {
                    detail: isValid
                        ? {
                              trigger: 'change'
                          }
                        : {
                              errors,
                              trigger: 'change'
                          }
                });
            }
            return newVal;
        },

        rulesChangeFun(newVal) {
            const newRules = this.initRules(newVal);
            if (this.formValidator) {
                this.formValidator.setRules(newRules);
            }
            return newVal;
        },

        showAllErrorsFun(errors) {
            Object.keys(this.newRules).forEach((k) => {
                this.showErrorFun(k, errors && errors[k]);
            });
        },

        showErrorsFun(objs, errors) {
            Object.keys(objs).forEach((k) => {
                this.showErrorFun(k, errors && errors[k]);
            });
        },

        showErrorFun(prop, error) {
            const formItem = this.formItems[prop];
            if (formItem && formItem.data.showError) {
                formItem.setError(error);
            }
        },

        validate(cb) {
            return this.formValidator.validate((isValid, errors) => {
                this.showAllErrorsFun(errors);
                const handleError = this.handleErrors(errors);
                this.$emit(isValid ? 'success' : 'fail', {
                    detail: isValid
                        ? {
                              trigger: 'validate'
                          }
                        : {
                              errors: handleError,
                              trigger: 'validate'
                          }
                });
                if (cb) {
                    cb(isValid, handleError);
                }
            });
        },

        // eslint-disable-next-line @typescript-eslint/no-unused-vars
        validateField(name, value, cb = (v, error = null) => {}) {
            return this.formValidator.validateField(name, value, (isValid, errors) => {
                this.showErrorFun(name, errors);
                const handleError = this.handleErrors(errors);
                this.$emit(isValid ? 'success' : 'fail', {
                    detail: isValid
                        ? {
                              trigger: 'validate'
                          }
                        : {
                              errors: handleError,
                              trigger: 'validate'
                          }
                });
                if (cb) {
                    cb(isValid, handleError);
                }
            });
        },

        handleErrors(errors) {
            if (errors) {
                const newErrors = [];
                this.rules.forEach((rule) => {
                    if (errors[rule.name]) {
                        errors[rule.name].name = rule.name;
                        newErrors.push(errors[rule.name]);
                    }
                });
                return newErrors;
            }
            return errors;
        },

        addMethod(ruleName, method) {
            return this.formValidator.addMethod(ruleName, method);
        }
    },
    created: function () {},
    watch: {
        models: {
            handler: function (newVal, oldVal) {
                if (!this.isInit) {
                    this.isInit = true;
                    return newVal;
                } // 这个必须在前面

                this.formValidator.setModel(newVal);
                this.isInit = true;
                const diffObj = (0, _object.diffObject)(oldVal, newVal);
                if (diffObj) {
                    let isValid = true;
                    const errors = [];
                    const errorMap = {};
                    Object.keys(diffObj).forEach((k) => {
                        this.formValidator.validateField(k, diffObj[k], function (isValided, error) {
                            if (error && error[k]) {
                                errors.push(error[k]);
                                errorMap[k] = error[k];
                            }
                            isValid = isValided;
                        });
                    });
                    this.showErrorsFun(diffObj, errorMap);
                    this.$emit(isValid ? 'success' : 'fail', {
                        detail: isValid
                            ? {
                                  trigger: 'change'
                              }
                            : {
                                  errors,
                                  trigger: 'change'
                              }
                    });
                }
                return newVal;
            },

            immediate: true,
            deep: true
        },

        rules: {
            handler: function (newVal) {
                const newRules = this.initRules(newVal);
                if (this.formValidator) {
                    this.formValidator.setRules(newRules);
                }
                return newVal;
            },

            immediate: true,
            deep: true
        }
    }
};
var _default = _formValidator.default;
exports.default = _default;

/***/
</script>
<style></style>
