package cn.com.victorysoft.business.controller;

import cn.com.victorysoft.business.util.JwtUtils;
import com.sinopec.siam.agent.common.SSOPrincipal;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("siam")
public class SiamController {

    @Value("${frontend.siam.url}")
    private String frontendSiamUrl;

    @SneakyThrows
    @GetMapping
    public void callback(HttpServletRequest request, HttpServletResponse response) {
        SSOPrincipal ssoPrincipal = (SSOPrincipal)request.getSession().getAttribute(SSOPrincipal.NAME_OF_SESSION_ATTR);
        String uid = ssoPrincipal.getUid();
        String realName = ssoPrincipal.getCn();
        String orgCode = "", deptName = "", deptFullName = "";
        List departmentNumberList = ssoPrincipal.getValueAsList("departmentNumber");
        if (departmentNumberList != null && departmentNumberList.size() > 0) {
            orgCode = (String) departmentNumberList.get(0);
        }
        List ouList = ssoPrincipal.getValueAsList("ou");
        if (ouList != null && ouList.size() > 0) {
            deptName = (String) ouList.get(0);
        }
        List spOrgNamePathList = ssoPrincipal.getValueAsList("spOrgNamePath");
        if (spOrgNamePathList != null && spOrgNamePathList.size() > 0) {
            deptFullName = (String) spOrgNamePathList.get(0);
        }
        log.info("获取统一身份信息：" + JSONObject.fromObject(ssoPrincipal).toString());
        log.info("uid：" + uid + "，cn：" + realName + "，orgCode：" + orgCode);
        // 生成token
        String token = JwtUtils.createToken(uid, realName, orgCode, deptName, deptFullName);
        response.sendRedirect(frontendSiamUrl + "?token=" + token + "&username=" + uid + "&orgCode=" + orgCode + "&realName=" + URLEncoder.encode(realName, "utf-8"));
    }
}
