package com.blueland.bpm.manage.web;

import java.sql.Struct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.StrUtil;
import org.activiti.bpmn.model.BpmnModel;
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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.blueland.bpm.engine.config.model.ActivityInfoConfig;
import com.blueland.bpm.engine.config.service.ActivityInfoConfigManager;
import com.blueland.bpm.engine.core.model.ActivityResourceModel;
import com.blueland.bpm.engine.core.model.ProcessDefinitionModel;
import com.blueland.bpm.engine.core.service.ProcessDefinitionService;
import com.blueland.bpm.engine.core.service.ProcessModelService;
import com.blueland.bpm.engine.util.ProcessModelUtils;
import com.blueland.bpm.identity.OrgService;
import com.blueland.bpm.identity.RoleService;
import com.blueland.bpm.identity.UserService;
import com.blueland.bpm.identity.model.Org;
import com.blueland.bpm.identity.model.Role;
import com.blueland.bpm.identity.model.User;
import com.blueland.bpm.manage.util.MyContants;

@Controller
@RequestMapping(value = "/actInfo/setActResource")
public class SetActUserController extends BaseProcessController {
	@Autowired
	private ProcessDefinitionService processDefinitionService;
	@Autowired
	private ProcessModelService processModelService;
	@Autowired
	private ActivityInfoConfigManager activityInfoConfigManager;
	@Autowired
	private UserService	userService;
	@Autowired
	private OrgService	orgService;
	@Autowired
	private RoleService	roleService;

	@RequestMapping(value = "list")
	public ModelAndView list(String procDefId, String actId,String opDataSource) {
		ModelAndView modelAndView = new ModelAndView(
				"/actInfo/setActResource/list");
		BpmnModel bpmnModel = processModelService
				.getBpmnModelByProcDefId(procDefId);
		UserTask userTask = ProcessModelUtils.findUserTask(bpmnModel, actId);
		List<ActivityResourceModel> activityResources=new ArrayList<ActivityResourceModel>();
		
		for (String groupId : userTask.getCandidateGroups()) {
			Role role=roleService.getRoleById(groupId);
			String roleName = "<font color='red'>该角色已失效</font>";
			Integer sort = 0;
			if(role != null&&role.getRoleName()!=null) {
				roleName = role.getRoleName();
			}if(role != null&&role.getRoleSort()!=null) {
				sort = role.getRoleSort();
			}
			ActivityResourceModel actitityResource=new ActivityResourceModel(groupId,"角色",roleName,0,"ROLE", sort);
			actitityResource.setRemark(groupId);
			activityResources.add(actitityResource);
		}
		for (String orgId : userTask.getCandidateOrgs()) {
			Org org=orgService.getOrgById(orgId);
			String orgName = "<font color='red'>该组组已失效</font>";
			int sort = 0;
			if(org != null) {
				orgName = orgService.getFullPathName(orgId,"/");
				if(StringUtils.isEmpty(orgName))  //fullpath只到公司，当绑定集团的时候，显示集团名称
					orgName = org.getOrgName();
				sort = org.getOrgSort();
			}
			ActivityResourceModel actitityResource=new ActivityResourceModel(orgId,"组织",orgName,0,"ORG", sort);
			actitityResource.setRemark(orgId);
			activityResources.add(actitityResource);
		}
		for (String userId : userTask.getCandidateUsers()) {
			User user=userService.getUserById(userId);
			String userName = "<font color='red'>该人员已失效</font>";
			String userCode=userId;
			int sort = 0;
			if(user != null && StrUtil.isNotEmpty(user.getUserId())){
				Org org = orgService.getOrgById(user.getOrgId());
				sort = user.getUserSort();
				if(org != null) {
					userName = orgService.getFullPathName(org.getOrgId(),"/") +"/"+ user.getUserName();
				}else{
					userName ="<font color='red'>组织无效</font>/"+ user.getUserName();
				}
				userCode=user.getUserCode();
			}
			ActivityResourceModel actitityResource=new ActivityResourceModel(userId,"人员",userName,0,"USER", sort);
			actitityResource.setRemark(userId);
			activityResources.add(actitityResource);
		}
		modelAndView.addObject("activityResources", activityResources);
		modelAndView.addObject("userTask", userTask);
		modelAndView.addObject("procDefId", procDefId);
		modelAndView.addObject("opDataSource",opDataSource);
		return modelAndView;
	}
	
