package com.sunyard.ssp.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sunyard.ssp.common.constant.CommonConstant;
import com.sunyard.ssp.modules.user.entity.ScUser;
import com.sunyard.ssp.modules.user.service.IScUserService;

import java.util.List;

public class UserUtil {
    private static SecurityUtil securityUtil = SpringUtil.getBean(SecurityUtil.class);
    private static IScUserService userService = SpringUtil.getBean(IScUserService.class);

    public static void verifyUser(ScUser u) throws Exception  {
        if (StrUtil.isBlank(u.getPassword()) || StrUtil.isBlank(u.getUsername())) {
            throw new Exception ("缺少必需表单字段");
        }

        /*if (u.getUsername().length() < 6 || u.getUsername().length() > 30){
            throw new Exception("用户名长度应为6到30字符");
        }*/

        if ( StrUtil.isNotBlank(u.getUsername())){
            if(CollectionUtils.isNotEmpty(userService.list(new QueryWrapper<ScUser>().lambda()
                    .eq(ScUser::getUsername,u.getUsername())))){
                throw new Exception("该用户名已被注册");
            }
        }

        /*if (!checkUserName(u.getUsername())){
            throw new Exception("用户名只能由数字、字母或下划线组成");
        }*/

        if ( StrUtil.isNotBlank(u.getTel()) ){
            if(CollectionUtils.isNotEmpty(userService.list(new QueryWrapper<ScUser>().lambda().eq(ScUser::getTel,u.getTel())))){
                throw new Exception("该手机号已绑定其他账户");
            }
        }

        if ( StrUtil.isNotBlank(u.getEmail())){
            List<ScUser>  t = userService.list(new QueryWrapper<ScUser>().lambda().eq(ScUser::getEmail,u.getEmail()));
            if(CollectionUtils.isNotEmpty(userService.list(new QueryWrapper<ScUser>().lambda().eq(ScUser::getEmail,u.getEmail())))){
                throw new Exception("该邮箱已绑定其他账户");
            }
        }

    }

    public static boolean checkUserName(String name) {
        String regExp = "^[0-9a-zA-Z_]{1,}$";
        if(name.matches(regExp)) {
            return true;
        }else {
            return false;
        }
    }

    public static void verifyUfield(String signInfo,Long userId) throws Exception  {
        //校验签名信息，用户id不为空
        if(StrUtil.isBlank(signInfo)){
            throw new Exception("签名信息不能为空");
        }
        if(null==userId){
            throw new Exception("用户id不能为空");
        }
        //查询用户绑定U盾公钥
        ScUser user = userService.getById(userId);
        if(null==user){
            throw new Exception("用户不存在");
        }
        if(StrUtil.isBlank(user.getUPublickey())){
            throw new Exception("用户未绑定U盾");
        }
        if(!CommonConstant.USER_STATUS_NORMAL.equals(user.getStatus())){
            throw new Exception("用户被禁用");
        }

    }
}
