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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
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.act.utils.ProcessDefCache;
import com.jeeplus.modules.serialnum.service.SerialNumTplService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.dao.WorkActivityProcessDao;
import com.jeeplus.modules.workactivity.entity.Activity;
import com.jeeplus.modules.workactivity.entity.WorkActivityProcess;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workactivity.service.WorkActivityProcessService;
import com.jeeplus.modules.workactivitymenu.entity.WorkActivityMenu;
import com.jeeplus.modules.workactivitymenu.service.WorkActivityMenuService;
import com.jeeplus.modules.workinvoice.entity.WorkInvoice;
import com.jeeplus.modules.workinvoice.service.WorkInvoiceService;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.modules.workinvoicedetail.entity.WorkInvoiceDetail;
import com.jeeplus.modules.workinvoicedetail.dao.WorkInvoiceDetailDao;

/**
 * 发票明细Service
 * @author lw
 * @version 2018-05-09
 */
@Service
@Transactional(readOnly = true)
public class WorkInvoiceDetailService extends CrudService<WorkInvoiceDetailDao, WorkInvoiceDetail> {
	@Autowired
	@Lazy
	private WorkInvoiceService workInvoiceService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private WorkInvoiceDetailDao workInvoiceDetailDao;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private SerialNumTplService serialNumTplService;


	public WorkInvoiceDetail get(String id) {
		WorkInvoiceDetail workInvoiceDetail = super.get(id);
		if(workInvoiceDetail!=null){
			String wId = workInvoiceDetail.getInvoiceId();
			if(StringUtils.isNotBlank(wId)){
				WorkInvoice workInvoice = workInvoiceService.get(wId);
				if(workInvoice!=null){
					workInvoiceDetail.setWorkInvoice(workInvoice);
				}
			}
		}
		return workInvoiceDetail;
	}
	
	public List<WorkInvoiceDetail> findList(WorkInvoiceDetail workInvoiceDetail) {
		return super.findList(workInvoiceDetail);
	}
	
	public Page<WorkInvoiceDetail> findPage(Page<WorkInvoiceDetail> page, WorkInvoiceDetail workInvoiceDetail) {
		return super.findPage(page, workInvoiceDetail);
	}
	public Page<WorkInvoiceDetail> findPages(Page<WorkInvoiceDetail> page, WorkInvoiceDetail workInvoiceDetail) {
		workInvoiceDetail.getSqlMap().put("dsf", dataScopeFilter(workInvoiceDetail.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_INVOICEDETAIL.getValue()));
		workInvoiceDetail.setPage(page);
		page.setList(dao.findLists(workInvoiceDetail));
		return page;
	}
	@Transactional(readOnly = false)
	public void save(WorkInvoiceDetail workInvoiceDetail) {
		super.save(workInvoiceDetail);
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkInvoiceDetail workInvoiceDetail) {
		super.delete(workInvoiceDetail);
	}

	@Transactional(readOnly = false)
	public void deletes(WorkInvoiceDetail workInvoiceDetail) {
		//清空退票信息实现逻辑删除退票申请
		workInvoiceDetail.setSign(null);
		workInvoiceDetail.setProcessInstanceId(null);
		workInvoiceDetail.setReturnNumber(null);
		workInvoiceDetail.setReturnReason(null);
		workInvoiceDetail.setReturnCancle(null);
		workInvoiceDetail.setReturnSign(null);
		workInvoiceDetail.setReturnDate(null);
		workInvoiceDetail.setReturnUser(null);
		workInvoiceDetail.setStatus(null);
		super.save(workInvoiceDetail);
	}

