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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.MultiInstanceLoopCharacteristics;
import org.activiti.bpmn.model.SubProcess;
import org.activiti.bpmn.model.UserTask;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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.page.Page;
import com.blueland.bpm.engine.config.model.ActivityInfoConfig;
import com.blueland.bpm.engine.config.model.ActivityOperatePower;
import com.blueland.bpm.engine.config.service.ActivityInfoConfigManager;
import com.blueland.bpm.engine.core.service.ProcessDefinitionService;
import com.blueland.bpm.engine.core.service.ProcessModelService;
import com.blueland.bpm.engine.core.service.ProcessTraceService;
import com.blueland.bpm.engine.util.ProcessModelUtils;
import com.blueland.bpm.manage.web.BaseProcessController;

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

@Controller
@RequestMapping(value = "/activityInfo")
public class ActivityInfoConfigController extends BaseProcessController {
	// 默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null;
	@Autowired
	private ActivityInfoConfigManager activityInfoConfigManager;
	@Autowired
	private ProcessDefinitionService processDefinitionService;
	@Autowired
	private ProcessTraceService processTraceService;
	@Autowired
	private ProcessModelService processModelService;
	private final String LIST_ACTION = "redirect:/activityInfo/list.do";

	public ActivityInfoConfigController() {
	}

	/**
	 * 执行搜索
	 **/
	@RequestMapping(value = "list")
	public ModelAndView list(HttpServletRequest request,
			ActivityInfoConfig query,String sys) {
		query.setPageSize(20);
		Page page = this.activityInfoConfigManager.findPage(query);
		ModelAndView result = new ModelAndView("/actInfo/list");
		result.addAllObjects(toModelMap(page, query));
		return result;
	}

	@RequestMapping(value = "main")
	public ModelAndView main(ActivityInfoConfig activityInfoConfig,
			HttpServletRequest request) {

		return new ModelAndView("/actInfo/main", "activityInfoConfig",
				activityInfoConfig);

	}

	/**
	 * 进入更新页面
	 **/
	@RequestMapping(value = "edit")
	public ModelAndView edit(HttpServletRequest request,
			ActivityInfoConfig params,String sys,String mAppId) {
		boolean isStartTask = false;
		BpmnModel bpmnModel = processModelService.getBpmnModelByProcDefId(params.getProcessDefId());
		UserTask userTask = ProcessModelUtils.findStartUserTask(bpmnModel);
		if(null!=userTask){
			if(userTask.getId().equals(params.getActivityDefId())){//当前环节是开始环节
				isStartTask = true;
			}
		}
		ActivityInfoConfig activityInfoConfig = (ActivityInfoConfig) activityInfoConfigManager
				.getByEntity(params);
		ModelAndView result = new ModelAndView("/actInfo/edit", "activityInfoConfig",
				activityInfoConfig);
		result.addObject("isStartTask", isStartTask);
		result.addObject("sys", sys);
		result.addObject("mAppId", mAppId);
		return result;
	}
	
	


	/**
	 * 保存更新对象
	 **/
	@RequestMapping(value = "update")
	@ResponseBody
	public String update(HttpServletRequest request, ActivityInfoConfig params,
			RedirectAttributes redirectAttributes) {
		BpmnModel bpmnModel = processModelService
				.getBpmnModelByProcDefId(params.getProcessDefId());
		UserTask userTask = ProcessModelUtils.findUserTask(bpmnModel, params.getActivityDefId());
		SubProcess subProcess = ProcessModelUtils.isSubProcessStartAct(bpmnModel,
				userTask.getId());
		boolean isUpdate = false;
		if (params.isMulti()) {
			if(params.getActivityDefDealType().equals("multi")){
				if (subProcess != null && subProcess.getLoopCharacteristics() == null) {
					userTask.setAssignee("${assignee}");
					MultiInstanceLoopCharacteristics multiInstance = new MultiInstanceLoopCharacteristics();
					multiInstance.setElementVariable("assignee");
					multiInstance.setInputDataItem("${assigneeList}");
					multiInstance.setSequential(false);
					subProcess.setLoopCharacteristics(multiInstance);
					isUpdate = true;
				} else if (subProcess==null && (userTask.getLoopCharacteristics() == null||userTask.getLoopCharacteristics().isSequential())) {
					userTask.setAssignee("${assignee}");
					MultiInstanceLoopCharacteristics multiInstance = new MultiInstanceLoopCharacteristics();
					multiInstance.setElementVariable("assignee");
					multiInstance.setInputDataItem("${assigneeList}");
					multiInstance.setSequential(false);
					userTask.setLoopCharacteristics(multiInstance);
					isUpdate = true;
				}
			}else if(params.getActivityDefDealType().equals("multi-x")){
				//多实例串行
				if (subProcess==null && (userTask.getLoopCharacteristics() == null||!userTask.getLoopCharacteristics().isSequential())) {
					userTask.setAssignee("${assignee}");
					MultiInstanceLoopCharacteristics multiInstance = new MultiInstanceLoopCharacteristics();
					multiInstance.setElementVariable("assignee");
					multiInstance.setInputDataItem("${assigneeList}");
					multiInstance.setSequential(true);
					userTask.setLoopCharacteristics(multiInstance);
					isUpdate = true;
				}
			} 
		}else if (subProcess != null && subProcess.getLoopCharacteristics() != null) {
			subProcess.setLoopCharacteristics(null);
			userTask.setAssignee("");
			isUpdate = true;
		} else if (userTask.getLoopCharacteristics() != null) {
			userTask.setLoopCharacteristics(null);
			userTask.setAssignee("");
			isUpdate = true;
		}
		if (isUpdate) {
			updateBpmnModel(bpmnModel, params.getProcessDefId(), true);
		}
		activityInfoConfigManager.update(params);
		return "SUCCESS";
	}

