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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunyard.ssp.modules.user.entity.ScPosition;
import com.sunyard.ssp.modules.user.service.IScPositionService;
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;

/**
 *  权限校验类
 * @author zs
 * @description:
 * @date: 2020/5/21 16:03
 */
@Component
public class PositionValidator implements Validator {

    @Autowired
    IScPositionService positionService;

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

        return ScPosition.class.equals(aClass);
    }

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

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

    }

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