package com.ygtx.web.controller.system;

import java.util.Date;
import java.util.List;
import java.util.Set;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ygtx.common.annotation.Anonymous;
import com.ygtx.common.constant.Constants;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.core.domain.entity.SysMenu;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginBody;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.core.text.Convert;
import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.SecurityUtils;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.framework.web.service.SysLoginService;
import com.ygtx.framework.web.service.SysPermissionService;
import com.ygtx.framework.web.service.TokenService;
import com.ygtx.system.service.ISysConfigService;
import com.ygtx.system.service.ISysMenuService;
import com.ygtx.system.service.ISysUserService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@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 ISysUserService userService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        
        // 检查是否为初始密码
        String initPassword = configService.selectConfigByKey("sys.user.initPassword");
        if (initPassword != null && initPassword.equals(loginBody.getPassword())) {
            // 验证用户名和密码是否正确
            try {
                String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                        loginBody.getUuid());
                // 如果能成功登录，说明是初始密码
                ajax.put("isInitPassword", true);
                ajax.put("message", "您使用的是初始密码，请修改密码后再登录");
                return ajax;
            } catch (Exception e) {
                // 用户名或密码错误
                ajax.put("isInitPassword", false);
            }
        }
        
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 初始密码修改
     */
    @Anonymous
    @PutMapping("/initPassword")
    public AjaxResult initPassword(@RequestBody LoginBody loginBody)
    {
        // 验证用户名和密码是否正确
        try {
            loginService.loginPreCheck(loginBody.getUsername(), loginBody.getPassword());

            String initPassword = configService.selectConfigByKey("sys.user.initPassword");
            if (initPassword.equals(loginBody.getPassword())) {
                return AjaxResult.error("新密码不可与初始密码相同");
            }
            // 更新用户密码
            SysUser user = userService.selectUserByUserName(loginBody.getUsername());
            if (user != null) {
                if (!SecurityUtils.matchesPassword(initPassword, user.getPassword())) {
                    return AjaxResult.error("用户密码已被修改");
                }
                user.setPassword(SecurityUtils.encryptPassword(loginBody.getPassword()));
                user.setPwdUpdateDate(new Date());
                userService.resetUserPwd(user.getUserId(), user.getPassword());
                return AjaxResult.success("密码修改成功");
            } else {
                return AjaxResult.error("用户不存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("密码修改失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @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();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @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;
    }
}