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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunyard.ssp.modules.user.entity.ScPermission;
import com.sunyard.ssp.modules.user.service.IScPermissionService;
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 PermissionValidator implements Validator {

    @Autowired
    IScPermissionService permissionService;

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

        return ScPermission.class.equals(aClass);
    }

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

            if(!permission.getName().equals(originPermission.getName())){
                if (!checkName(permission.getName())) {
                    errors.rejectValue("name","name already existed", "路由英文名已存在");
                }
            }

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

            if (!checkName(permission.getName())) {
                errors.rejectValue("name","name already existed", "路由英文名已存在");
            }

        }

    }

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

    private boolean checkName(String name){
        List<ScPermission> list = permissionService.list(new QueryWrapper<ScPermission>().lambda()
                .eq(ScPermission::getName, name)
                .orderByAsc(ScPermission::getSortOrder));
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }
}
