package com.ruoyi.web.controller.system;

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.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.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.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * CAS登录方法
     *
     * @param ticket  CAS票据
     * @param service 服务地址
     * @return 结果
     */
    @PostMapping("/cas/login")
    public AjaxResult casLogin(@RequestParam("ticket") String ticket, @RequestParam("service") String service) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.casLogin(ticket, service);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 移动端CAS登录方法
     *
     * @param ticket CAS票据
     * @return 结果
     */
    @PostMapping("/cas/app/login")
    public AjaxResult casAppLogin(@RequestParam("ticket") String ticket) {
        // 使用统一的CAS回调地址,与PC端保持一致
        String appService = "https://pasd.gxsdxy.cn/cas/cas-callback";
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.casLogin(ticket, appService);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 统一CAS登录方法 - 根据User-Agent自动分发到PC或移动端
     * 
     * @param ticket  CAS票据
     * @param request HttpServletRequest
     * @return 结果
     */
    @PostMapping("/cas/unified/login")
    public AjaxResult casUnifiedLogin(@RequestParam("ticket") String ticket,
            javax.servlet.http.HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        String service;

        // 由于CAS服务器回调时,User-Agent是CAS服务器的,所以直接使用统一的CAS回调地址
        // 这个地址应该与CAS登录请求时使用的service参数一致
        service = "https://pasd.gxsdxy.cn/cas/cas-callback";

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.casLogin(ticket, service);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 统一CAS回调分发 - 根据User-Agent重定向到PC或移动端
     * 
     * @param request HttpServletRequest
     * @return 重定向结果
     */
    @GetMapping("/cas/unified/callback")
    public org.springframework.web.servlet.ModelAndView unifiedCasCallback(
            javax.servlet.http.HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");

        org.springframework.web.servlet.ModelAndView modelAndView = new org.springframework.web.servlet.ModelAndView();

        // 检测是否为移动设备
        if (isMobileDevice(userAgent)) {
            modelAndView.setViewName("redirect:/app-cas/");
        } else {
            modelAndView.setViewName("redirect:/");
        }

        return modelAndView;
    }

    /**
     * 检测是否为移动设备
     * 
     * @param userAgent User-Agent字符串
     * @return 是否为移动设备
     */
    private boolean isMobileDevice(String userAgent) {
        if (userAgent == null) {
            return false;
        }

        userAgent = userAgent.toLowerCase();

        String[] mobileKeywords = {
                "android", "webos", "iphone", "ipad", "ipod", "blackberry",
                "windows phone", "iemobile", "opera mini", "mobile"
        };

        for (String keyword : mobileKeywords) {
            if (userAgent.contains(keyword)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().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);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}