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.fasterxml.jackson.annotation.JsonInclude;
import com.trade.common.validate.ValidatorGroup;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.constraints.NotNull;
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;

/**
 * Entity基类
 */
public abstract class BaseEntity<T extends Model<T>> extends Model<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotNull(message = "id不能为空", groups = {ValidatorGroup.Update.class})
    @TableId(type = IdType.AUTO)
    private Long id;
    /**
     * 创建者
     */
    @TableField(value = "create_by", fill = FieldFill.INSERT)
    private String createBy;
    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date gmtCreate;
    /**
     * 更新者
     */
    @TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
    private String updateBy;
    /**
     * 更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date gmtModified;

    @TableLogic
    private Integer deleted;
    // 乐观锁版本字段，具体的Model需要自己定义
    /*
     * @Version private Integer version;
     */

    @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;
    }

    /**
     * 请求参数
     */
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    @TableField(exist = false)
    private Map<String, Object> params;

    public String getCreateBy() {
        return createBy;
    }

    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }

    public String getUpdateBy() {
        return updateBy;
    }

    public void setUpdateBy(String updateBy) {
        this.updateBy = updateBy;
    }

    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 Map<String, Object> getParams() {
        if (params == null) {
            params = new HashMap<>();
        }
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

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

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

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

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