package org.dromara.web.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hotwj.platform.resourceManagement.company.domain.SysUserLoginPort;
import com.hotwj.platform.resourceManagement.company.mapper.SysUserLoginPortMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthUser;
import org.dromara.common.core.constant.*;
import org.dromara.common.core.domain.dto.PostDTO;
import org.dromara.common.core.domain.dto.RoleDTO;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.*;
import org.dromara.common.log.event.LogininforEvent;
import org.dromara.common.mybatis.helper.DataPermissionHelper;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.exception.TenantException;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysSocialBo;
import org.dromara.system.domain.vo.*;
import org.dromara.system.mapper.SysUserMapper;
import org.dromara.system.service.*;
import org.dromara.web.domain.bo.SmsResetPwdBo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.List;
import java.util.function.Supplier;

import static com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService.BUSINESS_ADMIN_ROLE_ID;
import static com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService.ENTERPRISE_PORT;

/**
 * 登录校验方法
 *
 * @author shihongwei
 */
@RequiredArgsConstructor
@Slf4j
@Service
public class SysLoginService {

    @Value("${user.password.maxRetryCount}")
    private Integer maxRetryCount;

    @Value("${user.password.lockTime}")
    private Integer lockTime;

    private static final String SYS_MENU_DEPENDENCY_KEY = "sys.menu.dependency";

    private final ISysTenantService tenantService;
    private final ISysPermissionService permissionService;
    private final ISysSocialService sysSocialService;
    private final ISysRoleService roleService;
    private final ISysDeptService deptService;
    private final ISysPostService postService;
    private final SysUserMapper userMapper;
    private final SysUserLoginPortMapper sysUserLoginPortMapper;
    private final ISysRolePermissionService sysRolePermissionService;
    private final ISysConfigService configService;


