package com.yeejoin.amos.boot.module.common.biz.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.workflow.feign.WorkflowFeignService;
import com.yeejoin.amos.boot.module.common.api.dto.CurrentStatusDto;
import com.yeejoin.amos.boot.module.common.api.dto.FailureDetailsDto;
import com.yeejoin.amos.boot.module.common.api.dto.FailureRepairlogDto;
import com.yeejoin.amos.boot.module.common.api.dto.StatusDto;
import com.yeejoin.amos.boot.module.common.api.entity.FailureDetails;
import com.yeejoin.amos.boot.module.common.api.entity.FailureRepairlog;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.api.entity.SourceFile;
import com.yeejoin.amos.boot.module.common.api.enums.FailureStatuEnum;
import com.yeejoin.amos.boot.module.common.api.mapper.FailureDetailsMapper;
import com.yeejoin.amos.boot.module.common.api.service.IFailureAuditService;
import com.yeejoin.amos.boot.module.common.api.service.IFailureDetailsService;
import com.yeejoin.amos.boot.module.common.api.service.IFailureRepairlogService;
import com.yeejoin.amos.boot.module.common.biz.constats.Constants;

/**
 * 服务实现类
 *
 * @author system_generator
 * @date 2021-08-04
 */
@Service
public class FailureDetailsServiceImpl extends BaseService<FailureDetailsDto, FailureDetails, FailureDetailsMapper>
        implements IFailureDetailsService {

    @Autowired
    SourceFileServiceImpl sourceFileServiceImpl;

    @Autowired
    WorkflowFeignService workflowFeignService;

    @Value("${failure.work.flow.processDefinitionKey:malfunction_repair}")
    private String processDefinitionKey;

    @Autowired
    FailureAuditServiceImpl failureAuditServiceImpl;

    @Autowired
    IFailureAuditService failureAuditService;

    @Autowired
    FailureRepairlogServiceImpl failureRepairlogService;

    @Autowired
    IFailureRepairlogService failureRepairlog;

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

    @Autowired
    FailureMaintainServiceImpl failureMaintainService;

    @Autowired
    FailureAuditServiceImpl ifailureAuditService;

    public static String EMERGENCY_COMMAND = "应急指挥科";
    public static String[] PROCESS_NAME = {"提交报修单", "审核", "维修", "验收", "维修中"};
    public static Integer SELECY_ALL = 6;
    public static Integer SELECY_STATUS = 7;
    public static Integer SELECY_ISUBMIT = 8;
    public static Integer SELECY_ACCEPT = 9;
    public String[] roleName = {"maintenance_department_maintenance_personnel", "emergency_command_staff", "emergency_command_leader", "maintenance_department"};

    /**
     * 分页查询接口
     *
     * @param type          查询类型
     * @param currentStatus 状态
     * @param startTime     起始时间
     * @param startTime     结束时间
     * @param userId        用户id
     */
    public IPage<FailureDetails> queryForFailureDetailsPage(Page<FailureDetails> page, ReginParams userInfo, Long currentStatus,
                                                            String startTime, String endTime, Integer userId, Integer type) {
        //当传递类型参数为全部查询时
        if (type.equals(SELECY_ALL)) {

            List<FailureDetails> list = this.baseMapper.selectAllPage(page.getCurrent(), page.getSize(), currentStatus, startTime, endTime, userId);
            IPage<FailureDetails> iPage = new Page<>();
            iPage.setRecords(list);
            return iPage;
        }
        //当传递类型参数为我提交时
        if (type.equals(SELECY_ISUBMIT)) {
            List<FailureDetails> list = baseMapper.selectISubPage(page.getCurrent(), page.getSize(), currentStatus, startTime, endTime, Integer.parseInt(userInfo.getUserModel().getUserId()));
            IPage<FailureDetails> iPage = new Page<>();
            iPage.setRecords(list);
            return iPage;
        }
        //当传递类型参数为我接收时
        if (type.equals(SELECY_ACCEPT)) {
            //当角色为维修人员时
            if (userInfo.getRole().getRoleName().equals(roleName[0])) {
                List<FailureDetails> failureDetails = baseMapper.selectForMaintain(currentStatus, startTime, endTime, userId, userInfo.getUserModel().getUserId(), page.getCurrent(), page.getSize());
                IPage<FailureDetails> iPage = new Page<>();
                iPage.setRecords(failureDetails);
                return iPage;

            } else if (userInfo.getRole().getRoleName().equals(roleName[2]) || userInfo.getRole().getRoleName().equals(roleName[3])) {
                List<FailureDetails> failureDetails = baseMapper.selectForAudit(currentStatus, startTime, endTime, userId, userInfo.getUserModel().getUserId(), page.getCurrent(), page.getSize());

                IPage<FailureDetails> iPage = new Page<>();
                iPage.setRecords(failureDetails);
                return iPage;
            } else {
                List<FailureDetails> failureDetails = baseMapper.selectYJ(currentStatus, startTime, endTime, userInfo.getUserModel().getUserId(), page.getCurrent(), page.getSize());

                IPage<FailureDetails> iPage = new Page<>();
                iPage.setRecords(failureDetails);
                return iPage;
            }
        }
        //否则就查询待处理
        return this.queryForWaitManage(page, userInfo, currentStatus, startTime, endTime, userId);
    }

    /**
     * web端列表查询
     */
    public IPage<FailureDetailsDto> queryForPageList(Page<FailureDetailsDto> page, ReginParams userInfo, Long currentStatus,
                                                     String startTime, String endTime, String submissionName, Long submissionBranchId,
                                                     Long sequenceNbr) {
        List<FailureDetailsDto> list = baseMapper.selectWebPage(page.getCurrent(), page.getSize(), currentStatus, startTime, endTime, submissionName, submissionBranchId, sequenceNbr);

        IPage<FailureDetailsDto> iPage = new Page<>();
        iPage.setRecords(list);
        iPage.setTotal(baseMapper.selectAllCount());
        return iPage;
    }

    /**
     * 待处理分页查询
     */
    public IPage<FailureDetails> queryForWaitManage(Page<FailureDetails> page, ReginParams userInfo, Long currentStatus,
                                                    String startTime, String endTime, Integer userId) {

        if (userInfo.getRole().getRoleName().equals(roleName[0])) {
            IPage<FailureDetails> wxIpage = new Page<FailureDetails>();
            List<FailureDetails> list = baseMapper.selectStatusWaitWx(page.getCurrent(), page.getSize(), currentStatus, startTime, endTime, userId);
            wxIpage.setRecords(list);
            return wxIpage;
        } else if (userInfo.getRole().getRoleName().equals(roleName[1])) {
            currentStatus = FailureStatuEnum.WAITING_SUBMIT.getCode().longValue();
            List<FailureDetails> list = baseMapper.selectStatusWaitTj(page.getCurrent(), page.getSize(), currentStatus, startTime, endTime, userId);
            IPage<FailureDetails> iPage = new Page<>();
            iPage.setRecords(list);
            return iPage;
        }
        List<FailureDetails> list = baseMapper.selectInProcessing(page.getCurrent(), page.getSize(), currentStatus, startTime, endTime, userId);
        IPage<FailureDetails> iPage = new Page<>();
        iPage.setRecords(list);
        return iPage;
    }


    /**
     * 根据状态查询
     */

    public FailureDetailsDto queryForOne(Long sequenceNbr) {
        FailureDetailsDto failureDetailsDto = this.queryBySeq(sequenceNbr);
        failureDetailsDto
                .setCurrentStatusName(Constants.currentStatusNameMap.get(failureDetailsDto.getCurrentStatus()));
        List<SourceFile> sourceFiles = sourceFileServiceImpl.findBySourceId(sequenceNbr);
        failureDetailsDto.setAttachment(sourceFiles);
        return failureDetailsDto;
    }

    /**
     * 根据状态查询
     */
    public List<FailureDetails> queryForFailureStatus(Long currentStatus) {
        String status = "";
        List<FailureStatuEnum> list = new ArrayList<>();
        list.add(FailureStatuEnum.WAITING_AUDIT);
        list.add(FailureStatuEnum.WAITING_SUBMIT);
        list.add(FailureStatuEnum.WAITING_MAINTAIN);
        list.add(FailureStatuEnum.WAITING_ACCEPTANCE);
        list.add(FailureStatuEnum.REFUSE);
        list.add(FailureStatuEnum.FINISH);
        for (int i = 0; i < list.size(); i++) {
            if (currentStatus.equals(list.get(i).getCode())) {
                status = list.get(i).getName();
            }
        }
        QueryWrapper<FailureDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("current_status", status).orderByDesc("submission_time");
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 查询任务状态数量
     */
    public List<CurrentStatusDto> queryStatusCount(ReginParams userInfo, Integer type, Long currentStatus, String startTime, String endTime, Integer userId) {
        List<StatusDto> statusDtos = null;
        if (type.equals(SELECY_STATUS) && userInfo.getRole().getRoleName().equals(roleName[0])) {
            statusDtos = baseMapper.selectStatusWx(currentStatus, startTime, endTime, userId);
        } else if (type.equals(SELECY_STATUS) && userInfo.getRole().getRoleName().equals(roleName[1])) {
            statusDtos = baseMapper.selectStatusFq(currentStatus, startTime, endTime, userId);
        } else if (type.equals(SELECY_ISUBMIT)) {
            statusDtos = baseMapper.selectStatusFqp(currentStatus, startTime, endTime, Integer.parseInt(userInfo.getUserModel().getUserId()));
        } else if (type.equals(SELECY_ALL)) {
            statusDtos = baseMapper.selectStatusCount(currentStatus, startTime, endTime, userId);
        } else if (type.equals(SELECY_ACCEPT)) {
            if (userInfo.getRole().getRoleName().equals(roleName[2]) || userInfo.getRole().getRoleName().equals(roleName[3])){
                statusDtos = baseMapper.selectAudit(currentStatus, startTime, endTime, userId, userInfo.getUserModel().getUserId());
            }else if (userInfo.getRole().getRoleName().equals(roleName[0])){
                statusDtos = baseMapper.selectMaintain(currentStatus, startTime, endTime, userId, userInfo.getUserModel().getUserId());
            }else {
                statusDtos = baseMapper.selectUserId(currentStatus, startTime, endTime, userInfo.getUserModel().getUserId());
            }
        } else {
            statusDtos = baseMapper.selectStatusLeader(currentStatus, startTime, endTime, userId);
        }
        List<CurrentStatusDto> currentStatusDtoList = new ArrayList<>();
        statusDtos.forEach(e -> {
            CurrentStatusDto currentStatusDto = new CurrentStatusDto();
            currentStatusDto.setCutrentStatusCount(e.getCurrentStatusCount());
            currentStatusDto.setCutrentStatusName(Constants.currentStatusNameMap.get(e.getCurrentStatus()));
            currentStatusDtoList.add(currentStatusDto);
        });
        return currentStatusDtoList;
    }

    /**
     * 发起故障保修单
     *
     * @throws Exception
     */
    @Transactional
    public Object savemodel(FailureDetailsDto failureDetailsDto, ReginParams userInfo) throws Exception {
        if (null != failureDetailsDto.getSequenceNbr()) {
            return updatetoModel(failureDetailsDto, userInfo);
        }

        String businessKey = buildOrderNo();
        JSONObject body = new JSONObject();
        body.put("businessKey", businessKey);
        body.put("processDefinitionKey", processDefinitionKey);
        JSONObject jsonObject = workflowFeignService.startByVariable(body);
        if (jsonObject == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            // return CommonResponseUtil.failure("启动流程失败");
        }
        JSONObject instance = jsonObject.getJSONObject("data");
        if (instance == null) {
            // return CommonResponseUtil.failure("无提交隐患权限");
        }
        failureDetailsDto.setCurrentStatus(FailureStatuEnum.WAITING_AUDIT.getCode());
        // 拿到流程processId
        failureDetailsDto.setProcessId(instance.getString("id"));
        FailureDetailsDto model = null;

        // 发起主表流程 并添加至报修日志
        failureDetailsDto.setSubmissionTime(new Date());
        failureDetailsDto.setFailureCode(buildOrderNo());

        String parentId = iOrgUsrService.getParentId(userInfo.getUserModel().getUserId());
        if (parentId != null){
            failureDetailsDto.setBizCode(Long.valueOf(parentId));
        }
        OrgUsr orgUsr = iOrgUsrService.getById(parentId);


        model = this.createWithModel(failureDetailsDto);

        if (ObjectUtils.isNotEmpty(failureDetailsDto.getAttachment())) {
            sourceFileServiceImpl.saveSourceFile(failureDetailsDto.getSequenceNbr(),
                    failureDetailsDto.getAttachment());
        }
        // 添加至报修日志
        Long faultId = model.getSequenceNbr();
        Integer processAuditorId = model.getSubmissionPid();
        String processResult = "提交报修单";


        String processDepartment = orgUsr.getBizOrgName();
        Long departmentId = failureDetailsDto.getBizCode();
        Date processTime = model.getSubmissionTime();
        String processAuditorName = failureDetailsDto.getSubmissionName();
        repairlog(faultId, processAuditorId, departmentId, processTime, processDepartment, processResult, processAuditorName);

        if (excuteTask(instance.getString("id"), userInfo, null)) {

            return true;
        } else {
            throw new Exception("执行流程失败");
        }

    }

    /**
     * 更新故障保修单
     */

    public Object updatetoModel(FailureDetailsDto failureDetailsDto, ReginParams userInfo) throws Exception {

        // 发起主表流程 并添加至报修日志
        failureDetailsDto.setSubmissionTime(new Date());
        failureDetailsDto.setCurrentStatus(FailureStatuEnum.WAITING_AUDIT.getCode());
        FailureDetailsDto model = this.updateWithModel(failureDetailsDto);

        if (ObjectUtils.isNotEmpty(failureDetailsDto.getAttachment())) {
            sourceFileServiceImpl.saveSourceFile(failureDetailsDto.getSequenceNbr(),
                    failureDetailsDto.getAttachment());
        }
        // 添加至报修日志
        Long faultId = model.getSequenceNbr();
        Integer processAuditorId = model.getSubmissionPid();
        String processResult = "重新提交报修单";
        String processDepartment = userInfo.getDepartment().getDepartmentName();
        Long departmentId = failureDetailsDto.getBizCode();
        Date processTime = model.getSubmissionTime();
        String processAuditorName = failureDetailsDto.getSubmissionName();
        repairlog(faultId, processAuditorId, departmentId, processTime, processDepartment, processResult, processAuditorName);
        if (excuteTask(failureDetailsDto.getProcessId(), userInfo, null)) {
            return true;
        } else {
            throw new Exception("执行流程失败");
        }

    }

    /**
     * 添加报修日志
     */
    @Transactional
    public Boolean repairlog(Long faultId, Integer processAuditorId, Long departmentId,
                             Date processTime, String processDepartment, String processResult, String processAuditorName) {
        FailureRepairlogDto failureRepairlogDto = new FailureRepairlogDto();
        failureRepairlogDto.setFaultId(faultId);
        failureRepairlogDto.setProcessAuditorId(processAuditorId);
        failureRepairlogDto.setProcessDepartmentId(departmentId);
        failureRepairlogDto.setProcessTime(processTime);
        failureRepairlogDto.setProcessDepartment(processDepartment);
        failureRepairlogDto.setProcessResult(processResult);
        failureRepairlogDto.setProcessAuditorName(processAuditorName);
        FailureRepairlogDto repairlogModel = failureRepairlogService.createWithModel(failureRepairlogDto);
        if (ObjectUtils.isNotEmpty(repairlogModel)) {
            return true;
        }
        return false;
    }

    @Transactional
    public boolean excuteTask(Long sequenceNbr, ReginParams userInfo, String condition) throws Exception {
        HashMap<String, Object> conditionMap = new HashMap<String, Object>();
        conditionMap.put("condition", Integer.parseInt(condition));
        Map<String, Object> map = checkExcuteTaskAuthMap(sequenceNbr, userInfo);
        if (Boolean.parseBoolean(map.get("checkFlag").toString())) {
            if (map.get("name").toString().startsWith(PROCESS_NAME[4])) {
                workflowFeignService.completeNoExecuteFromInstanceAdd(map.get("taskId").toString(), conditionMap);

            } else {
                workflowFeignService.pickupAndCompleteTask(map.get("taskId").toString(), conditionMap);
            }
            // 判断下一个节点是不是维修中,如果是则添加当前任务的执行人
            String nextTaskId = checkIsInMaintenance(sequenceNbr);
            if (nextTaskId != null) {
                workflowFeignService.pickuptask(nextTaskId);
            }
        }
        return true;
    }

    /**
     * 已经存在的操作人的任务执行，用于维修中节点完成任务
     *
     * @param sequenceNbr
     * @param userInfo
     * @return
     */
    public boolean excuteTaskOnlyOperation(Long sequenceNbr, ReginParams userInfo) {
        Map<String, Object> map = checkExcuteTaskAuthMap(sequenceNbr, userInfo);
        try {

            if (Boolean.parseBoolean(map.get("checkFlag").toString())
                    && map.get("checkFlag").toString().startsWith(PROCESS_NAME[4])) {
                workflowFeignService.completeByVariable(map.get("taskId").toString(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean excuteTask(String procressId, ReginParams userInfo, String condition) throws Exception {
        HashMap<String, Object> conditionMap = new HashMap<String, Object>();
        conditionMap.put("condition", condition);
        JSONObject teskObject = workflowFeignService.getTaskList(procressId);
        if (ObjectUtils.isNotEmpty(teskObject)) {
            JSONArray taskDetailArray = teskObject.getJSONArray("data");
            for (Object obj : taskDetailArray) {
                JSONObject detail = JSONObject.parseObject(JSONObject.toJSONString(obj));
                workflowFeignService.pickupAndCompleteTask(detail.getString("id"), conditionMap);
            }
        }
        return true;
    }

    public Object getNextTaskGroupName(String procressId) {
        JSONObject teskObject = workflowFeignService.getTaskList(procressId);
        JSONArray taskDetailArray = teskObject.getJSONArray("data");
        String currentRoleName = "";
        for (Object obj : taskDetailArray) {
            JSONObject detail = JSONObject.parseObject(JSONObject.toJSONString(obj));
            JSONObject taskGroupNameObject = workflowFeignService.getTaskGroupName(detail.getString("id"));
            for (Object object : taskGroupNameObject.getJSONArray("data")) {
                JSONObject taskGroupNameDetail = JSONObject.parseObject(JSONObject.toJSONString(object));
                currentRoleName = currentRoleName + taskGroupNameDetail.getString("groupId") + ",";
            }
        }
        return currentRoleName;
    }

    public boolean checkExcuteTaskAuth(Long sequenceNbr, ReginParams userInfo) {
        Map<String, Object> map = this.checkExcuteTaskAuthMap(sequenceNbr, userInfo);
        return Boolean.parseBoolean(map.get("checkFlag").toString());
    }

    public String checkIsInMaintenance(Long sequenceNbr) {
        FailureDetails details = this.baseMapper.selectById(sequenceNbr);
        String procressId = details.getProcessId();
        JSONObject teskObject = workflowFeignService.getTaskList(procressId);
        if (ObjectUtils.isNotEmpty(teskObject)) {
            JSONArray taskDetailArray = teskObject.getJSONArray("data");
            for (Object obj : taskDetailArray) {
                JSONObject detail = JSONObject.parseObject(JSONObject.toJSONString(obj));
                String name = detail.getString("name");
                if (name.startsWith(PROCESS_NAME[4])) {
                    String id = detail.getString("id");
                    return id;
                }
            }
        }
        return null;
    }

    public Map<String, Object> checkExcuteTaskAuthMap(Long sequenceNbr, ReginParams userInfo) {
        // 获取当前登录用户的角色
        String currentLoginUserRole = null;
   //     String currentLoginUserRole = userInfo.getRole().getRoleName();

        if (userInfo.getUserModel().getOrgNames().contains(roleName[0])) {
            currentLoginUserRole = roleName[0];
        }else      if (userInfo.getUserModel().getOrgNames().contains(roleName[1])) {
            currentLoginUserRole = roleName[1];
        }else      if (userInfo.getUserModel().getOrgNames().contains(roleName[2])) {
            currentLoginUserRole = roleName[2];
        }else      if (userInfo.getUserModel().getOrgNames().contains(roleName[3])) {
            currentLoginUserRole = roleName[3];
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("checkFlag", false);
        FailureDetailsDto failureDetailsDto = this.queryBySeq(sequenceNbr);
        // 获取送达部门的ID
        Long failureEquipmentId = failureDetailsDto.getSubmissionBranchId();
        FailureDetails details = this.baseMapper.selectById(sequenceNbr);
        String procressId = details.getProcessId();
        Long seq = Long.valueOf(iOrgUsrService.getParentId(userInfo.getUserModel().getUserId()));
        JSONObject teskObject = workflowFeignService.getTaskList(procressId);
        if (ObjectUtils.isNotEmpty(teskObject)) {
            JSONArray taskDetailArray = teskObject.getJSONArray("data");
            for (Object obj : taskDetailArray) {
                JSONObject detail = JSONObject.parseObject(JSONObject.toJSONString(obj));
                String name = detail.getString("name");
                JSONObject taskGroupNameObject = workflowFeignService.getTaskGroupName(detail.getString("id"));
                // 获取流程中原本设置的当前节点的执行权限
                JSONArray taskGroupNameDetail = taskGroupNameObject.getJSONArray("data");
                // 如果拿不到当前任务的执行角色，则返回校验失败
                if (ObjectUtils.isEmpty(taskGroupNameDetail)) {
                    continue;
                }
                String defaultExecutionRoleProcess = taskGroupNameDetail.getJSONObject(0).getString("groupId");
                // 判断当前登录人的角色是不是与流程中设置的当前任务节点权限一致，一致则执行，不一致则退出
                if (!defaultExecutionRoleProcess.equals(currentLoginUserRole)) {
                    continue;
                }
                // 当流程节点为应急指挥科时，需要判断当前用户所在的部门id和前面处理的用户部门id是否一致
                if (name.contains(EMERGENCY_COMMAND)) {
                    FailureRepairlog failureRepairlog = failureRepairlogService.findByFaultId(sequenceNbr);
                    Long auditDepartmentId = failureRepairlog.getProcessDepartmentId();
                    if (auditDepartmentId.intValue() == seq.intValue()) {
                        map.put("taskId", detail.getString("id"));
                        map.put("checkFlag", true);
                        map.put("name", detail.getString("name"));
                        break;
                    }
                } else {
                    // 判断当前节点任务属于送达部门节点时需要判断当前登录人所在的部门id是否与表单发起时设置的送达部门一致
                    if (failureEquipmentId.intValue() == seq.intValue()) {
                        map.put("taskId", detail.getString("id"));
                        map.put("checkFlag", true);
                        map.put("name", detail.getString("name"));
                        break;
                    }
                }
            }
        }
        return map;
    }

    /**
     * 獲取待處理的任務數量
     *
     * @param userInfo
     * @return
     */
    public int getPendingCount(ReginParams userInfo) {
        int countNum = 0;
        // 获取当前登录人的部门id
        Long seq = userInfo.getDepartment().getSequenceNbr();
        // 获取同角色信息的我的待办任务
        JSONObject taskListJson = workflowFeignService.getTasksNoAuth(processDefinitionKey,
                userInfo.getUserModel().getUserId());
        JSONArray taskList = JSONArray.parseArray(JSONObject.toJSONString(taskListJson.getString("data")));
        for (Object i : taskList) {
            JSONObject task = JSONObject.parseObject(JSONObject.toJSONString(i));
            String procressId = task.getString("processInstanceId");
            // 通过流程ID查找当前的故障报修表ID 的信息
            LambdaQueryWrapper<FailureDetails> wrapper = new LambdaQueryWrapper<FailureDetails>();
            wrapper.eq(FailureDetails::getProcessId, procressId);
            FailureDetails failureDetails = this.baseMapper.selectOne(wrapper);
            // 通过故障报修单查找创建人的部门ID
            FailureRepairlog failureRepairlog = failureRepairlogService.findByFaultId(failureDetails.getSequenceNbr());
            // 再去判断当前的任务节点信息是不是维修部门，是的话将于第一次填报保单的操作人部门id进行匹配，符合将视作为一条合法的待办任务
            if (task.getString("name").contains(EMERGENCY_COMMAND)) {
                Long auditDepartmentId = failureRepairlog.getProcessDepartmentId();
                if (auditDepartmentId.intValue() == seq.intValue()) {
                    countNum++;
                    break;
                }
            } else {
                // 判断当前节点任务属于送达部门节点时需要判断当前登录人所在的部门id是否与表单发起时设置的送达部门一致
                if (failureDetails.getFailureEquipmentId().intValue() == seq.intValue()) {
                    countNum++;
                    break;
                }
            }
        }
        return countNum;
    }

    public Object getCurrentProcessHistoryTask(Long id) {
        FailureDetailsDto failureDetailsDto = this.queryBySeq(id);
        String processId = failureDetailsDto.getProcessId();
        JSONObject object = workflowFeignService.queryHistoryTaskListByProcessId(processId);
        JSONArray datArray = null;
        if (ObjectUtils.isNotEmpty(object)) {
            datArray = object.getJSONArray("data");
        }

        List<Object> list = new ArrayList<Object>();
        if (datArray != null) {
            for (Object i : datArray) {
                JSONObject detail = JSONObject.parseObject(JSONObject.toJSONString(i));
                if (detail.containsKey("operator") && !detail.getString("name").contains("维修中")) {
                    // 从流程记录表中拿到处理人的名称
                    FailureRepairlog failureRepairlog = failureRepairlogService
                            .findByprocessAuditor(detail.getString("operator"));
                    if (failureRepairlog != null) {
                        detail.replace("operator", failureRepairlog.getProcessAuditorName() == null ? ""
                                : failureRepairlog.getProcessAuditorName());
                    }
                }
                list.add(detail);
            }
        }
        return list;
    }

    public static String buildOrderNo() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }

    /**
     * 获取当前登录人能够操作的任务执行Button类型
     *
     * @param sequenceNbr
     * @param userInfo
     * @return
     */
    public Integer getExcuteTaskAuthButton(Long sequenceNbr, ReginParams userInfo) {
        int flag = 0;
        Map<String, Object> map = this.checkExcuteTaskAuthMap(sequenceNbr, userInfo);
        if (Boolean.parseBoolean(map.get("checkFlag").toString())) {
            String buttonValueString = map.get("name").toString();
            if (buttonValueString.endsWith(PROCESS_NAME[0])) { // 提交维修单
                flag = 1;
            } else if (buttonValueString.endsWith(PROCESS_NAME[1])) { // 审核
                flag = 2;
                if (buttonValueString.startsWith(PROCESS_NAME[2])) {
                    flag = 3;
                }
            } else if (buttonValueString.endsWith(PROCESS_NAME[2])) {// 维修
                flag = 4;
            } else if (buttonValueString.endsWith(PROCESS_NAME[3])) {// 验收
                flag = 5;
            }
        }
        FailureDetails details = this.baseMapper.selectById(sequenceNbr);
        JSONObject object = workflowFeignService.queryHistoryTasksByProcessInstanceId(details.getProcessId());
        JSONArray array = object.getJSONArray("rows");
        for (Object historyDetail : array) {
            JSONObject historyDetailJson = JSONObject.parseObject(JSONObject.toJSONString(historyDetail));
            if ("rejected".equals(historyDetailJson.getString("activityId"))) {
                flag = 6;
            }
        }
        return flag;
    }

    public Object getCurrentTask(Long sequenceNbr) {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();
        JSONArray taskDetailArray = null;
        FailureDetails details = this.baseMapper.selectById(sequenceNbr);
        String procressId = details.getProcessId();
        JSONObject teskObject = workflowFeignService.getTaskList(procressId);
        if (ObjectUtils.isNotEmpty(teskObject)) {
            taskDetailArray = teskObject.getJSONArray("data");
            for (Object obj : taskDetailArray) {
                JSONObject detail = JSONObject.parseObject(JSONObject.toJSONString(obj));

                String name = detail.getString("name");
                Map<String, String> map = new HashMap<String, String>();
                map.put("name", name);
                if (name.startsWith(PROCESS_NAME[4])) {
                    String id = detail.getString("id");
                    JSONObject assignObject = workflowFeignService.getTaskAssign(id);
                    JSONObject resultObject = assignObject.getJSONObject("data");
                    if (resultObject != null) {
                        map.put("name", "维修部门维修人员 维修");
                        if (detail.containsKey("informerList")) {
                            JSONArray informerList = detail.getJSONArray("informerList");
                            if (informerList != null && informerList.size() > 0) {
                                for (Object informerDetail : informerList) {
                                    JSONObject informerDetailJson = JSONObject
                                            .parseObject(JSONObject.toJSONString(informerDetail));
                                    if (informerDetailJson.getString("userName")
                                            .equals(resultObject.getString("assignee"))) {
                                        map.put("assignee", informerDetailJson.getString("realName"));
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                list.add(map);
            }
        }
        return list;
    }
}