package com.palmnest.webapp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.core.util.GenPass;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.VirtualAccount;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.redis.BaseRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


/**
 * 用户登录成功后续逻辑处理
 * Created by HXT on 2018/8/6.
 */
@Slf4j
public class SimpleLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

	private RequestCache requestCache = new HttpSessionRequestCache();

	@Autowired
	private OrganizationManager organizationManager;
	@Autowired
	private BaseRedisService    baseRedisService;

	private long time = 60 * 60 * 24 * 7;//7天有效


	/**
	 * @param request
	 * @param response
	 * @param authentication
	 * @throws IOException
	 * @throws ServletException
	 */
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {

		log.info("---------用户登陆成功逻辑处理-----------");

		if (authentication.getPrincipal() instanceof UserDetails) {

			//获取登录用户信息
			User user = (User) authentication.getPrincipal();

			List<TbOrganization> list = organizationManager.getUserRelationOrganizationList(user.getId());

			//构建json数组存入项目id与名称
			JSONArray jsonArray = new JSONArray();
			for (TbOrganization t : list) {
				JSONObject obj = new JSONObject();
				obj.put("id", t.getId());
				obj.put("name", t.getName());
				obj.put("meetCode", t.getMettingClient());
				jsonArray.add(obj);
			}

			// TODO 标记 新旧融合
			// 此为后台用户 可管理 项目 列表 [{"id":6,"meetCode":"","name":"深圳中航苑飞亚达大厦"},...]
			// 存入redis缓存 对应key为: userManageOrg_userId
			baseRedisService.set(AppConstants.USERMANAGEORG + user.getId(), jsonArray.toJSONString());

			// 获取到原登陆成功后的跳转页面

			// 保存PCtoken
			// 与问卷、投诉表扬等对接
			Long   datatimeStr  = new Date().getTime();
			String sso_codeData = user.getUsername() + "|" + datatimeStr + "|" + CodeConstants.CLIENT_PC;
			String PcToken      = URLEncoder.encode(GenPass.Encrypt(sso_codeData), "UTF-8");
			request.getSession().setAttribute("PcToken", PcToken);
			log.info("SimpleLoginSuccessHandler PcToken===>" + PcToken);

		} else {
			VirtualAccount virAccount = (VirtualAccount) authentication.getPrincipal();// 登录的企业账号
			System.out.println(virAccount.getVirAccount());
		}


		SavedRequest savedRequest = requestCache.getRequest(request, response);
		if (savedRequest == null) {
			super.onAuthenticationSuccess(request, response, authentication);
			return;
		}
		String redirectUrl = savedRequest.getRedirectUrl();
		response.sendRedirect(redirectUrl);
	}
}
