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

import com.google.common.collect.Maps;
import com.jeeplus.common.oss.OSSClientUtil;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.JPushClientUtil;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
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.pushinfo.entity.Pushinfo;
import com.jeeplus.modules.pushinfo.service.PushinfoService;
import com.jeeplus.modules.sys.dao.UserDao;
import com.jeeplus.modules.sys.entity.Office;
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.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workapprovalcopy.entity.ApprovalCopy;
import com.jeeplus.modules.workapprovalcopy.service.ApprovalCopyService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreimbur.dao.WorkReimburDao;
import com.jeeplus.modules.workreimbur.entity.WorkReimbur;
import com.jeeplus.modules.workreimbur.entity.WorkReimburDetails;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 报销申请Service
 * @author fgy
 * @version 2018-01-19
 */
@SuppressWarnings("all")
@Service
@Transactional(readOnly = true)
public class WorkReimburService extends CrudService<WorkReimburDao, WorkReimbur> {

	@Autowired
	private WorkReimburDao workReimburDao;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private ApprovalCopyService approvalCopyService;
	@Autowired
	private WorkattachmentService workattachmentService;

	@Autowired
	private OfficeService officeService;
	@Autowired
	private PushinfoService pushinfoService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;

	public WorkReimbur get(String id) {
		WorkReimbur workReimbur = workReimburDao.get(id);
		Map<String,Object> variables=null;
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(workReimbur.getProcessInstanceId()).singleResult();
		if(historicProcessInstance!=null) {
			variables = Collections3.extractToMap(historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcessInstance.getId()).list(), "variableName", "value");
		} else {
			variables = runtimeService.getVariables(runtimeService.createProcessInstanceQuery().processInstanceId(workReimbur.getProcessInstanceId()).active().singleResult().getId());
		}
		workReimbur.setVariables(variables);

		List<Workattachment> workattachmentList = workattachmentService.getListByAttachmentIdAndFlag(workReimbur.getId(),"70");
		workReimbur.setWorkattachmentList(workattachmentList);

