package com.trade.common.core.dto;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.trade.common.validate.ValidatorGroup;

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

public class BaseDTO {

    /**
     * 搜索值
     */
    private String searchValue;

    @TableField(exist = false)
    private Map<String, String> errors = new HashMap<String, String>();

    public String getSearchValue() {
        return searchValue;
    }

    public void setSearchValue(String searchValue) {
        this.searchValue = searchValue;
    }


    /**
     * 是否有错误数据
     */
    public boolean hasErrors() {
        return CollUtil.isNotEmpty(errors);
    }

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

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

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