/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workreceiptssettle.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.DateUtils;
import com.jeeplus.common.utils.MenuStatusEnum;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.websocket.onchat.ChatServerPool;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.enums.ProjectStatusEnum;
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.workinvoicedetail.service.WorkInvoiceDetailService;
import com.jeeplus.modules.workinvoicereturn.service.WorkInvoiceReturnService;
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.workreceiptssettle.dao.WorkReceiptsSettleDao;
import com.jeeplus.modules.workreceiptssettle.entity.WorkReceiptsSettle;
import com.jeeplus.modules.workreceiptssettle.entity.WorkReceiptsSettleDetail;
import com.jeeplus.modules.workreceiptssettle.entity.WorkReceiptsSettleInvoice;
import org.activiti.engine.ActivitiObjectNotFoundException;
import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.service.CrudService;

/**
 * 收入结算Service
 * @author ssrh
 * @version 2018-06-28
 */
@Service
@Transactional(readOnly = true)
public class WorkReceiptsSettleService extends CrudService<WorkReceiptsSettleDao, WorkReceiptsSettle> {

    @Autowired
    private SerialNumTplService serialNumTplService;
    @Autowired
    private WorkReceiptsSettleInvoiceService settleInvoiceService;
    @Autowired
    private WorkReceiptsSettleDetailService settleDetailService;
    @Autowired
    private WorkInvoiceDetailService invoiceDetailService;
    @Autowired
    private WorkInvoiceReturnService invoiceReturnService;
    @Autowired
    private IdentityService identityService;
    @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 WorkActivityProcessDao workActivityProcessDao;

	public WorkReceiptsSettle get(String id) {
        WorkReceiptsSettle workReceiptsSettle = super.get(id);
        if(workReceiptsSettle!=null) {
            WorkReceiptsSettleDetail settleDetail = new WorkReceiptsSettleDetail();
            settleDetail.setSettleId(workReceiptsSettle.getId());
            workReceiptsSettle.setSettleDetailList(settleDetailService.findList(settleDetail));

            WorkReceiptsSettleInvoice settleInvoice = new WorkReceiptsSettleInvoice();
            settleInvoice.setSettleId(workReceiptsSettle.getId());
            workReceiptsSettle.setSettleInvoiceList(settleInvoiceService.findList(settleInvoice));
        }
        return workReceiptsSettle;
    }
	