		String totalAmount = "";
		List<WorkReimburDetails> detailsList = workReimburDao.getDetailsList(workReimbur);
		if(detailsList!=null && detailsList.size()>0){
			BigDecimal bd = new BigDecimal("0.00");
			for (int i = 0; i < detailsList.size(); i++) {
				WorkReimburDetails details = detailsList.get(i);
				if(StringUtils.isNotBlank(details.getReimburAmount())){
					bd = bd.add(new BigDecimal(details.getReimburAmount()));
				}
			}
			totalAmount = bd.toString();
		}
		workReimbur.setDetailsList(detailsList);
		workReimbur.setTotalAmount(totalAmount);
		return workReimbur;
	}
	
	public List<WorkReimbur> findList(WorkReimbur workReimbur) {
		return super.findList(workReimbur);
	}
	
	public Page<WorkReimbur> findPage(Page<WorkReimbur> page, WorkReimbur workReimbur) {
		workReimbur.getSqlMap().put("dsf", dataScopeFilter(workReimbur.getCurrentUser(), "o", "u","", MenuStatusEnum.WORK_REIMBUR.getValue()));
		workReimbur.setPage(page);
		page.setList(workReimburDao.findList(workReimbur));
		if(page.getList()!=null && page.getList().size()>0){
			for(WorkReimbur item : page.getList()) {
				String processInstanceId = item.getProcessInstanceId();
				HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
				if(historicProcessInstance!=null) {
					item.setHistoricProcessInstance(historicProcessInstance);
					item.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult());
				} else {
					ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
					if (processInstance != null){
						item.setProcessInstance(processInstance);
						item.setProcessDefinition(repositoryService.createProcessDefinitionQuery().processDefinitionId(processInstance.getProcessDefinitionId()).singleResult());
					}
				}
				ProcessInstance processInstance = actTaskService.getProcIns(item.getProcessInstanceId());
				if (processInstance!=null) {
					Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
					if (StringUtils.isNotBlank(taskInfok.getAssignee()) && taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
						item.setTask(taskInfok);
					}
				}
			}
		}
		return page;
	}
	
	@Transactional(readOnly = false)
	public void save(WorkReimbur workReimbur) {
		super.save(workReimbur);
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkReimbur workReimbur) {
		super.delete(workReimbur);
	}


	@Transactional(readOnly = false)
	public Map<String,Boolean> saveWorkReimbur(WorkReimbur workReimbur, MultipartFile[] this_upload_files) {{
		Map<String,Boolean> resultMap = Maps.newHashMap();
		try {
			String approverId = "";
			List<String> adds = workReimbur.getAdds();
			for(int i = 0;i<adds.size();i++){
				if(i + 1 == adds.size()){
					approverId += adds.get(i);
				}else{
					approverId += adds.get(i) + ",";
				}
			}
			workReimbur.setIds(approverId);
			Map<String, Object> variables = Maps.newHashMap();
			String type = "1";
			String alias = "1";
			List<String> assigneeList=new ArrayList<String>(); //分配任务的人员
			if(!UserUtils.getUser().isAdmin() && approverId!=null && !approverId.equals("")) {
				if (approverId.contains(UserUtils.getUser().getId())){
					logger.error("报销申请失败,审批人不能为本人");
					resultMap.put("flag",false);
					return resultMap;
				}
				String[] approverIds = approverId.split(",");
				for (int i =0 ;i<approverIds.length;i++){
					assigneeList.add(approverIds[i]);
				}
				type = approverIds.length+"";
				alias = approverIds[0];
			}
			variables.put("assigneeList", assigneeList);
			variables.put("count",assigneeList.size());
			Office office = UserUtils.getSelectOffice();
			Office company = UserUtils.getSelectCompany();
//			User CC = new User();
//			CC.setId(workPettyCash.getCCid());
			User user = UserUtils.getUser();//创建人

			workReimbur.setCompany(company);
			workReimbur.setOffice(office);
			workReimbur.setCreateBy(user);
			workReimbur.setUpdateBy(user);
			workReimbur.setDelFlag("0");
			workReimbur.setStatus("1");
			workReimbur.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
			workReimbur.setOfficeId(UserUtils.getSelectOffice()==null?"":UserUtils.getSelectOffice().getId());
			save(workReimbur,variables,type);

			List<WorkReimburDetails> workReimburDetails = workReimbur.getDetailsList();
			Iterator<WorkReimburDetails> iterator = workReimburDetails.iterator();
			while (iterator.hasNext()){
				WorkReimburDetails item = iterator.next();
				if(StringUtils.isBlank(item.getReimburAmount())
						&&StringUtils.isBlank(item.getReimburCategory())
						&&StringUtils.isBlank(item.getReimburDetail())){
					iterator.remove();
				}
			}
			for (int i = 0; i < workReimburDetails.size(); i++) {
				String UUid = UUID.randomUUID().toString().replaceAll("-","");
				workReimburDetails.get(i).setId(UUid);
				workReimburDetails.get(i).setWorkReimburId(workReimbur.getId());
			}
			this.saveReimburDetails(workReimburDetails);

			if(this_upload_files!=null&&this_upload_files.length>0){
				OSSClientUtil ossClientUtil = new OSSClientUtil();
				for (int i = 0; i < this_upload_files.length; i++) {
					MultipartFile file = this_upload_files[i];
					if(file!=null && !file.isEmpty()&& file.getSize()>0){
						uploadFile(ossClientUtil,file,workReimbur,"70");
					}
				}
			}

			ApprovalCopy approvalCopy = new ApprovalCopy();
			approvalCopy.setCCId(workReimbur.getCCid());
			approvalCopy.setUserId(user.getId());
			approvalCopy.setType("reimbur");
			approvalCopy.setRemarks(workReimbur.getRemarks());
			approvalCopy.setApprovalId(workReimbur.getId());
			approvalCopy.setApproverId(approverId);
			approvalCopy.setReadFlag("0");
			approvalCopyService.save(approvalCopy);

			//给抄送人、审批人发送通知
			if(approvalCopy!=null && org.apache.commons.lang3.StringUtils.isNotBlank(approvalCopy.getId())){
				String chaosongIds = approvalCopy.getCCId();//给所有抄送人发送通知
				String shenpiIds = alias;//给审批流程的第一个人发送通知
				this.sendNotify(chaosongIds,shenpiIds,approvalCopy.getApprovalId());
				String content = "审批信息 申请人:" + user.getName() + ",报销申请: 待审批!";
				UserUtils.pushIm(alias,content);
			}

			String title="审批";
			String content =  UserUtils.getUser().getName()+"的报销申请需要你审批";
			String status = "待审批";
			Office office1 = workReimbur.getOffice();
			String officeName = "";
			if (office1!=null){
				Office o = officeService.get(office1.getId());
				officeName = o.getName();
			}
			String totalAmount = "";
			List<WorkReimburDetails> detailsList = workReimburDao.getDetailsList(workReimbur);
			if(detailsList!=null && detailsList.size()>0){
				BigDecimal bd = new BigDecimal("0.00");
				for (int i = 0; i < detailsList.size(); i++) {
					WorkReimburDetails details = detailsList.get(i);
					if(StringUtils.isNotBlank(details.getReimburAmount())){
						bd = bd.add(new BigDecimal(details.getReimburAmount()));
					}
				}
				totalAmount = bd.toString();
			}
			String remakers = "报销申请部门："+officeName+ "\n"
					+"申请总额："+totalAmount;

			Map extras = new HashMap();
			extras.put("type", "4001");
			extras.put("id", workReimbur.getId());
			extras.put("procDefKey", "reimbur");

			boolean b = JPushClientUtil.sendNotificationToAlias(title, content, extras, alias);
			Pushinfo pushinfo = new Pushinfo();
			pushinfo.setCurrentUser(UserUtils.getUser());
			pushinfo.setRemarks(remakers);
			pushinfo.setUserId(UserUtils.getUser().getId());
			pushinfo.setType("4001");
			pushinfo.setPushId(workReimbur.getId());
			pushinfo.setTitle(title);
			pushinfo.setContent(content);
			pushinfo.setPushUserId(alias);
			pushinfo.setParentType("singleApproval");
			pushinfo.setStatus(status);
			pushinfo.setCompanyId(UserUtils.getSelectCompany()==null?"":UserUtils.getSelectCompany().getId());
			pushinfo.setAddcontent("reimbur");
			pushinfo.setMobile("ios,android");
			pushinfoService.save(pushinfo);
			if (b){
				resultMap.put("flag",true);
				resultMap.put("b",b);
				return resultMap;
			}
		} catch (Exception e) {
			logger.error("启动报销流程失败：", e);
		}
		resultMap.put("flag",false);
		return resultMap;
	}

	}
	@Transactional(readOnly = false)
	private void uploadFile(OSSClientUtil ossClientUtil, MultipartFile file, WorkReimbur workReimbur, String flag) {

		String fileName = file.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf("."));
		String url = ossClientUtil.uploadFile2OSS(file,"workReimbur");
		Workattachment workattachment = new Workattachment();
		workattachment.setUrl(url);
		workattachment.setType(fileType);
		workattachment.setAttachmentName(fileName);
		workattachment.setAttachmentUser(UserUtils.getUser().getId());
		workattachment.setAttachmentId(workReimbur.getId());
		workattachment.setCompanyId(UserUtils.getSelectCompany().getId());
		workattachment.setAttachmentFlag(flag);
		workattachmentService.save(workattachment);
	}

	@Transactional(readOnly = false)
	public void saveReimburDetails(List<WorkReimburDetails> workReimburDetails) {
		workReimburDao.saveReimburDetails(workReimburDetails);
	}

	@Transactional(readOnly = false)
	public void save(WorkReimbur workReimbur, Map<String, Object> variables, String type) {
		// 保存业务数据
		if (StringUtils.isBlank(workReimbur.getId())) {
			// 保存业务数据
			workReimbur.preInsert();
			workReimburDao.insert(workReimbur);
			logger.debug("save entity: {}", workReimbur);

			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(workReimbur.getCurrentUser().getId());

			// 启动流程
			String businessKey = workReimbur.getId().toString();
			variables.put("type", "reimbur");
			variables.put("busId", businessKey);
			variables.put("title", "oa报销申请");//设置标题；
			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ActUtils.PD_OA_REIMBUR[0], businessKey, variables);

			// 更新流程实例ID
			workReimbur.setProcessInstanceId(processInstance.getId());
			workReimbur.setProcessInstance(processInstance);
			workReimburDao.updateProcessInstanceId(workReimbur);

			logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[] {
					ActUtils.PD_OA_REIMBUR[0], businessKey, processInstance.getId(), variables });
		}else{
			workReimbur.preUpdate();
			workReimburDao.update(workReimbur);
			workReimbur.getAct().setComment(("yes".equals(workReimbur.getAct().getFlag())?"[重申] ":"[销毁] ")+workReimbur.getAct().getComment());

			// 完成流程任务
			Map<String, Object> vars = Maps.newHashMap();
			vars.put("reApply", "yes".equals(workReimbur.getAct().getFlag())? true : false);
			actTaskService.complete(workReimbur.getAct().getTaskId(), workReimbur.getAct().getProcInsId(), workReimbur.getAct().getComment(), workReimbur.getComment(), vars);
		}
	}

	@Transactional(readOnly = false)
	public void sendNotify(String chaosongIds, String shenpiIds, String workReimburId) {
		if(StringUtils.isNotBlank(workReimburId)){
			if(StringUtils.isNotBlank(chaosongIds)){
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setTitle(UserUtils.getUser().getName()+"发起了报销申请");
				notify.setRemarks("待通知");
				notify.setContent(UserUtils.getUser().getName()+"的报销申请");
				notify.setNotifyRole("");
				notify.setNotifyId(workReimburId);
				notify.setStatus("0");
				notify.setCompanyId(UserUtils.getSelectCompany().getId());
				notify.setType("37");
				String[] arr = chaosongIds.split(",");
				for (String id : arr){
					if(StringUtils.isNotBlank(id)){
						notify.setId("");
						notify.setUser(new User(id));
						workProjectNotifyService.save(notify);
					}
				}
			}
			if(StringUtils.isNotBlank(shenpiIds)){
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setTitle("您有新的报销申请待审批");
				notify.setRemarks("待审批");
				notify.setContent("报销申请--待审批");
				notify.setNotifyRole("");
				notify.setUser(new User(shenpiIds));
				notify.setNotifyId(workReimburId);
				notify.setStatus("0");
				notify.setCompanyId(UserUtils.getSelectCompany().getId());
				notify.setType("37");
				workProjectNotifyService.save(notify);
			}
		}
	}
	@Transactional(readOnly = false)
	public void auditSave(WorkReimbur workReimbur) {

		// 设置意见
		workReimbur.getAct().setComment(("yes".equals(workReimbur.getAct().getFlag())?"[同意] ":"[驳回] ")+workReimbur.getAct().getComment());
		workReimbur.preUpdate();
		this.update(workReimbur);
		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workReimbur.getAct().getTaskDefKey();

		//发送通知
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workReimbur.getId());
		notify.setCompanyId(UserUtils.getSelectCompany().getId());
		notify.setType("37");
		notify.setStatus("0");
		notify.setNotifyRole("");

		//业务逻辑对应的条件表达式
		String exp = "";
		// 审核环节
		if ("audit1".equals(taskDefKey)){
			exp = "pass";
		}else if ("audit2".equals(taskDefKey)){
			exp = "pass";
		}else if ("audit3".equals(taskDefKey)){
			exp = "pass";
		}else if ("audit4".equals(taskDefKey)){
			exp = "pass";
		}else if ("audit5".equals(taskDefKey)){
			exp = "pass";
		}else if("apply_end".equals(taskDefKey)){
			exp = "pass";
		}
		// 未知环节，直接返回
		else{
			return;
		}

		// 提交流程任务
		Map<String, Object> vars = Maps.newHashMap();
		vars.put(exp, "yes".equals(workReimbur.getAct().getFlag())? false : true);
		// 提交流程任务
		actTaskService.complete(workReimbur.getAct().getTaskId(), workReimbur.getAct().getProcInsId(), workReimbur.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workReimbur.getAct().getProcInsId());
		workReimbur.setStatus("2");
		if (!state){
			if ("yes".equals(workReimbur.getAct().getFlag())){
				workReimbur.setStatus("3");
			}else {
				workReimbur.setStatus("4");
			}
		}
		workReimbur.preUpdate();
		this.update(workReimbur);

		//需在workSealForm更新后 操作：
		//1待审核  2审核中 3通过 4驳回 5已撤销 6催办中
		if("2".equals(workReimbur.getStatus())){
			workReimbur = this.get(workReimbur.getId());
			String userId = workReimbur.getVariables().get("assignee").toString();
			if(StringUtils.isNotBlank(userId)){
				notify.setUser(UserUtils.get(userId));
			}
			notify.setTitle("您有新的报销申请待审批");
			notify.setRemarks("待审批");
			notify.setContent("报销申请--待审批");

		}else if("3".equals(workReimbur.getStatus())){
			notify.setUser(workReimbur.getCreateBy());
			notify.setTitle("您的报销申请已通过");
			notify.setRemarks("待通知");
			notify.setContent(workReimbur.getAct().getComment());
		}else if("4".equals(workReimbur.getStatus())){
			notify.setUser(workReimbur.getCreateBy());
			notify.setTitle("您的报销申请被驳回");
			notify.setRemarks("待通知");
			notify.setContent(workReimbur.getAct().getComment());
		}
		workProjectNotifyService.save(notify);

		//更新审核人的阅读状态
		WorkProjectNotify notify2 = new WorkProjectNotify();
		notify2.setUser(UserUtils.getUser());
		notify2.setNotifyId(workReimbur.getId());
		workProjectNotifyService.readByNotifyIdAndNotifyUser(notify2);

		//抄送
		if("3".equals(workReimbur.getStatus()) || "4".equals(workReimbur.getStatus())){
			ApprovalCopy approvalCopy = approvalCopyService.getByApprovalId(workReimbur.getId());
			if(approvalCopy!=null && StringUtils.isNotBlank(approvalCopy.getCCId())){
				WorkProjectNotify notify1= new WorkProjectNotify();
				notify1.setNotifyId(workReimbur.getId());
				notify1.setCompanyId(UserUtils.getSelectCompany().getId());
				notify1.setType("37");
				notify1.setStatus("0");
				notify1.setNotifyRole("");
				notify1.setContent(workReimbur.getAct().getComment());
				String[] ccIds = approvalCopy.getCCId().split(",");
				for(String ccId : ccIds){
					if(StringUtils.isNotBlank(ccId)){
						notify1.setUser(new User(ccId));
						if("3".equals(workReimbur.getStatus())){
							notify1.setTitle(UserUtils.get(workReimbur.getCreateBy().getId()).getName()+"的报销申请已通过");
						}
						if("4".equals(workReimbur.getStatus())){
							notify1.setTitle(UserUtils.get(workReimbur.getCreateBy().getId()).getName()+"的报销申请被驳回");
						}
						notify1.setRemarks("待通知");
						notify1.setId("");
						workProjectNotifyService.save(notify1);
					}
				}
			}
		}
	}

	@Transactional(readOnly = false)
	public void update(WorkReimbur workReimbur) {
		workReimburDao.update(workReimbur);
	}

	public WorkReimbur getByProcessInstanceId(String processInstanceId) {
		WorkReimbur workReimbur = workReimburDao.getByProcessInstanceId(processInstanceId);
		return workReimbur;
	}

	public WorkReimbur getById(String id) {
		WorkReimbur workReimbur = workReimburDao.get(id);
		return workReimbur;
	}

	@Transactional(readOnly = false)
	public Map getReimburById(String id, String type) {
		WorkReimbur workReimbur = this.getById(id);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String,Object> map = Maps.newHashMap();
		if(workReimbur!=null){
			User user = userDao.get(workReimbur.getCreateBy());
			String officeName = "";
			if(user!=null){
				map.put("userName", user.getName());
				map.put("users", user.getId());
				map.put("photo",user.getPhoto());
				Office office = user.getOffice();
				if(office!=null && office.getName()!=null){
					officeName = office.getName();
				}
			}
			map.put("officeName",officeName);
			map.put("status",workReimbur.getStatus());
			map.put("remarks",workReimbur.getRemarks());
			String office = "";
			if(workReimbur.getOffice()!=null && workReimbur.getOffice().getName()!=null){
				office = workReimbur.getOffice().getName();
			}
			String totalAmount = "";
			List<WorkReimburDetails> detailsList = workReimburDao.getDetailsList(workReimbur);
			if(detailsList!=null && detailsList.size()>0){
				BigDecimal bd = new BigDecimal("0.00");
				for (int i = 0; i < detailsList.size(); i++) {
					WorkReimburDetails details = detailsList.get(i);
					if(StringUtils.isNotBlank(details.getReimburAmount())){
						bd = bd.add(new BigDecimal(details.getReimburAmount()));
					}
				}
				totalAmount = bd.toString();
			}
			map.put("detailsList",detailsList);
			map.put("totalAmount",totalAmount);

			List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(id, "70");
			//map.put("attachmentList",attachmentList);
			String filePath = "";
			if(attachmentList!=null && attachmentList.size()>0){
				for (int i = 0; i < attachmentList.size(); i++) {
					if(StringUtils.isNotBlank(attachmentList.get(i).getUrl())){
						filePath += ","+attachmentList.get(i).getUrl();
					}
				}
			}
			if(filePath.startsWith(",")&&filePath.length()>2){
				filePath = filePath.substring(1);
			}
			map.put("files",filePath);

			map.put("approvalId",id);
			List<Act> list = actTaskService.histoicFlowList(workReimbur.getProcessInstanceId(), "", "");
			List<Act> list2 = actTaskService.toMyStartedList(workReimbur.getProcessInstanceId());
			if (list2!=null && list2.size()!=0) {
				Act act1 = list2.get(list2.size()-1);
				map.put("taskId", act1.getTaskId());
				map.put("taskName", act1.getTaskName());
				map.put("procInsId", act1.getProcInsId());
				map.put("procDefId", act1.getProcDefId());
				map.put("actStatus", act1.getStatus()==null?"todo":act1.getStatus());
				map.put("taskDefKey", act1.getTaskDefKey());
				map.put("procDefKey", "reimbur");
			}
			List list1 = new ArrayList();
			String approvalStatus = "0";
			String assigneeName = "";
			if (list!=null && list.size()!=0) {
				if (list.get(0).getHistIns().getActivityName().contains("审批")) {
					for (int i = list.size() - 1; i > -1; i--) {
						Act act = list.get(i);
						Map<String, Object> maps = new HashMap<String, Object>();
						String state = "0";
						String activityName = "";
						if (act.getHistIns().getActivityName().contains("审批")) {
							if (act.getDurationTime() != null && !act.getDurationTime().equals("")) {
								activityName = "已审批";
								if (UserUtils.getUser().getName().equals(act.getAssigneeName())){
									approvalStatus = "1";
								}
							} else {
								activityName = "待审批";
								state = "2";
							}
						} else {
							activityName = act.getHistIns().getActivityName();
						}
						maps.put("activityName", activityName);
						maps.put("assigneeName", UserUtils.getUser().getName().equals(act.getAssigneeName()) ? "我" : act.getAssigneeName());
						maps.put("startTime", act.getHistIns().getStartTime() == null ? "" : sdf.format(act.getHistIns().getStartTime()));
						maps.put("endTime", act.getHistIns().getEndTime() == null ? "" : sdf.format(act.getHistIns().getEndTime()));
						maps.put("durationTime", act.getDurationTime());
						maps.put("state", state);
						maps.put("userId", act.getCurrentUser().getId());
						list1.add(maps);
					}
				} else {
					if (workReimbur.getStatus().equals("4") || workReimbur.getStatus().equals("3")){
						for (int i = 0; i < list.size()-1; i++) {
							Act act = list.get(i);
							Map<String, Object> maps = new HashMap<String, Object>();
							String state = "0";
							String activityName = "";
							if (act.getHistIns().getActivityName().contains("发起申请")) {
								activityName = act.getHistIns().getActivityName();
								assigneeName = act.getAssigneeName();
							}else if (act.getHistIns().getActivityName().contains("审批")) {
								if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
									assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
								}
								if (act.getDurationTime() != null && !act.getDurationTime().equals("")) {
									activityName = "已审批";
									if (UserUtils.getUser().getName().equals(assigneeName)){
										approvalStatus = "1";
									}
									if (i == (list.size()-2) && workReimbur.getStatus().equals("4")){
										activityName = "审核驳回";
										state = "1";
									}else if (i == (list.size()-2) && workReimbur.getStatus().equals("3")){
										activityName = "审核成功";
									}
								} else {
									activityName = "待审批";
									state = "2";
								}
							}
							else {
								activityName = act.getHistIns().getActivityName();
								if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
									assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
								}
							}
							maps.put("activityName", activityName);
							maps.put("assigneeName", UserUtils.getUser().getName().equals(assigneeName) ? "我" : assigneeName);
							maps.put("startTime", act.getHistIns().getStartTime() == null ? "" : sdf.format(act.getHistIns().getStartTime()));
							maps.put("endTime", act.getHistIns().getEndTime() == null ? "" : sdf.format(act.getHistIns().getEndTime()));
							maps.put("durationTime", act.getDurationTime());
							maps.put("state", state);
							maps.put("userId", act.getCurrentUser().getId());
							list1.add(maps);
						}
					}else {
						for (int i = 0; i < list.size(); i++) {
							Act act = list.get(i);
							Map<String, Object> maps = new HashMap<String, Object>();
							String state = "0";
							String activityName = "";
							if (act.getHistIns().getActivityName().contains("发起申请")) {
								activityName = act.getHistIns().getActivityName();
								assigneeName = act.getAssigneeName();
							}else if (act.getHistIns().getActivityName().contains("审批")) {
								if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
									assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
								}
								if (act.getDurationTime() != null && !act.getDurationTime().equals("")) {
									activityName = "已审批";
									if (UserUtils.getUser().getName().equals(act.getAssigneeName())){
										approvalStatus = "1";
									}
								} else {
									activityName = "待审批";
									state = "2";
								}
							}
							else {
								activityName = act.getHistIns().getActivityName();
								if (UserUtils.get(act.getHistIns().getAssignee())!=null) {
									assigneeName = UserUtils.get(act.getHistIns().getAssignee()).getName();
								}
							}
							if (workReimbur.getStatus().equals("5") && i == list.size() - 1) {
								activityName = "已撤销";
								state = "1";
							}
							maps.put("activityName", activityName);
							maps.put("assigneeName", UserUtils.getUser().getName().equals(assigneeName) ? "我" : assigneeName);
							maps.put("startTime", act.getHistIns().getStartTime() == null ? "" : sdf.format(act.getHistIns().getStartTime()));
							maps.put("endTime", act.getHistIns().getEndTime() == null ? "" : sdf.format(act.getHistIns().getEndTime()));
							maps.put("durationTime", act.getDurationTime());
							maps.put("state", state);
							maps.put("userId", act.getCurrentUser().getId());
							list1.add(maps);
						}
					}
				}
			}
			map.put("approvalStatus", approvalStatus);
			ApprovalCopy approvalCopy = new ApprovalCopy();
			approvalCopy.setApprovalId(id);
			List<ApprovalCopy> approvalCopyList = approvalCopyService.findList(approvalCopy);
			String CCName = "";
			String CCId = "";
			Boolean readFlag = false;
			if (approvalCopyList!=null && approvalCopyList.size()!=0) {
				ApprovalCopy approvalCopy1 = approvalCopyList.get(0);
				CCId = approvalCopy1.getCCId();
				String[] CCid = approvalCopy1.getCCId().split(",");
				readFlag = approvalCopy1.getReadFlag().equals("0");
				if (type.equals("3") && readFlag){
					approvalCopy1.setReadFlag("1");
					approvalCopyService.save(approvalCopy1);
				}
				for (String userId : CCid) {
					User CCUser = UserUtils.get(userId);
					if (CCUser != null) {
						CCName = CCUser.getName() + ",";
					}
				}
				if (CCName.length() > 1) {
					CCName = CCName.substring(0, CCName.length() - 1);
				} else {
					CCName = "";
				}
			}
			map.put("nameCopy",CCName);
			map.put("CCId",CCId);
			map.put("process",list1);

		}
		return  map;
	}
}