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

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

import com.google.common.collect.Maps;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.act.utils.ActUtils;
import com.jeeplus.modules.projectrecord.dao.WorkProjectUserDao;
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.service.OfficeService;
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.workclientinfo.dao.WorkClientAttachmentDao;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workprojectnotify.util.UtilNotify;
import com.jeeplus.modules.workrepay.dao.WorkRepayDao;
import com.jeeplus.modules.workrepay.entity.WorkRepay;
import com.jeeplus.modules.workrepay.service.WorkRepayService;
import com.jeeplus.modules.workstaff.entity.WorkStaffBasicInfo;
import com.jeeplus.modules.workstaff.service.WorkStaffBasicInfoService;
import org.activiti.engine.*;
import org.activiti.engine.runtime.ProcessInstance;
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.workloan.entity.WorkLoan;
import com.jeeplus.modules.workloan.dao.WorkLoanDao;

/**
 * 借款Service
 * @author ssrh
 * @version 2018-10-16
 */
@Service
@Transactional(readOnly = true)
public class WorkLoanService extends CrudService<WorkLoanDao, WorkLoan> {

	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	protected TaskService taskService;
	@Autowired
	protected HistoryService historyService;
	@Autowired
	protected RepositoryService repositoryService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private WorkActivityProcessDao workActivityProcessDao;
	@Autowired
	private SerialNumTplService serialNumTplService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private WorkLoanDao workLoanDao;
	@Autowired
	@Lazy
	private WorkRepayService workRepayService;
	@Autowired
	private WorkStaffBasicInfoService workStaffBasicInfoService;
	@Autowired
	private WorkRepayDao workRepayDao;

