package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.exception.NotLoginException;
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 jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginBody;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.domain.model.RegisterBody;
import org.dromara.common.core.domain.model.SocialLoginBody;
import org.dromara.common.core.exception.user.UserException;
import org.dromara.common.core.utils.*;
import org.dromara.common.encrypt.annotation.ApiEncrypt;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.ratelimiter.annotation.RateLimiter;
import org.dromara.common.ratelimiter.enums.LimitType;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.social.config.properties.SocialProperties;
import org.dromara.common.social.utils.SocialUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.system.domain.bo.SysTenantBo;
import org.dromara.system.domain.vo.SysClientVo;
import org.dromara.system.domain.vo.SysTenantVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.*;
import org.dromara.web.domain.bo.SmsResetPwdBo;
import org.dromara.web.domain.vo.LoginTenantVo;
import org.dromara.web.domain.vo.LoginVo;
import org.dromara.web.domain.vo.TenantListVo;
import org.dromara.web.service.IAuthStrategy;
import org.dromara.web.service.SysLoginService;
import org.dromara.web.service.SysRegisterService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.net.URL;
import java.util.List;

/**
 * 认证
 *
 * @author shihongwei
 */
@Slf4j
@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/auth")
public class AuthController {

    private final SocialProperties socialProperties;
    private final SysLoginService loginService;
    private final SysRegisterService registerService;
    private final ISysConfigService configService;
    private final ISysTenantService tenantService;
    private final ISysSocialService socialUserService;
    private final ISysClientService clientService;
    private final ISysUserLoginPortService sysUserLoginPortService;
    private final ISysUserService userService;
    private final HotDriverMapper hotDriverMapper;
    private final HotCompanySafetyManagerMapper hotCompanySafetyManagerMapper;

    /**
     * 短信验证码重置密码
     */
    @ApiEncrypt
    @PostMapping("/sms/resetPwd")
    public R<Void> resetPwdBySms(@RequestBody String body) {
        SmsResetPwdBo resetPwdBody = JsonUtils.parseObject(body, SmsResetPwdBo.class);
        ValidatorUtils.validate(resetPwdBody);
        loginService.resetPwdBySms(resetPwdBody);
        return R.ok();
    }
    
    /**
     * 登录方法
     *
     * @param body 登录信息
     * @return 结果
     */
    @ApiEncrypt
    @PostMapping("/login")
    public R<LoginVo> login(@RequestBody String body) {
        LoginBody loginBody = JsonUtils.parseObject(body, LoginBody.class);
        ValidatorUtils.validate(loginBody);
        // 授权类型和客户端id
        String clientId = loginBody.getClientId();
        String grantType = loginBody.getGrantType();
        SysClientVo client = clientService.queryByClientId(clientId);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!SystemConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        // 校验租户
        loginService.checkTenant(loginBody.getTenantId());
        // 登录
        LoginVo loginVo = IAuthStrategy.login(body, client, grantType);

        return R.ok(loginVo);
    }

    /**
     * 获取当前用户可登录角色列表
     */
    @GetMapping("/loginRoles")
    public R<List<SysUserLoginPortVo>> getLoginRoles(@RequestParam(value = "clientId", required = false) String clientId) {
        StpUtil.checkLogin();
        Long userId = LoginHelper.getUserId();
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<SysUserLoginPortVo> allRoles = sysUserLoginPortService.selectLoginPortListByPort(userId, null);

        if (!LoginHelper.isSuperAdmin(userId)) {
            if (loginUser != null && CollUtil.isNotEmpty(loginUser.getAllowedPortIds())) {
                allRoles = allRoles.stream()
                        .filter(role -> loginUser.getAllowedPortIds().contains(role.getId()))
                        .toList();
            } else if (loginUser != null && loginUser.getCompanyRoleId() != null) {
                Long currentRoleId = loginUser.getCompanyRoleId();
                allRoles = allRoles.stream()
                        .filter(role -> currentRoleId.equals(role.getId()))
                        .toList();
            } else {
                allRoles = List.of();
            }
        }

        String currentClientKey = loginUser != null ? loginUser.getClientKey() : null;
        if (StringUtils.isNotBlank(clientId)) {
            SysClientVo client = clientService.queryByClientId(clientId);
            if (client != null && StringUtils.isNotBlank(client.getClientKey())) {
                currentClientKey = client.getClientKey();
            }
        }

        if ("app".equals(currentClientKey)) {
            allRoles = allRoles.stream()
                    .filter(role -> StringUtils.isNotBlank(role.getLoginPort())
                            && !ISysUserLoginPortService.HEADQUARTERS_PORT.equals(role.getLoginPort())
                            && !ISysUserLoginPortService.AGENT_PORT.equals(role.getLoginPort())
                            && !ISysUserLoginPortService.GOVERNMENT_PORT.equals(role.getLoginPort()))
                    .toList();
        }
        return R.ok(allRoles);
    }

