package com.usky.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.constants.Constants;
import com.usky.common.core.util.*;
import com.usky.common.redis.core.RedisHelper;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.common.core.exception.BusinessException;
import com.usky.system.domain.*;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.model.LoginUser;
import com.usky.system.service.enums.UserStatus;
import com.usky.system.service.util.AsyncManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {

    @Autowired
    private ISysLogininforService sysLogininforService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisHelper redisHelper;

    @Autowired
    private SysPersonService sysPersonService;

    @Autowired
    private  SysTenantService sysTenantService;

    @Autowired
    AsyncManager asyncManager;


    public final String LOGIN_QRCODE_VERIFY ="login_qrcode_verify";

    private static final Logger LOGGER = LoggerFactory.getLogger(SysLoginService.class);

    /**
     * 登录
     */
    public LoginUser login(String username, String password, Integer tenantId) {

        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,username,Constants.LOGIN_FAIL, "用户/密码必须填写", null);
            throw new BusinessException("用户/密码必须填写");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,username, Constants.LOGIN_FAIL, "用户密码不在指定范围", null);
            throw new BusinessException("用户密码不在指定范围");
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,username, Constants.LOGIN_FAIL, "用户名不在指定范围", null);
            throw new BusinessException("用户名不在指定范围");
        }

        // 查询用户信息
        LoginUser loginUser = new LoginUser();
        if (tenantId != null && tenantId != 0) {
            loginUser = sysUserService.getUserInfoOne(username, tenantId);
        } else {
            loginUser = sysUserService.getUserInfo(username);
        }

        SysUserVO user = loginUser.getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除", null);
            throw new BusinessException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员", null);
            throw new BusinessException("对不起，您的账号：" + username + " 已停用");
        }
        if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,username, Constants.LOGIN_FAIL, "用户密码错误", null);
            throw new BusinessException("用户不存在/密码错误");
        }

        //判断租户状态是否停用
        LambdaQueryWrapper<SysTenant> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SysTenant::getStatus, SysTenant::getDomain)
                .eq(SysTenant::getId, tenantId);
        List<SysTenant> list = sysTenantService.list(queryWrapper);
        if(CollectionUtils.isNotEmpty(list)){
            String status = list.get(0).getStatus();
            String domain = list.get(0).getDomain();
            if(status.equals("1")){
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                asyncManager.insertLog(request, tenantId,username, Constants.LOGIN_FAIL, "系统已停用，请联系管理员", null);
                throw new BusinessException("对不起，系统已停用，请联系管理员");
            }
        }

        // 获取部门ID
        LambdaQueryWrapper<SysUser> deptQueryWrapper = Wrappers.lambdaQuery();
        deptQueryWrapper.select(SysUser::getDeptId)
                .eq(SysUser::getDelFlag, 0)
                .eq(SysUser::getTenantId, tenantId)
                .and(w -> w.eq(SysUser::getUserName, username).or().eq(SysUser::getPhonenumber, username));
        SysUser sysUser = sysUserService.getOne(deptQueryWrapper);
        Integer deptId = 0; // 默认值为0，假设0表示没有部门ID
        if (sysUser != null) {
            deptId = sysUser.getDeptId().intValue(); // 将Long转换为Integer
        }

        SysPerson sysPerson = sysPersonService.getsysPerson(user.getUserId());
        loginUser.setSysPerson(sysPerson);
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        asyncManager.insertLog(request, tenantId,username, Constants.LOGIN_SUCCESS, "登录成功", deptId);
        return loginUser;
    }


    public SysUser appLogin(String username, String password, Integer tenantId, String phone, String verify, String method) {
        SysUser loginUser = new SysUser();
        //查询用户信息
        if (!StringUtils.isBlank(username) && !StringUtils.isBlank(password)) {
            // 用户名或密码为空 错误
            if (StringUtils.isAnyBlank(username, password)) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_FAIL, "用户/密码必须填写", null);
                throw new BusinessException("用户/密码必须填写");
            }

            // 密码如果不在指定范围内 错误
            if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                    || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_FAIL, "用户密码不在指定范围", null);
                throw new BusinessException("用户密码不在指定范围");
            }

            // 用户名不在指定范围内 错误
            if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                    || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_FAIL, "用户名不在指定范围", null);
                throw new BusinessException("用户名不在指定范围");
            }
            loginUser = sysUserService.getAppUserInfo(username, tenantId, null, method);
            if (Objects.isNull(loginUser)) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_FAIL, "用户不存在", null);
                throw new BusinessException("用户不存在");
            }

            if (!SecurityUtils.matchesPassword(password, loginUser.getPassword())) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_FAIL, "用户密码错误", null);
                throw new BusinessException("用户不存在/密码错误");
            }
        } else if(!StringUtils.isBlank(phone) && !StringUtils.isBlank(verify)) {
            //手机验证码登录
            if (StringUtils.isBlank(verify)) {
                throw new BusinessException("验证码不能为空");
            }
            if (!verify.equals(redisHelper.get(phone))) {
                throw new BusinessException("验证码错误");
            }
            if (StringUtils.isBlank(phone)) {
                throw new BusinessException("用户名或手机号不能为空");
            }
            loginUser = sysUserService.getAppUserInfo(null, tenantId, phone, method);
            // 获取部门ID
            LambdaQueryWrapper<SysUser> deptQueryWrapper = Wrappers.lambdaQuery();
            deptQueryWrapper.select(SysUser::getDeptId)
                    .eq(SysUser::getDelFlag, 0)
                    .eq(SysUser::getTenantId, tenantId)
                    .and(w -> w.eq(SysUser::getUserName, username).or().eq(SysUser::getPhonenumber, username));
            SysUser sysUser = sysUserService.getOne(deptQueryWrapper);
            Integer deptId = 0; // 默认值为0，假设0表示没有部门ID
            if (sysUser != null) {
                deptId = sysUser.getDeptId().intValue(); // 将Long转换为Integer
            }
        } else if(!StringUtils.isBlank(username) && !StringUtils.isBlank(verify)) {
            LOGGER.info("二维码验证码登录");
            if (StringUtils.isBlank(username)) {
                throw new BusinessException("用户名不能为空");
            }
            String qrCode_verify = LOGIN_QRCODE_VERIFY+":"+username;
            if (!verify.equals(redisHelper.get(qrCode_verify))) {
                throw new BusinessException("扫码验证码失败");
            }
            loginUser = sysUserService.getAppUserInfo(username, tenantId, null, method);
        }
        // 获取部门ID
        LambdaQueryWrapper<SysUser> deptQueryWrapper = Wrappers.lambdaQuery();
        deptQueryWrapper.select(SysUser::getDeptId)
                .eq(SysUser::getDelFlag, 0)
                .eq(SysUser::getTenantId, tenantId)
                .and(w -> w.eq(SysUser::getUserName, username).or().eq(SysUser::getPhonenumber, username));
        SysUser sysUser = sysUserService.getOne(deptQueryWrapper);
        Integer deptId = 0; // 默认值为0，假设0表示没有部门ID
        if (sysUser != null) {
            deptId = sysUser.getDeptId().intValue(); // 将Long转换为Integer
        }
        if (UserStatus.DELETED.getCode().equals(loginUser.getDelFlag())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除", null);
            throw new BusinessException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(loginUser.getStatus())) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员", null);
            throw new BusinessException("对不起，您的账号：" + loginUser.getUserName() + " 已停用");
        }

