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

import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.iam.dto.IamResponseDTO;
import org.jeecg.modules.iam.req.IamReq;
import org.jeecg.modules.iam.service.IamService;
import org.jeecg.modules.iam.vo.IamLoginUserVO;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysLogService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysRoleServiceImpl;
import org.jeecg.modules.utils.RedisLockUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static org.jeecg.common.constant.CommonConstant.DEFAULT_PASSWORD;

@Service
public class IamServiceImpl implements IamService {

    @Value("${iam.getUserInfoSucceed}")
    private String getUserInfoSucceed;

    @Value("${iam.defaultRoleCode}")
    private String defaultRoleCode;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private BaseCommonService baseCommonService;

    @Resource
    private SysRoleServiceImpl sysRoleService;

    @Resource
    private ISysUserRoleService sysUserRoleService;

    @Override
    public IamLoginUserVO login(String tempCode) {
        IamLoginUserVO result = new IamLoginUserVO();

        IamResponseDTO responseDTO = IamReq.execute(tempCode);
        if (getUserInfoSucceed.equals(responseDTO.getStatus())) {
            IamResponseDTO.LoginInfo loginInfo = responseDTO.getContent().getLoginInfo();

            boolean lock = RedisLockUtil.lock(loginInfo.getUserCode(), 10000L);
            if (!lock) {
                result.setErrCode("");
                result.setStatus("err");
                result.setMessage("操作频繁请稍后再试");
                return result;
            }

            // 1.查询本库是否存在改账号
            SysUser currentUser = sysUserService.lambdaQuery()
                    .eq(SysUser::getUsername, loginInfo.getUserCode()).last("limit 1")
                    .one();


            // 2.如果不存在则新增角色和用户
            if (currentUser == null) {
                currentUser = new SysUser();
                currentUser.setUsername(loginInfo.getUserCode());
                currentUser.setRealname(loginInfo.getUserName());
                currentUser.setWorkNo(loginInfo.getUserCode());
                String salt = oConvertUtils.randomGen(8);
                currentUser.setSalt(salt); //加盐
                String passwordEncode = PasswordUtil.encrypt(loginInfo.getUserCode(), DEFAULT_PASSWORD, salt);
                currentUser.setPassword(passwordEncode);// 默认密码
                currentUser.setUserIdentity(1);// 正式员工身份
                currentUser.setWorkNo(loginInfo.getUserCode());
                currentUser.setDelFlag(CommonConstant.DEL_FLAG_0);
                currentUser.setLoginTenantId(0);
                currentUser.setStatus(CommonConstant.USER_UNFREEZE);
                sysUserService.save(currentUser);

                // 查询默认角色
                SysRole role = sysRoleService.lambdaQuery()
                        .eq(SysRole::getRoleCode, defaultRoleCode)
                        .last("limit 1")
                        .one();


                // 保存默认角色和用户关联关系
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setRoleId(role.getId());
                sysUserRole.setUserId(currentUser.getId());
                sysUserRole.setTenantId(0);
                sysUserRoleService.save(sysUserRole);
            }

            //生成token&并设置有效时间
            String token = JwtUtil.sign(currentUser.getUsername(), currentUser.getPassword());
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);

            // 记录登录日志
            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(currentUser, loginUser);
            baseCommonService.addLog("用户名: " + currentUser.getRealname() + ",登录成功！", CommonConstant.LOG_TYPE_1, null, loginUser);


            result.setToken(token);
            result.setUserInfo(currentUser);

            RedisLockUtil.unlock(loginInfo.getUserCode());
        }

        result.setErrCode(responseDTO.getErrCode());
        result.setStatus(responseDTO.getStatus());
        result.setMessage(responseDTO.getMessage());

        return result;
    }
}
