package com.sunxung.factoring.entity.sys;

import org.hibernate.validator.constraints.Length;

import com.sunxung.factoring.component.util.SpringUtil;
import com.sunxung.factoring.entity.BaseEntity;
import com.sunxung.factoring.service.sys.DictionaryService;

/**
 * @Description:系统字典项实体类
 * @Date:2017年6月6日 下午12:00:24
 */
public class Dictionary extends BaseEntity {

    private static final long serialVersionUID = 1L;
    /** 父级字典Id */
    private Long parentId;
    /** 编码 */
    @Length(min = 1, max = 100, message = "编码必须是1~100个字符之间")
    private String code;
    /** 名称 */
    @Length(min = 1, max = 30, message = "名称必须是1~30个字符之间")
    private String name;
    /** 显示顺序 */
    private int gradation;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getParentId() {
        return parentId;
    }

    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    public int getGradation() {
        return gradation;
    }

    public void setGradation(int gradation) {
        this.gradation = gradation;
    }

    @Override
    public void validator(ValidatorType type) {
        super.validator(type);
        if (ValidatorType.ADD.equals(type)) {
            addValidator();
        } else if (ValidatorType.UPDATE.equals(type)) {
            updateValidator();
        }
    }

    /** 新增数据验证 */
    private void addValidator() {
        Dictionary dictionary = getDictionaryService().getByCode(code);
        if (dictionary != null) {
            getErrors().put("error", "该编码:" + code + "已存在");
        }
    }

    /** 修改数据验证 */
    private void updateValidator() {
        Dictionary dictionary = getDictionaryService().get(getId());
        if (dictionary == null) {
            getErrors().put("error", "该字典不存在");
            return;
        }
        Dictionary codedictionary = getDictionaryService().getByCode(dictionary.getCode());
        if (codedictionary != null && !getId().equals(codedictionary.getId())) {
            getErrors().put("error", "该编号已存在");
        }
    }

    private static DictionaryService dictionaryService;

    private DictionaryService getDictionaryService() {
        if (dictionaryService == null) {
            dictionaryService = SpringUtil.getBeanByType(DictionaryService.class);
        }
        return dictionaryService;
    }
}
