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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
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.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.dao.WorkBidProjectDao;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.dao.WorkClientLinkmanDao;
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.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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投标资格预审Controller
 * @author  mengxy
 * @version 2017-05-24
 */
@Controller
@RequestMapping(value = "${adminPath}/workprequalification/workPrequalification")
public class WorkPrequalificationController extends BaseController {

	@Autowired
	private WorkFullManageService workFullManageService;

	@Autowired
	private WorkBidProjectService workBidProjectService;

	@Autowired
	private WorkClientInfoService workClientInfoService;

	@Autowired
	private WorkProjectService workProjectService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private OfficeService officeService;

	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkBidProjectDao workBidProjectDao;
	@Autowired
	private WorkClientLinkmanDao workClientLinkmanDao;
	
	@ModelAttribute
	public WorkBidProject get(@RequestParam(required=false) String id) {
		WorkBidProject entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workBidProjectService.get(id);
		}
		if (entity == null){
			entity = new WorkBidProject();
		}
		return entity;
	}
	
	/**
	 * 资格预审项目列表页面
	 */
	@RequiresPermissions("workprequalification:workPrequalification:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkBidProject workBidProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		workBidProject.setName("2");
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workBidProject.setQueryCon(id);
		}
		/*if(role.getEnname().contains("bmzr")) {
			model.addAttribute("role", role);
		}else {
			model.addAttribute("role", "");
		}*/
		model.addAttribute("role", "");
		Page<WorkBidProject> page = workBidProjectService.findPage(new Page<WorkBidProject>(request, response), workBidProject);
		for (WorkBidProject workBidProject1:page.getList()){
			if(StringUtils.isNotBlank(workBidProject1.getProcessInstanceId())){
				boolean state = actTaskService.isProcessEnd(workBidProject1.getProcessInstanceId());
				if (state){
					workBidProject1.setQueryCon("true");
				}
			}
		}
		model.addAttribute("page", page);
		return "modules/workprequalification/workPrequalificationList";
	}

	/**
	 * 工单执行（完成任务）
	 * @param workBidProject
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkBidProject workBidProject,Map<String, Object> vars, Model model, RedirectAttributes redirectAttributes) {
		/*if (org.apache.commons.lang3.StringUtils.isBlank(workBidProject.getAct().getComment())){
			addMessage(model, "请填写审核意见。");
			return form(workBidProject, model);
		}*/
		//String str = workBidProjectService.auditSave(workBidProject);
		//addMessage(redirectAttributes, str);
		return "redirect:"+Global.getAdminPath()+"/workprequalification/workPrequalification/?repage";
	}

	/**
	 * 查看，增加，编辑资格预审项目表单页面
	 */
	@RequiresPermissions(value={"workprequalification:workPrequalification:view","workprequalification:workPrequalification:add","workprequalification:workPrequalification:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkBidProject workBidProject, Model model) {

		List<WorkClientLinkman>  list = workBidProject.getWorkClientLinkmanList();
		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("linkmanName", list == null ? "" : list.get(i).getName());
				map.put("linkmanOffice", list == null ? "" : list.get(i).getOffice());
				map.put("linkmanPosition", list == null ? "" : list.get(i).getPosition());
				map.put("QQ", list == null ? "" : list.get(i).getQq());
				map.put("linkmanPhone", list == null ? "" : list.get(i).getLinkPhone());
				map.put("linkmanMobile", list == null ? "" : list.get(i).getLinkMobile());
				map.put("linkmanEmail", list == null ? "" : list.get(i).getEmail());
				resultList.add(map);
			}
		}
		String linkmanList = JsonMapper.toJsonString(resultList);
		model.addAttribute("linkmanList",linkmanList);

		if (workBidProject.getAct()!=null && StringUtils.isNotBlank(workBidProject.getAct().getTaskId())){
			model.addAttribute("workPrequalification", workBidProject);
			return "modules/workprequalification/workPrequalificationAudit";
		}
		if(StringUtils.isNotBlank(workBidProject.getName()) && workBidProject.getName().equals("view")){
			model.addAttribute("workPrequalification", workBidProject);
			return "modules/workprequalification/workPrequalificationView";
		}
		if (StringUtils.isBlank(workBidProject.getId())){
			workBidProject.setProjectNumber(IdGen.uuid());
		}
		model.addAttribute("workPrequalification", workBidProject);
		return "modules/workprequalification/workPrequalificationForm";
	}



	/**
	 * 查询系统外客户
	 * @return
	 */
	@RequestMapping(value = "getExtCompany")
	@ResponseBody
	public AjaxJson getExtCompany(String workBidProjectId){
		AjaxJson j = new AjaxJson();
		WorkBidProject workBidProject = workBidProjectDao.get(workBidProjectId);
		List<WorkClientLinkman> list = Lists.newArrayList();
		if(workBidProject!=null && "1".equals(workBidProject.getIsExt())){
			WorkClientLinkman linkman =new WorkClientLinkman();
			linkman.setProjectId(workBidProjectId);
			list = workClientLinkmanDao.findListByProjectId(linkman);
		}
		j.put("list", list);
		return j;
	}

	/**
	 * 保存资格预审项目
	 */
	@RequiresPermissions(value={"workprequalification:workPrequalification:add","workprequalification:workPrequalification:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkBidProject workBidProject, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workBidProject)){
			return form(workBidProject, model);
		}
		if(!"1".equals(workBidProject.getIsExt())){
			workBidProject.setExtCompany("");
		}
		if(!workBidProject.getIsNewRecord()){//编辑表单保存
			WorkBidProject t = workBidProjectService.get(workBidProject.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBidProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			String contacts = workBidProject.getContacts();
			String members = workBidProject.getProjectMemberIds();
			t.setContacts(contacts);
			t.setProjectMember(members);
			String masters = workBidProject.getProjectMasterIds();
			t.setProjectMaster(masters);

			WorkProject workProject = workProjectService.get(t.getWorkProject().getId());
			workProject.setName(t.getProjectName());
			workProject.setUpdateBy(t.getUpdateBy());
			workProject.setUpdateDate(t.getUpdateDate());
			if (StringUtils.isNotBlank(t.getStatus()) &&t.getStatus().equals("4")){
				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);
				}
				//workBidProjectService.auditSave(t);
				//workProjectService.update(workProject);//保存项目总表
				workBidProjectService.save(t);//保存
				addMessage(redirectAttributes, "资格预审项目已重新申请!");
			}else {
				workProjectService.update(workProject);//保存项目总表
				workBidProjectService.save(t);
				addMessage(redirectAttributes, "修改资格预审项目成功!");
			}
		}else{//新增表单保存
			workBidProject.setStatus("2");
			String contacts = workBidProject.getContacts();
			String members = workBidProject.getProjectMemberIds();
			workBidProject.setContacts(contacts);
			workBidProject.setProjectMember(members);
			String masters = workBidProject.getProjectMasterIds();
			workBidProject.setProjectMaster(masters);
			workBidProject.setCompanyId(UserUtils.getSelectCompany().getId());
			workBidProject.setOfficeId(UserUtils.getSelectOffice().getId());

			WorkProject workProject = new WorkProject();
			workProject.setName(workBidProject.getProjectName());
			workProject.setNumber(workBidProject.getProjectNumber());
			workProject.setCreateBy(workBidProject.getCreateBy());
			workProject.setCreateDate(workBidProject.getCreateDate());
			workProject.setDelFlag("-1");
			workProject.setUpdateBy(workBidProject.getUpdateBy());
			workProject.setUpdateDate(workBidProject.getUpdateDate());
			workProject.setRemarks(workBidProject.getRemarks());
			workProject.setCompanyId(UserUtils.getSelectCompany().getId());
			workProject.setSort("投标项目");
			workProjectService.save(workProject);//保存项目总表
			workBidProject.setWorkProject(workProject);
			workBidProjectService.save(workBidProject);//保存

			Map<String, Object> variables = new HashMap<String, Object>();
			workBidProjectService.startProcess(workBidProject,variables);
			addMessage(redirectAttributes, "保存资格预审项目成功!");
		}
		return "redirect:"+Global.getAdminPath()+"/workprequalification/workPrequalification/?repage";
	}
	/**
	 * 保存资格预审项目
	 */
	@RequestMapping(value = "store")
	public String store(WorkBidProject workBidProject, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workBidProject)){
			return form(workBidProject, model);
		}
		if(!"1".equals(workBidProject.getIsExt())){
			workBidProject.setExtCompany("");
		}

		if(!workBidProject.getIsNewRecord()){//编辑表单保存
			WorkBidProject t = workBidProjectService.get(workBidProject.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBidProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			String contacts = workBidProject.getContacts();
			String members = workBidProject.getProjectMemberIds();
			t.setContacts(contacts);
			t.setProjectMember(members);
			String masters = workBidProject.getProjectMasterIds();
			workBidProject.setProjectMaster(masters);

			WorkProject workProject = workProjectService.get(t.getWorkProject().getId());
			workProject.setName(t.getProjectName());
			workProject.setUpdateBy(t.getUpdateBy());
			workProject.setUpdateDate(t.getUpdateDate());
			if (StringUtils.isNotBlank(t.getStatus()) &&t.getStatus().equals("4")){
				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);
				}
				//workBidProjectService.auditSave(t);
				workProjectService.update(workProject);//保存项目总表
				workBidProjectService.save(t);//保存
				addMessage(redirectAttributes, "资格预审项目已撤销!");
			}else {
				workProjectService.update(workProject);//保存项目总表
				workBidProjectService.save(t);
				addMessage(redirectAttributes, "修改资格预审项目成功!");
			}
		}else{//新增表单保存
			workBidProject.setStatus("1");
			String contacts = workBidProject.getContacts();
			String members = workBidProject.getProjectMemberIds();
			workBidProject.setContacts(contacts);
			workBidProject.setProjectMember(members);
			workBidProject.setCompanyId(UserUtils.getSelectCompany().getId());
			workBidProject.setOfficeId(UserUtils.getSelectOffice().getId());

			WorkProject workProject = new WorkProject();
			workProject.setName(workBidProject.getProjectName());
			workProject.setNumber(workBidProject.getProjectNumber());
			workProject.setCreateBy(workBidProject.getCreateBy());
			workProject.setCreateDate(workBidProject.getCreateDate());
			workProject.setDelFlag("-1");
			workProject.setUpdateBy(workBidProject.getUpdateBy());
			workProject.setUpdateDate(workBidProject.getUpdateDate());
			workProject.setRemarks(workBidProject.getRemarks());
			workProject.setSort("投标项目");
			workProjectService.save(workProject);//保存项目总表
			workBidProject.setWorkProject(workProject);

			workBidProjectService.save(workBidProject);//保存
			addMessage(redirectAttributes, "保存资格预审项目成功!");
		}
		return "redirect:"+Global.getAdminPath()+"/workprequalification/workPrequalification/?repage";
	}

	/**
	 * 删除资格预审项目
	 */
	@RequiresPermissions("workprequalification:workPrequalification:del")
	@RequestMapping(value = "delete")
	public String delete(WorkBidProject workBidProject, RedirectAttributes redirectAttributes) {
		WorkProject workProject = workBidProject.getWorkProject();
		workProjectService.delete(workProject);//删除总项目表数据
		workBidProjectService.delete(workBidProject);


		addMessage(redirectAttributes, "删除资格预审项目成功");
		return "redirect:"+Global.getAdminPath()+"/workprequalification/workPrequalification/?repage";
	}
	
	/**
	 * 批量删除资格预审项目
	 */
	@RequiresPermissions("workprequalification:workPrequalification:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			WorkProject workProject = workBidProjectService.get(id).getWorkProject();
			workProjectService.delete(workProject);//删除总项目表数据

			workBidProjectService.delete(workBidProjectService.get(id));

		}
		addMessage(redirectAttributes, "删除资格预审项目成功");
		return "redirect:"+Global.getAdminPath()+"/workprequalification/workPrequalification/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workprequalification:workPrequalification:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkBidProject WorkBidProject, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "资格预审项目"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkBidProject> page = workBidProjectService.findPage(new Page<WorkBidProject>(request, response, -1), WorkBidProject);
    		new ExportExcel("资格预审项目", WorkBidProject.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出资格预审项目记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workprequalification/workPrequalification/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workprequalification:workPrequalification: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<WorkBidProject> list = ei.getDataList(WorkBidProject.class);
			for (WorkBidProject workBidProject : list){
				try{
					workBidProjectService.save(workBidProject);
					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()+"/workprequalification/workPrequalification/?repage";
    }
	
	/**
	 * 下载导入资格预审项目数据模板
	 */
	@RequiresPermissions("workprequalification:workPrequalification:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "资格预审项目数据导入模板.xlsx";
    		List<WorkBidProject> list = Lists.newArrayList();
    		new ExportExcel("资格预审项目数据", WorkBidProject.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workprequalification/workPrequalification/?repage";
    }
	
	
	/**
	 * 选择招标单位
	 */
	@RequestMapping(value = "selectbiddingCompany")
	public String selectbiddingCompany(WorkClientInfo biddingCompany, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkClientInfo> page = workBidProjectService.findPageBybidCompany(new Page<WorkClientInfo>(request, response),  biddingCompany);
		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", biddingCompany);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	

	/**
	 * 选择招标单位
	 */
	@ResponseBody
	@RequestMapping(value = "selectLinkman")
	public AjaxJson selectLinkman(String clientId,HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxJson j = new AjaxJson();
		List<WorkClientLinkman> list = workClientInfoService.findLinkmanList(new WorkClientInfo(clientId));
		j.put("list", list);
		return j;
	}

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

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

			}

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

		return "modules/workprequalification/workPrequalificationHistoricList";
	}

	/**
	 * 审核信息
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "applyOnWorkBidProject")
	public String applyOnWorkBidProject(Act act, HttpServletResponse response, Model model) {
		// 获取流程XML上的表单KEY
		String formKey = "/workprequalification/workPrequalification/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(WorkBidProject workBidProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		//admin 可以查看所有流程  展示注释
//        User user = UserUtils.getUser();
//        if (!user.isAdmin()){
////            leave.setCompanyId(user.getComId());
//            if (!UserUtils.isManager()){
//                workReimbursement.setCreateBy(user);
//            }
//        }
		WorkBidProject workBidProject1 = workBidProjectService.get(workBidProject.getId());
		model.addAttribute("processInstanceId", workBidProject1.getProcessInstanceId());
		return "modules/workprequalification/workPrequalificationTask";
	}

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

}