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

import com.google.common.collect.Maps;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;
import com.jeeplus.common.utils.Collections3;
import com.jeeplus.common.utils.MenuStatusEnum;
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.ProcessDefCache;
import com.jeeplus.modules.projectrecord.dao.ProjectClientLinkmanDao;
import com.jeeplus.modules.projectrecord.dao.ProjectRecordsAlterDao;
import com.jeeplus.modules.projectrecord.entity.ProjectRecords;
import com.jeeplus.modules.projectrecord.entity.ProjectRecordsAlter;
import com.jeeplus.modules.projectrecord.enums.AlterStatusEnum;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
import com.jeeplus.modules.sys.entity.Dict;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.DictService;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.DictUtils;
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.workclientinfo.dao.WorkClientLinkmanDao;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
import com.jeeplus.modules.workcontractinfo.service.WorkContractInfoService;
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.projectrecord.dao.WorkProjectUserDao;
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.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 项目登记Service
 * @author ppt
 * @version 2018-05-02
 */
@Service
@Transactional(readOnly = true)
public class ProjectRecordsAlterService extends CrudService<ProjectRecordsAlterDao, ProjectRecordsAlter> {

	@Autowired
	private WorkProjectUserDao workProjectUserDao;
	@Autowired
	private ProjectClientLinkmanDao clientLinkmanDao;
	@Autowired
	private WorkClientLinkmanDao workClientLinkmanDao;
	@Autowired
	private DictService dictService;
	@Autowired
	private IdentityService identityService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkActivityMenuService workActivityMenuService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private WorkActivityProcessService workActivityProcessService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private ActivityService activityService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
	private  ProjectRecordsService recordsService;
	@Autowired
	private WorkContractInfoService contractInfoService;
    @Autowired
    private WorkClientAttachmentDao workClientAttachmentDao;
    @Autowired
    private WorkActivityProcessDao workActivityProcessDao;

	public ProjectRecordsAlter get(String id) {
		return super.get(id);
	}

	public List<ProjectRecordsAlter> findList(ProjectRecordsAlter projectRecords) {
		return super.findList(projectRecords);
	}

	public Page<ProjectRecordsAlter> findPage(Page<ProjectRecordsAlter> page, ProjectRecordsAlter projectRecords) {
		//设置数据权限
		projectRecords.getSqlMap().put("dsf", dataScopeFilter(projectRecords.getCurrentUser(), "o", "u", "s", MenuStatusEnum.PROJECT_RECORDSALTER.getValue()));
		projectRecords.setPage(page);
		List<ProjectRecordsAlter> recordsList = findList(projectRecords);
		//查询负责人信息
		for (ProjectRecordsAlter records : recordsList) {
			List<User> users = workProjectUserDao.queryProjectUsers(records.getId(), "1");
			records.setProjectLeaders(users);
		}
		page.setList(recordsList);
		return page;
	}

