package com.dsideal.sso.Controller;

import java.util.Map;
import java.util.UUID;

import com.dsideal.sso.Interceptor.EmptyInterface;
import com.dsideal.sso.Util.CommonUtil;
import com.dsideal.sso.Util.SsoLoginHelper;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;

public class AppLoginController extends Controller {
    /**
     * app登录
     *
     * @param username 用户名
     * @param password 密码
     */
    @Before({POST.class})
    @EmptyInterface({"username", "password"})
    public void doLogin(String username, String password) {
        JSONObject resultJson = new JSONObject();
        String passwordEncode = CommonUtil.getLdapPassword(password);
        Map<String, String> loginMap = CommonUtil.getLoginRouteMap(username);
        if (passwordEncode != null && (loginMap == null || !passwordEncode.equals(loginMap.get("password")))) {
            resultJson.put("success", false);
            resultJson.put("msg", "用户名或密码错误！");
            renderJson(resultJson);
        }
        String sessionId = UUID.randomUUID().toString();
        SsoLoginHelper.login(sessionId, loginMap);
        resultJson.put("success", true);
        resultJson.put("sessionId", sessionId);
        if (loginMap != null) {
            resultJson.put("identity_id", loginMap.get("identity_id"));
        }
        if (loginMap != null) {
            resultJson.put("person_id", loginMap.get("person_id"));
        }
        if (loginMap != null) {
            resultJson.put("person_name", loginMap.get("person_name"));
        }
        if (loginMap != null) {
            resultJson.put("bureau_id", loginMap.get("bureau_id"));
        }
        renderJson(resultJson);
    }

    /**
     * app登出
     *
     * @throws Exception
     */
    public void logout() {
        String sessionId = getPara("sessionId");
        SsoLoginHelper.logout(sessionId);
    }
}
