package com.blueland.bpm.manage.service;

import java.util.ArrayList;
import java.util.List;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.User;
import com.blueland.bpm.manage.util.BaseUser;

@Service
public class AgainSaveSessionService {
	@Autowired
	private UserService userService;
	@Autowired 
	private ApplicationManager applicationManager;
	/**
	 * 根据iv-user 重新注入session
	 * @param request
	 */
	public void saveSession(String appId,HttpServletRequest request,HttpServletResponse response){
		String userId=request.getHeader("iv-user");
		
		if(userId!=null){
			User user=userService.getUserById(userId);
			BaseUser bUser = BaseUser.getInstance();
			bUser.cleanCookieUser(request, response);
			bUser.setCookieUser(response, BaseUser.toUpperCase(user.getUserId()));
			List<ApplicationEntity> list =new ArrayList<ApplicationEntity>();
			if(StringUtils.isNotEmpty(appId)){
				ApplicationEntity app =applicationManager.getById(appId);
				if(app!=null){
					list.add(app);
				}
				
			}else{
				list = applicationManager.selectByUserId(userId);
			}
			if(list!=null && list.size()>0){
				filter(list,"task");
			}
			
			bUser.saveUserToSession(request,user,list);
		}
	}
	public void filter(List<ApplicationEntity> list,String task){
		for (int i=0;i<list.size();i++) {
			if(list.get(i).getAppType()==null||list.get(i).getAppType().equals(task)){
				list.remove(i);
				i--;
			}
		}
	}
}
