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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunyard.ssp.modules.user.entity.ScUser;
import com.sunyard.ssp.modules.user.service.IScUserService;
import com.sunyard.ssp.vo.ScUserVo;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
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 UserValidator implements Validator {

    @Autowired
    IScUserService userService;

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

        return ScUser.class.equals(aClass) || ScUserVo.class.equals(aClass);
    }

    @SneakyThrows
    @Override
    public void validate(Object o, Errors errors) {
        ScUser user;
        if (o instanceof ScUserVo) {
            user = new ScUser();
            BeanUtils.copyProperties(o, user);
        } else {
            user = (ScUser) o;
        }
        if (user.getId() != null) {
            //编辑
            ScUser origin = userService.getById(user.getId());
            if (user.getTel() != null && !user.getTel().equals(origin.getTel()) && !checkTel(user.getTel())){
                errors.rejectValue("tel","tel already existed", "手机号已被使用");
            }

            if(user.getEmail() != null && !user.getEmail().equals(origin.getEmail()) && !checkEmail(user.getEmail())){
                errors.rejectValue("email","email already existed", "邮箱已被使用");
            }

        } else {
            //新增
            if (!checkTel(user.getTel())) {
                errors.rejectValue("tel","tel already existed", "手机号已被使用");
            }

            if (!checkEmail(user.getEmail())) {
                errors.rejectValue("email","email already existed", "邮箱已被使用");
            }
        }

    }
    private boolean checkTel(String tel){
        if ("".equals(tel)){
            return true;
        }
        List<ScUser> list = userService.list(new QueryWrapper<ScUser>().lambda()
                .eq(ScUser::getTel, tel));
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }

    private boolean checkEmail(String email){
        if ("".equals(email)){
            return true;
        }
        List<ScUser> list = userService.list(new QueryWrapper<ScUser>().lambda()
                .eq(ScUser::getEmail, email));
        if (list != null && list.size() > 0) {
            return false;
        }
        return true;
    }
}
