package com.sunyard.ssp.modules.user.utils.validator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunyard.ssp.modules.user.entity.ScRole;
import com.sunyard.ssp.modules.user.service.IScRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.List;

/**
 *  角色校验类
  * @auther: ZS
  * @description:
  * @date: 2020/6/1 11:37
  */
@Component
public class RoleValidator implements Validator {

    @Autowired
    IScRoleService roleService;

    @Override
    public boolean supports(Class<?> aClass) {

        return ScRole.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ScRole role = (ScRole) o;
        if (role.getId() != null) {
            //编辑
            ScRole origin = roleService.getById(role.getId());
            if(StringUtils.isBlank(role.getName())){
                String colunm = "name";
                errors.rejectValue(colunm,String.format("%s must not be blank.", colunm), "名称不可为空");
            }
            if(!role.getName().equals(origin.getName()) && !checkName(role.getName())) {
                    errors.rejectValue("name","name already existed", "名称已存在");
            }

        } else {
            //新增
            if (!checkName(role.getName())) {
                errors.rejectValue("name","name already existed", "名称已存在");
            }
        }

    }

    private boolean checkName(String title){
        List<ScRole> list = roleService.list(new QueryWrapper<ScRole>().lambda()
                .eq(ScRole::getName, title));
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }
}
