package com.malk.guangming.controller;

import com.malk.guangming.config.GuangmingConfig;
import com.malk.guangming.service.DingTalkAuthService;
import com.malk.guangming.util.RSACrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@RestController
public class MailSsoController {

    @Autowired
    private DingTalkAuthService dingTalkAuthService;

    @Autowired
    private GuangmingConfig config;

    /**
     * 钉钉SSO跳转德惠邮箱
     * 前端通过JSAPI获取authCode后调用此接口，后端完成认证和加密后302跳转到邮箱
     *
     * @param authCode 钉钉免登授权码
     */
    @GetMapping("/sso/mail")
    public void ssoMail(@RequestParam String authCode, HttpServletResponse response) throws IOException {
        try {
            // 1. 通过authCode获取用户userId
            String userId = dingTalkAuthService.getUserId(authCode);
            log.info("[SSO邮箱] userId: {}", userId);

            // 2. 获取用户邮箱
//            String email = dingTalkAuthService.getUserEmail(userId);
//            String email = "leixiaochuan@brightfood.com";
            String email = "linke@brightfood.com";

            log.info("[SSO邮箱] email: {}", email);

            // 3. 截取邮箱@前面的部分作为uid
            String uid = email.contains("@") ? email.substring(0, email.indexOf("@")) : email;

            // 4. RSA加密 + URL安全处理
            String encryptedUid = RSACrypt.encrypt(uid, config.getMailSso().getPublicKey());
            String safeUid = RSACrypt.toUrlSafe(encryptedUid);

            // 5. 拼接SSO URL并跳转
            String ssoUrl = config.getMailSso().getSsoUrl() + "&uid=" + safeUid;
            log.info("[SSO邮箱] 跳转: {}", ssoUrl);
            response.sendRedirect(ssoUrl);

        } catch (Exception e) {
            log.error("[SSO邮箱] 登录失败", e);
            response.setContentType("text/html;charset=utf-8");
            String errMsg = e.getMessage() != null ? e.getMessage().replace("'", "\\'") : "未知错误";
            response.getWriter().write(
                "<!DOCTYPE html><html><head><meta charset='UTF-8'><meta name='viewport' content='width=device-width,initial-scale=1.0'>"
                + "<script src='https://g.alicdn.com/dingding/dingtalk-jsapi/3.0.12/dingtalk.open.js'></script></head>"
                + "<body><script>"
                + "if(/DingTalk/i.test(navigator.userAgent)){"
                +   "dd.device.notification.alert({title:'登录失败',message:'" + errMsg + "',buttonName:'返回',"
                +     "onSuccess:function(){dd.biz.navigation.close();}});"
                + "}else{"
                +   "document.body.innerHTML='<div style=\"display:flex;justify-content:center;align-items:center;height:100vh;font-family:sans-serif\">"
                +     "<div style=\"text-align:center\"><div style=\"width:48px;height:48px;margin:0 auto 16px;border-radius:50%;background:#fee;display:flex;justify-content:center;align-items:center;font-size:24px\">&#10060;</div>"
                +     "<p style=\"font-size:15px;color:#666\">" + errMsg + "</p></div></div>';"
                + "}"
                + "</script></body></html>"
            );
        }
    }
}