//        Integer deptId = 0; // 默认值为0，假设0表示没有部门ID
        // 确保在所有登录成功的路径中都获取部门ID
        if (loginUser != null && loginUser.getDeptId() != null) {
            deptId = loginUser.getDeptId().intValue();
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        asyncManager.insertLog(request, tenantId,loginUser.getUserName(), Constants.LOGIN_SUCCESS, "登录成功", deptId);
        return loginUser;
    }


    public void logout(Integer tenantId,String loginName) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        asyncManager.insertLog(request, tenantId,loginName, Constants.LOGOUT, "退出成功", null);
    }

    /**
     * 注册
     */
    public void register(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password)) {
            throw new BusinessException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new BusinessException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            throw new BusinessException("密码长度必须在5到20个字符之间");
        }

        // 注册用户信息
        SysUserVO sysUser = new SysUserVO();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        sysUserService.register(BeanMapperUtils.map(sysUser, SysUser.class));
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        asyncManager.insertLog(request, SecurityUtils.getTenantId(),username, Constants.REGISTER, "注册成功", null);
    }


    public String getQrCodeResult(@RequestParam String qrCode){
        Object o = redisHelper.get(LOGIN_QRCODE_VERIFY+ ":" + qrCode);
        if(null !=o) {
            String result = String.valueOf(o);
            return result;
        }
        return null;
    }


    public void qrCodeSend(@RequestParam String userName, @RequestParam String qrCode, @RequestParam Integer tenantId) {
        if(StringUtils.isBlank(userName)){
            throw new BusinessException("用户名不能为空");
        }
        if(StringUtils.isBlank(qrCode)){
            throw new BusinessException("二维码不能为空");
        }
        SysUser sysUser = sysUserService.selectUserByUserNameOne(userName,tenantId);
        String code = String.valueOf(new Random().nextInt(1000000));
        redisHelper.set(LOGIN_QRCODE_VERIFY+":"+userName,code,60,TimeUnit.SECONDS);
        redisHelper.set(LOGIN_QRCODE_VERIFY+":"+qrCode,userName+":"+code,60, TimeUnit.SECONDS);
    }

}