	@RequestMapping(value = "actOperatePowerList")
	public ModelAndView actOperatePowerList(HttpServletRequest request,
			ActivityInfoConfig params) {
		ModelAndView modelAndView = new ModelAndView(
				"/actInfo/actOperatePowerList");
		List<ActivityOperatePower> activityOperatePowerList = activityInfoConfigManager
				.findActivityOperatePower(params.getProcessDefId(),
						params.getActivityDefId());
		modelAndView.addObject("activityOperatePowerList",
				activityOperatePowerList);
		modelAndView.addObject("query", params);
		return modelAndView;
	}

	@RequestMapping(value = "addActOperatePower")
	@ResponseBody
	public String addActOperatePower(String[] opIds, String processDefId,
			String activityDefId) {
		if (opIds == null || opIds.length <= 0) {
			return ACTION_SUCCESS;
		}
		boolean isAdd = activityInfoConfigManager.addActivityOperatePower(
				new ArrayList(Arrays.asList(opIds)), processDefId,
				activityDefId);
		return ACTION_SUCCESS;
	}

	@RequestMapping(value = "removeActOperatePower")
	@ResponseBody
	public String removeActiOperatePower(String[] opIds, String processDefId,
			String activityDefId) {
		if (opIds == null || opIds.length <= 0) {
			return ACTION_SUCCESS;
		}
		boolean isRemove = activityInfoConfigManager
				.removeActivityOperatePower(
						new ArrayList(Arrays.asList(opIds)), processDefId,
						activityDefId);
		return ACTION_SUCCESS;
	}

	/**
	 * 环节配置
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "actSet")
	public ModelAndView actSet(HttpServletRequest request,
			ActivityInfoConfig query,String appId,String formId,String modelId,String procDefKey,String formCode,String mAppId) {
		ModelAndView result = new ModelAndView("/actInfo/actSet");
		if(StringUtils.isEmpty(query.getProcessDefId())) {
			return new ModelAndView("/procDefModelMgr/info");
		}
		result.addObject("query", query);
		result.addObject("appId", appId);
		result.addObject("formId", formId);
		result.addObject("modelId", modelId);
		result.addObject("procDefKey", procDefKey);
		result.addObject("formCode", formCode);
		result.addObject("mAppId", mAppId);
		return result;
	}
	/**
	 * 环节配置_v1
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "actSet_v1")
	public ModelAndView actSetV1(HttpServletRequest request,
			ActivityInfoConfig query,String appId,String formId,String modelId,String procDefKey,String formCode,String mAppId) {
		ModelAndView result = new ModelAndView("/actInfo/actSet_v1");
		if(StringUtils.isEmpty(query.getProcessDefId())) {
			return new ModelAndView("/procDefModelMgr/info");
		}
		String processDefinitionDiv =null;
		try {
			processDefinitionDiv=processTraceService.getProcessDefinitionDiv(query.getProcessDefId());
			String[] size =  processTraceService.getProcessDiagramSize(query.getProcessDefId());
        	result.addObject("imageWidth",size[0]);
        	result.addObject("imageHeight",size[1]);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result.addObject("query", query);
		result.addObject("appId", appId);
		result.addObject("formId", formId);
		result.addObject("modelId", modelId);
		result.addObject("procDefKey", procDefKey);
		result.addObject("formCode", formCode);
		result.addObject("mAppId", mAppId);
		result.addObject("processDefinitionDiv", processDefinitionDiv);
		return result;
	}
	
	
	/**
	 * 环节配置
	 * 
	 * @throws Exception
	 */
	@RequestMapping(value = "actConfig")
	public ModelAndView actConfig(HttpServletRequest request,
			ActivityInfoConfig query,String sys) {
		ModelAndView result = new ModelAndView("/actInfo/actConfig");
		ActivityInfoConfig activity =new ActivityInfoConfig();
		if(StringUtils.isEmpty(query.getActivityDefId())||StringUtils.isEmpty(query.getProcessDefId())) {
			activity =new ActivityInfoConfig();
		}
		activity = (ActivityInfoConfig) activityInfoConfigManager
				.getByEntity(query);
		result.addObject("activity", activity);
		result.addObject("sys", sys);
		return result;
	}
	
	/**
	 * 当前环节绑定的表单
	 * @param request
	 * @param params
	 * @param sys
	 * @return
	 */
	@RequestMapping(value = "getActForm")
	@ResponseBody
	public Map<String,Object> getActForm(HttpServletRequest request,
			@RequestBody Map<String,Object> params) {
		Map<String,Object> result = new HashMap<String, Object>();
		ActivityInfoConfig act = new ActivityInfoConfig();
		if(StringUtils.isNotEmpty(params.get("processDefId").toString()) && StringUtils.isNotEmpty(params.get("activityDefId").toString())){
			act.setProcessDefId(params.get("processDefId").toString());
			act.setActivityDefId(params.get("activityDefId").toString());
			ActivityInfoConfig activityInfoConfig = (ActivityInfoConfig) activityInfoConfigManager
					.getByEntity(act);
			
			result.put("flag", "success");
			result.put("msg", "操作成功");
			result.put("activityInfoConfig",activityInfoConfig);
			return result;
		}else{
			result.put("flag", "fail");
			result.put("msg", "参数异常");
			return result;
		}
		
	}
}

