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

import com.kingdee.eas.custom.integration.base.controller.AbstractAuthController;
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.OAuthService;
import com.kingdee.eas.custom.integration.base.service.StateValidator;
import com.kingdee.eas.custom.integration.base.service.detection.PlatformDetectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 钉钉认证控制器。
 *
 * <p>认证入口：{@code GET /auth/dingtalk?state=xxx}</p>
 * <p>回调地址：{@code GET /auth/callback/dingtalk/{appType}}（在钉钉开放平台注册）</p>
 * <p>新增钉钉应用时直接复用本类，无需改动。</p>
 */
@Controller
@RequestMapping("/auth")
public class DingtalkAuthController extends AbstractAuthController {

    public DingtalkAuthController(AppConfigService appConfigService,
                                  OAuthService oAuthService,
                                  StateValidator stateValidator,
                                  PlatformDetectionService detectionService) {
        super(appConfigService, oAuthService, stateValidator, detectionService);
    }

    @Override
    protected String platform() {
        return "dingtalk";
    }

    @GetMapping("/dingtalk")
    public void auth(@RequestParam(name = "state", required = false) String state,
                     HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(state)) {
            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "Invalid state");
        }
        doAuth(state, response);
        //适配玉湖钉钉认证业务，走移动bos钉钉预置接口
        //如需要走钉钉认证，请直接注释掉以下代码,取消注释doAuth(state, response);即可适配其他业务，请自行修改
//        String redirect = stateValidator.extractRedirect(state);
//        String appType = stateValidator.extractAppType(state);
//        if (StringUtils.isBlank(redirect) || StringUtils.isBlank(appType)) {
//            log.error("failed to extract redirect or appType from state, platform={}", platform());
//            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "Invalid state");
//        }
//
//        AppConfig config = appConfigService.get(platform(), appType);
//        if (config == null) {
//            log.error("app config not found, platform={}, appType={}", platform(), appType);
//            throw new IntegrationException(CommonErrorCodes.PARAM_MISSING, "config_not_found");
//        }
//
//        log.info("redirect to OAuth, platform={}, appType={}", platform(), appType);
//
//        String ua = request.getHeader("User-Agent");
//        DeviceType device = detectionService.detectDevice(ua);
//        //移动端跳转到移动bos
//        Boolean isRedirectMbos = RedirectTypeEnum.TO_MBOS.equals(config.getMobileRedirectType());
//        //桌面端跳转到 shr
//        Boolean isDesktopToShr = RedirectTypeEnum.TO_SHR.equals(config.getDesktopRedirectType());
//
//        String utf8String = StandardCharsets.UTF_8.toString();
//
//        if ((device == DeviceType.MOBILE && isRedirectMbos) || (device == DeviceType.DESKTOP && !isDesktopToShr)) {
//            //校验单据是否存在
//            SHRApiUtils.checkBillExist(redirect);
//
//            //跳转到预制移动bos页面
//            String mBosEid = config.getMBosEid();
//            String urlFlag = "https://mbos.kdeascloud.com/mbos";
//            if (redirect.startsWith(urlFlag)) {
//                //移动端地址不要带域名,因为不然会重复生成两遍域名
//                redirect = redirect.substring(urlFlag.length());
//            }
//            //跳转到钉钉移动bos页面
//            String redirectUrl = UriComponentsBuilder.fromUriString("https://mbos.kdeascloud.com/mbos/auth/dingtalk.html")
//                    .queryParam("CorpId", URLEncoder.encode(mBosEid, utf8String))
//                    .queryParam("eid", URLEncoder.encode(mBosEid, utf8String))
//                    .queryParam("replaceUrl", URLEncoder.encode(redirect, utf8String))
//                    .queryParam("AppKey", URLEncoder.encode(config.getAppId(), utf8String))
//                    .build(true)
//                    .toUriString();
//
//            String targetUrl = UriComponentsBuilder.fromUriString("dingtalk://dingtalkclient/page/link")
//                    .queryParam("url", URLEncoder.encode(redirectUrl, utf8String))
//                    .queryParam("pc_slide", "true")
//                    .build(true)
//                    .toUriString();
//
//            log.info("redirect to mbos, redirectUrl={}, appType={}, redirectUrl={}", platform(), appType, targetUrl);
//            response.sendRedirect(targetUrl);
//        } else {
//            doAuth(state, response);
//        }
    }

    @GetMapping("/callback/dingtalk/{appType}")
    public void callback(String code, String state,
                         @PathVariable String appType,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        doCallback(code, state, request, response);
    }
}
