package org.dromara.web.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.stp.parameter.SaLoginParameter;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hotwj.platform.driverManagement.driver.domain.HotDriver;
import com.hotwj.platform.driverManagement.driver.mapper.HotDriverMapper;
import com.hotwj.platform.resourceManagement.company.domain.vo.SysUserLoginPortVo;
import com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.domain.model.SmsLoginBody;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.exception.user.CaptchaExpireException;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.MessageUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserService;
import org.dromara.web.domain.vo.LoginVo;
import org.dromara.web.service.IAuthStrategy;
import org.dromara.web.service.SysLoginService;
import org.springframework.stereotype.Service;


/**
 * 短信认证策略
 *
 * @author shihongwei
 */
@Slf4j
@Service("sms" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class SmsAuthStrategy implements IAuthStrategy {

    private final SysLoginService loginService;
    private final ISysUserService sysUserService;
    private final ISysUserLoginPortService sysUserLoginPortService;
    private final HotDriverMapper hotDriverMapper;
    private final HotCompanySafetyManagerMapper hotCompanySafetyManagerMapper;

    @Override
    public LoginVo login(String body, SysClientVo client) {
        SmsLoginBody loginBody = JsonUtils.parseObject(body, SmsLoginBody.class);
        ValidatorUtils.validate(loginBody);
        String tenantId = loginBody.getTenantId();
        String phone = loginBody.getPhonenumber();
        String smsCode = loginBody.getSmsCode();
        LoginUser loginUser = TenantHelper.dynamic(tenantId, () -> {
            SysUserVo user = sysUserService.selectUserByPhonenumber(phone);
            if (ObjectUtil.isNull(user)) {
                throw new UserException("user.not.exists", phone);
            } else if (SystemConstants.DISABLE.equals(user.getStatus())) {
                throw new UserException("user.blocked", phone);
            }
            loginService.checkLogin(LoginType.SMS, tenantId, phone, () -> !validateSmsCode(tenantId, phone, smsCode));
            // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
            return loginService.buildLoginUser(user);
        });
        // 非移动端/或未指定公司角色ID时，走端口角色选择逻辑与密码登录保持一致
        Long userId = loginUser.getUserId();
        if (!"app".equals(client.getClientKey())) {
            return handleRolesAndLogin(client, loginUser, loginBody.getLoginPort(), loginBody.getCompanyRoleId());
        } else {
            // 移动端仅允许企业端和驾驶员端
            return handleAppRolesAndLogin(client, loginUser, loginBody.getCompanyRoleId());
        }
    }

    /**
     * 校验短信验证码
     */
    private boolean validateSmsCode(String tenantId, String phonenumber, String smsCode) {
        String code = RedisUtils.getCacheObject(GlobalConstants.CAPTCHA_CODE_KEY + phonenumber);
        if (StringUtils.isBlank(code)) {
            loginService.recordLogininfor(tenantId, phonenumber, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire"));
            throw new CaptchaExpireException();
        }
        return code.equals(smsCode);
    }

    private LoginVo handleRolesAndLogin(SysClientVo client, LoginUser loginUser, String loginPort, Long companyRoleId) {
        Long userId = loginUser.getUserId();
        java.util.List<SysUserLoginPortVo> allRoles = sysUserLoginPortService.selectLoginPortListByPort(userId, null);
        java.util.List<SysUserLoginPortVo> currentPortRoles = allRoles.stream()
                .filter(role -> StringUtils.isBlank(loginPort) || role.getLoginPort().equals(loginPort))
                .toList();
        if (CollUtil.isEmpty(currentPortRoles)) {
            throw new UserException("当前账号无该端口登录权限");
        }
        if (companyRoleId != null) {
            return loginWithSpecificRole(client, loginUser, allRoles, companyRoleId, currentPortRoles);
        }
        if (currentPortRoles.size() == 1) {
            return loginWithSpecificRole(client, loginUser, allRoles, currentPortRoles.get(0).getId(), currentPortRoles);
        }
        return buildMultiRoleResponse(currentPortRoles, allRoles);
    }

    private LoginVo handleAppRolesAndLogin(SysClientVo client, LoginUser loginUser, Long companyRoleId) {
        Long userId = loginUser.getUserId();
        java.util.List<SysUserLoginPortVo> allRoles = sysUserLoginPortService.selectLoginPortListByPort(userId, null);
        java.util.List<SysUserLoginPortVo> currentPortRoles = allRoles.stream()
                .filter(role -> ISysUserLoginPortService.ENTERPRISE_PORT.equals(role.getLoginPort())
                        || ISysUserLoginPortService.DRIVER_PORT.equals(role.getLoginPort()))
                .toList();
        if (CollUtil.isEmpty(currentPortRoles)) {
            throw new UserException("当前账号无移动端登录权限");
        }
        if (companyRoleId != null) {
            return loginWithSpecificRole(client, loginUser, allRoles, companyRoleId, currentPortRoles);
        }
        if (currentPortRoles.size() == 1) {
            return loginWithSpecificRole(client, loginUser, allRoles, currentPortRoles.get(0).getId(), currentPortRoles);
        }
        return buildMultiRoleResponse(currentPortRoles, allRoles);
    }

    private LoginVo loginWithSpecificRole(SysClientVo client, LoginUser loginUser, java.util.List<SysUserLoginPortVo> allRoles, Long roleId, java.util.List<SysUserLoginPortVo> currentPortRoles) {
        SysUserLoginPortVo selectedRole = currentPortRoles.stream()
                .filter(item -> roleId.equals(item.getId()))
                .findFirst()
                .orElseThrow(() -> new UserException("当前端口不存在该用户"));

        loginUser = loginService.buildLoginUserPerm(loginUser, selectedRole.getCompanyId(), false, selectedRole.getLoginPort());

        if (ISysUserLoginPortService.ENTERPRISE_PORT.equals(selectedRole.getLoginPort())) {
            LambdaQueryWrapper<HotCompanySafetyManager> lqw = new LambdaQueryWrapper<>();
            lqw.eq(HotCompanySafetyManager::getCompanyId, selectedRole.getCompanyId());
            lqw.eq(HotCompanySafetyManager::getUserId, loginUser.getUserId());
            lqw.eq(HotCompanySafetyManager::getStatus, 1L);
            lqw.eq(HotCompanySafetyManager::getIsResigned, 0L);
            lqw.orderByDesc(HotCompanySafetyManager::getCreateTime);
            lqw.last("limit 1");
            HotCompanySafetyManager manager = hotCompanySafetyManagerMapper.selectOne(lqw);
            if (manager != null) {
                loginUser.setBusinessUserId(String.valueOf(manager.getId()));
                loginUser.setUserType("sys_user");
            }
        } else if (ISysUserLoginPortService.DRIVER_PORT.equals(selectedRole.getLoginPort())) {
            org.dromara.system.domain.vo.SysUserVo sysUser = sysUserService.selectUserById(Long.valueOf(loginUser.getUserId()));
            if (sysUser != null) {
                LambdaQueryWrapper<HotDriver> lqw = new LambdaQueryWrapper<>();
                lqw.eq(HotDriver::getPhone, sysUser.getPhonenumber());
                lqw.eq(HotDriver::getCompanyId, selectedRole.getCompanyId());
                lqw.eq(HotDriver::getStatus, 1L);
                lqw.orderByDesc(HotDriver::getCreateTime);
                lqw.last("limit 1");
                HotDriver driver = hotDriverMapper.selectOne(lqw);
                if (driver != null) {
                    loginUser.setBusinessUserId(driver.getId());
                    loginUser.setUserType("sys_user");
                } else {
                    throw new UserException("该驾驶员已离职或档案不存在，无法登录");
                }
            }
        }

        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        SaLoginParameter model = new SaLoginParameter();
        model.setDeviceType(client.getDeviceType());
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        loginVo.setCompanyId(selectedRole.getCompanyId());
        loginVo.setRoles(currentPortRoles);
        loginVo.setAllRoles(allRoles);
        return loginVo;
    }

    private LoginVo buildMultiRoleResponse(java.util.List<SysUserLoginPortVo> currentPortRoles, java.util.List<SysUserLoginPortVo> allRoles) {
        LoginVo loginVo = new LoginVo();
        loginVo.setRoles(currentPortRoles);
        loginVo.setAllRoles(allRoles);
        return loginVo;
    }
}
