/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workengineeringproject.web;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
import com.jeeplus.modules.workengineeringproject.entity.WorkEngineeringProject;
import com.jeeplus.modules.workengineeringproject.entity.WorkProjectPlan;
import com.jeeplus.modules.workengineeringproject.entity.WorkProjectPlanEdit;
import com.jeeplus.modules.workengineeringproject.service.WorkEngineeringProjectService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 工程项目信息Controller
 * @author 杨帆
 * @version 2017-10-23
 */
@Controller
@RequestMapping(value = "${adminPath}/workengineeringproject/workEngineeringProject")
public class WorkEngineeringProjectController extends BaseController {

	@Autowired
	private WorkEngineeringProjectService workEngineeringProjectService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkContractInfoService workContractInfoService;
	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;

	@ModelAttribute
	public WorkEngineeringProject get(@RequestParam(required=false) String id) {
		WorkEngineeringProject entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workEngineeringProjectService.get(id);
		}
		if (entity == null){
			entity = new WorkEngineeringProject();
		}
		return entity;
	}
	
	/**
	 * 工程项目信息列表页面
	 */
	@RequiresPermissions("workengineeringproject:workEngineeringProject:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkEngineeringProject workEngineeringProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		//只是普通员工
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workEngineeringProject.setQueryCon(id);
		}
		Page<WorkEngineeringProject> page = workEngineeringProjectService.findPage(new Page<WorkEngineeringProject>(request, response), workEngineeringProject);
		List<WorkEngineeringProject> list = page.getList();
		for (WorkEngineeringProject entity :list){
			String hostOfficeMaster = entity.getHostOfficeMaster();
			if (StringUtils.isNotBlank(hostOfficeMaster)){
				String[] ids = hostOfficeMaster.split(",");
				String name = "";
				for (String str:ids) {
					User user = UserUtils.get(str);
					name += user.getName()+",";
				}
				if (StringUtils.isNotBlank(name)){
					name = name.substring(0,name.length() - 1);
				}
				entity.setHostOfficeMasterName(name);
			}
			if(StringUtils.isNotBlank(entity.getProcessInstanceId())){
				boolean state = actTaskService.isProcessEnd(entity.getProcessInstanceId());
				if (state){
					entity.setQueryCon("true");
				}
			}
		}
		model.addAttribute("page", page);
		model.addAttribute("name",false);
		model.addAttribute("zg", false);
		return "modules/workengineeringproject/workEngineeringProjectList";
	}

	/**
	 * 工程项目计划列表页面
	 */
	@RequiresPermissions("workengineeringproject:workEngineeringProject:planlist")
	@RequestMapping(value = {"planlist"})
	public String planlist(WorkEngineeringProject workEngineeringProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		Role role = UserUtils.getSelectRole().get(0);
		//只是普通员工
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workEngineeringProject.setQueryCon(id);
		}
		Page<WorkEngineeringProject> page = workEngineeringProjectService.findPage(new Page<WorkEngineeringProject>(request, response), workEngineeringProject);
		List<WorkEngineeringProject> list = page.getList();
		for (WorkEngineeringProject entity :list){
			String hostOfficeMaster = entity.getHostOfficeMaster();
			if (StringUtils.isNotBlank(hostOfficeMaster)){
				String[] ids = hostOfficeMaster.split(",");
				String name = "";
				for (String str:ids) {
					User user = UserUtils.get(str);
					name += user.getName()+",";
				}
				if (StringUtils.isNotBlank(name)){
					name = name.substring(0,name.length() - 1);
				}
				entity.setHostOfficeMasterName(name);
			}
		}
		model.addAttribute("page", page);
		model.addAttribute("name", role.getEnname().contains("bmzr")?true:false);
		model.addAttribute("zg", role.getEnname().contains("zg")?true:false);
		return "modules/workengineeringproject/workProjectPlanList";
	}

	/**
	 * 查看，增加，编辑工程项目信息表单页面
	 */
	@RequiresPermissions(value={"workengineeringproject:workEngineeringProject:view","workengineeringproject:workEngineeringProject:add","workengineeringproject:workEngineeringProject:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkEngineeringProject workEngineeringProject, Model model) {
		getSort(workEngineeringProject);
		if (StringUtils.isBlank(workEngineeringProject.getId())){
			workEngineeringProject.setOffice(UserUtils.getSelectOffice());
		}
		if (StringUtils.isBlank(workEngineeringProject.getId())){
			WorkProject w = new WorkProject();
			w.setNumber(IdGen.uuid());
			workEngineeringProject.setProjectId(w);
		}

		if(workEngineeringProject.getWorkClientInfo()!=null){
			WorkClientInfo workClientInfo = workClientInfoService.get(workEngineeringProject.getWorkClientInfo().getId());
			workEngineeringProject.setWorkClientInfo(workClientInfo);
			String linkmanListJson = workFullManageService.parseList2Json(workClientInfo);
			model.addAttribute("linkmanList",linkmanListJson);
		}

		if(StringUtils.isNotBlank(workEngineeringProject.getName()) && workEngineeringProject.getName().equals("view")){
			//model.addAttribute("workEngineeringProject", workEngineeringProject);
			return "modules/workengineeringproject/workEngineeringProjectView";
		}
		if (workEngineeringProject.getAct()!=null && StringUtils.isNotBlank(workEngineeringProject.getAct().getTaskId())){
			if(StringUtils.isBlank(workEngineeringProject.getHostOffice()) && StringUtils.isBlank(workEngineeringProject.getHostOfficeMaster())){
				User user = UserUtils.get(workEngineeringProject.getCreateBy().getId());
				Office office = officeService.get(user.getOffice().getId());
				workEngineeringProject.setHostOffice(office.getId());
				workEngineeringProject.setHostOfficeName(office.getName());
				workEngineeringProject.setHostOfficeMaster(user.getId());
				workEngineeringProject.setHostOfficeMasterName(user.getName());
			}
			model.addAttribute("workEngineeringProject", workEngineeringProject);
			return "modules/workengineeringproject/workEngineeringProjectAllocation";
		}

		/*if(StringUtils.isNotBlank(workEngineeringProject.getName()) && workEngineeringProject.getName().equals("edit")){
			if(StringUtils.isBlank(workEngineeringProject.getHostOffice()) && StringUtils.isBlank(workEngineeringProject.getHostOfficeMaster())){
				User user = UserUtils.get(workEngineeringProject.getCreateBy().getId());
				Office office = officeService.get(user.getOffice().getId());
				workEngineeringProject.setHostOffice(office.getId());
				workEngineeringProject.setHostOfficeName(office.getName());
				workEngineeringProject.setHostOfficeMaster(user.getId());
				workEngineeringProject.setHostOfficeMasterName(user.getName());
			}
			String processInstanceId = workEngineeringProject.getProcessInstanceId();
			HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
			if(historicProcessInstance!=null) {
				workEngineeringProject.setHistoricProcessInstance(historicProcessInstance);
				workEngineeringProject.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
			} else {
				ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
				if (processInstance != null){
					workEngineeringProject.setProcessInstance(processInstance);
					workEngineeringProject.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
				}
			}
			ProcessInstance processInstance = actTaskService.getProcIns(processInstanceId);
			if (processInstance!=null) {
				List<Task> taskList = actTaskService.getCurrentTaskList(processInstance);
				if(taskList!=null && taskList.size()>1){
					for (Task taskInfok:taskList) {
						if (taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
							Act act = new Act();
							act.setTaskId(taskInfok.getId());
							act.setTaskName(taskInfok.getName());
							act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
							act.setProcDefId(taskInfok.getProcessDefinitionId());
							act.setProcInsId(taskInfok.getProcessInstanceId());
							act.setTask(taskInfok);
							workEngineeringProject.setAct(act);
						}
					}
				}else {
					Task task = actTaskService.getCurrentTaskInfo(processInstance);
					Act act = new Act();
					act.setTaskId(task.getId());
					act.setTaskName(task.getName());
					act.setTaskDefKey(task.getTaskDefinitionKey());
					act.setProcDefId(task.getProcessDefinitionId());
					act.setProcInsId(task.getProcessInstanceId());
					act.setTask(task);
					workEngineeringProject.setAct(act);
				}
			}
			model.addAttribute("workEngineeringProject", workEngineeringProject);
			return "modules/workengineeringproject/workEngineeringProjectAllocation";
		}*/
		if(StringUtils.isNotBlank(workEngineeringProject.getPlan())){
			if(workEngineeringProject.getPlan().contains("plan")){
				String businessType = workEngineeringProject.getBusinessType();
				List<WorkProjectPlan> projectPlanList = new ArrayList<WorkProjectPlan>();
				if (StringUtils.isNotBlank(businessType) && !businessType.contains("2")&& !workEngineeringProject.getBusinessType().contains("H")) {
					workEngineeringProject.setName("1");
					WorkProjectPlan plan1 = new WorkProjectPlan();
					WorkProjectPlan plan2 = new WorkProjectPlan();
					WorkProjectPlan plan3 = new WorkProjectPlan();
					WorkProjectPlan plan4 = new WorkProjectPlan();
					WorkProjectPlan plan5 = new WorkProjectPlan();
					WorkProjectPlan plan6 = new WorkProjectPlan();
					plan1.setType("1");
					plan2.setType("1");
					plan3.setType("1");
					plan4.setType("1");
					plan5.setType("1");
					plan6.setType("1");
					plan1.setTaskName("收集资料");
					plan1.setStartTime(workEngineeringProject.getWorkStartDate());
					plan1.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan1.setProjectId(workEngineeringProject.getId());
					plan2.setProjectId(workEngineeringProject.getId());
					plan3.setProjectId(workEngineeringProject.getId());
					plan4.setProjectId(workEngineeringProject.getId());
					plan5.setProjectId(workEngineeringProject.getId());
					plan6.setProjectId(workEngineeringProject.getId());
					plan2.setTaskName("咨询报告初稿编制");
					plan2.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan3.setTaskName("征求客户意见");
					plan3.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan4.setTaskName("咨询报告初稿调整");
					plan4.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan5.setTaskName("报告送审");
					plan5.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan6.setTaskName("审查意见处理");
					plan6.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan6.setEndTime(workEngineeringProject.getWorkEndDate());
					plan1.preInsert();
					plan2.preInsert();
					plan3.preInsert();
					plan4.preInsert();
					plan5.preInsert();
					plan6.preInsert();
					projectPlanList.add(plan1);
					projectPlanList.add(plan2);
					projectPlanList.add(plan3);
					projectPlanList.add(plan4);
					projectPlanList.add(plan5);
					projectPlanList.add(plan6);

				} else {
					workEngineeringProject.setName("2");
					WorkProjectPlan plan1 = new WorkProjectPlan();
					WorkProjectPlan plan2 = new WorkProjectPlan();
					WorkProjectPlan plan3 = new WorkProjectPlan();
					WorkProjectPlan plan4 = new WorkProjectPlan();
					WorkProjectPlan plan5 = new WorkProjectPlan();
					WorkProjectPlan plan6 = new WorkProjectPlan();
					WorkProjectPlan plan7 = new WorkProjectPlan();
					WorkProjectPlan plan8 = new WorkProjectPlan();
					WorkProjectPlan plan9 = new WorkProjectPlan();
					WorkProjectPlan plan10 = new WorkProjectPlan();
					plan1.setType("2");
					plan2.setType("2");
					plan3.setType("2");
					plan4.setType("2");
					plan5.setType("2");
					plan6.setType("2");
					plan7.setType("2");
					plan8.setType("2");
					plan9.setType("2");
					plan10.setType("2");
					plan1.setProjectId(workEngineeringProject.getId());
					plan2.setProjectId(workEngineeringProject.getId());
					plan3.setProjectId(workEngineeringProject.getId());
					plan4.setProjectId(workEngineeringProject.getId());
					plan5.setProjectId(workEngineeringProject.getId());
					plan6.setProjectId(workEngineeringProject.getId());
					plan7.setProjectId(workEngineeringProject.getId());
					plan8.setProjectId(workEngineeringProject.getId());
					plan9.setProjectId(workEngineeringProject.getId());
					plan10.setProjectId(workEngineeringProject.getId());
					plan1.setTaskName("收集与熟悉资料");
					plan1.setStartTime(workEngineeringProject.getWorkStartDate());
					plan1.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan2.setTaskName("跟踪审计实施方案编制");
					plan2.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan3.setTaskName("资料与图纸问题沟通");
					plan3.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan4.setTaskName("成果文件初稿编制");
					plan4.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan5.setTaskName("初稿与委托方的沟通");
					plan5.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan6.setTaskName("初稿与施工单位的核对");
					plan6.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan7.setTaskName("调整成果文件初稿");
					plan7.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan8.setTaskName("成果文件委托方确认");
					plan8.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan9.setTaskName("出具定案单");
					plan9.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan10.setTaskName("出具审核报告");
					plan10.setRemindUser(UserUtils.get(workEngineeringProject.getCurrentUser().getId()));
					plan10.setEndTime(workEngineeringProject.getWorkEndDate());
					plan1.preInsert();
					plan2.preInsert();
					plan3.preInsert();
					plan4.preInsert();
					plan5.preInsert();
					plan6.preInsert();
					plan7.preInsert();
					plan8.preInsert();
					plan9.preInsert();
					plan10.preInsert();
					projectPlanList.add(plan1);
					projectPlanList.add(plan2);
					projectPlanList.add(plan3);
					projectPlanList.add(plan4);
					projectPlanList.add(plan5);
					projectPlanList.add(plan6);
					projectPlanList.add(plan7);
					projectPlanList.add(plan8);
					projectPlanList.add(plan9);
					projectPlanList.add(plan10);
				}
				List<WorkProjectPlan> list = workEngineeringProjectService.findProjectPlans(workEngineeringProject);
				List<WorkProjectPlanEdit> workProjectPlanEdits = workEngineeringProjectService.findProjectPlanEdit(workEngineeringProject);
				model.addAttribute("workProjectPlanEdits", workProjectPlanEdits);
				if (list != null && list.size() > 0) {
					workEngineeringProject.setWorkProjectPlans(list);
				} else {
					workEngineeringProject.setWorkProjectPlans(projectPlanList);
					workEngineeringProjectService.insertPlan(workEngineeringProject);
				}
				//workEngineeringProjectService.insertPlan(workEngineeringProject);
				List<Workattachment> attachmentList = workattachmentService.findAttachment(workEngineeringProject.getId(),"4");
				model.addAttribute("workEngineeringProject", workEngineeringProject);
				model.addAttribute("workAttachmentList",attachmentList);
				Set<User> users = new HashSet<User>();
				users.addAll(users(workEngineeringProject));
				model.addAttribute("users",users);
				if (workEngineeringProject.getPlan().equals("plan1")){
					return "modules/workengineeringproject/workProjectPlanAdd";
				}else if (workEngineeringProject.getPlan().equals("plan2")){
					return "modules/workengineeringproject/workProjectPlanEdit";
				}else if (workEngineeringProject.getPlan().equals("plan3")){
					Set<User> set = new HashSet<User>();
					set.addAll(users);
					model.addAttribute("userList",set);
					return "modules/workengineeringproject/workProjectPlanMaintain";
				}
			}
		}
		model.addAttribute("workEngineeringProject", workEngineeringProject);
		return "modules/workengineeringproject/workEngineeringProjectForm";
	}

	@RequestMapping(value = "getClientContractionInfo")
	public String getClientContractionInfo(WorkEngineeringProject workEngineeringProject, Model model) {
		if (StringUtils.isBlank(workEngineeringProject.getId())) {
			workEngineeringProject.setOffice(UserUtils.getSelectOffice());
		}
		String clientId = workEngineeringProject.getWorkClientInfo()==null?"":workEngineeringProject.getWorkClientInfo().getId();
		String contractId = workEngineeringProject.getContractId()==null?"":workEngineeringProject.getContractId().getId();
		WorkClientInfo workClientInfo = workClientInfoService.get(clientId);
		WorkContractInfo workContractInfo =workContractInfoService.get(contractId);
		List<Workattachment> attachmentClientList = workattachmentService.findAttachment(clientId,"6");
		List<Workattachment> attachmentContractList = workattachmentService.findAttachment(contractId,"44");
		model.addAttribute("workClientInfo",workClientInfo);
		model.addAttribute("bankSize",workClientInfo.getWorkClientBankList().size());
		model.addAttribute("linkManSize",workClientInfo.getWorkClientLinkmanList().size());
		model.addAttribute("attachmentSize",workClientInfo.getWorkAttachments().size());
		model.addAttribute("workContractInfo",workContractInfo);
		model.addAttribute("attachmentClientList",attachmentClientList);
		model.addAttribute("attachmentContractList",attachmentContractList);
		return "modules/workengineeringproject/workClientContractionView";
	}
	/**
	 * 查看，增加，编辑工程项目信息表单页面
	 */
	@RequestMapping(value = "addPlanRow")
	public String addPlanRow(WorkEngineeringProject workEngineeringProject, Model model) {
		WorkEngineeringProject engineeringProject = workEngineeringProjectService.get(workEngineeringProject.getId());
		HashSet<User> users = users(engineeringProject);
		model.addAttribute("users",users);
		WorkProjectPlan workProjectPlan = new WorkProjectPlan();
		workProjectPlan.setProjectId(workEngineeringProject.getId());
		if (!workEngineeringProject.getBusinessType().contains("2") && !workEngineeringProject.getBusinessType().contains("H")) {
			workProjectPlan.setType("1");
		} else {
			workProjectPlan.setType("2");
		}
		workProjectPlan.setRemindUser(UserUtils.get(engineeringProject.getCurrentUser().getId()));
		model.addAttribute("workProjectPlan", workProjectPlan);
		return "modules/workengineeringproject/workProjectPlanAddRow";
	}


	public HashSet<User> users(WorkEngineeringProject workEngineeringProject) {
		HashSet<String> users = new HashSet<String>();
		HashSet<User> userSet = new HashSet<User>();
		if(StringUtils.isNotBlank(workEngineeringProject.getHostOfficeMaster())){
			String[] ids = workEngineeringProject.getHostOfficeMaster().split(",");
			for (String id :ids){
				User user = UserUtils.get(id);
				users.add(user.getId());
			}
		}
		if(StringUtils.isNotBlank(workEngineeringProject.getJointlyOfficeMaster())){
			String[] ids = workEngineeringProject.getJointlyOfficeMaster().split(",");
			for (String id :ids){
				User user = UserUtils.get(id);
				users.add(user.getId());
			}
		}
		if(StringUtils.isNotBlank(workEngineeringProject.getHostOfficeMember())){
			String[] ids = workEngineeringProject.getHostOfficeMember().split(",");
			for (String id :ids){
				User user = UserUtils.get(id);
				users.add(user.getId());
			}
		}
		if(StringUtils.isNotBlank(workEngineeringProject.getJointlyOfficeMember())){
			String[] ids = workEngineeringProject.getJointlyOfficeMember().split(",");
			for (String id :ids){
				User user = UserUtils.get(id);
				users.add(user.getId());
			}
		}
		List<Role> roleList = systemService.getRoleList(UserUtils.getUser().getId(),"");
		for (Role r:roleList){
			if (r.getEnname().contains("zg")){
				List<User> userList = systemService.findUser(new User(new Role(r.getId())));
				if (userList!=null &&userList.size()!=0){
					for (User user :userList){
						users.add(user.getId());
					}
				}
				break;
			}
		}

		users.add(workEngineeringProject.getCreateBy().getId());
		for (String id :users){
			userSet.add(UserUtils.get(id));
		}
		return userSet;
	}
	/**
	 * 保存工程项目信息
	 */
	@RequiresPermissions(value={"workengineeringproject:workEngineeringProject:add","workengineeringproject:workEngineeringProject:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkEngineeringProject workEngineeringProject, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workEngineeringProject)){
			return form(workEngineeringProject, model);
		}
		if(workEngineeringProject != null){
			if(!Strings.isNullOrEmpty(workEngineeringProject.getTotalProjectId()) && !workEngineeringProject.getTotalProjectId().equals("0")){
				WorkEngineeringProject wc = workEngineeringProjectService.get(workEngineeringProject.getTotalProjectId());
				String isTotal = wc.getIsTotal();
				int count = 2;
				if (StringUtils.isNotBlank(isTotal)){
					count = Integer.parseInt(isTotal) + 1;
				}
				workEngineeringProject.setIsTotal(count+"");
				workEngineeringProject.setIsTotalName(toChinese(count+"")+"级项目");
				if(!Strings.isNullOrEmpty(wc.getTotalProjectIds())){
					workEngineeringProject.setTotalProjectIds(wc.getTotalProjectIds()+","+workEngineeringProject.getTotalProjectId());
				}else{
					workEngineeringProject.setTotalProjectIds(wc.getTotalProjectId()+","+workEngineeringProject.getTotalProjectId());
				}
				workEngineeringProject.setCommonFlag(wc.getCommonFlag());
			}else{
				workEngineeringProject.setIsTotal("1");
				workEngineeringProject.setTotalProjectId("0");
				workEngineeringProject.setCommonFlag(IdGen.uuid());
				workEngineeringProject.setIsTotalName("总项目");
			}
		}
		getSort(workEngineeringProject);
		if(!workEngineeringProject.getIsNewRecord()){//编辑表单保存
			WorkEngineeringProject t = workEngineeringProjectService.get(workEngineeringProject.getId());//从数据库取出记录的值
			String remarks = t.getRemarks();
			MyBeanUtils.copyBeanNotNull2Bean(workEngineeringProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值

			WorkProject workProject = workProjectService.get(t.getProjectId().getId());
			workProject.setName(t.getProjectId().getName());
			workProject.setUpdateBy(t.getUpdateBy());
			workProject.setUpdateDate(t.getUpdateDate());
			if(StringUtils.isNotBlank(remarks) && remarks.equals("重新申请")){
				String processInstanceId = workEngineeringProject.getProcessInstanceId();
				HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
				if(historicProcessInstance!=null) {
					workEngineeringProject.setHistoricProcessInstance(historicProcessInstance);
					workEngineeringProject.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
				} else {
					ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
					if (processInstance != null){
						workEngineeringProject.setProcessInstance(processInstance);
						workEngineeringProject.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
					}
				}
				ProcessInstance processInstance = actTaskService.getProcIns(workEngineeringProject.getProcessInstanceId());
				if (processInstance!=null) {
					Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
					Act act = new Act();
					act.setTaskId(taskInfok.getId());
					act.setTaskName(taskInfok.getName());
					act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
					act.setProcDefId(taskInfok.getProcessDefinitionId());
					act.setProcInsId(taskInfok.getProcessInstanceId());
					act.setTask(taskInfok);
					act.setFlag(workEngineeringProject.getRemarks()==null?"no":workEngineeringProject.getRemarks());
					t.setAct(act);
				}
				if (StringUtils.isNotBlank(t.getRemarks()) && t.getRemarks().equals("yes")){
					addMessage(redirectAttributes, "重新申请工程项目信息成功");
				}else {
					addMessage(redirectAttributes, "工程项目信息已撤销");
				}
				t.setRemarks("");
				workEngineeringProjectService.auditSave(t);
				model.addAttribute("workEngineeringProject", workEngineeringProject);

			}else {
				addMessage(redirectAttributes, "修改工程项目信息成功");
			}
			workProjectService.update(workProject);//保存项目总表
			workEngineeringProjectService.save(t);//保存
			return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
		}else{//新增表单保存
			workEngineeringProject.setStatus("1");
			workEngineeringProject.setCompanyId(UserUtils.getSelectCompany().getId());

			WorkProject w = new WorkProject();
			w.setNumber(workEngineeringProject.getProjectId().getNumber());
			w.setName(workEngineeringProject.getProjectId().getName());
			w.setContractId(workEngineeringProject.getContractId());
			w.setCreateBy(workEngineeringProject.getCreateBy());
			w.setCreateDate(workEngineeringProject.getCreateDate());
			w.setDelFlag(workEngineeringProject.getDelFlag());
			w.setUpdateBy(workEngineeringProject.getUpdateBy());
			w.setUpdateDate(workEngineeringProject.getUpdateDate());
			w.setCompanyId(UserUtils.getSelectCompany().getId());
			w.setRemarks(workEngineeringProject.getRemarks());
			w.setOfficeId(workEngineeringProject.getOffice()==null?"":workEngineeringProject.getOffice().getId());
			w.setSort("工程咨询");
			workProjectService.save(w);//保存总项目表
			workEngineeringProject.setProjectId(w);
			String masterId = "";
			if(!Strings.isNullOrEmpty(workEngineeringProject.getHostOfficeMaster())){
				String[] split = workEngineeringProject.getHostOfficeMaster().split(",");
				//主办负责人的部门负责人编号
				masterId += workFullManageService.getPeopleMaster(split) + ",";
			}
			if(!Strings.isNullOrEmpty(workEngineeringProject.getHostOfficeMember())){
				String[] split1 = workEngineeringProject.getHostOfficeMember().split(",");
				masterId += workFullManageService.getPeopleMaster(split1) + ",";
			}
			if(!Strings.isNullOrEmpty(workEngineeringProject.getJointlyOfficeMaster())){
				String[] split2 = workEngineeringProject.getJointlyOfficeMaster().split(",");
				masterId += workFullManageService.getPeopleMaster(split2) + ",";
			}
			if(!Strings.isNullOrEmpty(workEngineeringProject.getJointlyOfficeMember())){
				String[] split3 = workEngineeringProject.getJointlyOfficeMember().split(",");
				masterId += workFullManageService.getPeopleMaster(split3) + ",";
			}
			workEngineeringProject.setMasterId(masterId);
			workEngineeringProjectService.save(workEngineeringProject);//保存
			addMessage(redirectAttributes, "保存工程项目信息成功");
			return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
		}
	}

	public WorkEngineeringProject getSort(WorkEngineeringProject workEngineeringProject){
		if (!Strings.isNullOrEmpty(workEngineeringProject.getTotalProjectId()) && 30 == workEngineeringProject.getSort()){
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(workEngineeringProject.getId())){
				WorkEngineeringProject workEngineeringProjectChild = new WorkEngineeringProject();
				workEngineeringProjectChild.setTotalProjectId(workEngineeringProject.getTotalProjectId());
				List<WorkEngineeringProject> list = workEngineeringProjectService.findByList(workEngineeringProject);
				if (list.size() > 0){
					workEngineeringProject.setSort(list.get(list.size()-1).getSort());
					if (workEngineeringProject.getSort() != null){
						workEngineeringProject.setSort(workEngineeringProject.getSort() + 1);
					}
				}
			}
		}
		return workEngineeringProject;
	}
	/**
	 * 保存工程项目信息
	 */
	@RequestMapping(value = "savePlan")
	public String savePlan(WorkEngineeringProject workEngineeringProject, Model model, RedirectAttributes redirectAttributes
			) throws Exception {
		if (!beanValidator(model, workEngineeringProject)) {
			return form(workEngineeringProject, model);
		}
		try{
			workEngineeringProjectService.deletePlan(workEngineeringProject);
			//workEngineeringProject.setWorkProjectPlans(workProjectPlans);
			workEngineeringProjectService.insertPlan(workEngineeringProject);
		}catch (Exception e){
			logger.error("Exception e:"+e);
		}
		workEngineeringProject.setStatus("4");
		workEngineeringProjectService.update(workEngineeringProject);
		/*List<Workattachment> list = workEngineeringProject.getWorkAttachments();
		for (Workattachment workattachment:list){
			if (StringUtils.isBlank(workattachment.getAttachmentId())){
				workattachment.setAttachmentId(workEngineeringProject.getId());
				workattachmentService.save(workattachment);
			}
		}*/
		//workattachmentService.uploadattachment(multiRequest,workEngineeringProject.getId(),"workEngineeringProject","4");
		addMessage(redirectAttributes, "修改工程项目计划成功");
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/planlist?repage";
	}

	@RequestMapping(value = "addPlanRowData")
	@ResponseBody
	public HashMap<Object,Object> addPlanRowData(WorkProjectPlan workProjectPlan, Model model, RedirectAttributes redirectAttributes) throws Exception{
		HashMap<Object, Object> map = Maps.newHashMap();
		workProjectPlan.setId(IdGen.uuid());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		WorkEngineeringProject workEngineeringProject = new WorkEngineeringProject();
		List<WorkProjectPlan> list = new ArrayList<WorkProjectPlan>();
		list.add(workProjectPlan);
		workEngineeringProject.setWorkProjectPlans(list);

		workEngineeringProjectService.insertPlan(workEngineeringProject);
		map.put("projectId",workProjectPlan.getProjectId());
		map.put("taskCount",workProjectPlan.getTaskCount());
		map.put("taskName",workProjectPlan.getTaskName());
		map.put("startTime",workProjectPlan.getStartTime()==null?"":sdf.format(workProjectPlan.getStartTime()));
		map.put("endTime",workProjectPlan.getEndTime()==null?"":sdf.format(workProjectPlan.getEndTime()));
		map.put("remindUser",workProjectPlan.getRemindUser()==null?"":workProjectPlan.getRemindUser().getId());
		map.put("remindUserName",workProjectPlan.getRemindUser()==null?"":UserUtils.get(workProjectPlan.getRemindUser().getId()).getName());
		map.put("remindDate",workProjectPlan.getRemindDate()==null?"":sdf.format(workProjectPlan.getRemindDate()));
		map.put("completeUser",workProjectPlan.getCompleteUser()==null?"":workProjectPlan.getCompleteUser().getId());
		map.put("completeUserName",workProjectPlan.getCompleteUser()==null?"":UserUtils.get(workProjectPlan.getCompleteUser().getId()).getName());
		map.put("completeDate",workProjectPlan.getCompleteDate()==null?"":sdf.format(workProjectPlan.getCompleteDate()));
		map.put("type",workProjectPlan.getType());
		map.put("str","添加成功");
		map.put("ids",workProjectPlan.getId());
		return  map;
	}

	/**
	 * 删除施工单位联系人
	 */
	@RequestMapping(value = "deleteRow")
	@ResponseBody
	public String deleteRow(String ids,WorkProjectPlan workProjectPlan, RedirectAttributes redirectAttributes) {
		HashMap<Object, Object> map = Maps.newHashMap();
		try {
			WorkEngineeringProject workEngineeringProject = new WorkEngineeringProject();
			List<WorkProjectPlan> list = new ArrayList<WorkProjectPlan>();
			String idArray[] =ids.split(",");
			for(String id : idArray){
				WorkProjectPlan workProjectPlan1 = new WorkProjectPlan();
				workProjectPlan1.setId(id);
				list.add(workProjectPlan1);
			}
			workEngineeringProject.setWorkProjectPlans(list);
			workEngineeringProject.setBusinessType("A");
			workEngineeringProjectService.deletePlan(workEngineeringProject);
			//workEngineeringProjectService.delete(workProjectPlan);
			map.put("str","success");
			return JsonMapper.toJsonString(map);
		}catch (Exception e){
			map.put("str","false");
			return JsonMapper.toJsonString(map);
		}

//		addMessage(redirectAttributes, "删除施工单位联系人成功");
//		return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullConstruct/?repage";
	}

	/**
	 * 保存工程项目信息
	 */
	@RequestMapping(value = "storePlan")
	public String storePlan(WorkEngineeringProject workEngineeringProject, Model model, RedirectAttributes redirectAttributes) throws Exception {
		if (!beanValidator(model, workEngineeringProject)) {
			return form(workEngineeringProject, model);
		}
		List<WorkProjectPlan> workProjectPlans = workEngineeringProject.getWorkProjectPlans();
		try{
			workEngineeringProjectService.deletePlan(workEngineeringProject);
			workEngineeringProject.setWorkProjectPlans(workProjectPlans);
			workEngineeringProjectService.insertPlan(workEngineeringProject);
		}catch (Exception e){
			logger.error("Exception e:"+e);
		}
		/*List<Workattachment> list = workEngineeringProject.getWorkAttachments();
		for (Workattachment workattachment:list){
			if (StringUtils.isBlank(workattachment.getAttachmentId())){
				workattachment.setAttachmentId(workEngineeringProject.getId());
				workattachmentService.save(workattachment);
			}
		}*/
		//workattachmentService.uploadattachment(multiRequest,workEngineeringProject.getId(),"workEngineeringProject","4");
		if(StringUtils.isNotBlank(workEngineeringProject.getRemarks())){
			workEngineeringProjectService.updateRemakes(workEngineeringProject);
		}
		addMessage(redirectAttributes, "工程项目计划已保存！");
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/planlist?repage";
	}

	/**
	 *  单个删除阿里云上的文件，同时更新相关对象的附件信息
	 *  阿里云文件地址http://gangwan-app.oss-cn-hangzhou.aliyuncs.com/attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 *  其中阿里云删除接口所需的参数 key 指的是 attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 * @return
	 */
	@RequestMapping("/deleteFileFromAliyun")
	@ResponseBody
	public HashMap<Object, Object> deleteFileFromAliyun(String attachmentId,String url,Model model){
		if(StringUtils.isNotBlank(attachmentId)) {
			Workattachment workattachment = workattachmentService.get(attachmentId);
			workattachmentService.deleteFileFromAliyun(workattachment, workattachment == null ? url : workattachment.getUrl());
		}
		HashMap<Object, Object> map = Maps.newHashMap();
		map.put("str","success");
		return map;
	}

	/**
	 * 工单执行（完成任务）
	 * @param workEngineeringProject
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkEngineeringProject workEngineeringProject, Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) throws Exception {
//		if (org.apache.commons.lang3.StringUtils.isBlank(workEngineeringProject.getAct().getComment())){
//			addMessage(model, "请填写审核意见。");
//			return form(workEngineeringProject, model);
//		}
		WorkEngineeringProject t = workEngineeringProjectService.get(workEngineeringProject.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workEngineeringProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值

		WorkProject workProject = workProjectService.get(t.getProjectId().getId());
		workProject.setName(t.getProjectId().getName());
		workProject.setUpdateBy(t.getUpdateBy());
		workProject.setUpdateDate(t.getUpdateDate());
		workProjectService.update(workProject);//保存项目总表
		workEngineeringProjectService.save(t);//保存
		String str = workEngineeringProjectService.auditSave(workEngineeringProject);
		addMessage(redirectAttributes, str);
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
	}


	/**
	 * 删除工程项目信息
	 */
	@RequiresPermissions("workengineeringproject:workEngineeringProject:del")
	@RequestMapping(value = "delete")
	public String delete(WorkEngineeringProject workEngineeringProject, RedirectAttributes redirectAttributes) {
		WorkProject workProject = workEngineeringProject.getProjectId();
		workProjectService.delete(workProject);//删除总项目表数据
		workEngineeringProjectService.delete(workEngineeringProject);
		addMessage(redirectAttributes, "删除工程项目信息成功");
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
	}
	
	/**
	 * 批量删除工程项目信息
	 */
	@RequiresPermissions("workengineeringproject:workEngineeringProject:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			WorkProject workProject = workEngineeringProjectService.get(id).getProjectId();
			workProjectService.delete(workProject);//删除总项目表数据
			workEngineeringProjectService.delete(workEngineeringProjectService.get(id));
		}
		addMessage(redirectAttributes, "删除工程项目信息成功");
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workengineeringproject:workEngineeringProject:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkEngineeringProject workEngineeringProject, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工程项目信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkEngineeringProject> page = workEngineeringProjectService.findPage(new Page<WorkEngineeringProject>(request, response, -1), workEngineeringProject);
    		new ExportExcel("工程项目信息", WorkEngineeringProject.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出工程项目信息记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workengineeringproject:workEngineeringProject:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<WorkEngineeringProject> list = ei.getDataList(WorkEngineeringProject.class);
			for (WorkEngineeringProject workEngineeringProject : list){
				try{
					workEngineeringProjectService.save(workEngineeringProject);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条工程项目信息记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条工程项目信息记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入工程项目信息失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
    }
	
	/**
	 * 下载导入工程项目信息数据模板
	 */
	@RequiresPermissions("workengineeringproject:workEngineeringProject:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工程项目信息数据导入模板.xlsx";
    		List<WorkEngineeringProject> list = Lists.newArrayList(); 
    		new ExportExcel("工程项目信息数据", WorkEngineeringProject.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
    }

	/**
	 * 获取合同信息
	 * @return
	 */
	@RequestMapping(value = "getContractInfo")
	@ResponseBody
	public String getContractInfo() {
		String obj = request.getParameter("obj");
		WorkContractInfo workContractInfo = workContractInfoService.get(obj);
		WorkClientInfo workClientInfo = workClientInfoService.get(workContractInfo.getClient().getId());
		String clientName = "";
		if (workClientInfo!=null) {
			clientName = workClientInfo.getName();
		}
		WorkClientLinkman workClientLinkman = new WorkClientLinkman();
		workClientLinkman.setClientId(workClientInfo);
		List<WorkClientLinkman> list = workClientInfoService.findByClient(workClientLinkman);
		List<Map<Object,Object>> resultList = Lists.newArrayList();
		if(list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				HashMap<Object, Object> map = Maps.newHashMap();
				map.put("contractNum",workContractInfo.getContractNum());
				map.put("linkmanPosition", list == null ? "" : list.get(i).getPosition());
				map.put("linkmanName", list == null ? "" : list.get(i).getName());
				map.put("linkmanPhone", list == null ? "" : list.get(i).getLinkPhone());
				map.put("linkmanEmail", list == null ? "" : list.get(i).getEmail());
				map.put("QQ", list == null ? "" : list.get(i).getQq());
				map.put("clientName",clientName);
				map.put("clientId",workContractInfo.getClient().getId());
				resultList.add(map);
			}
		}else{
			HashMap<Object, Object> map = Maps.newHashMap();
			map.put("contractNum",workContractInfo.getContractNum());
			map.put("linkmanPosition", "");
			map.put("linkmanName", "");
			map.put("linkmanPhone", "");
			map.put("linkmanEmail", "");
			map.put("QQ", "");
			map.put("clientName",clientName);
			map.put("clientId",workContractInfo.getClient().getId());
			resultList.add(map);
		}
		String resultJsonStr = JsonMapper.toJsonString(resultList);
		return resultJsonStr;

//		map.put("contractNum",workContractInfo.getContractNum());
//		WorkClientInfo workClientInfo = workClientInfoService.get(workContractInfo.getClient().getId());
//		String clientName = "";
//		if (workClientInfo!=null) {
//			clientName = workClientInfo.getName();
//		}
//		map.put("clientName",clientName);
//		map.put("clientId",workContractInfo.getClient().getId());
//		WorkClientLinkman workClientLinkman = new WorkClientLinkman();
//		workClientLinkman.setClientId(workClientInfo);
//		List<WorkClientLinkman> Linkmanlist = workClientInfoService.findByClient(workClientLinkman);
//		map.put("linkmanPosition",Linkmanlist==null||Linkmanlist.size()==0?"":Linkmanlist.get(0).getPosition());
//		map.put("linkmanName",Linkmanlist==null||Linkmanlist.size()==0?"":Linkmanlist.get(0).getName());
//		map.put("linkmanPhone",Linkmanlist==null||Linkmanlist.size()==0?"":Linkmanlist.get(0).getLinkPhone());
//		map.put("linkmanEmail",Linkmanlist==null||Linkmanlist.size()==0?"":Linkmanlist.get(0).getEmail());
//		return JsonMapper.toJsonString(map);
	}

	/**
	 * 获取客户信息
	 * @return
	 */
	@RequestMapping(value = "getClientInfo")
	@ResponseBody
	public String getClientInfo() {
		String obj = request.getParameter("obj");
		WorkClientInfo workClientInfo = workClientInfoService.get(obj);
		String resultJsonStr = workFullManageService.parseList2Json(workClientInfo);
		return resultJsonStr;
	}

	/**
	 * 获取项目信息
	 * @return
	 */
	@RequestMapping(value = "getProjectPlanRows")
	@ResponseBody
	public String getProjectPlanRows()throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		HashMap<Object, Object> map = Maps.newHashMap();
		String id = request.getParameter("ids");
		String ipt = request.getParameter("ipts");
		String select = request.getParameter("selects");
		String[] ids = id.split(",");
		String[] ipts = ipt.split(",");
		String[] selects = select.split(",");
		boolean count = false;
		Set<String> idSet = new HashSet<String>();
		for (int i = 0; i < ids.length; i++) {
			if (i%6==0) {
				idSet.add(ids[i]);
				if (StringUtils.isBlank(ids[i])) {
					count = true;
				}
			}
		}
		for (String str:ipts) {
			if (StringUtils.isBlank(str)){
				count = true;
			}
		}
		for (String str:selects) {
			if (StringUtils.isBlank(str)){
				count = true;
			}
		}
		if (count){
			map.put("str","Fail! 数据不能为空");
		}else {
			map.put("str","Success");
				for (int i = 0; i < ipts.length; i++) {
					try {
						String projectPlanId = ids[i*6+5].replaceAll(" ", "");
						String completeUserDate = ipts[i].replaceAll(" ", "");
						String completeUserId = selects[i].replaceAll(" ", "");
						WorkProjectPlan workProjectPlan = workEngineeringProjectService.getProjectPlan(projectPlanId);
						workProjectPlan.setCompleteDate(sdf.parse(completeUserDate));
						workProjectPlan.setCompleteUser(new User(completeUserId));
						workProjectPlan.setStatus("1");
						workEngineeringProjectService.updateProjectPlan(workProjectPlan);
					}catch (Exception e){
						map.put("str","Fail! 数据异常");
					}
				}

		}

		return JsonMapper.toJsonString(map);
	}

	/**
	 * 选择合同外键id
	 */
	@RequestMapping(value = "selectcontractId")
	public String selectcontractId(WorkContractInfo contractId, String url,String type,String isTotal, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!"1".equals(UserUtils.getSelectCompany().getId())){
			contractId.setCompanyId(UserUtils.getSelectCompany().getId());
		}
		contractId.setContractState("5");
		//contractId.setContractType(type);(合同类型限制解除)
		contractId.setIsTotal(isTotal);
		contractId.setParentIds(UserUtils.getSelectCompany().getParentIds());
		Page<WorkContractInfo> page = workEngineeringProjectService.findPageBycontractId(new Page<WorkContractInfo>(request, response),  contractId);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("type", type);
		model.addAttribute("isTotal", isTotal);
		model.addAttribute("obj", contractId);
		model.addAttribute("page", page);
		return "modules/sys/gridselectContract";
	}
	/**
	 * 选择项目外键id
	 */
	@RequestMapping(value = "selectprojectId")
	public String selectprojectId(WorkBidProject projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompanyId(UserUtils.getSelectCompany().getId());
		Page<WorkBidProject> page = workEngineeringProjectService.findPageByprojectId(new Page<WorkBidProject>(request, response),  projectId);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", projectId);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}

	/**
	 * 读取所有流程
	 * @return
	 */
	@RequestMapping(value = "getProcess")
	public String getProcess(WorkEngineeringProject workEngineeringProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		//admin 可以查看所有流程  展示注释
//        User user = UserUtils.getUser();
//        if (!user.isAdmin()){
////            leave.setCompanyId(user.getComId());
//            if (!UserUtils.isManager()){
//                workReimbursement.setCreateBy(user);
//            }
//        }
		WorkEngineeringProject workEngineeringProject1 = workEngineeringProjectService.get(workEngineeringProject.getId());
		model.addAttribute("processInstanceId", workEngineeringProject1.getProcessInstanceId());
		model.addAttribute("processInstanceProofreadId", workEngineeringProject1.getProcessInstanceProofreadId());
		model.addAttribute("type", workEngineeringProject.getName());
		return "modules/workengineeringproject/workEngineeringProjectTask";
	}

	/**
	 * 启动流程
	 * @return
	 */
	@RequestMapping(value = "startposs")
	public String startposs(WorkEngineeringProject workEngineeringProject, HttpServletRequest request, HttpServletResponse response, Model model, RedirectAttributes redirectAttributes)throws Exception {
		Map<String, Object> variables = new HashMap<String, Object>();
		WorkEngineeringProject t = workEngineeringProjectService.get(workEngineeringProject.getId());//从数据库取出记录的值
		MyBeanUtils.copyBeanNotNull2Bean(workEngineeringProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
		t.setStatus("2");
		t.preUpdate();
		workEngineeringProjectService.update(t);
		workEngineeringProjectService.startProcess(t,variables);
		addMessage(redirectAttributes, "启动流程成功");
		return "redirect:"+Global.getAdminPath()+"/workengineeringproject/workEngineeringProject/?repage";
	}


	/**
	 * 选择报销项目
	 */
	@RequestMapping(value = "selectproject")
	public String selectproject(WorkEngineeringProject projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String isTotal, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompanyId(UserUtils.getSelectCompany().getId());
		projectId.setIsTotal(isTotal);
		Page<WorkEngineeringProject> page = workEngineeringProjectService.findPageByproject(new Page<WorkEngineeringProject>(request, response),  projectId);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", projectId);
		model.addAttribute("isTotal", isTotal);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallproject";
	}

	/**
	 * 选择报销项目
	 */
	@RequestMapping(value = "selectprojectTotal")
	public String selectprojectTotal(WorkEngineeringProject projectId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, String isTotal, HttpServletRequest request, HttpServletResponse response, Model model) {
		projectId.setCompanyId(UserUtils.getSelectCompany().getId());
		projectId.setIsTotal("1");
		Page<WorkEngineeringProject> page = workEngineeringProjectService.findPageByproject(new Page<WorkEngineeringProject>(request, response),  projectId);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", projectId);
		model.addAttribute("isTotal", isTotal);
		model.addAttribute("allowInput", true);
		model.addAttribute("page", page);
		return "modules/sys/gridselectcallproject";
	}

	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workEngineeringProjectTodoList"})
	public String workEngineeringProjectTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("projectallocation");
		List<Act> list = new ArrayList<>();
		list.addAll(actTaskService.todoList(act));
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("7854872f45b84acd893010e66a3db2c8",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.todoList(act));
		}
		List<WorkEngineeringProject> lists = new ArrayList<WorkEngineeringProject>();
		Role role = UserUtils.getSelectRole().get(0);
		String officeId = "";
		if (role.getDataScope().contains("4")){
			User user = UserUtils.getUser();
			officeId = user.getOffice().getId();
		}
		for (Act a : list) {
			WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.getByProcessInstanceId(a.getTask().getProcessInstanceId());
			if (workEngineeringProject != null && workEngineeringProject.getCompanyId().equals(companyId) && workEngineeringProject.getStatus() !=null && workEngineeringProject.getStatus().equals("2") ) {
				if (workEngineeringProject.getRemarks()==null || !workEngineeringProject.getRemarks().equals("重新申请")){
					User createBy = UserUtils.get(workEngineeringProject.getCreateBy().getId());
					if (StringUtils.isNotBlank(officeId)){
						if (officeId.equals(createBy.getOffice().getId())){
							if (a.getVars().getMap().get("applyUserId")!=null) {
								User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
								if (user != null) {
									a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
								}
							}
							workEngineeringProject.setAct(a);
							if (com.jeeplus.common.utils.StringUtils.isNotBlank(workEngineeringProject.getId())){
								workEngineeringProject.setName(officeService.get(companyId).getName());
							}
							lists.add(workEngineeringProject);
						}
					}else {
						if (a.getVars().getMap().get("applyUserId")!=null) {
							User user = UserUtils.get(a.getVars().getMap().get("applyUserId").toString());
							if (user != null) {
								a.getVars().getMap().put("applyUserId", UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
							}
						}
						workEngineeringProject.setAct(a);
						if (com.jeeplus.common.utils.StringUtils.isNotBlank(workEngineeringProject.getId())){
							workEngineeringProject.setName(officeService.get(companyId).getName());
						}
						lists.add(workEngineeringProject);
					}
				}
			}
		}
		model.addAttribute("list", lists);
		return "modules/workengineeringproject/workEngineeringProjectTodoList";
	}

	/**
	 * 已办任务
	 * @param act
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workEngineeringProjectHistoricList"})
	public String workEngineeringProjectHistoricList (Act act, HttpServletRequest request, HttpServletResponse response, Model model){
		act.setProcDefKey("projectallocation");
		List<Act> list = actTaskService.historicList(act);
		Office office = UserUtils.getSelectCompany();
		String companyId = office==null?"":office.getId();
		List<Activity> activities = activityService.groupByActivityMenu("7854872f45b84acd893010e66a3db2c8",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.historicList(act));
		}
		List<WorkEngineeringProject> lists = new ArrayList<WorkEngineeringProject>();
		for (Act a : list) {
			try {
				WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.getByProcessInstanceId(a.getHistTask().getProcessInstanceId());
				if (workEngineeringProject != null && workEngineeringProject.getCompanyId().equals(companyId)) {
					if (a.getVars().getMap().get("applyUserId")!=null){
						a.getVars().getMap().put("applyUserId",UserUtils.get(a.getVars().getMap().get("applyUserId").toString()).getName());
					}
					workEngineeringProject.setAct(a);
					if (com.jeeplus.common.utils.StringUtils.isNotBlank(workEngineeringProject.getId())){
						workEngineeringProject.setName(officeService.get(companyId).getName());
					}
					lists.add(workEngineeringProject);
				}
			}catch (Exception e){
				logger.info("Exception e"+e);
			}

		}
		model.addAttribute("list", lists);

		return "modules/workengineeringproject/workEngineeringProjectHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnWorkEngineeringProject")
	public String applyOnWorkEngineeringProject(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = "/workengineeringproject/workEngineeringProject/form";
		//logger.info("------formKeys:"+formKeys);
		// 获取流程实例对象
		if (act.getProcInsId() != null){
			if(actTaskService.getProcIns(act.getProcInsId())!=null){
				act.setProcIns(actTaskService.getProcIns(act.getProcInsId()));
			}else{
				act.setFinishedProcIns(actTaskService.getFinishedProcIns(act.getProcInsId()));
			}
		}
		return "redirect:" + ActUtils.getFormUrl(formKey, act);
	}

	private String toChinese(String string) {
		String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
		String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };

		String result = "";

		int n = string.length();
		for (int i = 0; i < n; i++) {

			int num = string.charAt(i) - '0';

			if (i != n - 1 && num != 0) {
				result += s1[num] + s2[n - 2 - i];
			} else {
				result += s1[num];
			}
			System.out.println("  "+result);
		}
		return result;

	}
}