	public List<WorkReceiptsSettle> findList(WorkReceiptsSettle workReceiptsSettle) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workReceiptsSettle.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_RECEIPTSSETTLE.getValue());
            workReceiptsSettle.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findList(workReceiptsSettle);
	}
	
	public Page<WorkReceiptsSettle> findPage(Page<WorkReceiptsSettle> page, WorkReceiptsSettle workReceiptsSettle) {
        if(!UserUtils.getUser().isAdmin()) {
            String dataScopeSql = dataScopeFilter(workReceiptsSettle.getCurrentUser(), "o", "u", "s", MenuStatusEnum.WORK_RECEIPTSSETTLE.getValue());
            workReceiptsSettle.getSqlMap().put("dsf", dataScopeSql);
        }
		return super.findPage(page, workReceiptsSettle);
	}
	
	@Transactional(readOnly = false)
	public String saveSettle(WorkReceiptsSettle workReceiptsSettle) {
        User createBy = workReceiptsSettle.getCreateBy();
        if(createBy != null){
            createBy = UserUtils.get(createBy.getId());
        }else {
            createBy = UserUtils.getUser();
            workReceiptsSettle.setCreateBy(createBy);
        }
        if(workReceiptsSettle.getCompany()==null||StringUtils.isBlank(workReceiptsSettle.getCompany().getId())){
            workReceiptsSettle.setCompany(UserUtils.getSelectCompany());
        }
	    if(StringUtils.isBlank(workReceiptsSettle.getNum())){
            workReceiptsSettle.setNum(serialNumTplService.genSerialNum(createBy.getCompany(),workReceiptsSettle.SERIAL_BIZCODE));
        }
		super.save(workReceiptsSettle);
        //保存结算明细
        this.updateInfo(workReceiptsSettle);
        return this.startAudit(workReceiptsSettle,workReceiptsSettle.getProcessInstanceId());
//        return "";
	}
	
	@Transactional(readOnly = false)
	public void delete(WorkReceiptsSettle workReceiptsSettle) {
		super.delete(workReceiptsSettle);
        if(workReceiptsSettle.getSettleDetailList()!=null){
            settleDetailService.deleteBySettleId(workReceiptsSettle.getId());
            for (WorkReceiptsSettleDetail settleDetail : workReceiptsSettle.getSettleDetailList()) {
                settleDetail.getInvoice().setSettleFlag("0");
                invoiceDetailService.updateSettleFlag(settleDetail.getInvoice());
            }
        }
        if(workReceiptsSettle.getSettleInvoiceList()!=null){
            settleInvoiceService.deleteBySettleId(workReceiptsSettle.getId());
        }
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workReceiptsSettle.getId());
        List<User> users = workProjectNotifyService.readByNotifyId(notify);
        if (users!=null && users.size()!=0){
            for (User user:users){
                UserUtils.pushMeIm(user.getId());
            }
        }
	}

    /**
     * 启动审批流程
     *
     * @param workReceiptsSettle
     */
    private String startAudit(WorkReceiptsSettle workReceiptsSettle, String processInstanceId){
        Map<String, Object> variables = new HashMap<String, Object>();
        identityService.setAuthenticatedUserId(workReceiptsSettle.getCurrentUser().getId());
        User createUser = UserUtils.getUser();
        String contentStr = "结算单号："+workReceiptsSettle.getNum()+"，结算人："+workReceiptsSettle.getCreateBy().getName()+"，结算日期："+ DateUtils.formatDate(workReceiptsSettle.getCreateDate());
        String titleStr = "结算部门："+ workReceiptsSettle.getOffice().getName();

        String businessKey = workReceiptsSettle.getId();
        Office office = UserUtils.getSelectOffice();
        WorkActivityMenu workActivityMenu = workActivityMenuService.findByParentAndOffice("ggh3125f1f194c82bdea93555c750904ewf", office);
        // 启动流程
        String processType = workActivityMenu.getProcessType();
        StringBuffer buffer = new StringBuffer();
        Activity activity = new Activity();
        WorkProjectNotify workProjectNotify = UtilNotify
                .saveNotify(workReceiptsSettle.getId(),
                        null,
                        workReceiptsSettle.getCompany().getId(),
                        titleStr,
                        contentStr,
                        "52",
                        "0",
                        "待审批",
                        ""
                );

        List<User> users = new ArrayList<>();
        List<User> scfgldList = UserUtils.getByRoleActivityEnname("scfgld",1,office.getId(),"7",workReceiptsSettle.getCreateBy());
        List<User> fpglyList = UserUtils.getByRoleActivityEnname("fpgly",3,office.getId(),"7",workReceiptsSettle.getCreateBy());
        List<User> cwzgList = UserUtils.getByRoleActivityEnname("cwzg",1,office.getId(),"7",workReceiptsSettle.getCreateBy());
        List<User> zjlList = UserUtils.getByRoleActivityEnname("zjl",1,office.getId(),"7",workReceiptsSettle.getCreateBy());
        List<User> cwfgldList = UserUtils.getByRoleActivityEnname("cwfgld",1,office.getId(),"7",workReceiptsSettle.getCreateBy());
        List<User> cnList = UserUtils.getByRoleActivityEnname("cn",1,office.getId(),"7",workReceiptsSettle.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(),"7",workReceiptsSettle.getCreateBy());
                    if (enusers.size()==0){
                        this.delete(workReceiptsSettle);
                        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(),"7",workReceiptsSettle.getCreateBy());
                }
                //人员审批
                if (StringUtils.isNotBlank(activity.getUser().getId())) {
                    users.add(activity.getUser());
                }
            }
            workProjectNotify.setId("");
        } else {
            if (scfgldList.size()==0 || fpglyList.size()==0 || cwzgList.size()==0 || zjlList.size()==0 || cwfgldList.size()==0 || cnList.size()==0){
                this.delete(workReceiptsSettle);
            }
            if (scfgldList.size()==0){
                return "流程审批人不能为空,角色市场分管领导下无用户,请联系管理员！";
            }
            processType = "receiptssettle";
            users.addAll(scfgldList);
        }
        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","7002");
            extras.put("procDefKey","52");
            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", "审批单：" + workReceiptsSettle.getNum());//设置标题；

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processType, businessKey, variables);
        //        workReceiptsSettle.setProcessInstance(processInstance);
        if (org.apache.commons.lang3.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);
            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(scfgldList,processInstance.getId(),1,1);
            workActivityProcessService.insertAuditsByType(fpglyList,processInstance.getId(),2,0);
            workActivityProcessService.insertAuditsByType(cwzgList,processInstance.getId(),3,0);
            workActivityProcessService.insertAuditsByType(zjlList,processInstance.getId(),4,0);
            workActivityProcessService.insertAuditsByType(cwfgldList,processInstance.getId(),5,0);
            workActivityProcessService.insertAuditsByType(cnList,processInstance.getId(),6,0);
        }
        workReceiptsSettle.setProcessInstanceId(processInstance.getId());
        workReceiptsSettle.setState(ProjectStatusEnum.IN_APRL.getValue());
        dao.updateProcessIdAndStatus(workReceiptsSettle);
        return "";
    }


    /**
     * 审核流程
     * @param workReceiptsSettle
     */
    @Transactional(readOnly = false)
    public String auditSave(WorkReceiptsSettle workReceiptsSettle,List<User> auditUsers) {
        String str = "结算单号："+workReceiptsSettle.getNum()+"，结算人："+workReceiptsSettle.getCreateBy().getName()+"，结算日期："+ DateUtils.formatDate(workReceiptsSettle.getCreateDate());
        String title = "结算部门："+ workReceiptsSettle.getOffice().getName();
        // 对不同环节的业务逻辑进行操作
        String taskDefKey = workReceiptsSettle.getAct().getTaskDefKey();
        if (!"modifyApply".equals(taskDefKey) && !taskDefKey.contains("audit")) {
            actTaskService.claim(workReceiptsSettle.getAct().getTaskId(), UserUtils.getUser().getId());
        }else {
            workReceiptsSettle.getAct().setFlag("yes");
        }
        this.updateInfo(workReceiptsSettle);
        String comment = "";
        if (ProjectStatusEnum.REJECTED.getValue() == workReceiptsSettle.getState()){
            comment = ("yes".equals(workReceiptsSettle.getAct().getFlag())?"[重新申请] ":"[已撤销] ");
        }else {
            comment = ("yes".equals(workReceiptsSettle.getAct().getFlag())?"[同意] ":"[驳回] ")+ workReceiptsSettle.getAct().getComment();
        }
        //yes 的时候状态为审核通过 否则为未通过
        //1 审核中 2 未通过
        workReceiptsSettle.setState(("yes".equals(workReceiptsSettle.getAct().getFlag()) ? ProjectStatusEnum.IN_APRL.getValue() : ProjectStatusEnum.REJECTED.getValue()));
        Map<String, Object> vars = Maps.newHashMap();
        //业务逻辑对应的条件表达式
        String exp = "";
        String taskCount = "";
        String notifyRole = "";
        int key = 0;
        String enname = "";
        int type = 1;
        List<Activity> activitieList = activityService.getByProcessInstanceId(workReceiptsSettle.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(workReceiptsSettle.getProcessInstanceId());
        List<WorkActivityProcess> workActivityProcesses = workActivityProcessService.findList(selectProcess);
        List<Activity> activities = workActivityMenu.getActivities();
        if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("receiptssettle")) {
            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(workReceiptsSettle.getAct().getFlag())) {
                        notifyRole = "调整收入结算";
                        workReceiptsSettle.setState(ProjectStatusEnum.REJECTED.getValue());
                        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 {
                        workActivityProcess.setIsApproval("1");
                    }
                }else if(taskDefKey.equals("modifyApply")){
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setId("");
                    workActivityProcess.setCount(0);
                    if (!"yes".equals(workReceiptsSettle.getAct().getFlag())) {
                        workReceiptsSettle.setState(ProjectStatusEnum.RECALL.getValue());
                        workActivityProcess.setIsApproval("2");
                    } else {
                        workActivityProcess.setIsApproval("1");
                    }
                    break;
                }
            }
        } else {
            workActivityMenu.setProcessType("receiptssettle");
            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 ("scfgld".equals(taskDefKey) && count.contains("1")) {
                    taskCount = "1";
                    exp = "pass";
                    if ("yes".equals(workReceiptsSettle.getAct().getFlag())) {
                        vars.put("fpglyList", auditUsers);
                        vars.put("fpglyCount",auditUsers.size());
                        workActivityProcessService.insertAuditsByType(auditUsers,workReceiptsSettle.getProcessInstanceId(),2,1);
                        notifyRole = "发票管理员审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "fpgly";
                        type=3;
                    } else {
                        notifyRole = "调整收入结算";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                } else if ("fpgly".equals(taskDefKey) && count.contains("2")) {
                    taskCount = "2";
                    exp = "pass";
                    if ("yes".equals(workReceiptsSettle.getAct().getFlag())) {
                        vars.put("cwzgList", auditUsers);
                        vars.put("cwzgCount",auditUsers.size());
                        workActivityProcessService.insertAuditsByType(auditUsers,workReceiptsSettle.getProcessInstanceId(),3,1);

                        notifyRole = "财务主管审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "cwzg";
                    } else {
                        notifyRole = "调整收入结算";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                } else if ("cwzg".equals(taskDefKey) && count.contains("3")) {
                    taskCount = "3";
                    exp = "pass";
                    if ("yes".equals(workReceiptsSettle.getAct().getFlag())) {
                        vars.put("zjlList", auditUsers);
                        vars.put("zjlCount",auditUsers.size());
                        workActivityProcessService.insertAuditsByType(auditUsers,workReceiptsSettle.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(workReceiptsSettle.getAct().getFlag())) {
                        vars.put("cwfgldList", auditUsers);
                        vars.put("cwfgldCount",auditUsers.size());
                        workActivityProcessService.insertAuditsByType(auditUsers,workReceiptsSettle.getProcessInstanceId(),5,1);

                        notifyRole = "财务分管领导审核";
                        workActivityProcess.setIsApproval("1");
                        enname = "cwfgld";
                    } else {
                        workActivityProcess.setIsApproval("2");
                        notifyRole = "调整收入结算";
                    }
                    break;
                } else if ("cwfgld".equals(taskDefKey) && count.contains("5")) {
                    taskCount = "5";
                    exp = "pass";
                    if ("yes".equals(workReceiptsSettle.getAct().getFlag())) {
                        vars.put("cnList", auditUsers);
                        vars.put("cnCount",auditUsers.size());
                        workActivityProcessService.insertAuditsByType(auditUsers,workReceiptsSettle.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(workReceiptsSettle.getAct().getFlag())) {
                        notifyRole = "审批通过";
                        workActivityProcess.setIsApproval("1");
                    } else {
                        notifyRole = "调整收入结算";
                        workActivityProcess.setIsApproval("2");
                    }
                    break;
                } else if ("modifyApply".equals(taskDefKey)&& count.contains("0")) {
                    notifyRole = "市场分管领导审批";
                    taskCount = "0";
                    exp = "pass";
                    workActivityProcess.setCount(0);
                    enname = "scfgld";
                    if (!"yes".equals(workReceiptsSettle.getAct().getFlag())) {
                        workReceiptsSettle.setState(ProjectStatusEnum.RECALL.getValue());
                    }
                    break;
                } else if ("apply_end".equals(taskDefKey)) {
                }

            }
        }
        // 设置意见
        workReceiptsSettle.getAct().setComment(("yes".equals(workReceiptsSettle.getAct().getFlag()) ? "[同意] " : "[驳回] ") + workReceiptsSettle.getAct().getComment());
        workReceiptsSettle.preUpdate();
        // 提交流程任务
        vars.put(exp, "yes".equals(workReceiptsSettle.getAct().getFlag()) ? true : false);
        vars.put("passs", true);
        workActivityProcessService.updateProcess(workActivityProcess,workActivityMenu,key,taskCount, workReceiptsSettle.getProcessInstanceId(),taskDefKey,"modifyApply", workReceiptsSettle.getAct().getFlag(),comment, activities);
        // 提交流程任务
        actTaskService.complete(workReceiptsSettle.getAct().getTaskId(), workReceiptsSettle.getAct().getProcInsId(), workReceiptsSettle.getAct().getComment(), vars);
        boolean state = actTaskService.isProcessEnd(workReceiptsSettle.getAct().getProcInsId());
        List<User> users = new ArrayList<>();
        List<User> userList = new ArrayList<>();
        if (!state) {
            String notifyStr = "结算单号："+workReceiptsSettle.getNum()+"，结算日期："+ DateUtils.formatDate(workReceiptsSettle.getCreateDate());
            users.add(workReceiptsSettle.getCreateBy());
            if ("yes".equals(workReceiptsSettle.getAct().getFlag())) {
                workReceiptsSettle.setState(ProjectStatusEnum.SIGNED.getValue());
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(workReceiptsSettle.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                workProjectNotifyService
                        .save(UtilNotify
                                .saveNotify(workReceiptsSettle.getId(),
                                        workReceiptsSettle.getCreateBy(),
                                        workReceiptsSettle.getCompany().getId(),
                                        title,
                                        notifyStr,
                                        "52",
                                        "0",
                                        "待通知",
                                        notifyRole));

            } else {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(workReceiptsSettle.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                if (ProjectStatusEnum.RECALL.getValue() != workReceiptsSettle.getState()){
                    workReceiptsSettle.setState(ProjectStatusEnum.REJECTED.getValue());
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(workReceiptsSettle.getId(),
                                            workReceiptsSettle.getCreateBy(),
                                            workReceiptsSettle.getCompany().getId(),
                                            title,
                                            notifyStr,
                                            "52",
                                            "0",
                                            "待通知",
                                            notifyRole));
                }
            }
            workActivityProcessService.deleteProcessIdAuditUsers(workReceiptsSettle.getProcessInstanceId());
        } else {
            if (StringUtils.isNotBlank(workActivityMenu.getProcessType()) && !workActivityMenu.getProcessType().equals("receiptssettle")) {
                WorkProjectNotify notify = new WorkProjectNotify();
                notify.setNotifyId(workReceiptsSettle.getId());
                userList = workProjectNotifyService.readByNotifyId(notify);
                //users.addAll(userList);
                WorkProjectNotify workProjectNotify = UtilNotify
                        .saveNotify(workReceiptsSettle.getId(),
                                new User(),
                                workReceiptsSettle.getCompany().getId(),
                                title,
                                str,
                                "52",
                                "0",
                                "待审批",
                                notifyRole);
                List<WorkProjectNotify> workProjectNotifys = activityService.getByFlagAndTaskDefKeyList(
                        activities,
                        workProjectNotify,
                        taskDefKey,
                        workReceiptsSettle.getAct().getFlag(),
                        taskCount,
                        workReceiptsSettle.getCreateBy(),
                        workReceiptsSettle.getOffice().getId(),
                        "7");
                for (WorkProjectNotify workProjectNotify1:workProjectNotifys){
                    users.add(workProjectNotify1.getUser());
                    workProjectNotify1.setId("");
                    workProjectNotify1.setIsNewRecord(false);
                    workProjectNotifyService.save(workProjectNotify1);
                }

            } else {
                if (!"yes".equals(workReceiptsSettle.getAct().getFlag())) {
                    WorkProjectNotify notify = new WorkProjectNotify();
                    notify.setNotifyId(workReceiptsSettle.getId());
                    userList = workProjectNotifyService.readByNotifyId(notify);
                    //users.addAll(userList);
                    workProjectNotifyService
                            .save(UtilNotify
                                    .saveNotify(workReceiptsSettle.getId(),
                                            workReceiptsSettle.getCreateBy(),
                                            workReceiptsSettle.getCompany().getId(),
                                            title,
                                            str,
                                            "52",
                                            "0",
                                            "重新申请",
                                            notifyRole));
                    users.add( workReceiptsSettle.getCreateBy());
                } else {
                    if (StringUtils.isNotBlank(enname)) {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workReceiptsSettle.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        //users.addAll(userList1);
                        WorkProjectNotify workProjectNotify = UtilNotify
                                .saveNotify(workReceiptsSettle.getId(),
                                        new User(),
                                        workReceiptsSettle.getCompany().getId(),
                                        title,
                                        str,
                                        "52",
                                        "0",
                                        "待审批",
                                        notifyRole);
//                        List<User> userLists = UserUtils.getByRoleActivityEnnames(enname, workReceiptsSettle.getOffice().getId(),"7", workReceiptsSettle.getCreateBy());
                        users.addAll(auditUsers);
                        for (User user1:auditUsers){
                            workProjectNotify.setUser(user1);
                            workProjectNotify.setId("");
                            workProjectNotify.setIsNewRecord(false);
                            workProjectNotifyService.save(workProjectNotify);
                            Map<String,Object> extras = new HashMap<>();
                            extras.put("type","7002");
                            extras.put("procDefKey","52");
                            if(enname.contains("cn")||enname.contains("fpgly")){
                                extras.put("type","7001");
                            }
                            extras.put("id",workProjectNotify.getId());
                            UserUtils.pushInfoToApp(title,str,extras,user1.getId());
                        }
                    }else {
                        WorkProjectNotify notify = new WorkProjectNotify();
                        notify.setNotifyId(workReceiptsSettle.getId());
                        userList = workProjectNotifyService.readByNotifyId(notify);
                        users.add(workReceiptsSettle.getCreateBy());
                        workProjectNotifyService
                                .save(UtilNotify
                                        .saveNotify(workReceiptsSettle.getId(),
                                                workReceiptsSettle.getCreateBy(),
                                                workReceiptsSettle.getCompany().getId(),
                                                title,
                                                str,
                                                "52",
                                                "0",
                                                "重新申请",
                                                notifyRole));
                    }
                }
            }
        }
        if (StringUtils.isNotBlank(title) && users!=null && users.size()!=0) {
            for (User u : users) {
                UserUtils.pushIm(u.getId(),title);
            }
        }
        if (StringUtils.isNotBlank(title) && userList!=null && userList.size()!=0) {
            for (User u : userList) {
                UserUtils.pushMeIm(u.getId());
            }
        }
        dao.update(workReceiptsSettle);
        return "保存审核意见成功！";
    }

    private void updateInfo(WorkReceiptsSettle workReceiptsSettle) {
        if(workReceiptsSettle.getSettleDetailList()!=null){
            for (WorkReceiptsSettleDetail settleDetail : workReceiptsSettle.getSettleDetailList()) {
                settleDetail.setSettleId(workReceiptsSettle.getId());
                if(settleDetail.getIsNewRecord()){
                    //修改发票结算状态
                    settleDetail.getInvoice().setSettleFlag("1");
                    invoiceDetailService.updateSettleFlag(settleDetail.getInvoice());
                }
                if("1".equals(settleDetail.getDelFlag())){
                    settleDetail.getInvoice().setSettleFlag("0");
                    invoiceDetailService.updateSettleFlag(settleDetail.getInvoice());
                    settleDetailService.delete(settleDetail);
                }else {
                    settleDetailService.save(settleDetail);
                }
            }
        }
        //保存子公司发票明细
        if(workReceiptsSettle.getSettleInvoiceList()!=null){
            for (WorkReceiptsSettleInvoice settleInvoice : workReceiptsSettle.getSettleInvoiceList()) {
                settleInvoice.setSettleId(workReceiptsSettle.getId());
                if("1".equals(settleInvoice.getDelFlag())){
                    settleInvoiceService.delete(settleInvoice);
                }else {
                    settleInvoiceService.save(settleInvoice);
                }
            }
        }
    }

    @Transactional(readOnly = false)
    public void updateStateById(WorkReceiptsSettle workReceiptsSettle) {
        dao.updateProcessIdAndStatus(workReceiptsSettle);
    }

    @Transactional(readOnly = false)
    public void cancelProcess(WorkReceiptsSettle workReceiptsSettle) throws Exception {

        WorkActivityProcess process = new WorkActivityProcess();
        process.setProcessInstanceId(workReceiptsSettle.getProcessInstanceId());
        process.setIsApproval("0");
        //List<WorkActivityProcess> processList1 = workActivityProcessService.findByProcInsId(process);
        WorkActivityProcess workActivityProcess = new WorkActivityProcess();
        workActivityProcess.setProcessInstanceId(workReceiptsSettle.getProcessInstanceId());
        List<WorkActivityProcess> processList = workActivityProcessService.findList(workActivityProcess);
        WorkProjectNotify notify = new WorkProjectNotify();
        notify.setNotifyId(workReceiptsSettle.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()+",收入结算编号:"+workReceiptsSettle.getNum() +" 强制撤销!\"," +
                            "\"useType\":\"sys\"}";
                    ChatServerPool.sendMessageToUser(toUserConn, message);//同时向本人发送消息
                    //ChatServerPool.sendMessageToUser(toUserConn, u.getId() + "_sys_审批信息 " + "报销人:" + user.getName() + ",报销编号:" + workReimbursement.getNumber() + " 强制撤销!");//同时向本人发送消息
                }*/
                UserUtils.pushIm(u.getId(),"申请人:"+ user.getName()+",收入结算编号:"+workReceiptsSettle.getNum() +" 强制撤销!");
            }
        }
        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);

            //结束该流程,设为"撤销"状态月
            WorkReceiptsSettle receiptsSettle = new WorkReceiptsSettle();
            workReceiptsSettle.setId(workReceiptsSettle.getId());
            workReceiptsSettle.setState(ProjectStatusEnum.RECALL.getValue());
            workReceiptsSettle.setProcessInstanceId(workReceiptsSettle.getProcessInstanceId());
            workReceiptsSettle.preUpdate();
            this.updateStateById(workReceiptsSettle);
            actTaskService.endProcessInstance(workReceiptsSettle.getProcessInstanceId(), "收入结算-撤回");
        }
    }

    public boolean validateInvoiceNum(String invoiceNum, String comId,String id) {
        int cou = dao.countByInvoiceNumAndComp(invoiceNum,comId,id);
        if(cou>0){
            return true;
        }
        cou = invoiceDetailService.countByNumAndComp(invoiceNum,comId);
        if(cou>0){
            return true;
        }
        cou = invoiceReturnService.countByNumAndComp(invoiceNum,comId);
        if(cou>0){
            return true;
        }
        return false;
    }
}