    public Page<WorkInvoiceDetail> findPageWithDept(Page<WorkInvoiceDetail> workInvoiceDetailPage, WorkInvoiceDetail invoice) {
	    invoice.setPage(workInvoiceDetailPage);
	    workInvoiceDetailPage.setList(dao.findListWithDept(invoice));
        return workInvoiceDetailPage;
    }
	public Page<WorkInvoiceDetail> findPageReturn(Page<WorkInvoiceDetail> workInvoiceDetailPage, WorkInvoiceDetail invoice) {
		invoice.getSqlMap().put("dsf", dataScopeFilter(invoice.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_INVOICEDETAIL.getValue()));
		invoice.setPage(workInvoiceDetailPage);
		workInvoiceDetailPage.setList(dao.findListReturn(invoice));
		return workInvoiceDetailPage;
	}
    public int updateIncomeMoney(WorkInvoiceDetail invoice) {
	    invoice.preUpdate();
        return dao.update(invoice);
    }

	/**
	 * 提交存储
	 * @param
	 * @param variables
	 */
	@Transactional(readOnly = false)
	public String saves(WorkInvoiceDetail workInvoiceDetail,Map<String, Object> variables,String processInstanceId) {
		try {
			if(StringUtils.isBlank(workInvoiceDetail.getReturnNumber())) {
				workInvoiceDetail.setReturnNumber(serialNumTplService.genSerialNum(UserUtils.get(workInvoiceDetail.getCreateBy().getId()).getCompany(), workInvoiceDetail.SERIAL_BIZCODE));
			}
			User user = UserUtils.getUser();
			super.save(workInvoiceDetail);
			WorkInvoice workInvoice = new WorkInvoice();
			if(workInvoiceDetail.getWorkInvoice()!=null){
				if(StringUtils.isNotBlank(workInvoiceDetail.getWorkInvoice().getId())){
					workInvoice = workInvoiceService.get(workInvoiceDetail.getWorkInvoice().getId());
				}
			}
			String str =  "退票申请人："+UserUtils.get(workInvoiceDetail.getCreateBy().getId()).getName()+",退票发票号："+workInvoiceDetail.getNumber();
			// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
			identityService.setAuthenticatedUserId(user.getId());
			// 启动流程
			String businessKey = workInvoiceDetail.getId().toString();
			Office office = UserUtils.getSelectOffice();
			WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("ggh3125f1f194c82bdea9uiopc750906", office);//menuid
			// 启动流程
			String processType = workActivityMenu.getProcessType();
			StringBuffer buffer = new StringBuffer();
			Activity activity = new Activity();
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(workInvoiceDetail.getId(),
							null,
							workInvoiceDetail.getComId(),
							"退票申请人："+UserUtils.get(workInvoiceDetail.getCreateBy().getId()).getName()+",退票发票号："+workInvoiceDetail.getNumber(),
							str,
							"40",
							"0",
							"待审批",
							""
					);
			List<User> users = new ArrayList<>();
			if (StringUtils.isNotBlank(workActivityMenu.getId())) {
				workProjectNotify.setNotifyRole("");
				workActivityMenu = workActivityMenuService.get(workActivityMenu.getId());
				List<Activity> activities = workActivityMenu.getActivities();
				for (Activity a : activities) {
					String encount = a.getEncount();
					String enlist = a.getEnlist();
					if (a.getRole()!=null && StringUtils.isNotBlank(a.getRole().getEnname())){
						List enusers = UserUtils.getByRoleActivityEnnames(a.getRole().getEnname(),office.getId(),"6",workInvoiceDetail.getCreateBy());
						if (enusers.size()==0){
							this.deletes(workInvoiceDetail);
							return "流程审批人不能为空,角色"+a.getRole().getName()+"下无用户,请联系管理员！";
						}
						variables.put(enlist, enusers);
						variables.put(encount, enusers.size());
					}
					if (a.getDelFlag().equals("0") && a.getCount() == 1) {
						activity = a;
					}
				}
				buffer.append(activity.getRole().getEnname());
				if (activity != null && StringUtils.isNotBlank(activity.getId())) {
					//角色审批
					if (StringUtils.isNotBlank(activity.getRole().getEnname())) {
						users = UserUtils.getByRoleActivityEnnames(activity.getRole().getEnname(),office.getId(),"6",workInvoiceDetail.getCreateBy());
					}
					//人员审批
					if (StringUtils.isNotBlank(activity.getUser().getId())) {
						users.add(activity.getUser());
					}
				}
				workProjectNotify.setId("");
			} else {
				List<User> fpglys = new ArrayList<>();
				List<User> zgkjs = new ArrayList<>();
				List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"6",workInvoiceDetail.getCreateBy());
				List<User> fglds = UserUtils.getByRoleActivityEnname("fgld",2,office.getId(),"6",workInvoiceDetail.getCreateBy());
				if(workInvoice!=null){
					//1总公司0分公司
					if("1".equals(workInvoice.getExt())){
						fpglys = UserUtils.getByRoleActivityEnname("fpgly",1,office.getId(),"6",workInvoiceDetail.getCreateBy());
						zgkjs = UserUtils.getByRoleActivityEnname("zghj",1,office.getId(),"6",workInvoiceDetail.getCreateBy());
					}else if("0".equals(workInvoice.getExt())){
						fpglys = UserUtils.getByRoleActivityEnname("fpgly",3,office.getId(),"6",workInvoiceDetail.getCreateBy());
						zgkjs = UserUtils.getByRoleActivityEnname("zghj",3,office.getId(),"6",workInvoiceDetail.getCreateBy());
					}
				}
				variables.put("bmzrList", bmzrs);
				variables.put("fgldList", fglds);
				variables.put("fpglyList", fpglys);
				variables.put("zgkjList", zgkjs);
				if (bmzrs.size()==0 || fglds.size()==0 || fpglys.size()==0 || zgkjs.size()==0){
					this.deletes(workInvoiceDetail);
				}
				if (bmzrs.size()==0){
					return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
				}
				if (fglds.size()==0){
					return "流程审批人不能为空,角色分管领导下无用户,请联系管理员！";
				}
				if (fpglys.size()==0){
					return "流程审批人不能为空,角色发票管理员下无用户,请联系管理员！";
				}
				if (zgkjs.size()==0){
					return "流程审批人不能为空,角色主管会计下无用户,请联系管理员！";
				}
				variables.put("bmzrcount",bmzrs.size());
				variables.put("fgldcount",fglds.size());
				variables.put("fpglycount",fpglys.size());
				variables.put("zgkjcount",zgkjs.size());
				processType = "workinvoicereturn";
				users.addAll(bmzrs);
			}
			for (User u : users){
				workProjectNotify.setUser(u);
				workProjectNotify.setId("");
				workProjectNotifyService
						.save(workProjectNotify);
				/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
				for (WebSocket toUserConn:toUserConns) {
					String message = "{\"to\":\""+u.getId()+"\"," +
							"\"msg\":\"审批信息 申请人:" + user.getName() + ",发票单号:"+ workInvoiceDetail.getNumber() + " 待审批!\"," +
							"\"useType\":\"sys\"}";
					ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
				}*/
				UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",发票单号:"+workInvoiceDetail.getNumber());
			}
			variables.put("type", processType);
			variables.put("busId", businessKey);
			variables.put("title", "审批单：" + workInvoiceDetail.getNumber());//设置标题；

			ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
			workInvoiceDetail.setProcessInstance(processInstance);
			if (StringUtils.isNotBlank(processInstanceId)) {
				workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
				workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			}
			// 更新流程实例ID
			workInvoiceDetail.setProcessInstanceId(processInstance.getId());
			workInvoiceDetailDao.updateProcessInstanceId(workInvoiceDetail);
			List<Activity> list = workActivityMenu.getActivities();
			if (list != null && list.size() != 0) {
				workActivityProcessService.saveList(list, processInstance.getId());
			} else {
				WorkActivityProcess workActivityProcess = new WorkActivityProcess();
				workActivityProcess.setProcessKey("workinvoicereturn");
				workActivityProcess.setCount(1);
				workActivityProcess.setProcessInstanceId(processInstance.getId());
				workActivityProcess.setIsApproval("0");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcess.setCount(2);
				workActivityProcess.setId("");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcess.setCount(3);
				workActivityProcess.setId("");
				workActivityProcessService.save(workActivityProcess);
				workActivityProcess.setCount(4);
				workActivityProcess.setId("");
				workActivityProcessService.save(workActivityProcess);
			}
			logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
					ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		}catch (Exception e){
			logger.info("Exception e:"+e);
			return "Exception e:"+e;
		}
		return "";
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkInvoiceDetail workInvoiceDetail) {
		try {
			String str =  "退票申请人："+UserUtils.get(workInvoiceDetail.getCreateBy().getId()).getName()+",退票发票号："+workInvoiceDetail.getNumber();
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workInvoiceDetail.getAct().getTaskDefKey();
			if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
				actTaskService.claim(workInvoiceDetail.getAct().getTaskId(), UserUtils.getUser().getId());
			}else {
				workInvoiceDetail.getAct().setFlag("yes");
			}
			String comment = "";
			if (workInvoiceDetail.getStatus().equals("4")){
				comment = ("yes".equals(workInvoiceDetail.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
			}else {
				comment = ("yes".equals(workInvoiceDetail.getAct().getFlag())?"[同意] ":"[驳回] ")+workInvoiceDetail.getAct().getComment();
			}
			//yes 的时候状态为审核通过 否则为未通过
			//1 审核中 2 未通过
			workInvoiceDetail.setStatus(("yes".equals(workInvoiceDetail.getAct().getFlag()) ? "2" : "4"));
			String buffer = UserUtils.getRoleActivityEnname(UserUtils.getSelectCompany().getId(),workInvoiceDetail.getCreateBy());
			Map<String, Object> vars = Maps.newHashMap();
			//业务逻辑对应的条件表达式
			String exp = "";
			String taskCount = "";
			String notifyRole = "";
			int key = 0;
			String enname = "";
			List<Activity> activitieList = activityService.getByProcessInstanceId(workInvoiceDetail.getProcessInstanceId());
			WorkActivityMenu workActivityMenu = new WorkActivityMenu();
			if (activitieList != null && activitieList.size() != 0) {
				workActivityMenu.setProcessType(activitieList.get(0).getProcessKey());
				workActivityMenu.setActivities(activitieList);
			}

			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			WorkActivityProcess selectProcess = new WorkActivityProcess();
			selectProcess.setProcessInstanceId(workInvoiceDetail.getProcessInstanceId());
			List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
			List<Activity> activities = workActivityMenu.getActivities();
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workinvoicereturn")) {
				key = 1;
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					if (taskDefKey.equals(activityProcess.getActivityTask()) && !taskDefKey.equals("modifyApply")) {
						taskCount = activityProcess.getCount()+"";
						workActivityProcess = activityProcess;
						if (!workActivityProcess.getIsApproval().equals("0")) {
							workActivityProcess.setId("");
						}
						exp = "pass";
						if (!"yes".equals(workInvoiceDetail.getAct().getFlag())) {
							workInvoiceDetail.setStatus("4");
							str += " 被驳回!";
							workActivityProcess.setIsApproval("2");
							String returnBack = "-1";
							for (Activity activity : activities) {
								if (activity.getCount() == activityProcess.getCount()) {
									notifyRole = activity.getName();
									returnBack = activity.getReturnBack();
									break;
								}
							}
							if (returnBack.equals("0")) {
								workActivityProcess.setId("");
							}

						} else {
							str += " 待审批!";
							workActivityProcess.setIsApproval("1");
						}
					}else if(taskDefKey.equals("modifyApply")){
						notifyRole = "调整申请";
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setId("");
						workActivityProcess.setCount(0);
						if (!"yes".equals(workInvoiceDetail.getAct().getFlag())) {
							workInvoiceDetail.setStatus("3");
							str += " 已撤销!";
							workActivityProcess.setIsApproval("2");
						} else {
							str += " 重新申请!";
							workActivityProcess.setIsApproval("1");
						}
						break;
					}
				}
			} else {
				workActivityMenu.setProcessType("workinvoicereturn");
				for (int i = 0; i < workActivityProcesses.size(); i++) {
					WorkActivityProcess activityProcess = workActivityProcesses.get(i);
					String count = activityProcess.getCount() + "";
					workActivityProcess = activityProcess;
					if (!workActivityProcess.getIsApproval().equals("0")) {
						workActivityProcess.setId("");
					}
					// 审核环节
					if ("bmzr".equals(taskDefKey) && count.contains("1")) {
						taskCount = "1";
						exp = "pass";
						if ("yes".equals(workInvoiceDetail.getAct().getFlag())) {
							notifyRole = "分管领导审核";
							workActivityProcess.setIsApproval("1");
							str += " 待审批!";
							enname = buffer + "fgld";
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
							str += " 被驳回!";
						}
						break;
					} else if ("fgld".equals(taskDefKey) && count.contains("2")) {
						taskCount = "2";
						exp = "pass";
						if ("yes".equals(workInvoiceDetail.getAct().getFlag())) {
							workActivityProcess.setIsApproval("1");
							notifyRole = "发票管理员审核";
							str += " 待审批!";
							enname = buffer + "fpgly";
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
							str += " 被驳回!";
						}
						break;
					} else if ("fpgly".equals(taskDefKey) && count.contains("3")) {
						taskCount = "3";
						exp = "pass";
						if ("yes".equals(workInvoiceDetail.getAct().getFlag())) {
							workActivityProcess.setIsApproval("1");
							notifyRole = "主管会计审核";
							str += " 待审批!";
							enname = buffer + "zghj";
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
							str += " 被驳回!";
						}
						break;
					} else if ("zgkj".equals(taskDefKey) && count.contains("4")) {
						taskCount = "4";
						exp = "pass";
						if ("yes".equals(workInvoiceDetail.getAct().getFlag())) {
							workActivityProcess.setIsApproval("1");
							notifyRole = "审核通过";
							str += " 待审批!";
						} else {
							notifyRole = "调整申请";
							workActivityProcess.setIsApproval("2");
							str += " 被驳回!";
						}
						break;
					}  else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
						taskCount = "0";
						exp = "pass";
						workActivityProcess.setCount(0);
						enname = buffer + "bmzr";
						if (!"yes".equals(workInvoiceDetail.getAct().getFlag())) {
							workInvoiceDetail.setStatus("3");
						}
						str += " 待审批!";
						break;
					} else if ("apply_end".equals(taskDefKey)) {
					}

				}
			}
			// 设置意见
			workInvoiceDetail.getAct().setComment(("yes".equals(workInvoiceDetail.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workInvoiceDetail.getAct().getComment());
			workInvoiceDetail.preUpdate();
			// 提交流程任务
			vars.put(exp, "yes".equals(workInvoiceDetail.getAct().getFlag()) ? true : false);
			vars.put("passs", true);
			workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workInvoiceDetail.getProcessInstanceId(),taskDefKey,"modifyApply",workInvoiceDetail.getAct().getFlag(),comment, activities);
			// 提交流程任务
			actTaskService.complete(workInvoiceDetail.getAct().getTaskId(), workInvoiceDetail.getAct().getProcInsId(), workInvoiceDetail.getAct().getComment(), vars);
			boolean state = actTaskService.isProcessEnd(workInvoiceDetail.getAct().getProcInsId());
			List<User> users = new ArrayList<>();
			String title = "";
			if (!state) {
				users.add(workInvoiceDetail.getCreateBy());
				if ("yes".equals(workInvoiceDetail.getAct().getFlag())) {
					title = "您的退票申请:"+workInvoiceDetail.getNumber()+"审核：已通过!";
					workInvoiceDetail.setStatus("5");
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workInvoiceDetail.getId());
					List<User> userList = workProjectNotifyService.readByNotifyId(notify);
					users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workInvoiceDetail.getId(),
											workInvoiceDetail.getCreateBy(),
											workInvoiceDetail.getComId(),
											title,
											str,
											"40",
											"0",
											"待通知",
											""));

				} else {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workInvoiceDetail.getId());
					List<User> userList = workProjectNotifyService.readByNotifyId(notify);
					users.addAll(userList);
					if (StringUtils.isNotBlank(workInvoiceDetail.getStatus()) && !workInvoiceDetail.getStatus().equals("3")){
						title = "您的退票申请:"+workInvoiceDetail.getNumber()+"审核：被驳回!";
						workInvoiceDetail.setStatus("4");
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workInvoiceDetail.getId(),
												workInvoiceDetail.getCreateBy(),
												workInvoiceDetail.getComId(),
												title,
												str,
												"40",
												"0",
												"待通知",
												""));
					}
				}
			} else {
				if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workinvoicereturn")) {
					title = "退票申请人："+UserUtils.get(workInvoiceDetail.getCreateBy().getId()).getName()+",退票发票号："+workInvoiceDetail.getNumber()+" 待审批!";
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workInvoiceDetail.getId());
					List<User> userList = workProjectNotifyService.readByNotifyId(notify);
					users.addAll(userList);
					WorkProjectNotify workProjectNotify = UtilNotify
							.saveNotify(workInvoiceDetail.getId(),
									new User(),
									workInvoiceDetail.getComId(),
									title,
									str,
									"40",
									"0",
									"待审批",
									"");
					List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
							activities,
							workProjectNotify,
							taskDefKey,
							workInvoiceDetail.getAct().getFlag(),
							taskCount,
							workInvoiceDetail.getCreateBy(),
							workInvoiceDetail.getOfficeId(),
							"6");
					for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
						users.add(workProjectNotify1.getUser());
						workProjectNotify1.setId("");
						workProjectNotify1.setIsNewRecord(false);
						workProjectNotifyService
								.save(workProjectNotify1);
					}

				} else {
					if (!"yes".equals(workInvoiceDetail.getAct().getFlag())) {
						title = "您的退票申请单:"+workInvoiceDetail.getNumber()+"被驳回,请重新申请!";
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workInvoiceDetail.getId());
						List<User> userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workInvoiceDetail.getId(),
												workInvoiceDetail.getCreateBy(),
												workInvoiceDetail.getComId(),
												title,
												str,
												"40",
												"0",
												"重新申请",
												""));
						users.add( workInvoiceDetail.getCreateBy());
					} else {
						if (StringUtils.isNotBlank(enname)) {
							title = "退票申请人："+UserUtils.get(workInvoiceDetail.getCreateBy().getId()).getName()+",退票发票号："+workInvoiceDetail.getNumber()+" 待审批!";
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workInvoiceDetail.getId());
							List<User> userList1 = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList1);
							WorkProjectNotify workProjectNotify = UtilNotify
									.saveNotify(workInvoiceDetail.getId(),
											new User(),
											workInvoiceDetail.getComId(),
											title,
											str,
											"40",
											"0",
											"待审批",
											"");
							List<User> userList = UserUtils.getByRoleActivityEnnames(enname,workInvoiceDetail.getOfficeId(),"6",workInvoiceDetail.getCreateBy());
							for (User user1:userList){
								users.add(user1);
								workProjectNotify.setUser(user1);
								workProjectNotify.setId("");
								workProjectNotify.setIsNewRecord(false);
								workProjectNotifyService
										.save(workProjectNotify);
							}
						}else {
							title = "您的退票申请单:"+workInvoiceDetail.getNumber()+"被驳回,请重新申请!";
							WorkProjectNotify notify = new WorkProjectNotify();
							notify.setNotifyId(workInvoiceDetail.getId());
							List<User> userList = workProjectNotifyService.readByNotifyId(notify);
							users.addAll(userList);
							users.add(workInvoiceDetail.getCreateBy());
							workProjectNotifyService
									.save(UtilNotify
											.saveNotify(workInvoiceDetail.getId(),
													workInvoiceDetail.getCreateBy(),
													workInvoiceDetail.getComId(),
													title,
													str,
													"40",
													"0",
													"重新申请",
													""));
						}
					}
				}
			}
			if (StringUtils.isNotBlank(title) && users!=null && users.size()!=0) {
				for (User u : users) {
					/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
					for (WebSocket toUserConn : toUserConns) {
						String message = "{\"to\":\""+u.getId()+"\"," +
								"\"msg\":\"审批信息 "+title+"\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),title);

				}
			}
			workInvoiceDetailDao.update(workInvoiceDetail);
			return "保存审核意见成功！";
		}catch (ActivitiObjectNotFoundException e){
			logger.error("ActivitiObjectNotFoundException e:"+e);
			return "流程已审批，不能重新审批！";
		}catch (Exception e){
			logger.error("Exception e:"+e);
			return "保存审核意见失败！！";
		}
	}


	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkInvoiceDetail getByProcessInstanceId(String processInstanceId) {
		WorkInvoiceDetail workInvoiceDetail = workInvoiceDetailDao.getByProcessInstanceId(processInstanceId);
		return workInvoiceDetail;
	}

	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkInvoiceDetail workInvoiceDetail) {
		String invalidateProcessInstanceId = workInvoiceDetail.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workInvoiceDetail.getProcessInstanceId());
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workInvoiceDetail.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workInvoiceDetail.getId());
			List<User> userList = workProjectNotifyService.readByNotifyId(notify);
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					User user = UserUtils.get(u.getId());
					/*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
					for (WebSocket toUserConn : toUserConns) {
						String message = "{\"to\":\""+u.getId()+"\"," +
								"\"msg\":\"审批信息 退票申请人:"+ user.getName()+",退票发票单号:"+workInvoiceDetail.getNumber() +" 强制撤销!\"," +
								"\"useType\":\"sys\"}";
						ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
					}*/
					UserUtils.pushIm(u.getId(),"退票申请人:"+ user.getName()+",退票发票单号:"+workInvoiceDetail.getNumber() +" 强制撤销!");

				}
			}
			if(processList!=null && processList.size()>0){
				for (int i =0;i<processList.size();i++) {
					WorkActivityProcess p = processList.get(i);
					if(StringUtils.isNotBlank(p.getIsApproval()) && "0".equals(p.getIsApproval())){
						p.setDelFlag("1");
						p.setIsApproval("-1");
						workActivityProcessDao.updateDelFlagAndIsApproval(p);
					}
				}
				WorkActivityProcess pro = new WorkActivityProcess();
				pro.setId("");
				pro.preInsert();
				pro.setDelFlag("0");
				pro.setRemarks("[强制撤销]");
				pro.setProcessKey(processList.get(0).getProcessKey());
				pro.setIsApproval("1");
				pro.setProcessInstanceId(processList.get(0).getProcessInstanceId());
				pro.setCount(0);
				workActivityProcessDao.insert(pro);
			}

			//结束该流程,设为"撤销"状态
			actTaskService.endProcessInstance(invalidateProcessInstanceId,"报销-强制撤销");
			workInvoiceDetail.setStatus("3");
			workInvoiceDetail.preUpdate();
			workInvoiceDetailDao.update(workInvoiceDetail);

		}catch (ActivitiObjectNotFoundException e){
			System.err.println("撤销异常，因为这个流程已不存在!");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}

    public Page<WorkInvoiceDetail> findPageByCompany(Page<WorkInvoiceDetail> workInvoiceDetailPage, WorkInvoiceDetail invoice) {
        invoice.setPage(workInvoiceDetailPage);
        List<WorkInvoiceDetail> invoiceDetails = dao.findPageByCompany(invoice);
        workInvoiceDetailPage.setList(invoiceDetails);
        return workInvoiceDetailPage;
    }

    public void updateSettleFlag(WorkInvoiceDetail invoice) {
        dao.updateSettleFlag(invoice);
    }

	public int countByNumber(String number) {
		return dao.countByNumber(number);
	}

    public int countByNumAndComp(String invoiceNum, String comId) {
        return dao.countByNumAndComp(invoiceNum,comId);
    }
}