	@Transactional(readOnly = false)
	public void saveProject(ProjectRecordsAlter projectRecordsAlter, AlterStatusEnum alterStatus) throws Exception {
        WorkContractInfo workContractInfo = contractInfoService.get(projectRecordsAlter.getWorkContractInfo().getId());
		ProjectRecords records = recordsService.get(projectRecordsAlter.getAlterBeforeRecords().getId());

		if(records.getProjectStatus()!=ProjectStatusEnum.SIGNED.getValue() && records.getProjectStatus()!=ProjectStatusEnum.ON_CHANGE.getValue()){
			throw  new Exception("项目状态发生变动，不能发起变更");
		}else if(records.getProjectStatus()==ProjectStatusEnum.ON_CHANGE.getValue() && AlterStatusEnum.TSTORE.getValue() != projectRecordsAlter.getProjectStatus()
                && AlterStatusEnum.REJECTED.getValue() != projectRecordsAlter.getProjectStatus()&&AlterStatusEnum.RECALL.getValue() != projectRecordsAlter.getProjectStatus()){
            throw  new Exception("项目状态发生变动，不能发起变更");
        }
        Integer oldStatus = projectRecordsAlter.getProjectStatus();
        projectRecordsAlter.setProjectStatus(alterStatus.getValue());
        //更新原有项目状态信息
        records.setProjectStatus(ProjectStatusEnum.ON_CHANGE.getValue());
        records.preUpdate();
        recordsService.updateSelectiveById(records);

        if(StringUtils.isBlank(projectRecordsAlter.getAlterProjectId())){
            projectRecordsAlter.setAlterProjectId(projectRecordsAlter.getProjectId()+"-变更-"+this.countAlter(projectRecordsAlter.getProjectId()));
        }
		User createBy = projectRecordsAlter.getCreateBy();
		if(createBy != null){
			createBy = UserUtils.get(createBy.getId());
		}else {
		    createBy = UserUtils.getUser();
        }
		Office company= new Office();
        Office office =  new Office();
        if(StringUtils.isNotBlank((projectRecordsAlter.getWorkContractInfo().getId()))){
            //有合同状态
            workContractInfo = contractInfoService.get(projectRecordsAlter.getWorkContractInfo().getId());
            company.setId(workContractInfo.getCompanyId());
//			office.setId(workContractInfo.getChargeCompany());
            office.setId(UserUtils.getUser().getOffice().getId());
        }else{
            //无合同
            company.setId(UserUtils.getUser().getCompany().getId());
            office.setId(UserUtils.getUser().getOffice().getId());
        }
		projectRecordsAlter.setCompany(company);
		projectRecordsAlter.setOffice(office);
		super.save(projectRecordsAlter);
		//保存项目负责人
		List<User> leaders = projectRecordsAlter.getProjectLeaders();
		this.saveProjectUsers(projectRecordsAlter.getId(), leaders, true);
		//保存委托方联系人
		List<WorkClientLinkman> workClientLinkmanList = projectRecordsAlter.getWorkClientLinkmanList();
		this.saveLinkmanInfos(projectRecordsAlter.getId(), workClientLinkmanList, true);
		//保存施工方联系信息
		List<WorkClientLinkman> constructionLinkmanList = projectRecordsAlter.getWorkConstructionLinkmanList();
		this.saveLinkmanInfos(projectRecordsAlter.getId(), constructionLinkmanList, false);
		this.saveAttachments(projectRecordsAlter);
		if (AlterStatusEnum.TSTORE.getValue()== projectRecordsAlter.getProjectStatus()||AlterStatusEnum.REJECTED.getValue()==oldStatus)return;
		//启动审批流程
		this.startAudit(projectRecordsAlter, projectRecordsAlter.getProcessInstanceId());
	}

    private int countAlter(String projectId) {
	    return dao.countAlter(projectId)+1;
    }

    /**
	 * 保存委托方和施工方联系人信息
	 *
	 * @param projectId
	 * @param linkmanList
	 * @param isEntrust   是否委托方
	 */
	private void saveLinkmanInfos(String projectId, List<WorkClientLinkman> linkmanList, boolean isEntrust) {
		assert (projectId != null);
        if(linkmanList == null || linkmanList.isEmpty()){
            return;
        }
		HashMap<String, Object> map = new HashMap<>(5);
		map.put("projectId", projectId);
		map.put("linkmanList", linkmanList);
		int entrust = 0;
		if (isEntrust) {
			entrust = 1;
		}
		clientLinkmanDao.deleteProjectLinkmans(projectId, entrust);
		map.put("isEntrust", entrust);
		clientLinkmanDao.batchInsert(map);
	}

	/**
	 * 保存项目组成员信息
	 *
	 * @param projectId
	 * @param users
	 * @param isMaster
	 */
	private void saveProjectUsers(String projectId, List<User> users, boolean isMaster) {
		assert (projectId != null);
		assert (users != null && !users.isEmpty());
		HashMap<String, Object> map = new HashMap<>(5);
		List<String> memberIds = new ArrayList<>(users.size());
		for (User user : users) {
			memberIds.add(user.getId());
		}
		map.put("memberIds", memberIds);
		map.put("projectId", projectId);
		String master = null;
		if (isMaster) {
			master = "1";
            workProjectUserDao.deleteProjectMasterMembers(map);
           /* map.put("isMaster", "0");
            workProjectUserDao.batchInsert(map);*/
		} else {
			master = "0";
		}
		workProjectUserDao.deleteProjectMembers(projectId, master);
		map.put("isMaster", master);
		workProjectUserDao.batchInsert(map);
	}

	@Transactional(readOnly = false)
	public void delete(ProjectRecordsAlter projectRecords) {
		//删除项目负责人
		workProjectUserDao.deleteProjectMembers(projectRecords.getId(), "1");
		//删除项目组成员
//		workProjectUserDao.deleteProjectMembers(projectRecords.getId(), "0");
		//删除委托方联系人
		clientLinkmanDao.deleteProjectLinkmans(projectRecords.getId(), 1);
		//删除施工方联系人
		clientLinkmanDao.deleteProjectLinkmans(projectRecords.getId(), 0);
		super.delete(projectRecords);
		//修改原项目状态
		if (projectRecords.getAlterBeforeRecords()!=null){
			ProjectRecords records = new ProjectRecords();
			records.preUpdate();
			records.setId(projectRecords.getAlterBeforeRecords().getId());
			records.setProjectStatus(ProjectStatusEnum.SIGNED.getValue());
			recordsService.updateSelectiveById(records);
		}
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(projectRecords.getId());
        List<User> users = workProjectNotifyService.readByNotifyId(notify);
        if (users!=null && users.size()!=0){
            for (User user:users){
                UserUtils.pushMeIm(user.getId());
            }
        }
	}

