package com.blueland.bpm.manage.config.web;

import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;

import org.activiti.bpmn.model.BpmnModel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestMapping;
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.common.base.BaseSpringController;
import com.blueland.bpm.common.page.Page;
import com.blueland.bpm.common.util.HttpUtils;
import com.blueland.bpm.engine.config.model.ProcessInfoConfig;
import com.blueland.bpm.engine.config.service.ProcessInfoConfigManager;
import com.blueland.bpm.engine.core.model.ProcessDefinitionModel;
import com.blueland.bpm.engine.core.service.ProcessConfigService;
import com.blueland.bpm.engine.core.service.ProcessDefinitionService;
import com.blueland.bpm.engine.core.service.ProcessModelService;
import com.blueland.bpm.manage.util.BaseUser;
import com.blueland.bpm.manage.web.SequenceFlowController;

/**
 * @author lw
 * @version 1.0
 * @since  
 */


@Controller
@RequestMapping(value = "/processInfo")
public class ProcessInfoConfigController extends BaseSpringController{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	@Autowired
	private ProcessDefinitionService processDefinitionService;
	@Autowired
	private ProcessInfoConfigManager processInfoConfigManager;
	@Autowired
	private ProcessModelService processModelService;
	@Autowired
	SequenceFlowController sequenceFlowController;
	@Autowired
	ProcessConfigService processConfigService;
	protected Logger logger = LoggerFactory.getLogger(getClass());
	private final String LIST_ACTION = "redirect:/procDefMgr/procInfo/list.do";
	
	public ProcessInfoConfigController() {
	}
	

	/**
	 * 增加了@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,ProcessInfoConfig query) {
		Page page = this.processInfoConfigManager.findPage(query);
		ModelAndView result = new ModelAndView("/procDefMgr/procInfo/list");
		result.addAllObjects(toModelMap(page, query));
		return result;
	}
	
	/** 
	 * 查看对象
	 **/
	@RequestMapping(value = "show")
	public ModelAndView show(HttpServletRequest request)  {
		String id = new String(request.getParameter("processDefId"));
		ProcessInfoConfig processInfoConfig = (ProcessInfoConfig)processInfoConfigManager.getById(id);
		return new ModelAndView("/procDefMgr/procInfo/show","processInfoConfig",processInfoConfig);
	}
	 	/** 
	 * 进入新增页面
	 **/
	@RequestMapping(value = "create")
	public ModelAndView create(HttpServletRequest request,ProcessInfoConfig processInfoConfig)  {
		return new ModelAndView("/procDefMgr/procInfo/create","processInfoConfig",processInfoConfig);
	}
	
	/** 
	 * 保存新增对象
	 **/
	@RequestMapping(value = "save")
	public ModelAndView save(HttpServletRequest request,ProcessInfoConfig processInfoConfig,RedirectAttributes redirectAttributes)  {
		processInfoConfigManager.save(processInfoConfig);
		redirectAttributes.addFlashAttribute(ACTION_MESSAGE, CREATED_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}
	
	/**
	 * 进入更新页面
	 **/
	@RequestMapping(value = "edit")
	public ModelAndView edit(HttpServletRequest request,String procDefId)  {
		if(StringUtils.isEmpty(procDefId)) {
			return new ModelAndView("/procDefModelMgr/info");
		}
		ProcessInfoConfig processInfoConfig =null;
		if(StringUtils.isNotEmpty(procDefId)){
			processInfoConfig = (ProcessInfoConfig)processInfoConfigManager.getById(procDefId);
		}
		return new ModelAndView("/procDefMgr/procInfo/edit","processInfoConfig",processInfoConfig);
	}
	
	/**
	 * 进入更新页面
	 **/
	@RequestMapping(value = "editTable")
	public ModelAndView editTable(HttpServletRequest request,String procDefId)  {
		ProcessInfoConfig processInfoConfig =null;
		if(StringUtils.isNotEmpty(procDefId)){
			processInfoConfig = (ProcessInfoConfig)processInfoConfigManager.getById(procDefId);
		}
		return new ModelAndView("/procDefMgr/procInfo/editTable","processInfoConfig",processInfoConfig);
	}
	
	/**
	 * 保存更新对象
	 **/
	@RequestMapping(value = "update")
	@ResponseBody
	public String update(HttpServletRequest request,ProcessInfoConfig processInfoConfig,RedirectAttributes redirectAttributes)  {
		String id = new String(request.getParameter("processDefId"));
		processInfoConfigManager.saveOrUpdate(processInfoConfig);
		if(StringUtils.isNotEmpty(processInfoConfig.getProcessStartAuth())){
			BpmnModel bpmnModel=processModelService.getBpmnModelByProcDefId(processInfoConfig.getProcessDefId());
			String[] processStartAuths=processInfoConfig.getProcessStartAuth().split(";");
			for (String processStartAuth : processStartAuths) {
				String[] auths=processStartAuth.split(":");
				if("ROLE".equals(auths[0])){
					bpmnModel.getMainProcess().getCandidateStarterGroups().add(auths[1]);
				}else if("USERS".equals(auths[0])){
					bpmnModel.getMainProcess().getCandidateStarterUsers().add(auths[1]);
				}
			}
			sequenceFlowController.updateBpmnModel(bpmnModel, processInfoConfig.getProcessDefId(),false);
		}
		return UPDATE_SUCCESS;
	}
	
	/**
	 * 当流程定义为更新状态时,需要将流程定义与模型进行同步
	 **/
	@RequestMapping(value = "syncProcessDefToModel")
	@ResponseBody
	public void syncProcessDefToModel(HttpServletRequest request, String modelKey) {
		ProcessInfoConfig processInfoConfig = null;
		try {
			ProcessDefinitionModel processDefinition = processDefinitionService
					.getProcessDefBykey(modelKey);
			if (processDefinition == null) {
				return;
			}
			processInfoConfig = (ProcessInfoConfig) processInfoConfigManager
					.getById(processDefinition.getProcDefId());
			if (processInfoConfig != null && processInfoConfig.isUpdate()&&ProcessInfoConfig.PROCESS_MODEL_SYNC_STATE_N.equals(processInfoConfig.getProcessModelSyncState())) {
				processInfoConfig.setProcessModelSyncState(ProcessInfoConfig.PROCESS_MODEL_SYNC_STATE_Y);
				boolean isSync=processModelService.syncProcessModelToJsonModel(processInfoConfig
								.getProcessDefId());
				if(isSync){
					processInfoConfigManager.update(processInfoConfig);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 *删除对象
	 **/
	@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("processDefId"));
			
			processInfoConfigManager.removeById(id);
		}
		redirectAttributes.addFlashAttribute(ACTION_MESSAGE, DELETE_SUCCESS);
		return new ModelAndView(LIST_ACTION);
	}

}

