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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

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.service.OfficeService;
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.workbidproject.entity.WorkBidProject;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.modules.sys.entity.Workattachment;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
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 com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.workvisa.entity.WorkVisa;
import com.jeeplus.modules.workvisa.service.WorkVisaService;

/**
 * 工程签证Controller
 * @author liuw
 * @version 2017-10-31
 */
@Controller
@RequestMapping(value = "${adminPath}/workvisa/workVisa")
public class WorkVisaController extends BaseController {

	@Autowired
	private WorkVisaService workVisaService;
	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private WorkattachmentService workattachmentService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private ActivityService activityService;

	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private RuntimeService runtimeService;

	@ModelAttribute
	public WorkVisa get(@RequestParam(required=false) String id) {
		WorkVisa entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workVisaService.get(id);
		}
		if (entity == null){
			entity = new WorkVisa();
		}
		return entity;
	}
	
	/**
	 * 工程签证列表页面
	 */
	//@RequiresPermissions("workvisa:workVisa:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkVisa workVisa, HttpServletRequest request, HttpServletResponse response, Model model) {
		workVisa.setCompanyId(UserUtils.getSelectCompany().getId());
		Page<WorkVisa> page = workVisaService.findPage(new Page<WorkVisa>(request, response), workVisa);
		List<WorkVisa> list = page.getList();
		List<WorkVisa> list2 = new ArrayList<WorkVisa>();
		for (WorkVisa entity :list){
			boolean state = true;
			if(StringUtils.isNotBlank(entity.getProcessInstanceId())){
				state = actTaskService.isProcessEnd(entity.getProcessInstanceId());
			}else{
				state = false;
			}
			entity.setProcessEnded(state);
			list2.add(entity);
		}
		page.setList(list2);
		model.addAttribute("page", page);
		return "modules/workvisa/workVisaList";
	}
	/**
	 * 工单执行（完成任务）
	 * @param workVisa
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkVisa workVisa,Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) {
		/*if (org.apache.commons.lang3.StringUtils.isBlank(workVisa.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workVisa, model,request);
		}*/
		String str = workVisaService.auditSave(workVisa);
		WorkFullManage w = new WorkFullManage();
		WorkFullManage w1 = workVisa.getFullManage();
		w.setId(w1.getId());
		model.addAttribute("workFullManage", w);
		addMessage(redirectAttributes, str);
		return "redirect:"+Global.getAdminPath()+"/workvisamanage/workVisaManage/?repage";
	}
	/**
	 * 查看，增加，编辑工程签证表单页面
	 */
	//@RequiresPermissions(value={"workvisa:workVisa:view","workvisa:workVisa:add","workvisa:workVisa:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkVisa workVisa, Model model,HttpServletRequest request) {

		String wf=request.getParameter("wf");
		if(wf!=null){
			WorkFullManage workF = workFullManageService.getWF(wf);
			model.addAttribute("workFullManage", workF);
		}
		List<Workattachment> attachmentList = workVisaService.findAttachment(workVisa);
		model.addAttribute("workAttachmentList", attachmentList);
		model.addAttribute("workVisa", workVisa);
		if (workVisa.getAct()!=null && StringUtils.isNotBlank(workVisa.getAct().getTaskId())){
			return "modules/workvisa/workVisaAudit";
		}
		if(StringUtils.isNotBlank(workVisa.getName()) && workVisa.getName().equals("view")){
			return "modules/workvisa/workVisaView";
		}
		if (StringUtils.isBlank(workVisa.getId())){
			workVisa.setVisaNumber( IdGen.uuid());
		}
		return "modules/workvisa/workVisaForm";
	}

	/**
	 * 保存工程签证
	 */
	//@RequiresPermissions(value={"workvisa:workVisa:add","workvisa:workVisa:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkVisa workVisa, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workVisa)){
			return form(workVisa, model,request);
		}
		if(!workVisa.getIsNewRecord()){//编辑表单保存
			WorkVisa t = workVisaService.get(workVisa.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workVisa, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			t.setCompanyId(UserUtils.getSelectCompany().getId());
			String remarks = t.getRemarks();
			if(StringUtils.isNotBlank(remarks) && remarks.equals("重新申请")){
			//if (StringUtils.isNotBlank(t.getStatus()) &&t.getStatus().equals("3")){
				String processInstanceId = t.getProcessInstanceId();
				HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
				if(historicProcessInstance!=null) {
					t.setHistoricProcessInstance(historicProcessInstance);
					t.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
				} else {
					ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
					if (processInstance != null){
						t.setProcessInstance(processInstance);
						t.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
					}
				}
				ProcessInstance processInstance = actTaskService.getProcIns(t.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("yes");
					t.setAct(act);
				}
				t.setRemarks("");
				workVisaService.auditSave(t);
				workVisaService.save(t);//保存
				List<Workattachment> list = workVisa.getWorkAttachments();
				if(list!=null && list.size()>0){
					for (int i = 0; i < list.size(); i++) {
						Workattachment w = list.get(i);
						if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")){
							w.setAttachmentId(workVisa.getId());
							w.setCompanyId(workVisa.getCompanyId());
							w.setAttachmentUser(UserUtils.getUser().getId());
							w.setId("");
							workattachmentService.save(w);
						}
					}
				}
				addMessage(redirectAttributes, "工程签证单已重新申请!");
			}else {
				workVisaService.save(t);//保存
				List<Workattachment> list = workVisa.getWorkAttachments();
				if(list!=null && list.size()>0){
					for (int i = 0; i < list.size(); i++) {
						Workattachment w = list.get(i);
						if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")){
							w.setAttachmentId(workVisa.getId());
							w.setCompanyId(workVisa.getCompanyId());
							w.setAttachmentUser(UserUtils.getUser().getId());
							w.setId("");
							workattachmentService.save(w);
						}
					}
				}
				addMessage(redirectAttributes, "修改工程签证成功");
			}
		}else{//新增表单保存
			workVisa.setStatus("2");
			workVisa.setCompanyId(UserUtils.getSelectCompany().getId());
			workVisa.setOfficeId(UserUtils.getSelectOffice().getId());
			workVisaService.save(workVisa);//保存
			List<Workattachment> list = workVisa.getWorkAttachments();
			if(list!=null && list.size()>0){
				for (int i = 0; i < list.size(); i++) {
					Workattachment w = list.get(i);
					if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")){
						w.setAttachmentId(workVisa.getId());
						w.setCompanyId(workVisa.getCompanyId());
						w.setAttachmentUser(UserUtils.getUser().getId());
						w.setId("");
						workattachmentService.save(w);
					}
				}
			}

			Map<String, Object> variables = new HashMap<String, Object>();
			workVisaService.startProcess(workVisa,variables);
			addMessage(redirectAttributes, "保存工程签证成功");
		}
		return "redirect:"+Global.getAdminPath()+"/workvisamanage/workVisaManage/?repage";
	}
	/**
	 * 保存资格预审项目
	 */
	@RequestMapping(value = "store")
	public String store(WorkVisa workVisa, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request, @RequestParam("attachment_file") MultipartFile attachment_file) throws Exception{
		if (!beanValidator(model, workVisa)){
			return form(workVisa, model,request);
		}
		if(!workVisa.getIsNewRecord()){//编辑表单保存
			WorkVisa t = workVisaService.get(workVisa.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workVisa, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			t.setCompanyId(UserUtils.getSelectCompany().getId());

			if (StringUtils.isNotBlank(t.getStatus()) &&t.getStatus().equals("3")){
				String processInstanceId = t.getProcessInstanceId();
				HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
				if(historicProcessInstance!=null) {
					t.setHistoricProcessInstance(historicProcessInstance);
					t.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
				} else {
					ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
					if (processInstance != null){
						t.setProcessInstance(processInstance);
						t.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
					}
				}
				ProcessInstance processInstance = actTaskService.getProcIns(t.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("no");
					t.setAct(act);
				}
				workVisaService.auditSave(t);
				workVisaService.save(t);//保存
				List<Workattachment> list = workVisa.getWorkAttachments();
				if(list!=null && list.size()>0){
					for (int i = 0; i < list.size(); i++) {
						Workattachment w = list.get(i);
						if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")){
							w.setAttachmentId(workVisa.getId());
							w.setCompanyId(workVisa.getCompanyId());
							w.setAttachmentUser(UserUtils.getUser().getId());
							w.setId("");
							workattachmentService.save(w);
						}
					}
				}
				addMessage(redirectAttributes, "工程签证单已撤销!");
			}else {
				workVisaService.save(t);//保存
				List<Workattachment> list = workVisa.getWorkAttachments();
				if(list!=null && list.size()>0){
					for (int i = 0; i < list.size(); i++) {
						Workattachment w = list.get(i);
						if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")){
							w.setAttachmentId(workVisa.getId());
							w.setCompanyId(workVisa.getCompanyId());
							w.setAttachmentUser(UserUtils.getUser().getId());
							w.setId("");
							workattachmentService.save(w);
						}
					}
				}
				addMessage(redirectAttributes, "修改工程签证成功");
			}
		}else{//新增表单保存
			workVisa.setStatus("1");
			workVisa.setCompanyId(UserUtils.getSelectCompany().getId());
			workVisa.setOfficeId(UserUtils.getSelectOffice().getId());
			workVisaService.save(workVisa);//保存
			List<Workattachment> list = workVisa.getWorkAttachments();
			if(list!=null && list.size()>0){
				for (int i = 0; i < list.size(); i++) {
					Workattachment w = list.get(i);
					if (StringUtils.isNotBlank(w.getUrl()) && !w.getUrl().equals("null")){
						w.setAttachmentId(workVisa.getId());
						w.setCompanyId(workVisa.getCompanyId());
						w.setAttachmentUser(UserUtils.getUser().getId());
						w.setId("");
						workattachmentService.save(w);
					}
				}
			}

			addMessage(redirectAttributes, "暂存工程签证成功");
		}
		return "redirect:"+Global.getAdminPath()+"/workvisamanage/workVisaManage/?repage";
	}
	/**
	 * 删除工程签证
	 */
	//@RequiresPermissions("workvisamanage:workVisaManage:list")
	//@RequiresPermissions("workvisa:workVisa:del")
	@RequestMapping(value = "delete")
	public String delete(WorkVisa workVisa, RedirectAttributes redirectAttributes) {
		workVisaService.delete(workVisa);
		List<Workattachment> attachmentList = workVisaService.findAttachment(workVisa);
		for(Workattachment workattachment:attachmentList){
			if(workVisa != null && workVisa.getId() != null){
				workVisaService.deleteFileFromAliyun(workattachment);
			}
		}
		addMessage(redirectAttributes, "删除工程签证成功");
		return "redirect:"+Global.getAdminPath()+"/workvisamanage/workVisaManage/workVisaList";
		//return "redirect:"+Global.getAdminPath()+"/workvisamanage/workVisaManage/list";
	}
	
	/**
	 * 批量删除工程签证
	 */
	//@RequiresPermissions("workvisa:workVisa:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workVisaService.delete(workVisaService.get(id));
		}
		addMessage(redirectAttributes, "删除工程签证成功");
		return "redirect:"+Global.getAdminPath()+"/workvisa/workVisa/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workvisa:workVisa:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkVisa workVisa, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工程签证"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkVisa> page = workVisaService.findPage(new Page<WorkVisa>(request, response, -1), workVisa);
    		new ExportExcel("工程签证", WorkVisa.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出工程签证记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workvisa/workVisa/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workvisa:workVisa: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<WorkVisa> list = ei.getDataList(WorkVisa.class);
			for (WorkVisa workVisa : list){
				try{
					workVisaService.save(workVisa);
					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()+"/workvisa/workVisa/?repage";
    }
	
	/**
	 * 下载导入工程签证数据模板
	 */
	@RequiresPermissions("workvisa:workVisa:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "工程签证数据导入模板.xlsx";
    		List<WorkVisa> list = Lists.newArrayList(); 
    		new ExportExcel("工程签证数据", WorkVisa.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workvisa/workVisa/?repage";
    }
	
	
	/**
	 * 选择全过程管理项目
	 */
	@RequestMapping(value = "selectfullManage")
	public String selectfullManage(WorkFullManage fullManage, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkFullManage> page = workVisaService.findPageByfullManage(new Page<WorkFullManage>(request, response),  fullManage);
		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", fullManage);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}

	/**
	 * 上传附件
	 * @param multiRequest
	 * @return
	 */
	@RequestMapping("/evaluateUpload")
	@ResponseBody
	public String evaluateUpload(MultipartHttpServletRequest multiRequest){
		String title = multiRequest.getParameter("title");
		String userId = multiRequest.getParameter("id");

		workVisaService.uploadEvaludate(multiRequest);

		return title;
	}
	/**
	 *  单个删除阿里云上的文件，同时更新相关对象的附件信息
	 *  阿里云文件地址http://gangwan-app.oss-cn-hangzhou.aliyuncs.com/attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 *  其中阿里云删除接口所需的参数 key 指的是 attachment-file/workBidingDocument/3fcf03e37b3ba0fd5c7821998e392395.doc
	 * @return
	 */
	@RequestMapping("/deleteFileFromAliyun")
	public String deleteFileFromAliyun(@RequestParam("attachmentId") String attachmentId,WorkVisa workVisa,Model model,HttpServletRequest request){
		Workattachment workattachment = workattachmentService.get(attachmentId);
		if(workVisa != null && workVisa.getId() != null){
			workVisaService.deleteFileFromAliyun(workattachment);
		}
		return "redirect:"+Global.getAdminPath()+"/workvisamanage/workVisaManage/workVisaList";
	}

	/**
	 * 待办任务列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"workVisaTodoList"})
	public String workVisaTodoList(Act act, HttpServletRequest request, HttpServletResponse response, Model model) {
		act.setProcDefKey("workVisa");
		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("9574872f45b84acd89jjj1e66a3db2c8",companyId);
		for (Activity activity:activities){
			act.setProcDefKey(activity.getProcessKey());
			list.addAll(actTaskService.todoList(act));
		}
		List<WorkVisa> lists = new ArrayList<WorkVisa>();
		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) {
			WorkVisa workVisa = workVisaService.getByProcessInstanceId(a.getTask().getProcessInstanceId());
			if (workVisa != null && workVisa.getCompanyId().equals(companyId) && workVisa.getStatus() !=null && workVisa.getStatus().equals("2")) {
				User createBy = UserUtils.get(workVisa.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());
							}
						}
						workVisa.setAct(a);
						/*if (com.jeeplus.common.utils.StringUtils.isNotBlank(workVisa.getId())){
							workVisa.setName(officeService.get(companyId).getName());
						}*/
						lists.add(workVisa);
					}
				}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());
						}
					}
					workVisa.setAct(a);
					/*if (com.jeeplus.common.utils.StringUtils.isNotBlank(workVisa.getId())){
						workVisa.setName(officeService.get(companyId).getName());
					}*/
					lists.add(workVisa);
				}
			}
		}
		model.addAttribute("list", lists);
		return "modules/workvisa/workVisaTodoList";
	}

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

		return "modules/workvisa/workVisaHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnWorkBidProject")
	public String applyOnWorkBidProject(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = "/workvisa/workVisa/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);
	}

	/**
	 * 读取所有流程
	 * @return
	 */
	@RequestMapping(value = "getProcess")
	public String getProcess(WorkVisa workVisa, HttpServletRequest request, HttpServletResponse response, Model model) {
		//admin 可以查看所有流程  展示注释
//        User user = UserUtils.getUser();
//        if (!user.isAdmin()){
////            leave.setCompanyId(user.getComId());
//            if (!UserUtils.isManager()){
//                workReimbursement.setCreateBy(user);
//            }
//        }
		WorkVisa workVisa1 = workVisaService.get(workVisa.getId());
		model.addAttribute("processInstanceId", workVisa1.getProcessInstanceId());
		return "modules/workvisa/workVisaTask";
	}

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