	/**
	 * 设置项目组成员信息
	 *
	 * @param records
	 */
	public void queryUserNames(ProjectRecordsAlter records) {
		//查询负责人信息
		List<User> users = workProjectUserDao.queryProjectUsers(records.getId(), "1");
		records.setProjectLeaders(users);
		records.setLeaderNameStr(Collections3.extractToString(users, "name", ","));
		records.setLeaderIds(Collections3.extractToString(users, "id", ","));

		//查询项目组成员信息
		List<User> members = workProjectUserDao.isDelFalg(records.getId(), "");
		records.setProjectMembers(members);
		records.setMemberNameStr(Collections3.extractToString(members, "name", ","));
		records.setMemberIds(Collections3.extractToString(members, "id", ","));
	}

	/**
	 * 设置联系人信息
	 *
	 * @param projectRecords
	 */
	public void queryLinkmanInfos(ProjectRecordsAlter projectRecords) {
		List<WorkClientLinkman> clientLinkmanList = workClientLinkmanDao.queryProjectLinkmans(projectRecords.getId(), 1);
		projectRecords.setWorkClientLinkmanList(clientLinkmanList);
		List<WorkClientLinkman> constructionLinkmanList = workClientLinkmanDao.queryProjectLinkmans(projectRecords.getId(), 0);
		projectRecords.setWorkConstructionLinkmanList(constructionLinkmanList);
	}

