package com.trade.common.core.domain;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.trade.common.validate.ValidatorGroup;
import org.springframework.format.annotation.DateTimeFormat;

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

public class BizBaseEntity<T extends Model<T>> extends Model<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    /**
     * 创建者
     */
    @TableId(type = IdType.ASSIGN_ID)
    // @NotNull(message = "id不能为空", groups = {OnUpdate.class})
    private Long id;
    /**
     * 创建时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date gmtCreate;
    /**
     * 更新时间
     */
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date gmtModified;
    @TableLogic
    private Integer deleted;
    @TableField(exist = false)
    private Map<String, String> errors = new HashMap<String, String>();

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Date getGmtCreate() {
        return gmtCreate;
    }

    public void setGmtCreate(Date gmtCreate) {
        this.gmtCreate = gmtCreate;
    }

    public Date getGmtModified() {
        return gmtModified;
    }

    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }

    public Integer getDeleted() {
        return deleted;
    }

    public void setDeleted(Integer deleted) {
        this.deleted = deleted;
    }

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

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

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

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