	@RequestMapping(value = "setAllResourcelist")
	public ModelAndView setAllResourcelist(String processDefId) {
		ModelAndView modelAndView = new ModelAndView(
				"/actInfo/setActResource/allResourceslist");
		if(StringUtils.isEmpty(processDefId)) {
			return new ModelAndView("/procDefModelMgr/info");
		}
		BpmnModel bpmnModel = processModelService
				.getBpmnModelByProcDefId(processDefId);
		List<ActivityInfoConfig> actInfoConfigs = activityInfoConfigManager
				.findActivityInfoConfigs(processDefId);

		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

		for (ActivityInfoConfig actInfoConfig : actInfoConfigs) {
			Map<String, Object> map = new HashMap<String, Object>();
			List<ActivityResourceModel> activityResources = new ArrayList<ActivityResourceModel>();
			UserTask userTask = ProcessModelUtils.findUserTask(bpmnModel,
					actInfoConfig.getActivityDefId());
			if (null != userTask) {
				for (String groupId : userTask.getCandidateGroups()) {
					Role role=roleService.getRoleById(groupId);
					String roleName = "<font color='red'>该角色已失效</font>";
					Integer sort = 0;
					if(role != null&&role.getRoleName()!=null) {
						roleName = role.getRoleName();
					}if(role != null&&role.getRoleSort()!=null) {
						sort = role.getRoleSort();
					}
					ActivityResourceModel actitityResource=new ActivityResourceModel(groupId,"角色",roleName,0,"ROLE", sort);
					actitityResource.setRemark(groupId);
					activityResources.add(actitityResource);
				}
				for (String orgId : userTask.getCandidateOrgs()) {
					Org org=orgService.getOrgById(orgId);
					String orgName = "<font color='red'>该组组已失效</font>";
					int sort = 0;
					if(org != null) {
						orgName = orgService.getFullPathName(orgId,"/");
						if(StringUtils.isEmpty(orgName))  //fullpath只到公司，当绑定集团的时候，显示集团名称
							orgName = org.getOrgName();
						sort = org.getOrgSort();
					}
					ActivityResourceModel actitityResource=new ActivityResourceModel(orgId,"组织",orgName,0,"ORG", sort);
					actitityResource.setRemark(orgId);
					activityResources.add(actitityResource);
				}
				for (String userId : userTask.getCandidateUsers()) {
					User user=userService.getUserById(userId);
					String userName = "<font color='red'>该人员已失效</font>";
					String userCode=userId;
					int sort = 0;
					if(user!=null && StrUtil.isNotEmpty(user.getUserId())){
						Org org = orgService.getOrgById(user.getOrgId());
						sort = user.getUserSort();
						if(org != null) {
							userName = orgService.getFullPathName(org.getOrgId(),"/") +"/"+ user.getUserName();
						}else{
							userName ="<font color='red'>组织无效</font>/"+ user.getUserName();
						}
						userCode=user.getUserCode();
					}
					ActivityResourceModel actitityResource=new ActivityResourceModel(userId,"人员",userName,0,"USER", sort);
					actitityResource.setRemark(userId);
					activityResources.add(actitityResource);
				}
				
				
				map.put("userTask", userTask);
				map.put("activityResources", activityResources);
				result.add(map);
			} else {
				// 这里除去用户任务的其他节点 不需要分配人员和角色，所以查询出来的userTask为空，在这里相当于排除掉这些节点
				System.out.println(actInfoConfig.getActivityDefId());
			}

		}

		modelAndView.addObject("result", result);
		// modelAndView.addObject("activityResources", activityResources);
		// modelAndView.addObject("userTask", userTask);
		modelAndView.addObject("procDefId", processDefId);
		return modelAndView;
	}

	@RequestMapping(value = "save")
	@ResponseBody
	public String save(String procDefId, String actId, String resourceStr) {
		Set<String> orgs = new HashSet<String>();
		Set<String> users = new HashSet<String>();
		Set<String> groups = new HashSet<String>();
//		List<String> orgs = new ArrayList<String>();
//		List<String> users = new ArrayList<String>();
//		List<String> groups = new ArrayList<String>();
		if (StringUtils.isEmpty(resourceStr)) {
			return this.ACTION_ERROR;
		}
		String[] resources = null;
		if (resourceStr.indexOf(",") != -1) {
			resources = resourceStr.split(",");
		} else {
			resources = new String[] { resourceStr };
		}
		if (resources == null || resources.length <= 0) {
			return this.ACTION_ERROR;
		}
		for (String allResource : resources) {
			String[] temp = allResource.split("#");
			String resourceType = temp[0];
			String resourceId = temp[1];
			if ("ORG".equals(resourceType)) {
				orgs.add(resourceId);
			} else if ("USER".equals(resourceType)) {
				users.add(resourceId);
			} else if ("ROLE".equals(resourceType)) {
				groups.add(resourceId);
			}
		}
		if (groups.isEmpty() && users.isEmpty() && orgs.isEmpty()) {
			return this.ACTION_ERROR;
		}
		boolean result = addActResource(procDefId, actId, orgs, groups, users);
		return result ? this.ACTION_SUCCESS : this.ACTION_ERROR;
	}

	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(String procDefId, String actId, String[] resources
			,HttpServletRequest request) {
		List<String> orgs = new ArrayList<String>();
		List<String> users = new ArrayList<String>();
		List<String> groups = new ArrayList<String>();
		if (resources == null || resources.length <= 0) {
			return this.ACTION_ERROR;
		}
		for (String allResource : resources) {
			String[] temp = allResource.split("#");
			String resourceType = temp[0];
			String resourceId = temp[1];
			if ("ORG".equals(resourceType)) {
				orgs.add(resourceId);
			} else if ("USER".equals(resourceType)) {
				users.add(resourceId);
			} else if ("ROLE".equals(resourceType)) {
				groups.add(resourceId);
			}
		}
		if (groups.isEmpty() && users.isEmpty() && orgs.isEmpty()) {
			return this.ACTION_ERROR;
		}
		boolean result = deleteActResource(procDefId, actId, orgs, groups,
				users);
		MyContants.saveUserOperate(request,"procDefId;actId,resources", 
				result, result?"删除成功":"删除失败",
						MyContants.LOGIN_SESSION_USER,MyContants.APPLICATION);
		return result ? this.ACTION_SUCCESS : this.ACTION_ERROR;
	}
	
