package com.ruoyi.web.controller.system;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WechatLoginStatus;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.WechatService;
import com.ruoyi.system.mapper.WechatLoginStatusMapper;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private WechatLoginStatusMapper wechatLoginStatusMapper;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
    	// System.out.println("loginBody:" + loginBody.toString());
    	String username = null;
    	String password = null;
    	try {
			username = new String(Base64.getDecoder().decode(loginBody.getUsername()), "UTF-8");
			password = new String(Base64.getDecoder().decode(loginBody.getPassword()), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			return AjaxResult.error("解密字符串出错:" + e.getMessage());
		}
    	
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(username, password, loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        log.debug("ajax:{}", ajax.toString());
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 微信登录
     * 
     * @param loginId 登录ID
     * @return 结果
     */
    @PostMapping("/wechat/login")
    public AjaxResult wechatLogin(@RequestParam String loginId)
    {
        try {
            // 查询登录状态
            WechatLoginStatus loginStatus = wechatLoginStatusMapper.selectWechatLoginStatusById(loginId);
            if (loginStatus == null) {
                return AjaxResult.error("登录状态不存在");
            }
            
            // 检查状态是否为已确认
            if (!"2".equals(loginStatus.getStatus())) {
                return AjaxResult.error("登录状态不正确");
            }
            
            // 根据openid查询用户
            SysUser user = userService.selectUserByWechatOpenid(loginStatus.getOpenid());
            if (user == null) {
                return AjaxResult.error("未找到绑定的用户");
            }
            
            // 检查用户状态
            if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                return AjaxResult.error("用户已被删除");
            }
            if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                return AjaxResult.error("用户已被禁用");
            }
            
            // 创建登录用户对象
            LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
            
            // 生成令牌
            String token = tokenService.createToken(loginUser);
            
            // 更新登录状态为已使用
            loginStatus.setStatus("4"); // 已使用
            loginStatus.setUpdateTime(new Date());
            wechatLoginStatusMapper.updateWechatLoginStatus(loginStatus);
            
            AjaxResult ajax = AjaxResult.success();
            ajax.put(Constants.TOKEN, token);
            return ajax;
        } catch (Exception e) {
            log.error("微信登录失败", e);
            return AjaxResult.error("微信登录失败: " + e.getMessage());
        }
    }
}