	@SuppressWarnings("unchecked")
	public WorkLoan get(String id) {
		WorkLoan workLoan = super.get(id);
		if(workLoan!=null){
			WorkRepay workRepay = new WorkRepay();
			workRepay.setStatus("5");
			workRepay.setWorkLoan(workLoan);
			List<WorkRepay> list = workRepayService.findList(workRepay);
			workLoan.setWorkRepays(list);
			//合同未还款累计
			if(workLoan.getProjectRecords()!=null && workLoan.getProjectRecords().getWorkContractInfo()!=null && StringUtils.isNotBlank(workLoan.getProjectRecords().getWorkContractInfo().getId())){
				Double contractNotRepay = this.getContractRepay(workLoan.getProjectRecords().getWorkContractInfo());
				workLoan.setContractNotRepay(contractNotRepay+"");
			}
			//未还借款累计
			if(workLoan.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workLoan.getWorkStaffBasicInfo().getUserId())){
				Double notRepay = this.getnotRepay(workLoan.getWorkStaffBasicInfo());
				workLoan.setNotRepay(notRepay+"");
			}
			//还款金额
			if(StringUtils.isNotBlank(workLoan.getId())){
				Double repay = this.getRepay(workLoan);
				workLoan.setRepay(repay+"");
			}

		}
		return workLoan;
	}
	public WorkLoan getLon(String id) {
		WorkLoan workLoan = super.get(id);
		if(workLoan!=null){
			WorkRepay workRepay = new WorkRepay();
			workRepay.setStatus("5");
			workRepay.setWorkLoan(workLoan);
			List<WorkRepay> list = workRepayService.findList(workRepay);
			workLoan.setWorkRepays(list);
			//合同未还款累计
			if(workLoan.getProjectRecords()!=null && workLoan.getProjectRecords().getWorkContractInfo()!=null && StringUtils.isNotBlank(workLoan.getProjectRecords().getWorkContractInfo().getId())){
				Double contractNotRepay = this.getContractRepay(workLoan.getProjectRecords().getWorkContractInfo());
				workLoan.setContractNotRepay(contractNotRepay+"");
			}
			//未还借款累计
			String notRepay=workRepayDao.findSumRepayList(workLoan.getId());
			workLoan.setNotRepay(String.valueOf(Double.parseDouble(workLoan.getMoney()) - Double.parseDouble(notRepay)));
		}
		return workLoan;
	}
	public Double getnotRepay(WorkStaffBasicInfo workStaffBasicInfo){
		//未还借款累计
		List<WorkLoan> list1 = this.findListByUser(workStaffBasicInfo.getUserId(),"3");
		double moneyCount= 0.00;//借款
		for(int i=0;i<list1.size();i++){
			WorkLoan workLoan = list1.get(i);
			if(StringUtils.isNotBlank(workLoan.getMoney())){
				moneyCount = moneyCount + Double.parseDouble(workLoan.getMoney());
			}
		}
		//部分还款
		List<WorkLoan> list2 = this.findListByUser(workStaffBasicInfo.getUserId(),"2");
		for(int i=0;i<list2.size();i++){
			WorkLoan workLoan = list2.get(i);
			Double repay = this.getRepay(workLoan);
			if(StringUtils.isNotBlank(workLoan.getMoney()) && repay!=null){
				moneyCount = moneyCount + (Double.parseDouble(workLoan.getMoney()) - repay);
			}
		}
		return moneyCount;
	}

	public Double getContractRepay(WorkContractInfo workContractInfo){
		//合同未还累计
		//未还款
		List<WorkLoan> list1 = this.findListByContract(workContractInfo.getId(),"3");
		double moneyCount= 0.00;//借款
		for(int i=0;i<list1.size();i++){
			WorkLoan workLoan = list1.get(i);
			if(StringUtils.isNotBlank(workLoan.getMoney())){
				moneyCount = moneyCount + Double.parseDouble(workLoan.getMoney());
			}
		}
		//部分还款
		List<WorkLoan> list2 = this.findListByContract(workContractInfo.getId(),"2");
		for(int i=0;i<list2.size();i++){
			WorkLoan workLoan = list2.get(i);
			if(StringUtils.isNotBlank(workLoan.getMoney()) && StringUtils.isNotBlank(workLoan.getRepay())){
				moneyCount = moneyCount + (Double.parseDouble(workLoan.getMoney()) - Double.parseDouble(workLoan.getRepay()));
			}
		}
		return moneyCount;
	}
	public Double getRepay(WorkLoan workLoan){
		//借款-还款累计
		double moneyCount= 0.00;
		WorkRepay workRepay = new WorkRepay();
		workRepay.setStatus("5");
		workRepay.setWorkLoan(workLoan);
		List<WorkRepay> list = workRepayService.findList(workRepay);
		for(int i=0;i<list.size();i++){
			WorkRepay w = list.get(i);
			if(StringUtils.isNotBlank(w.getMoney())){
				moneyCount = moneyCount+(Double.parseDouble(w.getMoney()));
			}
		}
		return moneyCount;
	}
	public List<WorkLoan> findList(WorkLoan workLoan) {
		return super.findList(workLoan);
	}
	
	public Page<WorkLoan> findPage(Page<WorkLoan> page, WorkLoan workLoan) {
		workLoan.getSqlMap().put("dsf", dataScopeFilter(workLoan.getCurrentUser(), "o", "u","s", MenuStatusEnum.WORK_REIMBURSEMENT.getValue()));
		workLoan.setPage(page);
		page.setList(findList(workLoan));
		return page;
	}

	/**
	 * 暂存
	 * @param
	 */
	@Transactional(readOnly = false)
	public  void save(WorkLoan workLoan){
		if (StringUtils.isBlank(workLoan.getNum())) {
			User user = UserUtils.getUser();
			workLoan.setNum(serialNumTplService.genSerialNum(user.getCompany(), workLoan.SERIAL_BIZCODE));
		}
		super.save(workLoan);
	}

	@Transactional(readOnly = false)
	public String save(WorkLoan workLoan, Map<String, Object> variables, String processInstanceId) {
		User user = UserUtils.getUser();
		if (StringUtils.isBlank(workLoan.getNum())) {
			workLoan.setNum(serialNumTplService.genSerialNum(user.getCompany(), workLoan.SERIAL_BIZCODE));
		}
		super.save(workLoan);
		Office office = null;
		if(workLoan!=null && workLoan.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workLoan.getWorkStaffBasicInfo().getId())){
			WorkStaffBasicInfo workStaffBasicInfo=workStaffBasicInfoService.getAchives(workLoan.getWorkStaffBasicInfo().getId());
			if(workStaffBasicInfo!=null){
				office = workStaffBasicInfo.getOffice();
			}
		}
		if(office == null || StringUtils.isBlank(office.getId())){
			return "借款人档案信息有误，请确认!";
		}
		String str = "借款申请编号:"+workLoan.getNum()+",借款人:"+workLoan.getWorkStaffBasicInfo().getName()+",所属部门:"+office.getName();
		String title = "借款人:"+workLoan.getWorkStaffBasicInfo().getName();
		// 用来设置启动流程的人员ID，引擎会自动把用户ID保存到activiti:initiator中
		identityService.setAuthenticatedUserId(user.getId());
		// 启动流程
		String businessKey = workLoan.getId().toString();
		WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("ggh3125f1f194c82bdea93555c75edfv", office);
		// 启动流程
		String processType = workActivityMenu.getProcessType();
		StringBuffer buffer = new StringBuffer();
		Activity activity = new Activity();
		WorkProjectNotify workProjectNotify = UtilNotify
				.saveNotify(workLoan.getId(),
						null,
						workLoan.getCompanyId(),
						title,
						str,
						"87",
						"0",
						"待审批",
						""
				);
		List<User> users = new ArrayList<>();
		List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"29",workLoan.getCreateBy());
		List<User> fglds = UserUtils.getByRoleActivityEnname("fgld",2,office.getId(),"29",workLoan.getCreateBy());
		List<User> cws = UserUtils.getByRoleActivityEnname("cwzg",3,office.getId(),"29",workLoan.getCreateBy());
		List<User> zjls = UserUtils.getByRoleActivityEnname("zjl",3,office.getId(),"29",workLoan.getCreateBy());
		List<User> cwzjs = UserUtils.getByRoleActivityEnname("cwfgld",3,office.getId(),"29",workLoan.getCreateBy());
		List<User> cns = UserUtils.getByRoleActivityEnname("cn",3,office.getId(),"29",workLoan.getCreateBy());
		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(),"29",workLoan.getCreateBy());
					if (enusers.size()==0){
						workLoan.setStatus("1");
						super.save(workLoan);
						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(),"29",workLoan.getCreateBy());
				}
				//人员审批
				if (StringUtils.isNotBlank(activity.getUser().getId())) {
					users.add(activity.getUser());
				}
			}
			workProjectNotify.setId("");
		} else {
			variables.put("bmzrList", bmzrs);
            /*variables.put("fgldList", fglds);
            variables.put("cwList", cws);
            variables.put("zjlList", zjls);
            variables.put("cwzjList", cwzjs);
            variables.put("cnList", cns);*/
			//|| fglds.size()==0 || cws.size()==0 || zjls.size()==0 || cwzjs.size()==0 || cns.size()==0
			if (bmzrs.size()==0 ){
				workLoan.setStatus("1");
				super.save(workLoan);
			}
			if (bmzrs.size()==0){
				return "流程审批人不能为空,角色部门负责人下无用户,请联系管理员！";
			}
           /* if (fglds.size()==0){
                return "流程审批人不能为空,角色分管领导下无用户,请联系管理员！";
            }
            if (cws.size()==0){
                return "流程审批人不能为空,角色财务主管下无用户,请联系管理员！";
            }
            if (zjls.size()==0){
                return "流程审批人不能为空,角色总经理下无用户,请联系管理员！";
            }
            if (cwzjs.size()==0){
                return "流程审批人不能为空,角色财务分管领导下无用户,请联系管理员！";
            }
            if (cns.size()==0){
                return "流程审批人不能为空,角色出纳下无用户,请联系管理员！";
            }*/
			variables.put("bmzrcount",bmzrs.size());
            /*variables.put("fgldcount",fglds.size());
            variables.put("cwcount",cws.size());
            variables.put("zjlcount",zjls.size());
            variables.put("cwzjcount",cwzjs.size());
            variables.put("cncount",cns.size());*/
			processType = "workloan";
			users.addAll(bmzrs);
		}
		for (User u : users){
			workProjectNotify.setUser(u);
			workProjectNotify.setId("");
			workProjectNotify.setNotifyRole("部门负责人审批");
			workProjectNotifyService
					.save(workProjectNotify);
               /* List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
                for (WebSocket toUserConn:toUserConns) {
                   String message = "{\"to\":\""+u.getId()+"\"," +
                            "\"msg\":\"审批信息 报销人:" + user.getName() + ",报销编号:"+ workReimbursement.getNumber() + " 待审批!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                }*/
			Map<String,Object> extras = new HashMap<>();
			extras.put("type","7002");
			extras.put("id",workProjectNotify.getId());
			extras.put("procDefKey","13");
			UserUtils.pushInfoToApp(title,str,extras,u.getId());
			UserUtils.pushIm(u.getId(),str);
		}
		variables.put("type", processType);
		variables.put("busId", businessKey);
		variables.put("title", "审批单：" + workLoan.getNum());//设置标题；

		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
		workLoan.setProcessInstance(processInstance);
		if (StringUtils.isNotBlank(processInstanceId)) {
			workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
			workActivityProcessService.deleteProcessInstanceId(processInstanceId);
			workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
		}
		// 更新流程实例ID
		workLoan.setProcessInstanceId(processInstance.getId());
		workLoanDao.updateProcessInstanceId(workLoan);
		List<Activity> list = workActivityMenu.getActivities();
		if (list != null && list.size() != 0) {
			workActivityProcessService.saveList(list, processInstance.getId());
		} else {
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessKey("workloan");
			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);
			workActivityProcess.setCount(5);
			workActivityProcess.setId("");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcess.setCount(6);
			workActivityProcess.setId("");
			workActivityProcessService.save(workActivityProcess);
			workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);
			workActivityProcessService.insertAuditsByType(fglds,processInstance.getId(),2,0);
			workActivityProcessService.insertAuditsByType(cws,processInstance.getId(),3,0);
			workActivityProcessService.insertAuditsByType(zjls,processInstance.getId(),4,0);
			workActivityProcessService.insertAuditsByType(cwzjs,processInstance.getId(),5,0);
			workActivityProcessService.insertAuditsByType(cns,processInstance.getId(),6,0);
		}
		logger.debug("start process of {key={}, bkey={}, pid={}, variables={}}", new Object[]{
				ActUtils.PD_REIMBURSEMENT[0], businessKey, processInstance.getId(), variables});
		return "";
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkLoan workLoan) {
		super.delete(workLoan);
		WorkProjectNotify notify = new WorkProjectNotify();
		notify.setNotifyId(workLoan.getId());
		List<User> users = workProjectNotifyService.readByNotifyId(notify);
		if (users!=null && users.size()!=0){
			for (User user:users){
				UserUtils.pushMeIm(user.getId());
			}
		}
	}

	/**
	 * 审核流程
	 * @param
	 */
	@Transactional(readOnly = false)
	public String auditSave(WorkLoan workLoan,List<User> auditUsers) {
		Office office = null;
		if(workLoan!=null && workLoan.getWorkStaffBasicInfo()!=null && StringUtils.isNotBlank(workLoan.getWorkStaffBasicInfo().getId())){
			WorkStaffBasicInfo workStaffBasicInfo=workStaffBasicInfoService.getAchives(workLoan.getWorkStaffBasicInfo().getId());
			if(workStaffBasicInfo!=null){
				office = workStaffBasicInfo.getOffice();
			}
		}
		if(office == null || StringUtils.isBlank(office.getId())){
			return "借款人档案信息有误，请确认!";
		}
		String str = "借款申请编号:"+workLoan.getNum()+",借款人:"+workLoan.getWorkStaffBasicInfo().getName()+",所属部门:"+office.getName();
		String title = "借款人:"+workLoan.getWorkStaffBasicInfo().getName();

		// 对不同环节的业务逻辑进行操作
		String taskDefKey = workLoan.getAct().getTaskDefKey();
		if (!"modifyApply".equals(taskDefKey)) {
			actTaskService.claim(workLoan.getAct().getTaskId(), UserUtils.getUser().getId());
		}else{
			workLoan.getAct().setFlag("yes");
		}
		String comment = "";
		if (workLoan.getStatus().equals("4")){
			comment = ("yes".equals(workLoan.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
		}else {
			comment = ("yes".equals(workLoan.getAct().getFlag())?"[同意] ":"[驳回] ")+workLoan.getAct().getComment();
		}
		//yes 的时候状态为审核通过 否则为未通过
		//1 审核中 2 未通过
		workLoan.setStatus(("yes".equals(workLoan.getAct().getFlag()) ? "2" : "4"));
		Map<String, Object> vars = Maps.newHashMap();
		//业务逻辑对应的条件表达式
		String exp = "";
		String taskCount = "";
		String notifyRole = "";
		int key = 0;
		String enname = "";
		List<Activity> activitieList = activityService.getByProcessInstanceId(workLoan.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(workLoan.getProcessInstanceId());
		List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
		List<Activity> activities = workActivityMenu.getActivities();
		if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workloan")) {
			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(workLoan.getAct().getFlag())) {
						workLoan.setStatus("4");
						workActivityProcess.setIsApproval("2");
						String returnBack = "-1";
						for (Activity activity : activities) {
							if (activity.getCount() == activityProcess.getCount()) {
								returnBack = activity.getReturnBack();
								notifyRole = activity.getName();
								break;
							}
						}
						if (returnBack.equals("0")) {
							workActivityProcess.setId("");
						}

					} else {
						workActivityProcess.setIsApproval("1");
					}
				}else if(taskDefKey.equals("modifyApply")){
					notifyRole = "调整申请";
					taskCount = "0";
					exp = "pass";
					workActivityProcess.setId("");
					workActivityProcess.setCount(0);
					if (!"yes".equals(workLoan.getAct().getFlag())) {
						workLoan.setStatus("3");
						workActivityProcess.setIsApproval("2");
					} else {
						workActivityProcess.setIsApproval("1");
					}
					break;
				}
			}
		} else {
			workActivityMenu.setProcessType("workloan");
			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(workLoan.getAct().getFlag())) {
						vars.put("fgldList", auditUsers);
						vars.put("fgldcount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workLoan.getProcessInstanceId(),2,1);
						workActivityProcess.setIsApproval("1");
						notifyRole = "分管领导审核";
						enname = "fgld";
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("fgld".equals(taskDefKey) && count.contains("2")) {
					taskCount = "2";
					exp = "pass";
					if ("yes".equals(workLoan.getAct().getFlag())) {
						vars.put("cwList", auditUsers);
						vars.put("cwcount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workLoan.getProcessInstanceId(),3,1);
						notifyRole = "财务审核";
						workActivityProcess.setIsApproval("1");
						enname = "cwzg";
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("cw".equals(taskDefKey) && count.contains("3")) {
					taskCount = "3";
					exp = "pass";
					if ("yes".equals(workLoan.getAct().getFlag())) {
						vars.put("zjlList", auditUsers);
						vars.put("zjlcount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workLoan.getProcessInstanceId(),4,1);
						notifyRole = "总经理审核";
						workActivityProcess.setIsApproval("1");
						enname = "zjl";
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("zjl".equals(taskDefKey) && count.contains("4")) {
					taskCount = "4";
					exp = "pass";
					if ("yes".equals(workLoan.getAct().getFlag())) {
						vars.put("cwzjList", auditUsers);
						vars.put("cwzjcount",auditUsers.size());
						notifyRole = "财务分管领导审核";
						workActivityProcessService.insertAuditsByType(auditUsers,workLoan.getProcessInstanceId(),5,1);

						workActivityProcess.setIsApproval("1");
						enname = "cwfgld";
					} else {
						workActivityProcess.setIsApproval("2");
						notifyRole = "调整申请";
					}
					break;
				} else if ("cwzj".equals(taskDefKey) && count.contains("5")) {
					taskCount = "5";
					exp = "pass";
					if ("yes".equals(workLoan.getAct().getFlag())) {
						vars.put("cnList", auditUsers);
						vars.put("cncount",auditUsers.size());
						workActivityProcessService.insertAuditsByType(auditUsers,workLoan.getProcessInstanceId(),6,1);
						notifyRole = "报销付款";
						workActivityProcess.setIsApproval("1");
						enname = "cn";
					} else {
						workActivityProcess.setIsApproval("2");
						notifyRole = "调整申请";
					}
					break;
				} else if ("cn".equals(taskDefKey) && count.contains("6")) {
					taskCount = "6";
					exp = "pass";
					if ("yes".equals(workLoan.getAct().getFlag())) {
						notifyRole = "审批通过";
						workActivityProcess.setIsApproval("1");
					} else {
						notifyRole = "调整申请";
						workActivityProcess.setIsApproval("2");
					}
					break;
				} else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
					taskCount = "0";
					notifyRole = "部门负责人审批";
					exp = "pass";
					workActivityProcess.setCount(0);
					enname = "bmzr";
					if (!"yes".equals(workLoan.getAct().getFlag())) {
						workLoan.setStatus("3");
					}
					break;
				} else if ("apply_end".equals(taskDefKey)) {
				}

			}
		}
		// 设置意见
		workLoan.getAct().setComment(("yes".equals(workLoan.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workLoan.getAct().getComment());
		workLoan.preUpdate();
		// 提交流程任务
		vars.put(exp, "yes".equals(workLoan.getAct().getFlag()) ? true : false);
		vars.put("passs", true);
		workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount,workLoan.getProcessInstanceId(),taskDefKey,"modifyApply",workLoan.getAct().getFlag(),comment, activities);
		// 提交流程任务
		actTaskService.complete(workLoan.getAct().getTaskId(), workLoan.getAct().getProcInsId(), workLoan.getAct().getComment(), vars);
		boolean state = actTaskService.isProcessEnd(workLoan.getAct().getProcInsId());
		List<User> users = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		if (!state) {
			users.add(workLoan.getCreateBy());
			if ("yes".equals(workLoan.getAct().getFlag())) {
				workLoan.setStatus("5");
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workLoan.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				workProjectNotifyService
						.save(UtilNotify
								.saveNotify(workLoan.getId(),
										workLoan.getCreateBy(),
										workLoan.getCompanyId(),
										title,
										str,
										"87",
										"0",
										"待通知",
										notifyRole));
			} else {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workLoan.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				if (StringUtils.isNotBlank(workLoan.getStatus()) && !workLoan.getStatus().equals("3")){
					workLoan.setStatus("4");
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workLoan.getId(),
											workLoan.getCreateBy(),
											workLoan.getCompanyId(),
											title,
											str,
											"87",
											"0",
											"待通知",
											notifyRole));
				}
			}
			workActivityProcessService.deleteProcessIdAuditUsers(workLoan.getProcessInstanceId());
		} else {
			if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("workloan")) {
				WorkProjectNotify notify = new WorkProjectNotify();
				notify.setNotifyId(workLoan.getId());
				userList = workProjectNotifyService.readByNotifyId(notify);
				//users.addAll(userList);
				WorkProjectNotify workProjectNotify = UtilNotify
						.saveNotify(workLoan.getId(),
								new User(),
								workLoan.getCompanyId(),
								title,
								str,
								"87",
								"0",
								"待审批",
								notifyRole);
				List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
						activities,
						workProjectNotify,
						taskDefKey,
						workLoan.getAct().getFlag(),
						taskCount,
						workLoan.getCreateBy(),
						workLoan.getOfficeId(),
						"29");
				for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
					users.add(workProjectNotify1.getUser());
					workProjectNotify1.setId("");
					workProjectNotify1.setIsNewRecord(false);
					workProjectNotifyService
							.save(workProjectNotify1);
					if (!"modifyApply".equals(taskDefKey)){
						Map<String,Object> extras = new HashMap<>();
						if ( "cn".equals(taskDefKey) ){
							extras.put("type","7001");
						}else {
							extras.put("type","7002");
						}
						extras.put("id",workProjectNotify.getId());
						extras.put("procDefKey","87");
						UserUtils.pushInfoToApp(title,str,extras,workProjectNotify1.getUser().getId());

					}
				}

			} else {
				if (!"yes".equals(workLoan.getAct().getFlag())) {
					WorkProjectNotify notify = new WorkProjectNotify();
					notify.setNotifyId(workLoan.getId());
					userList = workProjectNotifyService.readByNotifyId(notify);
					//users.addAll(userList);
					workProjectNotifyService
							.save(UtilNotify
									.saveNotify(workLoan.getId(),
											workLoan.getCreateBy(),
											workLoan.getCompanyId(),
											title,
											str,
											"87",
											"0",
											"重新申请",
											notifyRole));
					users.add( workLoan.getCreateBy());
				} else {
					if (StringUtils.isNotBlank(enname)) {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workLoan.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						//users.addAll(userList1);
						WorkProjectNotify workProjectNotify = UtilNotify
								.saveNotify(workLoan.getId(),
										new User(),
										workLoan.getCompanyId(),
										title,
										str,
										"87",
										"0",
										"待审批",
										notifyRole);
						users.addAll(auditUsers);
						for (User user1:auditUsers){
							workProjectNotify.setId("");
							workProjectNotify.setUser(user1);
							workProjectNotify.setIsNewRecord(false);
							workProjectNotifyService
									.save(workProjectNotify);
							if (!"modifyApply".equals(taskDefKey)){
								Map<String,Object> extras = new HashMap<>();
								if ("cn".equals(taskDefKey) ){
									extras.put("type","7001");
								}else {
									extras.put("type","7002");
								}
								extras.put("id",workProjectNotify.getId());
								extras.put("procDefKey","87");
								UserUtils.pushInfoToApp(title,str,extras,user1.getId());

							}
						}
					}else {
						WorkProjectNotify notify = new WorkProjectNotify();
						notify.setNotifyId(workLoan.getId());
						userList = workProjectNotifyService.readByNotifyId(notify);
						users.addAll(userList);
						users.add(workLoan.getCreateBy());
						workProjectNotifyService
								.save(UtilNotify
										.saveNotify(workLoan.getId(),
												workLoan.getCreateBy(),
												workLoan.getCompanyId(),
												title,
												str,
												"87",
												"0",
												"重新申请",
												notifyRole));
					}
				}
			}
		}
		if (users!=null && users.size()!=0) {
			for (User u : users) {
				UserUtils.pushIm(u.getId(),str);
			}
		}
		if (userList!=null && userList.size()!=0) {
			for (User u : userList) {
				UserUtils.pushMeIm(u.getId());
			}
		}

		workLoanDao.update(workLoan);
		return "保存审核意见成功！";
	}
	/**
	 * 获取流程详细信息
	 * @param processInstanceId
	 */
	@SuppressWarnings("unchecked")
	public WorkLoan getByProcessInstanceId(String processInstanceId) {
		WorkLoan workLoan = workLoanDao.getByProcessInstanceId(processInstanceId);
		return workLoan;
	}
	/**
	 * 强制撤销
	 * @param
	 */
	@Transactional(readOnly = false)
	public void cancelInvalidate(WorkLoan workLoan) {
		String invalidateProcessInstanceId = workLoan.getProcessInstanceId();
		try {
			//将流程图中尚未走到的task的流程追踪信息逻辑删除，添加一条"撤销"流程追踪信息
			WorkActivityProcess process = new WorkActivityProcess();
			process.setProcessInstanceId(workLoan.getProcessInstanceId());
			process.setIsApproval("0");
			//List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
			WorkActivityProcess workActivityProcess = new WorkActivityProcess();
			workActivityProcess.setProcessInstanceId(workLoan.getProcessInstanceId());
			List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
			WorkProjectNotify notify = new WorkProjectNotify();
			notify.setNotifyId(workLoan.getId());
			List<User> userList = workProjectNotifyService.readByNotifyId(notify);
			if (userList!=null && userList.size()!=0) {
				for (User u : userList) {
					User user = UserUtils.get(u.getId());
					UserUtils.pushMeIm(user.getId());
				}
			}
			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.setDelFlag("0");
				pro.preInsert();
				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,"强制撤销");
			workLoan.setStatus("3");
			workLoan.preUpdate();
			workLoanDao.update(workLoan);
		}catch (ActivitiObjectNotFoundException e){
			System.err.println("撤销异常，因为这个流程已不存在!");
			e.printStackTrace();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	public List<WorkLoan> findListByContract(String contractId,String repayState){
		return workLoanDao.findListByContract(contractId,repayState);
	}
	public List<WorkLoan> findListByUser(String userId,String repayState){
		return workLoanDao.findListByUser(userId,repayState);
	}
}