package com.inkasso.factoring.common.entity;

import com.baomidou.mybatisplus.annotation.TableField;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 验证基类
 */
public class ValidatorEntity implements Serializable {

    private static final long serialVersionUID = 1L;
    @TableField(exist = false)
    private Map<String, String> errors = new HashMap<String, String>();

    /** 是否有错误数据 */
    public boolean hasErrors() {
        return errors != null && errors.size() > 0;
    }

    public Map<String, String> getErrors() {
        return errors;
    }

    /**
     * 数据合法性验证
     * 
     * @param type 验证类型
     */
    public void validator(ValidatorType type) {
        Set<ConstraintViolation<ValidatorEntity>> violations = getValidator().validate(this, Default.class,
                type.getCls());
        errors = new HashMap<String, String>();
        if (violations != null && violations.size() > 0) {
            for (ConstraintViolation<ValidatorEntity> entity : violations) {
                errors.put(entity.getPropertyPath().toString(), entity.getMessage());
            }
        }
    }

    /** 获取验证实例 */
    private Validator getValidator() {
        // 构造验证实例
        return Validation.buildDefaultValidatorFactory().getValidator();
    }

    public static enum ValidatorType {
        ADD, UPDATE, TEMP;

        public Class<?> getCls() {
            switch (this) {
                case ADD:
                    return Add.class;
                case UPDATE:
                    return Update.class;
                case TEMP:
                    return Temp.class;
                default:
                    return null;
            }
        }
    }

    public static interface Add {
    }

    public static interface Update {
    }

    public static interface Temp {
    }
}
