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

import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.custom.integration.base.bizEnum.DeviceType;
import com.kingdee.eas.custom.integration.base.bizEnum.RedirectTypeEnum;
import com.kingdee.eas.custom.integration.base.config.AppConfig;
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.service.AppConfigService;
import com.kingdee.eas.custom.integration.base.service.StateValidator;
import com.kingdee.eas.custom.integration.base.service.detection.PlatformDetectionService;
import com.kingdee.eas.custom.integration.base.util.EncryptUtil;
import com.kingdee.eas.custom.integration.base.util.SHRApiUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: heyuan
 * @date: 2026/4/9 14:05
 * @description: 工号统一认证接口
 */
@Controller
@RequestMapping("/auth/V2")
public class EmpNoUnifiedAuthController {
    private Logger log = LoggerFactory.getLogger(EmpNoUnifiedAuthController.class);


    private final AppConfigService appConfigService;
    private final StateValidator stateValidator;
    private final PlatformDetectionService detectionService;

    public EmpNoUnifiedAuthController(AppConfigService appConfigService,
                                      StateValidator stateValidator,
                                      PlatformDetectionService detectionService) {
        this.appConfigService = appConfigService;
        this.stateValidator = stateValidator;
        this.detectionService = detectionService;
    }

    /**
     * 工号单点登录
     *
     * @param state
     * @param request
     * @return
     */
    @RequestMapping("/sso")
    public void ssoByNumber(String state, HttpServletRequest request, HttpServletResponse response) throws IntegrationException {
        log.info("统一认证 ssoSHRByNumber 开始 state{}", state);

        if (StringUtils.isBlank(state)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "Invalid state");
        }

        String redirect = stateValidator.extractRedirect(state);
        if (StringUtils.isBlank(redirect)) {
            log.error("统一认证 ssoByNumber 重定向地址为空!");
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "重定向地址不能为空");
        }

        String number = stateValidator.extractAppType(state);
        if (StringUtils.isBlank(number)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "获取用户失败");
        }

        //String ua = request.getHeader("User-Agent");
        //String platformBase = detectionService.detectBasePlatform(ua);
        String platformBase = "feishu";
//        if (platformBase == null) {
//            log.warn("unsupported client, UA={}", ua);
//            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "unsupported_client");
//        }
        //客户端类型
        //DeviceType device = detectionService.detectDevice(ua);
        DeviceType device = DeviceType.MOBILE;
        String platformFull = platformBase + (device != null ? "_" + device.name().toLowerCase() : "");

        AppConfig appConfig = appConfigService.getPrimaryApp(platformBase);

        if (appConfig == null) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "未加载到配置");
        }

        log.info("统一认证, platform={}, device={}, number={}, redirect={}",
                platformFull, device, number, redirect);
        try {
            //解密number
            number = EncryptUtil.decryptToStr(number);
        } catch (Exception e) {
            log.error("统一认证 ssoByNumber 解密number失败:{}", e.getMessage(), e);
            throw new IntegrationException(CommonErrorCodes.SYSTEM_ERROR, "解密用户信息失败");
        }

        log.info("统一认证解密成功number: {}", number);
        try {
            //2、检查用户是否存在
            UserInfo userInfo = SHRApiUtils.getUserInfo(appConfig.getUserMappingField(), number);

            //3、检查单据是否存在
            SHRApiUtils.checkBillExist(redirect);

            String targetUrl = null;

            Boolean isRedirectMbos = RedirectTypeEnum.TO_MBOS.equals(appConfig.getMobileRedirectType());
            Boolean isDesktopToShr = RedirectTypeEnum.TO_SHR.equals(appConfig.getDesktopRedirectType());

            if ((device == DeviceType.MOBILE && isRedirectMbos) || (device == DeviceType.DESKTOP && !isDesktopToShr)) {
                //跳转移动bos
                if (!redirect.contains("eid=")) {
                    String mBosEid = appConfig.getMBosEid();
                    redirect += "&eid=" + mBosEid;
                }
                targetUrl = SHRApiUtils.generateToMBosUrl(userInfo.getNumber(), redirect);
            } else {
                targetUrl = SHRApiUtils.generateDirectLoginUrl(appConfigService.getShrServerName(), userInfo.getNumber(), redirect);
            }

            log.error("统一认证 ssoSHRByNumber 单点sHR地址: {}", targetUrl);
            response.sendRedirect(targetUrl);
        } catch (Exception e) {
            log.error("统一认证 ssoSHRByNumber 单点sHR失败:{}", e.getMessage(), e);
            throw new IntegrationException(CommonErrorCodes.SYSTEM_ERROR, e.getMessage());
        }
    }
}

