package com.kingdee.eas.custom.integration.sng.controller;

import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.custom.integration.base.bizEnum.UserMappingFieldEnum;
import com.kingdee.eas.custom.integration.base.exception.CommonErrorCodes;
import com.kingdee.eas.custom.integration.base.exception.IntegrationException;
import com.kingdee.eas.custom.integration.base.util.SHRApiUtils;
import com.kingdee.eas.custom.integration.sng.service.SNGApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;

/**
 * @author: heyuan
 * @date: 2026/4/9 14:05
 * @description: sng客户端单点移动bos
 * url: /qy/sng/ssoMbos/
 */
@Controller
@RequestMapping("/sng")
public class SNGController {
    private static final Logger logger = LoggerFactory.getLogger(SNGController.class);

    private final SNGApiService sngApiService;

    public SNGController(SNGApiService sngApiService) {
        this.sngApiService = sngApiService;
    }

    /**
     * 单点移动bos
     *
     * @param code 用户账号
     * @return
     */
    @GetMapping("/ssoMbos")
    public String ssoMbos(String code, String appId, String redirectUrl) throws IntegrationException {
        logger.info("ssoMbos 开始 code: {}, appId: {}, redirectUrl: {}", code, appId, redirectUrl);

        if (!StringUtils.hasText(code)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "code不能为空");
        }
        if (!StringUtils.hasText(appId)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "应用ID不能为空");
        }
        if (!StringUtils.hasText(redirectUrl)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "重定向地址不能为空");
        }
        try {
            //1、获取token
            String sngToken = sngApiService.getToken(appId);

            //2、获取sng客户端用户账号
            String userNumber = sngApiService.getUserNumber(sngToken, code);

            if (!StringUtils.hasText(userNumber)) {
                throw new IntegrationException(CommonErrorCodes.USER_NOT_EXIST, "用户账号为空");
            }
            logger.info("ssoMbos 用户账号: {}", userNumber);

            //3、检查sHR用户是否存在
            UserInfo userInfo = SHRApiUtils.getUserInfo(UserMappingFieldEnum.USER_NUMBER, userNumber);

            //4、构建单点移动bos地址
            String targetUrl = SHRApiUtils.generateToMBosUrl(userInfo.getNumber(), redirectUrl);

            logger.info("ssoMbos 单点移动bos地址: {}", targetUrl);

            return targetUrl;
        } catch (UnsupportedEncodingException e) {
            logger.error("ssoMbos 失败:{}", e.getMessage(), e);
            throw new IntegrationException(CommonErrorCodes.SYSTEM_ERROR, "单点移动bos失败", e);
        }
    }
}

