package org.jeecg.modules.system.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.service.ISaOAuth2Service;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: nation_depart
 * @Author: jeecg-boot
 * @Date:   2022-02-28
 * @Version: V1.0
 */
@Service
public class SaOauth2ServiceImpl implements ISaOAuth2Service {

    @Resource
    private ISysUserDepartService sysUserDepartService;
    @Resource
    private ISysDepartService sysDepartService;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public SaResult userLogin(SysUser sysUser, String relPwd, String realKey){
        StpUtil.login(sysUser.getId());
        String tokenValue = StpUtil.getTokenValue();
        HashMap<String, String> map = new HashMap<>();
        SysUserDepart sysUserDepart = sysUserDepartService.getbyUserId(sysUser.getId());
        SysDepart sysDepart = sysDepartService.getById(sysUserDepart.getDepId());
        Pattern compile = Pattern.compile("^.*(?=.{8,})(?=.*\\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? _.]).*$");
        Matcher matcher = compile.matcher(relPwd);
        boolean matches = matcher.matches();
        if (!matches){
           return SaResult.error("您的密码安全等级低，请联系部门或地区管理员重置密码！");
        }
        map.put("departCode",sysDepart.getDepartCode());
        map.put("username",sysUser.getRealname());
        map.put("satoken-server",tokenValue);
        map.put("departName",sysUser.getDepartName());
        redisUtil.del(realKey);
        return SaResult.data(map);
    }

    @Override
    public SaResult userLoginNation(SysUser sysUser) {
        StpUtil.login(sysUser.getId());
        String tokenValue = StpUtil.getTokenValue();
        HashMap<String, String> map = new HashMap<>();
        SysUserDepart sysUserDepart = sysUserDepartService.getbyUserId(sysUser.getId());
        SysDepart sysDepart = sysDepartService.getById(sysUserDepart.getDepId());
        map.put("departCode",sysDepart.getDepartCode());
        map.put("username",sysUser.getRealname());
        map.put("satoken-server",tokenValue);
        map.put("departName",sysUser.getDepartName());
        return SaResult.data(map);
    }

}
