package com.ygtx.web.controller.common;

import com.ygtx.common.constant.Constants;
import com.ygtx.common.core.domain.AjaxResult;
import com.ygtx.common.core.domain.model.LoginBody;
import com.ygtx.web.service.IceSsoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * ICE单点登录控制器
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/ice/sso")
public class IceSsoController
{
    private static final Logger log = LoggerFactory.getLogger(IceSsoController.class);

    @Autowired
    private IceSsoService iceSsoService;

    /**
     * ICE SSO登录接口
     * 
     * @param loginBody 应用令牌
     * @return 登录结果
     */
    @PostMapping("/login")
    public AjaxResult ssoLogin(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        try 
        {
            // 验证必要参数
            if (loginBody.getApptoken() == null || loginBody.getApptoken().trim().isEmpty())
            {
                return AjaxResult.error("apptoken参数不能为空");
            }
            
            // 从配置中获取appid
            String configuredAppid = iceSsoService.getConfiguredAppid();
            if (configuredAppid == null || configuredAppid.trim().isEmpty()) 
            {
                return AjaxResult.error("系统配置的appid不能为空");
            }

            // 调用SSO服务处理登录逻辑
            Map<String, Object> result = iceSsoService.handleSsoLogin(loginBody.getApptoken(), configuredAppid, 0);
            
            if (result != null && "0".equals(result.get("ret"))) 
            {
                // 登录成功，返回token
                Map<String, Object> userData = (Map<String, Object>) result.get("data");
                String token = iceSsoService.processUserLogin(userData);
                ajax.put(Constants.TOKEN, token);
            } 
            else 
            {
                // 登录失败
                String errorMsg = result != null ? (String) result.get("msg") : "获取用户信息失败";
                return AjaxResult.error(errorMsg);
            }
        } 
        catch (Exception e) 
        {
            log.error("ICE SSO登录过程发生异常", e);
            if (e.getMessage().contains("用户不存在")) {
                return AjaxResult.error("用户不存在");
            }
            return AjaxResult.error("SSO登录过程发生异常：" + e.getMessage());
        }
        return ajax;
    }
}