	@RequestMapping(value = "deleteForResourcesManage")
	@ResponseBody
	public String deleteForResourcesManage(String procDefId, String actId, String resources
			,HttpServletRequest request) {
		List<String> orgs = new ArrayList<String>();
		List<String> users = new ArrayList<String>();
		List<String> groups = new ArrayList<String>();
		String[] resourcesArr = resources.split(",");
		if (resourcesArr == null || resourcesArr.length <= 0) {
			return this.ACTION_ERROR;
		}
		for (String allResource : resourcesArr) {
			String[] temp = allResource.split("#");
			String resourceType = temp[0];
			String resourceId = temp[1];
			if ("ORG".equals(resourceType)) {
				orgs.add(resourceId);
			} else if ("USER".equals(resourceType)) {
				users.add(resourceId);
			} else if ("ROLE".equals(resourceType)) {
				groups.add(resourceId);
			}
		}
		if (groups.isEmpty() && users.isEmpty() && orgs.isEmpty()) {
			return this.ACTION_ERROR;
		}
		boolean result = deleteActResource(procDefId, actId, orgs, groups,
				users);
		
		MyContants.saveUserOperate(request,"procDefId;actId,resources", 
				result, result?"删除成功":"删除失败",
						MyContants.LOGIN_SESSION_USER,MyContants.APPLICATION);
		return result ? this.ACTION_SUCCESS : this.ACTION_ERROR;
	}

	private boolean addActResource(String procDefId, String actId,
			Set<String> orgs, Set<String> groups, Set<String> users) {
//	private boolean addActResource(String procDefId, String actId,
//			List<String> orgs, List<String> groups, List<String> users) {
		boolean result = false;
		ProcessDefinitionModel processDefinition = processDefinitionService
				.getProcessDef(procDefId);
		if (processDefinition == null) {
			return result;
		}
		BpmnModel bpmnModel = processModelService
				.getBpmnModelByProcDefId(procDefId);
		UserTask userTask = ProcessModelUtils.findUserTask(bpmnModel, actId);
		if (orgs != null && !orgs.isEmpty()) {
			orgs.addAll(userTask.getCandidateOrgs());
			List<String> orgIds = new ArrayList<String>();
			orgIds.addAll(orgs);
			userTask.setCandidateOrgs(orgIds);
//			userTask.getCandidateOrgs().addAll(orgs);
		}
		if (groups != null && !groups.isEmpty()) {
			groups.addAll(userTask.getCandidateGroups());
			List<String> groupIds = new ArrayList<String>();
			groupIds.addAll(groups);
			userTask.setCandidateGroups(groupIds);
//			userTask.getCandidateGroups().addAll(groups);
		}
		if (users != null && !users.isEmpty()) {
			users.addAll(userTask.getCandidateUsers());
			List<String> userIds = new ArrayList<String>();
			userIds.addAll(users);
			userTask.setCandidateUsers(userIds);
//			userTask.getCandidateUsers().addAll(users);
		}
		return updateBpmnModel(
				bpmnModel, processDefinition, false);

	}

	private boolean deleteActResource(String procDefId, String actId,
			List<String> orgs, List<String> groups, List<String> users) {
		boolean result = false;
		ProcessDefinitionModel processDefinition = processDefinitionService
				.getProcessDef(procDefId);
		if (processDefinition == null) {
			return result;
		}
		BpmnModel bpmnModel = processModelService
				.getBpmnModelByProcDefId(procDefId);
		UserTask userTask = ProcessModelUtils.findUserTask(bpmnModel, actId);
		if (orgs != null && !orgs.isEmpty()) {
			userTask.getCandidateOrgs().removeAll(orgs);
		}
		if (groups != null && !groups.isEmpty()) {
			userTask.getCandidateGroups().removeAll(groups);
		}
		if (users != null && !users.isEmpty()) {
			userTask.getCandidateUsers().removeAll(users);
		}
		return updateBpmnModel(
				bpmnModel, processDefinition, false);

	}

}