	/**
	 * 启动审批流程
	 *
	 * @param projectRecordsAlter
	 */
    private void startAudit(ProjectRecordsAlter projectRecordsAlter,String processInstanceId) throws Exception {
        Map<String, Object> variables = new HashMap<String, Object>();
        identityService.setAuthenticatedUserId(projectRecordsAlter.getCurrentUser().getId());
        Office office = projectRecordsAlter.getOffice();
        office = officeService.get(office.getId());
        projectRecordsAlter.setOffice(office);
        String contentStr = "项目变更编号："+projectRecordsAlter.getAlterProjectId()+"，项目名称："+ projectRecordsAlter.getProjectName()+"，创建人："+projectRecordsAlter.getCreateBy().getName()+"，所属部门："+projectRecordsAlter.getOffice().getName();
        String titleStr = "项目名称："+ projectRecordsAlter.getProjectName();

        String businessKey = projectRecordsAlter.getId();
        WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("807c6d4b5623474792fe78ff1fd1cdff", office);
        // 启动流程
        String processType = workActivityMenu.getProcessType();
        StringBuffer buffer = new StringBuffer();
        Activity activity = new Activity();
        WorkProjectNotify workProjectNotify = UtilNotify
                .saveNotify(projectRecordsAlter.getId(),
                        null,
                        projectRecordsAlter.getCompany().getId(),
                        titleStr,
                        contentStr,
                        "41",
                        "0",
                        "待审批",
                        ""
                );

        List<User> users = new ArrayList<>();
        List<User> bmzrs = UserUtils.getByRoleActivityEnname("bmzr",2,office.getId(),"4",projectRecordsAlter.getCreateBy());
        if (StringUtils.isNotBlank(workActivityMenu.getId())) {
            processType = workActivityMenu.getProcessType();
            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(),"8",projectRecordsAlter.getCreateBy());
                    if (enusers.size()==0){
                            /*this.delete(projectRecordsAlter);
                            for (WorkClientAttachment workClientAttachment : projectRecordsAlter.getWorkAttachments()) {
                                workClientAttachmentDao.delete(workClientAttachment);
                            }*/
                        throw new Exception("流程审批人不能为空,角色"+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(),"4",projectRecordsAlter.getCreateBy());
                }
                //人员审批
                if (StringUtils.isNotBlank(activity.getUser().getId())) {
                    users.add(activity.getUser());
                }
            }
            workProjectNotify.setId("");
        } else {
            if (bmzrs==null||bmzrs.size()==0){
                    /*this.delete(projectRecordsAlter);
                    if (projectRecordsAlter.getWorkAttachments()!=null) {
                        for (WorkClientAttachment workClientAttachment : projectRecordsAlter.getWorkAttachments()) {
                            workClientAttachmentDao.delete(workClientAttachment);
                        }
                    }*/
                throw new Exception("流程审批人不能为空,角色部门负责人下无用户,请联系管理员！");
            }
            processType = "projectAlter";
            variables.put("applyUserId", projectRecordsAlter.getCreateBy().getId());
            variables.put("bmzrCount",bmzrs.size());
            variables.put("bmzrList",bmzrs);
            users.addAll(bmzrs);
        }
        List<String> userIds = new ArrayList<>(users.size());
        for (User u : users){
            userIds.add(u.getId());
            workProjectNotify.setUser(u);
            workProjectNotify.setId("");
            workProjectNotify.setNotifyRole("部门负责人审批");
            workProjectNotifyService.save(workProjectNotify);
            Map<String,Object> extras = new HashMap<>();
            extras.put("type","7003");
            extras.put("procDefKey","41");
            extras.put("id",workProjectNotify.getId());
            UserUtils.pushInfoToApp(titleStr,contentStr,extras,u.getId());
        }
        UserUtils.pushIm(userIds,contentStr);

        variables.put("busId", businessKey);
        variables.put("type", processType);
        variables.put("title", "审批单：" + projectRecordsAlter.getProjectName());//设置标题；

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
        //        projectRecordsAlter.setProcessInstance(processInstance);
        if (StringUtils.isNotBlank(processInstanceId)) {
            workActivityProcessService.updateProcessInstanceId(processInstance.getId(),processInstanceId);
            workActivityProcessService.deleteProcessInstanceId(processInstanceId);
            workActivityProcessService.deleteProcessIdAuditUsers(processInstanceId);
        }
        List<Activity> list = workActivityMenu.getActivities();
        if (list != null && list.size() != 0) {
            workActivityProcessService.saveList(list, processInstance.getId());
        } else {
            WorkActivityProcess workActivityProcess = new WorkActivityProcess();
            workActivityProcess.setProcessKey(processType);
            workActivityProcess.setCount(1);
            workActivityProcess.setProcessInstanceId(processInstance.getId());
            workActivityProcess.setIsApproval("0");
            workActivityProcessService.save(workActivityProcess);
            workActivityProcessService.insertAuditsByType(bmzrs,processInstance.getId(),1,1);

        }
        projectRecordsAlter.setProcessInstanceId(processInstance.getId());
        projectRecordsAlter.setProjectStatus(AlterStatusEnum.IN_APRL.getValue());
        dao.updateProcessIdAndStatus(projectRecordsAlter);
        //更新原有项目状态信息
        ProjectRecords records = recordsService.get(projectRecordsAlter.getAlterBeforeRecords().getId());
        records.setAlterProcessId(processInstance.getId());
        records.preUpdate();
        recordsService.updateSelectiveById(records);
    }

	@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
	public void updateSelectiveById(ProjectRecordsAlter projectRecords) {
		dao.updateSelectiveById(projectRecords);
	}

	public ProjectRecordsAlter getByProcessInstanceId(String procInsId) {
		ProjectRecordsAlter records = dao.findUniqueByProperty("process_instance_id", procInsId);
		if(records!=null) {
            List<User> users = workProjectUserDao.queryProjectUsers(records.getId(), "1");
            records.setProjectLeaders(users);
        }
		return records;
	}

    /**
     * @param projectRecordsAlter
     * @return
     */
	@Transactional(readOnly = false)
	public String auditSave(ProjectRecordsAlter projectRecordsAlter,List<User> auditUsers) throws Exception {
        int projectStatus = projectRecordsAlter.getProjectStatus();
        String taskDefKey = projectRecordsAlter.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit") ) {
            actTaskService.claim(projectRecordsAlter.getAct().getTaskId(), UserUtils.getUser().getId());
            List<User> leaders = projectRecordsAlter.getProjectLeaders();
            this.saveProjectUsers(projectRecordsAlter.getId(), leaders, true);
        }else {
            projectRecordsAlter.getAct().setFlag("yes");
            saveProject(projectRecordsAlter,AlterStatusEnum.IN_APRL);
        }

        String comment = "";
        if ( projectStatus == AlterStatusEnum.REJECTED.getValue()) {
            comment = ("yes".equals(projectRecordsAlter.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
        }else {
            comment = ("yes".equals(projectRecordsAlter.getAct().getFlag())?"[同意] ":"[驳回] ")+ projectRecordsAlter.getAct().getComment();
        }

        if (!"yes".equals(projectRecordsAlter.getAct().getFlag())) {
            projectRecordsAlter.setProjectStatus(AlterStatusEnum.REJECTED.getValue());
        }

        User createUser = UserUtils.get(projectRecordsAlter.getCreateBy().getId());

        Map<String, Object> vars = Maps.newHashMap();
        String notifyRole = "";
        //业务逻辑对应的条件表达式
        User user = null;
        List<Activity> activitieList = activityService.getByProcessInstanceId(projectRecordsAlter.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(projectRecordsAlter.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        String  taskCount = "1";
        String enname = "";
        Office office = officeService.get(projectRecordsAlter.getOffice().getId());
        projectRecordsAlter.setOffice(office);
        String notifyStr = "项目变更编号："+projectRecordsAlter.getAlterProjectId()+"，项目名称："+ projectRecordsAlter.getProjectName();
        String title = "项目名称："+ projectRecordsAlter.getProjectName();
        int key = 0;
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("projectAlter")) {
            key = 1;
            for (int i = 0; i < workActivityProcesses.size(); i++) {
                WorkActivityProcess activityProcess = workActivityProcesses.get(i);
                if (taskDefKey.equals("modifyApply")) {
                    taskCount = "0";
                    workActivityProcess.setId("");
                    workActivityProcess.setCount(0);
                    if (!"yes".equals(projectRecordsAlter.getAct().getFlag())) {
                        projectRecordsAlter.setProjectStatus(AlterStatusEnum.RECALL.getValue());
                        workActivityProcess.setIsApproval("2");
                        vars.put("pass", false);
                    } else {
                        vars.put("pass", true);
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                } else {
                    taskCount = activityProcess.getCount()+"";
                    workActivityProcess = activityProcess;
                    if (!workActivityProcess.getIsApproval().equals("0")) {
                        workActivityProcess.setId("");
                    }
                    for (Activity activity : activities) {
                        if (activity.getCount() == activityProcess.getCount()) {
                            notifyRole = activity.getName();
                            break;
                        }
                    }
                    if (!"yes".equals(projectRecordsAlter.getAct().getFlag())) {
                        notifyRole = "调整项目变更";
                        projectRecordsAlter.setProjectStatus(AlterStatusEnum.REJECTED.getValue());
                        workActivityProcess.setIsApproval("2");
                        String returnBack = "-1";
                        for (Activity activity : activities) {
                            if (activity.getCount() == activityProcess.getCount()) {
                                returnBack = activity.getReturnBack();
                                break;
                            }
                        }
                        if (returnBack.equals("0")) {
                            workActivityProcess.setId("");
                        }
                        vars.put("pass", false);
                    } else {
                        workActivityProcess.setIsApproval("1");
                        vars.put("pass", true);
                    }
                    break;
                }
            }
        }else {
            workActivityMenu.setProcessType("projectAlter");
            for (int i = 0; i < workActivityProcesses.size(); i++) {
                WorkActivityProcess activityProcess = workActivityProcesses.get(i);
                String count = String.valueOf(activityProcess.getCount());
                workActivityProcess = activityProcess;
                if (!workActivityProcess.getIsApproval().equals("0")) {
                    workActivityProcess.setId("");
                }
                // 审核环节
                if ("bmzr".equals(taskDefKey) && "1".equals(count)) {
                    taskCount = count;
                    if ("yes".equals(projectRecordsAlter.getAct().getFlag())) {
                        workActivityProcess.setIsApproval("1");
                        vars.put("pass", true);
                        notifyRole = "审批通过";
                    } else {
                        workActivityProcess.setIsApproval("2");
                        vars.put("pass", false);
                        user = createUser;
                        notifyRole = "调整项目变更";
                    }
                    break;
                } else if ("modifyApply".equals(taskDefKey) && "0".equals(count)) {
                    taskCount = "0";
                    enname = "bmzr";
                    workActivityProcess.setCount(0);
                    if("yes".equals(projectRecordsAlter.getAct().getFlag())){
                        workActivityProcess.setIsApproval("1");
                        vars.put("pass",true);
                        notifyRole = "部门负责人审批";
                    }else{
                        workActivityProcess.setIsApproval("2");
                        projectRecordsAlter.setProjectStatus(AlterStatusEnum.RECALL.getValue());
                        vars.put("pass",false);
                    }
                    break;
                }
            }
        }
        workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount, projectRecordsAlter.getProcessInstanceId(),taskDefKey,"modifyApply", projectRecordsAlter.getAct().getFlag(),comment, activities);
        // 设置意见
        projectRecordsAlter.getAct().setComment(comment);
        projectRecordsAlter.preUpdate();
        // 提交流程任务
        actTaskService.complete(projectRecordsAlter.getAct().getTaskId(), projectRecordsAlter.getAct().getProcInsId(), projectRecordsAlter.getAct().getComment(), vars);
        boolean state = actTaskService.isProcessEnd(projectRecordsAlter.getAct().getProcInsId());
        List<User> users = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        if(!state) {
            users.add(projectRecordsAlter.getCreateBy());
            if ("yes".equals(projectRecordsAlter.getAct().getFlag())) {
                projectRecordsAlter.setProjectStatus(AlterStatusEnum.SIGNED.getValue());
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(projectRecordsAlter.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                workProjectNotifyService
                        .save(UtilNotify
                                .saveNotify(projectRecordsAlter.getId(),
                                        projectRecordsAlter.getCreateBy(),
                                        projectRecordsAlter.getCompany().getId(),
                                        title,
                                        notifyStr,
                                        "41",
                                        "0",
                                        "待通知",
                                        notifyRole));
            } else {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(projectRecordsAlter.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                if (projectRecordsAlter.getProjectStatus()!= AlterStatusEnum.RECALL.getValue()){
                    projectRecordsAlter.setProjectStatus(AlterStatusEnum.REJECTED.getValue());
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(projectRecordsAlter.getId(),
                                            projectRecordsAlter.getCreateBy(),
                                            projectRecordsAlter.getCompany().getId(),
                                            title,
                                            notifyStr,
                                            "41",
                                            "0",
                                            "待通知",
                                            notifyRole));
                }
            }
            workActivityProcessService.deleteProcessIdAuditUsers(projectRecordsAlter.getProcessInstanceId());
        }else{
            String str = notifyStr +"，创建人："+projectRecordsAlter.getCreateBy().getName()+"，所属部门："+projectRecordsAlter.getOffice().getName();
            if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("projectAlter")) {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(projectRecordsAlter.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                WorkProjectNotify workProjectNotify = UtilNotify
                        .saveNotify(projectRecordsAlter.getId(),
                                new User(),
                                projectRecordsAlter.getCompany().getId(),
                                title,
                                str,
                                "41",
                                "0",
                                "待审批",
                                notifyRole);
                String count = taskDefKey.replace("audit","").replace("task","");
                List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
                        activities,
                        workProjectNotify,
                        taskDefKey,
                        projectRecordsAlter.getAct().getFlag(),
                        count,
                        projectRecordsAlter.getCreateBy(),
                        projectRecordsAlter.getOffice().getId(),
                        "4");
                for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
                    users.add(workProjectNotify1.getUser());
                    workProjectNotify1.setId("");
                    workProjectNotify1.setIsNewRecord(false);
                    workProjectNotifyService.save(workProjectNotify1);
                }
            }else {
                if (!"yes".equals(projectRecordsAlter.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(projectRecordsAlter.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    WorkProjectNotify workProjectNotify = UtilNotify
                            .saveNotify(projectRecordsAlter.getId(),
                                    user,
                                    projectRecordsAlter.getCompany().getId(),
                                    title,
                                    str,
                                    "41",
                                    "0",
                                    "重新申请",
                                    notifyRole);
                    workProjectNotifyService.save(workProjectNotify);
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(projectRecordsAlter.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(projectRecordsAlter.getId(),
                                        new User(),
                                        projectRecordsAlter.getCompany().getId(),
                                        title,
                                        str,
                                        "41",
                                        "0",
                                        "待审批",
                                        notifyRole);
                        for (User user1:auditUsers){
                            users.add(user1);
                            workProjectNotify.setUser(user1);
                            workProjectNotify.setId("");
                            workProjectNotify.setIsNewRecord(false);
                            workProjectNotifyService.save(workProjectNotify);
                            Map<String,Object> extras = new HashMap<>();
                            extras.put("type","7003");
                            extras.put("procDefKey","41");
                            extras.put("id",workProjectNotify.getId());
                            UserUtils.pushInfoToApp(title,str,extras,user1.getId());
                        }
                    }else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(projectRecordsAlter.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.add(projectRecordsAlter.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(projectRecordsAlter.getId(),
                                                projectRecordsAlter.getCreateBy(),
                                                projectRecordsAlter.getCompany().getId(),
                                                title,
                                                str,
                                                "41",
                                                "0",
                                                "重新申请",
                                                notifyRole));
                    }
                }
            }
        }

        if (StringUtils.isNotBlank(title) && users!=null && users.size()!=0) {
            List<String> userIds = new ArrayList<>(users.size());
            for (User u : users) {
                userIds.add(u.getId());
            }
            UserUtils.pushIm(userIds,title);
        }
        if (userList!=null && userList.size()!=0) {
            for (User u : userList) {
                UserUtils.pushMeIm(u.getId());
            }
        }

        if(projectRecordsAlter.getProjectStatus()==AlterStatusEnum.SIGNED.getValue()){
            //更新原有项目状态信息
            ProjectRecords records = recordsService.get(projectRecordsAlter.getAlterBeforeRecords().getId());
            recordsService.queryContractInfos(records);
            recordsService.queryLinkmanInfos(records);
            recordsService.queryWorkAttachment(records);
            recordsService.queryUserNames(records);
            ProjectRecords oldRecords = new ProjectRecords();
            BeanUtils.copyProperties(oldRecords,records);
            oldRecords.setId(null);
            oldRecords.setProjectStatus(ProjectStatusEnum.INVALID.getValue());
            recordsService.saveProject(oldRecords,ProjectStatusEnum.INVALID);
            projectRecordsAlter.setAlterBeforeRecords(oldRecords);
            String rid = records.getId();
            //查询当前变更信息
            this.queryLinkmanInfos(projectRecordsAlter);
            this.queryUserNames(projectRecordsAlter);
            this.queryContractInfo(projectRecordsAlter);
            recordsService.queryWorkAttachment(records);
            List<WorkClientAttachment> workAttachments = records.getWorkAttachments();
            BeanUtils.copyProperties(records, projectRecordsAlter);
            if(workAttachments!=null){
                records.setWorkAttachments(workAttachments);
            }
            this.queryWorkAttachment(projectRecordsAlter);
            if(projectRecordsAlter.getWorkAttachments()!=null){
                if(records.getWorkAttachments()==null){
                    records.setWorkAttachments(new ArrayList<WorkClientAttachment>());
                }
                for (WorkClientAttachment workClientAttachment : projectRecordsAlter.getWorkAttachments()) {
                    workClientAttachment.setId(null);
                    workClientAttachment.setAttachmentId(null);
                    records.getWorkAttachments().add(workClientAttachment);
                }
            }
            records.setId(rid);
            records.setProjectStatus(ProjectStatusEnum.SIGNED.getValue());
            records.setCreateBy(oldRecords.getCreateBy());
            records.setCreateDate(oldRecords.getCreateDate());
            records.preUpdate();
            recordsService.saveProject(records,ProjectStatusEnum.SIGNED);
        }
        dao.updateSelectiveById(projectRecordsAlter);
        return "保存审核意见成功！";

	}

	public void queryContractInfo(ProjectRecordsAlter projectRecords) {
		WorkContractInfo workContractInfo = contractInfoService.get(projectRecords.getWorkContractInfo().getId());
		workContractInfo.setConstructionProjectTypeStr(DictUtils.getDictLabel(String.valueOf(workContractInfo.getConstructionProjectType()), "construction_project_type", ""));
        if(workContractInfo.getWorkClientInfoList()!=null&&!workContractInfo.getWorkClientInfoList().isEmpty()){
            StringBuilder workClinetInfoIds = new StringBuilder();
            for (WorkClientInfo workClientInfo : workContractInfo.getWorkClientInfoList()) {
                workClinetInfoIds.append(workClientInfo.getId()).append(",");
            }
            workClinetInfoIds.deleteCharAt(workClinetInfoIds.length()-1);
            workContractInfo.setWorkClinetInfoIds(workClinetInfoIds.toString());
        }
		projectRecords.setWorkContractInfo(workContractInfo);
	}

	private void notifyProjectLeaders (ProjectRecordsAlter projectRecords, User createUser, String str){
		List<User> projectLeaders = projectRecords.getProjectLeaders();
		for (User leader : projectLeaders) {
			WorkProjectNotify workProjectNotify = UtilNotify
					.saveNotify(projectRecords.getId(),
							leader,
							createUser.getComId(),
							str,
							projectRecords.getAct().getComment(),
							"41",
							"0",
							"待审批",
							"");
			workProjectNotify.setOfficeId(createUser.getOffice().getId());
			workProjectNotify.preInsert();
			workProjectNotify.setCreateBy(projectRecords.getCreateBy());
			workProjectNotifyService.insert(workProjectNotify);
		}
	}

    /**
     * 获取已办任务
     * @return
     */
    public List<ProjectRecordsAlter> historicList(Act act){
        String userId = UserUtils.getUser().getId();
        HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery().finished().taskAssignee(userId);
        // 设置查询条件
        if (StringUtils.isNotBlank(act.getProcDefKey())){
            query.processDefinitionKey(act.getProcDefKey());
        }
        if (act.getBeginDate() != null){
            query.taskCompletedAfter(act.getBeginDate());
        }
        if (act.getEndDate() != null){
            query.taskCompletedBefore(act.getEndDate());
        }
        // 查询总数
        List<HistoricTaskInstance> list = query.list();
        List<ProjectRecordsAlter> list1 = new ArrayList<ProjectRecordsAlter>();
        Office office = UserUtils.getSelectCompany();
        String companyId = office==null?"":office.getId();
        for (HistoricTaskInstance histTask : list) {
			ProjectRecordsAlter projectRecords = this.getByProcessInstanceId(histTask.getProcessInstanceId());
            if (projectRecords != null && projectRecords.getCompany().getId().equals(companyId)) {
                projectRecords.setCreateBy(UserUtils.get(projectRecords.getCreateBy().getId()));
                historyService.getHistoricIdentityLinksForProcessInstance(histTask.getProcessInstanceId());
                act.setHistTask(histTask);
                act.setVars(histTask.getProcessVariables());
                act.setProcDef(ProcessDefCache.get(histTask.getProcessDefinitionId()));
                act.setStatus("finish");
                projectRecords.setAct(act);
                List<User> users = workProjectUserDao.queryProjectUsers(projectRecords.getId(), "1");
                projectRecords.setProjectLeaders(users);
                list1.add(projectRecords);
            }
        }
//        workReimbursement.setPage(page);
        return list1;
    }

    public void queryWorkAttachment(ProjectRecordsAlter projectRecords) {
        WorkClientAttachment attchment = new WorkClientAttachment();
        attchment.setAttachmentId(projectRecords.getId());
        List<WorkClientAttachment> attachments = workClientAttachmentDao.findList(attchment);
        projectRecords.setWorkAttachments(attachments);
    }

    private void saveAttachments(ProjectRecordsAlter projectRecords) {
        if (projectRecords.getWorkAttachments()!=null && !projectRecords.getWorkAttachments().isEmpty()) {
            //保存附件信息
            for (WorkClientAttachment workClientAttachment : projectRecords.getWorkAttachments()) {
                if (StringUtils.isBlank(workClientAttachment.getId())&&StringUtils.isNotBlank(workClientAttachment.getAttachmentId())) {
                    continue;
                }
                if (StringUtils.isBlank(workClientAttachment.getId())&&StringUtils.isBlank(workClientAttachment.getUrl())) {
                    continue;
                }
                if (WorkClientAttachment.DEL_FLAG_NORMAL.equals(workClientAttachment.getDelFlag())) {
                    workClientAttachment.setAttachmentId(projectRecords.getId());
                    workClientAttachment.setAttachmentFlag("82");
                    workClientAttachment.setAttachmentUser(UserUtils.getUser().getId());
                    if (StringUtils.isBlank(workClientAttachment.getId()) || "null".equals(workClientAttachment.getId())) {
                        workClientAttachment.preInsert();
                        workClientAttachmentDao.insert(workClientAttachment);
                    } else {
                        workClientAttachment.preUpdate();
                        workClientAttachmentDao.update(workClientAttachment);
                    }
                } else {
                    workClientAttachmentDao.delete(workClientAttachment);
                }
            }
        }
    }

    public void queryProjectAlterDetail(ProjectRecordsAlter projectRecordsAlter) {
        //设置合同信息
        this.queryContractInfo(projectRecordsAlter);
        //设置项目组成员
        this.queryUserNames(projectRecordsAlter);
        //设置委托方联系人信息
        this.queryLinkmanInfos(projectRecordsAlter);
        //设置附件信息
        this.queryWorkAttachment(projectRecordsAlter);
    }

    @Transactional(readOnly = false)
    public void cancelProcess(ProjectRecordsAlter projectRecordsAlter) {
        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(projectRecordsAlter.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(projectRecordsAlter.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(projectRecordsAlter.getId());
        List<User> userList = workProjectNotifyService.readByNotifyId(notify);
        if (userList!=null && userList.size()!=0) {
            for (User u : userList) {
                User user = UserUtils.get(u.getId());
                UserUtils.pushIm(u.getId(),"申请人 "+user.getName() +",项目登记审批:"+projectRecordsAlter.getProjectName() +" 强制撤销!");
                /*List<WebSocket> toUserConns = ChatServerPool.getWebSocketByUser(u.getId());
                for (WebSocket toUserConn : toUserConns) {
                    String message = "{\"to\":\""+u.getId()+"\"," +
                            "\"msg\":\"审批信息 申请人:"+ user.getName()+",项目登记审批:"+projectRecordsAlter.getProjectName() +" 强制撤销!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                    //ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.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.setIsApproval("-1");
                    p.setDelFlag("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);
            ProjectRecordsAlter projectRecords = new ProjectRecordsAlter();
            projectRecords.setId(projectRecordsAlter.getId());
            projectRecords.setProjectStatus(AlterStatusEnum.RECALL.getValue());
            projectRecords.preUpdate();
            this.updateSelectiveById(projectRecords);
        }
    }
}