package org.jeecg.modules.cas.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jasig.cas.client.validation.Assertion;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.modules.base.service.BaseCommonService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
 * CAS单点登录客户端登录认证
 * </p>
 *
 * @Author zhoujf
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/cas/client")
public class CasClientController {
    @Value("${wellbore.redirect-url}")
    private String redirectUrl;

    @Value("${wellbore.redirect-cas-url}")
    private String redirectCasUrl;

    @Resource
    private BaseCommonService baseCommonService;
    /**
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ApiOperation("登录接口")
    @GetMapping("/validateLogin")
    public Object validateLogin(HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        Result<JSONObject> result = new Result<JSONObject>();
        log.info("Rest api login.");
        try {
            final String principal = ((Assertion) request.getSession().getAttribute(CommonConstant.CAS_USER_SESSION_KEY)).getPrincipal().getName();
            if (StringUtils.isEmpty(principal)) {
                throw new Exception("No principal was found in the response from the CAS server.");
            }
            log.info("重定向地址:{}",redirectUrl);
            baseCommonService.addLog("用户名: " + principal + ",登录成功！", CommonConstant.LOG_TYPE_1, null);
            response.sendRedirect(redirectUrl);
        } catch (Exception e) {
            //e.printStackTrace();
            result.error500(e.getMessage());
        }

        log.info("Rest api login out.{}",result);
        return new HttpEntity<>(result);
    }

    @GetMapping("/redirect")
    public void redirectIframe(HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        log.info("重定向地址:{}",redirectCasUrl);
        response.sendRedirect(redirectCasUrl);
    }
}
