package com.blueland.bpm.manage.web;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.blueland.bpm.application.model.ApplicationEntity;
import com.blueland.bpm.application.service.Application2UserManager;
import com.blueland.bpm.application.service.ApplicationManager;
import com.blueland.bpm.common.base.BaseSpringController;
import com.blueland.bpm.common.page.Page;
import com.blueland.bpm.common.util.HttpUtils;
import com.blueland.bpm.engine.core.model.ProcessDefinitionModel;
import com.blueland.bpm.engine.core.model.SearchProcessListDTO;
import com.blueland.bpm.engine.core.service.ProcessDefinitionService;
import com.blueland.bpm.engine.util.cache.ShareCache;
import com.blueland.bpm.identity.model.User;
import com.blueland.bpm.manage.util.BaseUser;
import com.blueland.bpm.manage.util.MyContants;

@Controller
@RequestMapping(value = "applicationMgr")
public class ApplicationController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	@Autowired
	private ApplicationManager applicationManager;
	@Autowired
	private Application2UserManager application2UserManager;
	@Autowired
	private ProcessDefinitionService processDefinitionService;
	
	private final String LIST_ACTION = "redirect:/applicationMgr/list.do";
	
	public ApplicationController() {
	}
	

	/**
	 * 增加了@ModelAttribute的方法可以在本controller的方法调用前执行,可以存放一些共享变量,如枚举值
	 */
	@ModelAttribute
	public void init(ModelMap model) {
		//model.put("now", new java.sql.Timestamp(System.currentTimeMillis()));
	}
	
	/** 
	 * 执行搜索 
	 **/
	@RequestMapping(value = "list")
	public ModelAndView list(HttpServletRequest request,ApplicationEntity query) {
		boolean isebpmAdmin =(Boolean) request.getSession().getAttribute(BaseUser.ROLE_EBPMADMIN);
		if(!isebpmAdmin){
			String currentAppId = request.getSession().getAttribute(MyContants.APP_ID_KEY).toString();
			query.setAppId(currentAppId);
		}
		
		query.setAppTypes("('inner','outside')");
		Page page = this.applicationManager.findPageByMgr(query);
		ModelAndView result = new ModelAndView("/applicationMgr/list");
		result.addAllObjects(toModelMap(page, query));
		return result;
	}
	
	/** 
	 * 查看对象
	 **/
	@RequestMapping(value = "show")
	public ModelAndView show(HttpServletRequest request)  {
		String id = new String(request.getParameter("appId"));
		ApplicationEntity application = (ApplicationEntity)applicationManager.getById(id);
		return new ModelAndView("/applicationMgr/show","application",application);
	}
	
	/** 
	 * 进入新增页面
	 **/
	@RequestMapping(value = "create")
	public ModelAndView create(HttpServletRequest request,ApplicationEntity application)  {
		return new ModelAndView("/applicationMgr/create","application",application);
	}
	
	/** 
	 * 保存新增对象
	 **/
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(HttpServletRequest request,ApplicationEntity application,String appManagerIds)  {
		HttpSession session=request.getSession(false);
		String[] users = appManagerIds.split(",");
		User userData=(User)session.getAttribute(MyContants.LOGIN_SESSION_USER);
		application.setAppCreatorId(userData.getUserId());
		applicationManager.save(application);
		application2UserManager.addApplicationUser(application.getAppId(), users);
		//redirectAttributes.addFlashAttribute(ACTION_MESSAGE, CREATED_SUCCESS);
		ShareCache.setIpList(applicationManager.getAllowIpList());
		return ACTION_SUCCESS;
	}
	
	/**
	 * 进入更新页面
	 **/
	@RequestMapping(value = "edit")
	public ModelAndView edit(HttpServletRequest request)  {
		String id = new String(request.getParameter("appId"));
		ApplicationEntity application = (ApplicationEntity)applicationManager.getById(id);
		return new ModelAndView("/applicationMgr/edit","application",application);
	}
	
	/**
	 * 保存更新对象
	 **/
	@RequestMapping(value = "update")
	@ResponseBody
	public String update(HttpServletRequest request,ApplicationEntity application,String appManagerIds)  {
		String id = new String(request.getParameter("appId"));
		applicationManager.update(application);
		String[] users = appManagerIds.split(",");
		application2UserManager.deleteApplicationUser(id);
		application2UserManager.addApplicationUser(id, users);
		//redirectAttributes.addFlashAttribute(ACTION_MESSAGE, UPDATE_SUCCESS);
		ShareCache.setIpList(applicationManager.getAllowIpList());
		return ACTION_SUCCESS;
	}
		
	@RequestMapping(value = "delete")
	public ModelAndView delete(HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		String[] items = request.getParameterValues("items");
		for (int i = 0; i < items.length; i++) {
			Hashtable params = HttpUtils.parseQueryString(items[i]);
			String id = new String((String) params.get("appId"));
			SearchProcessListDTO searchProcessListDTO = new SearchProcessListDTO();
			searchProcessListDTO.setTenantId(id);
			// 查询符合条件的流程定义列表
			List<ProcessDefinitionModel> processDefinitions = processDefinitionService
					.findProcessDefsNotCascide(searchProcessListDTO);
			System.out.println("查询到出的流程定义列表:" + processDefinitions.size());
			if (processDefinitions.size() == 0) {
				application2UserManager.deleteApplicationUser(id);
				applicationManager.removeById(id);
				redirectAttributes.addFlashAttribute(ACTION_MESSAGE,
						DELETE_SUCCESS);
			} else {
				redirectAttributes.addFlashAttribute(ACTION_MESSAGE,
						"该应用系统内包含流程定义，无法进行删除操作!");
			}
		}
		return new ModelAndView(LIST_ACTION);
	}
	
	/**
	 * 提供给快速开发平台同步应用
	 * @param request
	 * @param application
	 * @param appManagerIds
	 * @param flag
	 * @return
	 */
	@RequestMapping(value = "syncApp")
	@ResponseBody
	public String syncApp(HttpServletRequest request,@RequestBody Map<String,Object> params)  {
		if(params.containsKey("appId") && params.containsKey("appName") && params.containsKey("appManagerIds")
				&& params.containsKey("flag") && params.containsKey("userId")){
			String[] users = params.get("appManagerIds").toString().split(",");
			ApplicationEntity application = new ApplicationEntity();
			application.setAppCreatorId( params.get("userId").toString());
			application.setAppId(params.get("appId").toString());
			application.setAppName(params.get("appName").toString());
			String appId =application.getAppId();
			ApplicationEntity app = applicationManager.getById(appId);
			if(params.get("flag").equals("Y")){//如果是需要建应用，先查找这个应用是否存在，存在就更新应用，删除人员，新增人员，否则新增应用、新增人员
				application.setAppStatus("N");
				application.setAppType("inner");
				application.setAppProvider("湖南天惟");
				if(app==null){
					applicationManager.save(application);
					application2UserManager.addApplicationUser(appId, users);			
				}else{
					applicationManager.update(application);
					application2UserManager.deleteApplicationUser(appId);
					application2UserManager.addApplicationUser(appId, users);
				}
			}else{
				if(app!=null){//如果有该应用制为停用
					application.setAppStatus("T");
					application.setAppProvider("湖南天惟");
					applicationManager.update(application);
				}
			}
		}else{
			System.out.println("调用syncApp接口失败,appId、appName、appManagerIds、flag为必填参数，入参为："+params);
			return  ACTION_ERROR;
		}
		
		
		//ShareCache.setIpList(applicationManager.getAllowIpList());
		return ACTION_SUCCESS;
	}
}
