package com.ygtx.web.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ygtx.common.constant.UserConstants;
import com.ygtx.common.core.domain.entity.SysUser;
import com.ygtx.common.core.domain.model.LoginUser;
import com.ygtx.common.config.IceSsoProperties;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.common.utils.http.IceSsoHttpUtil;
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.ISysUserService;
import com.ygtx.web.service.IceSsoService;
import com.ygtx.web.util.SsoUserSyncUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * ICE单点登录服务实现
 * 
 * @author ruoyi
 */
@Service
public class IceSsoServiceImpl implements IceSsoService
{
    private static final Logger log = LoggerFactory.getLogger(IceSsoServiceImpl.class);

    @Autowired
    private IceSsoProperties iceSsoProperties;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private IceSsoHttpUtil iceSsoHttpUtil;

    @Autowired
    private SsoUserSyncUtil ssoUserSyncUtil;

    /**
     * 处理SSO登录逻辑
     */
    @Override
    public Map<String, Object> handleSsoLogin(String apptoken, String appid, Integer oauth)
    {
        // 从ICE系统获取用户信息
        return getIceUserInfo(apptoken, appid, oauth);
    }

    /**
     * 获取ICE用户信息
     */
    @Override
    public Map<String, Object> getIceUserInfo(String apptoken, String appid, Integer oauth)
    {
        try 
        {
            // 准备请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("apptoken", apptoken);
            params.put("appid", appid);
            params.put("oauth", oauth);

            // 发送HTTP请求到ICE系统
//            String response = sendHttpPostRequest(iceSsoProperties.getSso().getUrl(), params);
            String response = "{\n" +
                    "    \"ret\": \"0\",\n" +
                    "    \"msg\": \"用户信息获取成功\",\n" +
                    "\"data\": {\n" +
                    "       \"username\": \"admin\",\n" +
                    "       \"employee_num\": \"admin\",\n" +
                    "       \"company_num\": \"当前登录公司的MDM编号可能为空\"},\n" +
                    "\"time\":\"Thu Nov 05 04:12:55 +0000 2020\"\n" +
                    "}\n";

            if (response == null || response.isEmpty()) 
            {
                log.error("获取ICE用户信息失败：响应为空");
                Map<String, Object> errorResult = new HashMap<>();
                errorResult.put("ret", "1");
                errorResult.put("msg", "获取用户信息失败：响应为空");
                return errorResult;
            }

            // 解析响应
            JSONObject jsonResponse = JSON.parseObject(response);
            String ret = jsonResponse.getString("ret");
            
            if ("0".equals(ret)) 
            {
                log.info("成功获取ICE用户信息");
            } 
            else 
            {
                log.error("获取ICE用户信息失败：{}", jsonResponse.getString("msg"));
            }

            return jsonResponse;
        } 
        catch (Exception e) 
        {
            log.error("获取ICE用户信息过程中发生异常", e);
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("ret", "1");
            errorResult.put("msg", "获取用户信息过程中发生异常：" + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 处理用户登录逻辑
     */
    @Override
    public String processUserLogin(Map<String, Object> userData)
    {
        if (userData == null) 
        {
            throw new RuntimeException("用户数据不能为空");
        }

        // 提取用户信息
        String username = (String) userData.get("username");
        String employeeNum = (String) userData.get("employee_num");
        String companyNum = (String) userData.get("company_num");

        if (username == null || username.trim().isEmpty()) 
        {
            throw new RuntimeException("用户名不能为空");
        }

        // 根据用户名查找用户
        SysUser user = findOrCreateUser(username, employeeNum, companyNum);
        
        if (user == null) 
        {
            throw new RuntimeException("用户不存在");
        }

        // 创建LoginUser对象
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));

        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 查找或创建用户
     */
    private SysUser findOrCreateUser(String username, String employeeNum, String companyNum)
    {
        // 使用SsoUserSyncUtil同步用户信息
        Map<String, Object> userData = new HashMap<>();
        userData.put("username", username);
        userData.put("employee_num", employeeNum);
        userData.put("company_num", companyNum);
        
        return ssoUserSyncUtil.syncIceUser(userData);
    }

    /**
     * 发送HTTP POST请求
     */
    private String sendHttpPostRequest(String url, Map<String, Object> params)
    {
        try 
        {
            return iceSsoHttpUtil.sendPostRequest(url, params);
        } 
        catch (Exception e) 
        {
            log.error("发送HTTP请求失败", e);
            return null;
        }
    }
    
    @Override
    public String getConfiguredAppid() {
        return iceSsoProperties.getSso().getAppId();
    }
}