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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunyard.ssp.modules.user.entity.ScDepartment;
import com.sunyard.ssp.modules.user.service.IScDepartmentService;
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/22 09:30
 */
@Component
public class DepartmentValidator implements Validator {

    @Autowired
    IScDepartmentService departmentService;

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

        return ScDepartment.class.equals(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        ScDepartment department = (ScDepartment) o;
        if (department.getId() != null) {
            //编辑
            ScDepartment originDepartment = departmentService.getById(department.getId());
            if(StringUtils.isBlank(department.getTitle())){
                String colunm = "title";
                errors.rejectValue(colunm,String.format("%s must not be blank.", colunm), "名称不可为空");
            }
            if(!department.getTitle().equals(originDepartment.getTitle()) && !checkTitle(department.getTitle())) {
                errors.rejectValue("title", "title already existed","名称已存在");
            }

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

    }

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