package com.vetti.web.controller.system;

import java.util.*;

import cn.hutool.core.collection.CollectionUtil;
import com.vetti.common.core.domain.R;
import com.vetti.common.core.domain.dto.LoginDto;
import com.vetti.common.utils.MessageUtils;
import com.vetti.hotake.domain.HotakeCvInfo;
import com.vetti.hotake.service.IHotakeCvInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.vetti.common.constant.Constants;
import com.vetti.common.core.domain.AjaxResult;
import com.vetti.common.core.domain.entity.SysMenu;
import com.vetti.common.core.domain.entity.SysUser;
import com.vetti.common.core.domain.model.LoginBody;
import com.vetti.common.core.domain.model.LoginUser;
import com.vetti.common.core.text.Convert;
import com.vetti.common.utils.DateUtils;
import com.vetti.common.utils.SecurityUtils;
import com.vetti.common.utils.StringUtils;
import com.vetti.framework.web.service.SysLoginService;
import com.vetti.framework.web.service.SysPermissionService;
import com.vetti.framework.web.service.TokenService;
import com.vetti.system.service.ISysConfigService;
import com.vetti.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Api(tags ="登录模块")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private IHotakeCvInfoService cvInfoService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("登录方法")
    @PostMapping("/login")
    public R<LoginDto> login(@RequestBody LoginBody loginBody)
    {
        LoginDto loginDto = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        
        // TODO: 安全功能集成 - 记录登录会话到安全表
        // 在用户成功登录后，记录会话信息到hotake_security_login_sessions表
        // 用于支持"Login Sessions"功能，显示用户的所有活跃会话
        try {
            String ipAddress = com.vetti.common.utils.ip.IpUtils.getIpAddr();
            String userAgent = com.vetti.common.utils.ServletUtils.getRequest().getHeader("User-Agent");
            // 使用Spring的ApplicationContext来获取bean，避免循环依赖
            try {
                Object securityService = com.vetti.common.utils.spring.SpringUtils.getBean("hotakeSecurityServiceImpl");
                if (securityService != null) {
                    // 使用反射调用方法
                    java.lang.reflect.Method method = securityService.getClass().getMethod(
                        "recordLoginSession", Long.class, String.class, String.class, String.class);
                    method.invoke(securityService, loginDto.getUserId(), loginDto.getToken(), ipAddress, userAgent);
                }
            } catch (Exception e) {
                // 安全服务不存在或调用失败，不影响登录流程
            }
        } catch (Exception e) {
            // 记录会话失败不影响登录流程
        }
        
        // 如果是候选者，查询是否有简历
        if (loginDto.getUser() != null && "candidate".equals(loginDto.getUser().getSysUserType())) {
            HotakeCvInfo query = new HotakeCvInfo();
            query.setUserId(loginDto.getUserId());
            query.setCvFileType("cv");  // 只查询简历类型的文件
            List<HotakeCvInfo> cvList = cvInfoService.selectHotakeCvInfoList(query);
            
            // 设置简历状态标识
            loginDto.setHasCv(!CollectionUtil.isEmpty(cvList));
            loginDto.setCvCount(cvList != null ? cvList.size() : 0);
        }
        
        return R.ok(loginDto,"");
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        Map mapInfo = new HashMap();
        mapInfo.put("user", user);
        mapInfo.put("roles", roles);
        mapInfo.put("permissions", permissions);
        mapInfo.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mapInfo.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        ajax.put("data", mapInfo);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
    
    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }


    /**
     * 忘记密码
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation("忘记密码")
    @PostMapping("/forgotPassword")
    public AjaxResult handlePassword(@RequestBody LoginBody loginBody)
    {
        loginService.resetPassword(loginBody.getUsername(),loginBody.getPassword(),loginBody.getRepeatPassword(),loginBody.getCode(),loginBody.getUuid());
        return AjaxResult.success(MessageUtils.messageCustomize("systemCommonTip10001"));
    }

    /**
     * 退出登录
     * 
     * @return 结果
     */
    @ApiOperation("退出登录")
    @PostMapping("/logout")
    public AjaxResult logout()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        loginService.logout(loginUser);
        return AjaxResult.success("退出成功");
    }
}