    /**
     * 短信验证码重置密码
     */
    public void resetPwdBySms(SmsResetPwdBo body) {
        // 1. 校验验证码
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + body.getMobile();
        String captcha = RedisUtils.getCacheObject(verifyKey);
        if (captcha == null) {
            throw new UserException("验证码已失效");
        }
        if (!body.getCode().equalsIgnoreCase(captcha)) {
            throw new UserException("验证码错误");
        }
        RedisUtils.deleteObject(verifyKey);

        // 2. 查询用户
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhonenumber, body.getMobile()));
        if (user == null) {
            throw new UserException("该手机号未注册");
        }

        // 3. 重置所有端口的子密码
        // 业务规则：移动端忘记密码，重置该手机号关联的所有企业端口的子密码，确保用户能登录任意关联企业
        String encryptedPwd = BCrypt.hashpw(body.getPassword());

        sysUserLoginPortMapper.update(null, new LambdaUpdateWrapper<SysUserLoginPort>()
                .set(SysUserLoginPort::getSubPassword, encryptedPwd)
                .eq(SysUserLoginPort::getUserId, user.getUserId()));

        // 可选：是否同时也重置主密码？
        // 如果系统不仅依赖子密码，也依赖主密码（如超级管理员），则需要重置。
        // 但目前移动端主要面向企业员工和司机，他们使用子密码。
        // 为了保险起见，如果该用户是普通用户（非admin），也可以同步更新主密码（视业务而定）。
        // 这里暂时只更新子密码，符合前文“完全依赖子密码验证”的修改。
    }

    /**
     * 绑定第三方用户
     *
     * @param authUserData 授权响应实体
     */
    @Lock4j
    public void socialRegister(AuthUser authUserData) {
        String authId = authUserData.getSource() + authUserData.getUuid();
        // 第三方用户信息
        SysSocialBo bo = BeanUtil.toBean(authUserData, SysSocialBo.class);
        BeanUtil.copyProperties(authUserData.getToken(), bo);
        Long userId = LoginHelper.getUserId();
        bo.setUserId(userId);
        bo.setAuthId(authId);
        bo.setOpenId(authUserData.getUuid());
        bo.setUserName(authUserData.getUsername());
        bo.setNickName(authUserData.getNickname());
        List<SysSocialVo> checkList = sysSocialService.selectByAuthId(authId);
        if (CollUtil.isNotEmpty(checkList)) {
            throw new ServiceException("此三方账号已经被绑定!");
        }
        // 查询是否已经绑定用户
        SysSocialBo params = new SysSocialBo();
        params.setUserId(userId);
        params.setSource(bo.getSource());
        List<SysSocialVo> list = sysSocialService.queryList(params);
        if (CollUtil.isEmpty(list)) {
            // 没有绑定用户, 新增用户信息
            sysSocialService.insertByBo(bo);
        } else {
            // 更新用户信息
            bo.setId(list.get(0).getId());
            sysSocialService.updateByBo(bo);
            // 如果要绑定的平台账号已经被绑定过了 是否抛异常自行决断
            // throw new ServiceException("此平台账号已经被绑定!");
        }
    }


    /**
     * 退出登录
     */
    public void logout() {
        try {
            LoginUser loginUser = LoginHelper.getLoginUser();
            if (ObjectUtil.isNull(loginUser)) {
                return;
            }
            if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
                // 超级管理员 登出清除动态租户
                TenantHelper.clearDynamic();
            }
            recordLogininfor(loginUser.getTenantId(), loginUser.getUsername(), Constants.LOGOUT, MessageUtils.message("user.logout.success"));
        } catch (Exception ignored) {
        } finally {
            try {
                StpUtil.logout();
            } catch (Exception ignored) {
            }
        }
    }

    /**
     * 记录登录信息
     *
     * @param tenantId 租户ID
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     */
    public void recordLogininfor(String tenantId, String username, String status, String message) {
        LogininforEvent logininforEvent = new LogininforEvent();
        logininforEvent.setTenantId(tenantId);
        logininforEvent.setUsername(username);
        logininforEvent.setStatus(status);
        logininforEvent.setMessage(message);
        logininforEvent.setRequest(ServletUtils.getRequest());
        SpringUtils.context().publishEvent(logininforEvent);
    }

    /**
     * 构建登录用户
     */
    public LoginUser buildLoginUser(SysUserVo user) {
        LoginUser loginUser = new LoginUser();
        Long userId = user.getUserId();
        loginUser.setTenantId(user.getTenantId());
        loginUser.setUserId(userId);
        loginUser.setDeptId(user.getDeptId());
        loginUser.setUsername(user.getUserName());
        loginUser.setNickname(user.getNickName());
        loginUser.setUserType(user.getUserType());
        if (ObjectUtil.isNotNull(user.getDeptId())) {
            Opt<SysDeptVo> deptOpt = Opt.of(user.getDeptId()).map(deptService::selectDeptById);
            loginUser.setDeptName(deptOpt.map(SysDeptVo::getDeptName).orElse(StringUtils.EMPTY));
            loginUser.setDeptCategory(deptOpt.map(SysDeptVo::getDeptCategory).orElse(StringUtils.EMPTY));
        }
        List<SysRoleVo> roles = roleService.selectRolesByUserId(userId);
        List<SysPostVo> posts = postService.selectPostsByUserId(userId);
        loginUser.setRoles(BeanUtil.copyToList(roles, RoleDTO.class));
        loginUser.setPosts(BeanUtil.copyToList(posts, PostDTO.class));
        return loginUser;
    }

    /**
     * 构建登录用户数据和菜单权限
     */
    public LoginUser buildLoginUserPerm(LoginUser loginUser, Long companyId, boolean isSuperAdmin, String loginPort) {
        Long userId = loginUser.getUserId();
        loginUser.setCompanyId(companyId);
        loginUser.setLoginPort(loginPort);
        loginUser.setIsAdmin(isSuperAdmin);

        if (isSuperAdmin) {
            loginUser.setMenuPermission(permissionService.getMenuPermission(userId));
            loginUser.setRolePermission(permissionService.getRolePermission(userId));
        } else {
            if (ObjectUtil.isNull(companyId)) {
                throw new ServiceException("公司ID不能为空");
            }

            if (ENTERPRISE_PORT.equals(loginPort)) {
                loginUser.setMenuPermission(permissionService.getMenuPermissionByCompanyId(userId, companyId, loginPort));
                loginUser.setRolePermission(permissionService.getRolePermissionByCompanyId(userId, companyId, loginPort));
                // 直接添加企业端的权限了
                loginUser.setPermissionCodes(sysRolePermissionService.getPermissionCodesByRoleId(BUSINESS_ADMIN_ROLE_ID));

                // 处理企业端权限依赖
                processPermissionDependencies(loginUser.getMenuPermission());
            } else {
                loginUser.setMenuPermission(permissionService.getMenuPermissionByCompanyId(userId, companyId, loginPort));
                loginUser.setRolePermission(permissionService.getRolePermissionByCompanyId(userId, companyId, loginPort));
                loginUser.setPermissionCodes(sysRolePermissionService.getPermissionCodesByCompanyId(userId, companyId, loginPort));
            }
        }

        return loginUser;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId, String ip) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(ip);
        sysUser.setLoginDate(DateUtils.getNowDate());
        sysUser.setUpdateBy(userId);
        DataPermissionHelper.ignore(() -> userMapper.updateById(sysUser));
    }

    /**
     * 登录校验
     */
    public void checkLogin(LoginType loginType, String tenantId, String account, Supplier<Boolean> supplier) {
        String errorKey = CacheConstants.PWD_ERR_CNT_KEY + account;
        String loginFail = Constants.LOGIN_FAIL;

        // 获取用户登录错误次数，默认为0 (可自定义限制策略 例如: key + account + ip)
        int errorNumber = ObjectUtil.defaultIfNull(RedisUtils.getCacheObject(errorKey), 0);
        // 锁定时间内登录 则踢出
        if (errorNumber >= maxRetryCount) {
            recordLogininfor(tenantId, account, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
            throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
        }

        if (supplier.get()) {
            // 错误次数递增
            errorNumber++;
            RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
            // 达到规定错误次数 则锁定登录
            if (errorNumber >= maxRetryCount) {
                recordLogininfor(tenantId, account, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
                throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
            } else {
                // 未达到规定错误次数
                recordLogininfor(tenantId, account, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
                throw new UserException(loginType.getRetryLimitCount(), errorNumber);
            }
        }

        // 登录成功 清空错误次数
        RedisUtils.deleteObject(errorKey);
    }

    /**
     * 校验租户
     *
     * @param tenantId 租户ID
     */
    public void checkTenant(String tenantId) {
        if (!TenantHelper.isEnable()) {
            return;
        }
        if (StringUtils.isBlank(tenantId)) {
            throw new TenantException("tenant.number.not.blank");
        }
        if (TenantConstants.DEFAULT_TENANT_ID.equals(tenantId)) {
            return;
        }
        SysTenantVo tenant = tenantService.queryByTenantId(tenantId);
        if (ObjectUtil.isNull(tenant)) {
            log.info("登录租户：{} 不存在.", tenantId);
            throw new TenantException("tenant.not.exists");
        } else if (SystemConstants.DISABLE.equals(tenant.getStatus())) {
            log.info("登录租户：{} 已被停用.", tenantId);
            throw new TenantException("tenant.blocked");
        } else if (ObjectUtil.isNotNull(tenant.getExpireTime()) && new Date().after(tenant.getExpireTime())) {
            log.info("登录租户：{} 已超过有效期.", tenantId);
            throw new TenantException("tenant.expired");
        }
    }

    /**
     * 处理权限依赖（从配置中读取）
     *
     * @param perms 当前权限集合
     */
    private void processPermissionDependencies(java.util.Set<String> perms) {
        if (CollUtil.isEmpty(perms)) {
            return;
        }
        // 读取配置
        String configJson = configService.selectConfigByKey(SYS_MENU_DEPENDENCY_KEY);
        if (StringUtils.isBlank(configJson)) {
            return;
        }

        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
            mapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
            String cleanJson = mapper.readTree(configJson).toString();
            JSONObject config = JSONUtil.parseObj(cleanJson);

            // 1. 添加基础权限 (basics)
            JSONArray basics = config.getJSONArray("basics");
            if (CollUtil.isNotEmpty(basics)) {
                perms.addAll(basics.toList(String.class));
            }

            // 2. 处理依赖 (dependencies)
            JSONObject dependencies = config.getJSONObject("dependencies");
            if (dependencies != null) {
                boolean changed = true;
                // 循环处理以解决多级依赖问题（最大循环10次防止死循环）
                int loopCount = 0;
                while (changed && loopCount < 10) {
                    changed = false;
                    java.util.Set<String> newDeps = new java.util.HashSet<>();
                    for (String perm : perms) {
                        JSONArray deps = dependencies.getJSONArray(perm);
                        if (CollUtil.isNotEmpty(deps)) {
                            for (Object depObj : deps) {
                                String dep = (String) depObj;
                                if (!perms.contains(dep) && !newDeps.contains(dep)) {
                                    newDeps.add(dep);
                                }
                            }
                        }
                    }
                    if (!newDeps.isEmpty()) {
                        perms.addAll(newDeps);
                        changed = true;
                    }
                    loopCount++;
                }
            }
        } catch (Exception e) {
            log.error("处理权限依赖配置异常", e);
        }
    }

}