    /**
     * 切换登录端口
     *
     * @param portId 端口ID
     */
    @PostMapping("/switch/{portId}")
    public R<LoginVo> switchPort(@PathVariable Long portId, @RequestParam("clientId") String clientId) {
        String grantType = "password";
        SysClientVo client = clientService.queryByClientId(clientId);
        // 查询不到 client 或 client 内不包含 grantType
        if (ObjectUtil.isNull(client) || !StringUtils.contains(client.getGrantType(), grantType)) {
            log.info("客户端id: {} 认证类型：{} 异常!.", clientId, grantType);
            return R.fail(MessageUtils.message("auth.grant.type.error"));
        } else if (!SystemConstants.NORMAL.equals(client.getStatus())) {
            return R.fail(MessageUtils.message("auth.grant.type.blocked"));
        }
        StpUtil.checkLogin();
        Long userId = LoginHelper.getUserId();
        LoginUser loginUser = LoginHelper.getLoginUser();

        // 校验切换权限（基于子密码一致性）
        if (!LoginHelper.isSuperAdmin(userId)) {
            if (CollUtil.isEmpty(loginUser.getAllowedPortIds()) || !loginUser.getAllowedPortIds().contains(portId)) {
                return R.fail("无法切换身份：该身份密码与当前登录密码不一致，请重新登录");
            }
        }

        // 查询所有端口角色，支持切换端口
        List<SysUserLoginPortVo> allRoles = sysUserLoginPortService.selectLoginPortListByPort(userId, null);
        SysUserLoginPortVo selectedRole = allRoles.stream()
            .filter(item -> portId.equals(item.getId()))
            .findFirst()
            .orElseThrow(() -> new UserException("当前端口不存在该用户", ""));

        // 在此处设置权限
        loginUser = loginService.buildLoginUserPerm(loginUser, selectedRole.getCompanyId(), false, selectedRole.getLoginPort());
        loginUser.setIsAdmin(false);
        loginUser.setCompanyRoleId(selectedRole.getId());
        loginUser.setCompanyId(selectedRole.getCompanyId());
        loginUser.setCompanyName(selectedRole.getCompanyName());
        loginUser.setUsername(selectedRole.getUsername());

        // 设置业务ID和用户类型
        if (ISysUserLoginPortService.ENTERPRISE_PORT.equals(selectedRole.getLoginPort())) {
            // 企业端：通过 userId + companyId 唯一确定人员信息
            // 考虑到可能存在多条记录（如离职重聘），取最新的一条
            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())) {
            SysUserVo sysUser = userService.selectUserById(Long.valueOf(loginUser.getUserId()));
            if (sysUser != null) {
                // 驾驶员端：通过 phone + companyId 唯一确定驾驶员信息
                // 考虑到可能存在多条记录（如历史数据），取最新的一条
                LambdaQueryWrapper<HotDriver> lqw = new LambdaQueryWrapper<>();
                lqw.eq(HotDriver::getPhone, sysUser.getPhonenumber());
                lqw.eq(HotDriver::getCompanyId, selectedRole.getCompanyId());
                lqw.eq(HotDriver::getStatus, 1L);
                lqw.eq(HotDriver::getAuditStatus, 1);
                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("该驾驶员已离职或未审核通过，无法登录");
                }
            }
        }

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

        // 重新登录(刷新token)
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setCompanyId(selectedRole.getCompanyId());
        loginVo.setRoles(allRoles);
        loginVo.setAllRoles(allRoles);
        return R.ok(loginVo);
    }

    /**
     * 前端回调绑定授权(需要token)
     *
     * @param loginBody 请求体
     * @return 结果
     */
    @PostMapping("/social/callback")
    public R<Void> socialCallback(@RequestBody SocialLoginBody loginBody) {
        // 校验token
        StpUtil.checkLogin();
        // 获取第三方登录信息
        AuthResponse<AuthUser> response = SocialUtils.loginAuth(
                loginBody.getSource(), loginBody.getSocialCode(),
                loginBody.getSocialState(), socialProperties);
        AuthUser authUserData = response.getData();
        // 判断授权响应是否成功
        if (!response.ok()) {
            return R.fail(response.getMsg());
        }
        loginService.socialRegister(authUserData);
        return R.ok();
    }


    /**
     * 取消授权(需要token)
     *
     * @param socialId socialId
     */
    @DeleteMapping(value = "/unlock/{socialId}")
    public R<Void> unlockSocial(@PathVariable Long socialId) {
        // 校验token
        StpUtil.checkLogin();
        Boolean rows = socialUserService.deleteWithValidById(socialId);
        return rows ? R.ok() : R.fail("取消授权失败");
    }


    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 用户注册
     */
    @ApiEncrypt
    @PostMapping("/register")
    public R<Void> register(@Validated @RequestBody RegisterBody user) {
        if (!configService.selectRegisterEnabled(user.getTenantId())) {
            return R.fail("当前系统没有开启注册功能！");
        }
        registerService.register(user);
        return R.ok();
    }

    /**
     * 登录页面租户下拉框
     *
     * @return 租户列表
     */
    @RateLimiter(time = 60, count = 20, limitType = LimitType.IP)
    @GetMapping("/tenant/list")
    public R<LoginTenantVo> tenantList(HttpServletRequest request) throws Exception {
        // 返回对象
        LoginTenantVo result = new LoginTenantVo();
        boolean enable = TenantHelper.isEnable();
        result.setTenantEnabled(enable);
        // 如果未开启租户这直接返回
        if (!enable) {
            return R.ok(result);
        }

        List<SysTenantVo> tenantList = tenantService.queryList(new SysTenantBo());
        List<TenantListVo> voList = MapstructUtils.convert(tenantList, TenantListVo.class);
        try {
            // 如果只超管返回所有租户
            if (LoginHelper.isSuperAdmin()) {
                result.setVoList(voList);
                return R.ok(result);
            }
        } catch (NotLoginException ignored) {
        }

        // 获取域名
        String host;
        String referer = request.getHeader("referer");
        if (StringUtils.isNotBlank(referer)) {
            // 这里从referer中取值是为了本地使用hosts添加虚拟域名，方便本地环境调试
            host = referer.split("//")[1].split("/")[0];
        } else {
            host = new URL(request.getRequestURL().toString()).getHost();
        }
        // 根据域名进行筛选
        List<TenantListVo> list = StreamUtils.filter(voList, vo ->
            StringUtils.equalsIgnoreCase(vo.getDomain(), host));
        result.setVoList(CollUtil.isNotEmpty(list) ? list : voList);
        return R.ok(result);
    }

}
