/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.maintain.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tofly.api.DepartmentClient;
import com.tofly.api.GdglinfoClient;
import com.tofly.api.UserClent;
import com.tofly.api.UserTaskClient;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.auth.ToflyUser;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.es.GpsUpload;
import com.tofly.es.PdaDeviceUpload;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.*;
import com.tofly.gpsboot.mapper.comm.AuditMapper;
import com.tofly.gpsboot.mapper.maintain.RepairrecordMapper;
import com.tofly.gpsboot.mapper.maintain.RepairuserMapper;
import com.tofly.gpsboot.mapper.plan.CheckhistoryMapper;
import com.tofly.gpsboot.service.comm.IAuditService;
import com.tofly.gpsboot.service.comm.IDisposeDateService;
import com.tofly.gpsboot.service.paln.CheckhistoryService;
import com.tofly.gpsboot.util.WordUtil;
import com.tofly.pojo.comm.Audit;
import com.tofly.pojo.comm.vo.AuditVo;
import com.tofly.pojo.comm.vo.ImageVo;
import com.tofly.pojo.maintain.dto.RepairorderDto;
import com.tofly.pojo.maintain.dto.RepairuserChildDto;
import com.tofly.pojo.maintain.vo.*;
import com.tofly.pojo.maintain.vo.datail.*;
import com.tofly.pojo.message.Usertask;
import com.tofly.pojo.plan.Checkhistory;
import com.tofly.pojo.plan.dto.TaskMessageDto;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.maintain.RepairorderMapper;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.es.IGpsUploadService;
import com.tofly.gpsboot.service.maintain.*;
import com.tofly.gpsboot.service.mq.IPlanMessageService;
import com.tofly.gpsboot.service.sign.PdasignService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.pojo.Department;
import com.tofly.pojo.User;
import com.tofly.pojo.maintain.*;
import com.tofly.pojo.plan.Pdasign;
import com.tofly.pojo.plan.vo.CheckhistoryVo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jxls.util.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 抢维修工单信息表
 *
 * @author admin
 * @date Tue Apr 06 00:00:00 CST 2021
 */
@Service("repairorderService")
@Slf4j
public class RepairorderServiceImpl extends ServiceImpl<RepairorderMapper, Repairorder> implements RepairorderService {

    @Autowired
    private RepairtypeService repairtypeService;

    @Autowired
    private RepairuserService repairuserService;

    @Autowired
    private RepairplandetailService repairplandetailService;

    @Autowired
    private IFileInfoService iFileInfoService;
    @Value("${xrty.ftp.repairOrder}")
    private String repairOrderFilePath;

    @Autowired
    private UserClent userClent;

    @Autowired
    private DepartmentClient departmentClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IPlanMessageService iPlanMessageService;

    @Autowired
    private RepairrecordService repairrecordService;

    @Autowired
    private RepairrebutService repairrebutService;

    @Autowired
    private RepairrelayService repairrelayService;

    @Autowired
    private PdasignService pdasignService;

    @Autowired
    private IGpsUploadService iGpsUploadService;
    @Autowired
    private IDisposeDateService iDisposeDateService;
    @Autowired
    private GdglinfoClient gdglinfoClient;
    @Autowired
    private IAuditService iAuditService;
    @Autowired
    private PipeMfRecordService pipeMfRecordService;

    @Autowired
    private RepairorderMapper repairorderMapper;

    @Autowired
    private RepairrecordMapper repairrecordMapper;
    @Autowired
    private RepairgoodsService repairgoodsService;

    @Autowired
    private RepairrejectService repairrejectService;
    @Autowired
    private CheckhistoryService checkhistoryService;

    @Autowired
    private RepairuserMapper repairuserMapper;
    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private CheckhistoryMapper checkhistoryMapper;
    @Autowired
    private UserTaskClient userTaskClient;

    @Override
    public List<RepairorderVo> viewConversion(List<Repairorder> infoList) {
        List<RepairorderVo> planVoList = new ArrayList<>();
        infoList.forEach(info -> {
            RepairorderVo baseInfo = JSON.parseObject(JSON.toJSONString(info), RepairorderVo.class);
            // 工单来源/维修类型/是否查看/是否驳回/是否转发/工单状态/年计划派工人/是否自动派工
            baseInfo.setOrderSource(OrderSourceEnum.getCodeForValue(info.getOrderSource()));
            baseInfo.setIsread(IsReadEnum.getCodeForValue(info.getIsread()));
            baseInfo.setIsrebut(IsRejectedEnum.getCodeForValue(info.getIsrebut()));
            baseInfo.setIsrelay(IsForwardingEnum.getCodeForValue(info.getIsrelay()));
            baseInfo.setState(OrderStateEnum.getCodeForValue(info.getState()));
            baseInfo.setIsDispatching(IsDispatchingEnum.getCodeForValue(info.getIsDispatching()));
            baseInfo.setArtificialEndFlagName(IsArtificialEndFlagEnum.getCodeForValue(info.getArtificialEndFlag()));
            baseInfo.setMaintenanceFlagName(IsRespectEnum.getCodeForValue(info.getMaintenanceFlag()));

            // 返回审核链信息
            List<Audit> list = iAuditService.list(new QueryWrapper<Audit>().lambda().eq(Audit::getAuditPlanId, info.getId()).eq(Audit::getAuditType, AuditTypeEnum.AUDIT_TYPE_REPAIR_RECORD.getCode()));
            if (null != list && list.size() > 0) {
                Audit audit = list.get(0);
                User result1 = userClent.getById(audit.getAuditUser()).getResult();
                if (null != result1) {
                    baseInfo.setAuditUserName(result1.getRealName());
                }
                baseInfo.setAuditTime(audit.getAuditTime());
                baseInfo.setAuditNote(WordUtil.transform(audit.getAuditNote()));
                baseInfo.setAuditSate(AuditSateEnum.getCodeForValue(audit.getAuditState()));
            }
            baseInfo.setDispatchingId(info.getDispatchingId());
            baseInfo.setAddress(WordUtil.transform(info.getAddress()));
            baseInfo.setUnit(WordUtil.transform(info.getUnit()));
            baseInfo.setNotes(WordUtil.transform(info.getNotes()));
            planVoList.add(baseInfo);
        });
        return planVoList;
    }


    public Page<RepairorderVo> getRepairOrderPage_Old(Page page, RepairorderDto parDto) {
        Date signStartTime = parDto.getStartTime();
        Date signEndTime = parDto.getEndTime();
        Repairorder repairOrder = JSONObject.parseObject(JSON.toJSONString(parDto), Repairorder.class);

        QueryWrapper<Repairorder> queryWrapper = new QueryWrapper<>();
        if (null != signStartTime) {
            queryWrapper.ge("START_TIME", signStartTime);
            repairOrder.setStartTime(null);

        }
        if (null != signEndTime) {
            queryWrapper.le("END_TIME", signEndTime);
            repairOrder.setEndTime(null);
        }
        String state = parDto.getState();
        if (!StringUtils.isEmpty(state)) {
            List<String> stateList = Arrays.stream(state.split(Constant.CSV)).map(String::trim)
                    .collect(Collectors.toList());
            queryWrapper.in("STATE", stateList);
            repairOrder.setState(null);
        }
        String orderCode = parDto.getOrderCode();
        if (!StringUtils.isEmpty(orderCode)) {
            queryWrapper.like("ORDER_CODE", orderCode);
            repairOrder.setOrderCode(null);
        }

        String address = parDto.getAddress();
        if (!StringUtils.isEmpty(address)) {
            queryWrapper.like("ADDRESS", address);
            repairOrder.setAddress(null);
        }
        if (!StringUtils.isEmpty(parDto.getFlag())) {
            // 获取对应用户下子计划的工单列表id
            Set<Long> collect = repairuserService.list(new QueryWrapper<Repairuser>().lambda().eq(Repairuser::getRespUser, SecurityUtils.getUserId())).stream().map(Repairuser::getRepairId).collect(Collectors.toSet());
            if (collect.size() > 0) {
                queryWrapper.in("ID", collect);
            } else {
                queryWrapper.in("ID", 0);
            }
        } else {
            Long dispatchingId = parDto.getDispatchingId();
            if (null != dispatchingId) {
                queryWrapper.eq("DISPATCHING_ID", dispatchingId);
            } else {
                // 当前部门下用户才有权限
                Long departmentId = SecurityUtils.getUser().getDepartmentId();
                Set<Long> userIdList = departmentClient.getDeptUserList(departmentId).getResult().stream().map(User::getId).collect(Collectors.toSet());
                queryWrapper.in("DISPATCHING_ID", userIdList);
            }
        }
        queryWrapper.setEntity(repairOrder);
        queryWrapper.orderByDesc("CREATE_TIME");
        Page infoPageList = this.page(page, queryWrapper);
        infoPageList.setRecords(this.viewConversion(infoPageList.getRecords()));
        return infoPageList;



    }

    @Override
    public Page<RepairorderVo> getRepairOrderPage(Page page, RepairorderDto parDto) {

        // 工单处理审核历史查询条件
        if(!"1".equals(parDto.getRecordAuditFlag())){
            Long executorId = parDto.getExecutorId();
            Long executorDeptId = parDto.getExecutorDeptId();
            Long dispatchingId = parDto.getDispatchingId();
            if (null == dispatchingId) {
                // 获取查询用户处理列表
                String deptUsers = iDisposeDateService.getDeptUsers(executorId, executorDeptId);
                Set<Long> userIdList = Arrays.stream(deptUsers.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toSet());
                parDto.setUserIdList(userIdList);
            }
        }
      if(StringUtil.isNotEmpty(parDto.getFlag()) && parDto.getFlag().equals("1")){
          Set<Long> userIdList=new HashSet<>();
          userIdList.clear();
          userIdList.add(SecurityUtils.getUserId());
          parDto.setUserIdList(userIdList);
      }
        Page infoPageList = baseMapper.getPageRepairInfo(page,parDto);
        infoPageList.setRecords(this.viewConversion(infoPageList.getRecords()));
        return infoPageList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Repairorder savaPlanInfo(List<MultipartFile> fileList, RepairorderDto parDto) throws BusinessException {
        StringBuilder fileIdList = new StringBuilder("");
        // 判断当前是否有文件,则存入返回文件id
        if (null != fileList && fileList.size() > 0) {
            fileIdList = iFileInfoService.saveFileList(fileList, repairOrderFilePath, FileTableEnum.TF_YWPN_REPAIRORDER_W.getTableName());

        }
        Repairorder plan = JSON.parseObject(JSON.toJSONString(parDto), Repairorder.class);
        // 生成工单编码
        Long userId = SecurityUtils.getUserId();
        if(StringUtils.isEmpty(parDto.getOrderCode())){
            plan.setOrderCode(this.sendOrderCode(userId));
        }

        // 根据文件id反射填充对象
        if (!StringUtils.isEmpty(fileIdList.toString())) {
            plan.setFileIds(fileIdList.toString());
        }

        //  判断当前对象是否派发对象,若当前需要派发 修改当前工单状态 为 未开始
        String isDispatching = parDto.getIsDispatching();
        if (IsDispatchingEnum.IS_DISPATCHING_YES.getCode().equals(isDispatching)) {
            plan.setState(OrderStateEnum.ORDER_STATE_NOT_START.getCode());
            // 赋值派工人为当前创建对象
           // plan.setDispatchingId(userId);
        }
        plan.setDispatchingId(userId);
        this.save(plan);
        if (OrderSourceEnum.ORDER_SOURCE_HOTLINE.getCode().equals(parDto.getOrderSource())) {
            Long dispatchingId = parDto.getDispatchingId();
            plan.setCreateUser(dispatchingId);
            plan.setDispatchingId(dispatchingId);
            this.updateById(plan);
        }
        // 1.新增到 抢维修工单个人任务信息表
        List<RepairuserChildDto> repairUserChildDtoList = parDto.getRepairUserChildDtoList();
        if (null != repairUserChildDtoList && repairUserChildDtoList.size() > 0) {
            log.info("抢维修工单个人任务信息:{}", JSON.toJSONString(repairUserChildDtoList));
            this.addRepairUserList(plan, repairUserChildDtoList, IsDispatchingEnum.IS_DISPATCHING_YES.getCode().equals(isDispatching));
        }

        // 处理派发逻辑
        if (IsDispatchingEnum.IS_DISPATCHING_YES.getCode().equals(isDispatching)) {
            this.dispatching(plan);
        }
        return plan;
    }

    /**
     * 新增处理多个个人任务
     *
     * @param repairUserChildDtoList
     * @return
     */
    @Override
    public void addRepairUserList(Repairorder plan, List<RepairuserChildDto> repairUserChildDtoList, Boolean flag) {
        repairUserChildDtoList.forEach(info -> {
            Repairuser repairUser = JSON.parseObject(JSON.toJSONString(info), Repairuser.class);
            repairUser.setRepairId(plan.getId());
            if (flag) {
                repairUser.setState(OrderStateEnum.ORDER_STATE_NOT_START.getCode());
            } else {
                repairUser.setState(OrderStateEnum.ORDER_STATE_NOT_WORK.getCode());
            }

            repairuserService.save(repairUser);
        });

    }

    @Override
    public boolean dispatching(Repairorder repairorder) {
        // 派工处理
        List<Repairorder> repairorderList = new ArrayList<>();
        repairorderList.add(repairorder);
        TaskMessageDto taskMessageDto = new TaskMessageDto();
        taskMessageDto.setRepairOrderList(repairorderList);
        // 2.抢维修任务发送
        iPlanMessageService.orderSendMessage(JSON.toJSONString(taskMessageDto));
        return true;
    }

    @Override
    public RepairOrderDetailVo getPlanInfo(Long id, String flag) throws BusinessException {
        RepairOrderDetailVo detailVo = new RepairOrderDetailVo();
        Repairorder order = this.getById(id);

        // 个人工单信息
        List<RepairuserVo> repairOrderUserInfoList = this.getRepairOrderUserInfo(id, flag);

        detailVo.setRepairUserVoList(repairOrderUserInfoList);
        // 工单/派工信息
        List<Repairorder> repairOrderList = new ArrayList<>();
        repairOrderList.add(order);
        detailVo.setRepairorderVo(this.viewConversion(repairOrderList).get(0));
        // 工单处理/审核列表信息
        if (null != repairOrderUserInfoList && repairOrderUserInfoList.size() > 0) {
            Set<Long> collect = repairOrderUserInfoList.stream().map(RepairuserVo::getId).collect(Collectors.toSet());
            // 工单养护信息
            detailVo.setPipeMfRecordList(this.getPipeMfRecordList(collect));
            // 工单维修处理信息
            detailVo.setRepairRecordVoList(this.getRepairRecordVoList(collect));
            // 驳回列表信息
            detailVo.setRepairRebutVoList(this.getRepairRebutVoList(collect));
            // 转发列表信息
            detailVo.setRepairRelayVoList(this.getRepairRelayVoList(collect));
        }


        return detailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePlanInfo(List<MultipartFile> fileList, RepairorderDto parDto) throws BusinessException {
        if (iDisposeDateService.isDisposePermissions(parDto.getCreateUser()) || iDisposeDateService.isDisposePermissions(parDto.getDispatchingId())) {

            // 对已下发未开始的临时任务，可对其巡检任务内容进行修改。计划性任务不可修改。
            String state = parDto.getState();
//        String orderSource = parDto.getOrderSource();
//        if (OrderSourceEnum.ORDER_SOURCE_PLAN.getCode().equals(orderSource)) {
//            throw new BusinessException(Constant.TASK_REPAIR_ORDER_YEAR_NOT_UPDATE_CODE, Constant.TASK_REPAIR_ORDER_YEAR_NOT_UPDATE);
//        }
            if (!OrderStateEnum.ORDER_STATE_NOT_WORK.getCode().equals(state)) {
                throw new BusinessException(Constant.TASK_PLAN_NOT_UPDATE_CODE, Constant.TASK_PLAN_NOT_UPDATE);
            }

            Repairorder updateRecord = JSONObject.parseObject(JSON.toJSONString(parDto), Repairorder.class);
            List<Long> fileIdLongList = new ArrayList<>();
            if (null != fileList && fileList.size() > 0) {
                StringBuilder fileIdList = iFileInfoService.saveFileList(fileList, repairOrderFilePath, FileTableEnum.TF_YWPN_REPAIRORDER_W.getTableName());
                fileIdLongList = Arrays.stream(fileIdList.toString().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            }
            Repairorder record = this.getById(parDto.getId());
            String lostFileIds = record.getFileIds();
            String fileIds = parDto.getFileIds();
            List<Long> removeFileId = new ArrayList<>();
            List<Long> fileIdLongs = new ArrayList<>();

            if (!StringUtils.isEmpty(fileIds)) {
                fileIdLongs = Arrays.stream(fileIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
            }
            // 判断当前文件是否有更新
            if (!StringUtils.isEmpty(lostFileIds) && lostFileIds.equals(fileIds)) {
                List<Long> lostFileIdLongs = Arrays.stream(lostFileIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList());
                List<Long> finalFileIdLongs = fileIdLongs;
                lostFileIdLongs.forEach(lost -> {
                    if (!finalFileIdLongs.contains(lost)) {
                        removeFileId.add(lost);
                    }
                });
                // 删除对应文件数据
                if (removeFileId.size() > 0) {
                    // 删除远程文件
                    iFileInfoService.removeFileList(removeFileId);
                }
                if (lostFileIdLongs.size() > 0) {
                    // 删除远程文件
                    iFileInfoService.removeFileList(lostFileIdLongs);
                }

            }
            // 更新数据信息
            fileIdLongList.addAll(fileIdLongs);
            if (fileIdLongList.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder("");
                fileIdLongList.forEach(info -> {
                    stringBuilder.append(info).append(Constant.CSV);
                });
                updateRecord.setFileIds(stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString());
            }
            // 清空信息
            List<Long> idList = new ArrayList<>();
            idList.add(updateRecord.getId());
            this.clearRepairOrder(idList);
            // 走保存
            parDto.setFileIds(updateRecord.getFileIds());
            parDto.setOrderCode(record.getOrderCode());
            this.savaPlanInfo(null, parDto);
        } else {
            throw new BusinessException(Constant.IS_DISPOSE_PERMISSIONS_NULL_CODE, Constant.IS_DISPOSE_PERMISSIONS_NULL);
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePlanInfo(List<Long> idList) throws BusinessException {
        // 对已下发未开始的临时任务，可对其巡检任务内容进行删除。计划性任务不可删除。
        List<Repairorder> list = this.list(new QueryWrapper<Repairorder>().lambda().in(Repairorder::getId, idList));
        list.forEach(info -> {
            if (!iDisposeDateService.isDisposePermissions(info.getCreateUser())) {
                throw new BusinessException(Constant.IS_DISPOSE_PERMISSIONS_NULL_CODE, Constant.IS_DISPOSE_PERMISSIONS_NULL);

            }
            String state = info.getState();
            String orderSource = info.getOrderSource();
            if (PlanTypeEnum.PLAN_TYPE_MONTH.getCode().equals(orderSource)) {
                throw new BusinessException(Constant.TASK_REPAIR_ORDER_YEAR_NOT_DELETE_CODE, Constant.TASK_REPAIR_ORDER_YEAR_NOT_DELETE);
            }
            if (!OrderStateEnum.ORDER_STATE_NOT_WORK.getCode().equals(state)) {
                throw new BusinessException(Constant.TASK_PLAN_NOT_DELETE_CODE, Constant.TASK_PLAN_NOT_DELETE);
            }

        });
        this.clearRepairOrder(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Repairorder> generateRepairOrder(Long yearId) {
        // 获取抢维修年计划详情
        List<Repairplandetail> repairPlanDetailList = repairplandetailService.list(new QueryWrapper<Repairplandetail>().lambda().eq(Repairplandetail::getYearId, yearId));
        List<Repairorder> resultOrderList = new ArrayList<>();
        if (null != repairPlanDetailList && repairPlanDetailList.size() > 0) {
            repairPlanDetailList.forEach(info -> {
                Repairorder order = new Repairorder();
                order.setYearId(info.getYearId());
                order.setMonth(info.getMonth());
                order.setOrderSource(OrderSourceEnum.ORDER_SOURCE_PLAN.getCode());
                order.setOrderCode(sendOrderCode(SecurityUtils.getUserId()));
                order.setTypeId(info.getTypeId());
                order.setNum(info.getNum());
                order.setDispatchingId(info.getRespUser());
                order.setNotes(info.getNotes());
                this.save(order);
                resultOrderList.add(order);
                //加入默认处理人为派工人，否则工单查询里面找不到对应的数据
                List<RepairuserChildDto> repairUserChildDtoList=new ArrayList<>();
                RepairuserChildDto repairuserChildDto=new RepairuserChildDto();
                repairuserChildDto.setRespUser(info.getRespUser());
                repairuserChildDto.setPlanNum(info.getNum());
                repairUserChildDtoList.add(repairuserChildDto);
                this.addRepairUserList(order,repairUserChildDtoList,false);

            });
        } else {
            throw new BusinessException(Constant.TASK_REPAIR_ORDER_YEAR_NOT_NULL_CODE, Constant.TASK_REPAIR_ORDER_YEAR_NOT_NULL);
        }
        return resultOrderList;
    }

    @Override
    public Boolean orderRejected(Long repairOrderId, String notes) {
        // 处理人接收到抢维修工单时，认为此工单不是本部门处理工单，可以在进入到工单处理页面进行工单驳回，驳回时填写驳回原因说明，驳回成功后以消息提示工单派发人，派发人可重新进行派发。
        Repairorder repairOrder = this.getById(repairOrderId);
        // 当前工单来源不是热线则不能驳回
        if (OrderSourceEnum.ORDER_SOURCE_HOTLINE.getCode().equals(repairOrder.getOrderSource())) {
            // 判断当前工单状态是否是处于已完成、驳回、转发,若是则不能驳回
            if (OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode().equals(repairOrder.getState())
                    && OrderStateEnum.ORDER_STATE_REJECTED.getCode().equals(repairOrder.getState())
                    && OrderStateEnum.ORDER_STATE_BEEN_TRANSFERRED.getCode().equals(repairOrder.getState())) {
                throw new BusinessException(Constant.TASK_REPAIR_ORDER_EXECUTION_PROCESSED_CODE, Constant.TASK_REPAIR_ORDER_EXECUTION_PROCESSED);
            }
            // 判断当前用户是否已经提交过工单处理,若已提交则不允许驳回
            List<Repairuser> repairUserList = repairuserService.list(new QueryWrapper<Repairuser>().lambda().eq(Repairuser::getRepairId, repairOrderId));
            //  1.删除当前工单下的个人工单信息 2.修改工单是否驳回状态为 1 是 工单状态修改为 6 驳回 3.给工单派发人发送消息驳回信息
            if (null != repairUserList && repairUserList.size() > 0) {
                Set<Long> collect = repairUserList.stream().map(Repairuser::getId).collect(Collectors.toSet());
                // 有效数据
                List<Repairrecord> repairRecordList = repairrecordService.list(new QueryWrapper<Repairrecord>().lambda().in(Repairrecord::getRepairUserid, collect).eq(Repairrecord::getFlag, "1"));
                List<PipeMfRecord> pipeMfRecordList = pipeMfRecordService.list(new QueryWrapper<PipeMfRecord>().lambda().in(PipeMfRecord::getRepairUserId, collect).eq(PipeMfRecord::getFlag, "1"));
                if (null != repairRecordList && repairRecordList.size() > 0) {
                    throw new BusinessException(Constant.TASK_REPAIR_ORDER_PROCESSED_CODE, Constant.TASK_REPAIR_ORDER_PROCESSED);
                } else if (null != pipeMfRecordList && pipeMfRecordList.size() > 0) {
                    throw new BusinessException(Constant.TASK_REPAIR_ORDER_PROCESSED_CODE, Constant.TASK_REPAIR_ORDER_PROCESSED);
                }
            }
            repairOrder.setIsrebut(IsRejectedEnum.IS_REJECTED_YES.getCode());
            repairOrder.setState(OrderStateEnum.ORDER_STATE_REJECTED.getCode());
            // 抢维修任务待办清除
            // 待办事项处理
            Usertask usertask = new Usertask();
            usertask.setTableName(MessageTopicEnum.TASK_PLAN_MAINTENANCE_ORDER.getTableName());
            usertask.setTableId(repairOrderId);
            List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
            if (null != result && result.size() > 0) {
                result.forEach(task->{
                    task.setHandleTime(new Date());
                    task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                    userTaskClient.updateById(task);
                });

            }
            this.updateById(repairOrder);
            // 新增驳回记录
            Repairreject repairreject = new Repairreject();
            repairreject.setRepairId(repairOrderId);
            repairreject.setRejectTime(DateTimeUtil.convertLDTToDate(LocalDateTime.now()));
            repairreject.setRejectNote(notes);
            repairreject.setRejectUserId(SecurityUtils.getUserId());
            repairrejectService.save(repairreject);
            iPlanMessageService.orderRejectedSendMessage(repairOrder, notes);
            // 回调工单
            if (OrderSourceEnum.ORDER_SOURCE_HOTLINE.getCode().equals(repairOrder.getOrderSource())) {
                // 调用工单回调驳回接口
                Boolean aBoolean = gdglinfoClient.gdGdUpdateState(String.valueOf(repairOrderId), 0).getResult();
                log.info("调用工单回调驳回接口工单id: {},是否成功: {}", repairOrderId, aBoolean);
            }
        } else {
            throw new BusinessException(Constant.TASK_REPAIR_ORDER_HOTLINE_CODE, Constant.TASK_REPAIR_ORDER_HOTLINE);
        }
        return true;
    }

    @Override
    public Boolean orderForwarding(Long repairOrderId, Long forwardingUserId, String notes) {
        // 处理人接收到抢维修工单时，由于其他的事不能及时处理，可转发给同部门下的人员进行处理。进入到工单处理页面进行工单转发，转发时填写转接处理人、转发原因说明，转发成功后以消息提示转接处理人，以便及时查收处理。
        Repairorder repairOrder = this.getById(repairOrderId);
        // 判断当前工单状态是否是处于已完成、驳回、转发,若是则不能转发
        if (OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode().equals(repairOrder.getState())
                && OrderStateEnum.ORDER_STATE_REJECTED.getCode().equals(repairOrder.getState())
                && OrderStateEnum.ORDER_STATE_BEEN_TRANSFERRED.getCode().equals(repairOrder.getState())) {
            throw new BusinessException(Constant.TASK_REPAIR_ORDER_EXECUTION_FORWARDING_PROCESSED_CODE, Constant.TASK_REPAIR_ORDER_EXECUTION_FORWARDING_PROCESSED);
        }
        // 判断当前用户是否已经提交过工单处理,若已提交则不允许转发
        List<Repairuser> repairUserList = repairuserService.list(new QueryWrapper<Repairuser>().lambda().eq(Repairuser::getRepairId, repairOrderId));
        //  1.修改当前工单下的个人工单为转发人 2.修改工单是否转发状态为 1 是 工单状态修改为 8 已转移 3.给工单派发人发送消息转发信息
        if (null != repairUserList && repairUserList.size() > 0) {
            Repairuser repairuser = repairUserList.get(0);
            Long aLong = repairuser.getId();
            Long respUser = repairuser.getRespUser();
            List<Repairrecord> repairRecordList = repairrecordService.list(new QueryWrapper<Repairrecord>().lambda().eq(Repairrecord::getRepairUserid, aLong));
            if (null != repairRecordList && repairRecordList.size() > 0) {
                throw new BusinessException(Constant.TASK_REPAIR_ORDER_FORWARDING_PROCESSED_CODE, Constant.TASK_REPAIR_ORDER_FORWARDING_PROCESSED);
            }
            repairuser.setRespUser(forwardingUserId);
            repairuserService.updateById(repairuser);

            // 抢维修任务待办清除
            // 待办事项处理
            Usertask usertask = new Usertask();
            usertask.setTableName(MessageTopicEnum.TASK_PLAN_MAINTENANCE_ORDER.getTableName());
            usertask.setHandleUser(respUser);
            usertask.setTableId(repairOrderId);
            List<Usertask> result = userTaskClient.getUserTaskInfo(usertask).getResult();
            if (null != result && result.size() > 0) {
                result.forEach(task->{
                    task.setHandleTime(new Date());
                    task.setIshandle(UserTaskStateEnumEnum.IS_HANDLER_COMPLETED.getCode());
                    userTaskClient.updateById(task);
                });

            }
            repairOrder.setIsrelay(IsForwardingEnum.IS_FORWARDING_YES.getCode());
            repairOrder.setState(OrderStateEnum.ORDER_STATE_BEEN_TRANSFERRED.getCode());
            this.updateById(repairOrder);

            iPlanMessageService.orderForwardingSendMessage(repairOrder, forwardingUserId, notes);
        }

        return true;
    }

    /**
     * 删除对应工单任务
     *
     * @param orderList
     */
    private void clearRepairOrder(List<Long> orderList) {
        // 删除当前工单信息
        // 删除个人任务信息
        this.removeByIds(orderList);
        repairuserService.remove(new QueryWrapper<Repairuser>().lambda().in(Repairuser::getRepairId, orderList));
    }

    /**
     * 根据抢维修工单上报id/用户id获取抢维修个人信息
     *
     * @param repairId
     * @param flag
     * @return
     */
    private List<RepairuserVo> getRepairOrderUserInfo(Long repairId, String flag) {
        Set<Long> longSet = new HashSet<>();
        ToflyUser user = SecurityUtils.getUser();
        // 若flag为空则查询当前用户下所属部门的所有子任务
        if (IsOverEnum.IS_OVER_NO.getCode().equals(flag)) {
            Long departmentId = user.getDepartmentId();
            Set<Long> collect = departmentClient.getDeptUserList(departmentId).getResult().stream().map(User::getId).collect(Collectors.toSet());
            longSet.addAll(collect);
        } else {
            longSet.add(user.getUserid());
        }

        return repairuserService.viewConversion(repairuserService.list(new QueryWrapper<Repairuser>().lambda().eq(Repairuser::getRepairId, repairId).in(Repairuser::getRespUser, longSet)));
    }


    /**
     * 根据个人工单信息获取养护处理记录
     *
     * @param collect
     * @return
     */
    private List<PipeMfRecord> getPipeMfRecordList(Set<Long> collect) {
        return pipeMfRecordService.list(new QueryWrapper<PipeMfRecord>().lambda().in(PipeMfRecord::getRepairUserId, collect));
    }

    /**
     * 根据个人工单信息获取工单处理记录
     *
     * @param collect
     * @return
     */
    private List<RepairrecordVo> getRepairRecordVoList(Set<Long> collect) {
        List<Repairrecord> list = repairrecordService.list(new QueryWrapper<Repairrecord>().lambda().in(Repairrecord::getRepairUserid, collect));
        return repairrecordService.viewConversion(list);
    }

    /**
     * 根据个人工单信息获取工单驳回信息
     *
     * @param collect
     * @return
     */
    private List<RepairrebutVo> getRepairRebutVoList(Set<Long> collect) {
        List<Repairrebut> list = repairrebutService.list(new QueryWrapper<Repairrebut>().lambda().in(Repairrebut::getRepairUserid, collect));
        return repairrebutService.viewConversion(list);
    }

    /**
     * 根据个人工单信息获取工单转发信息
     *
     * @param collect
     * @return
     */
    private List<RepairrelayVo> getRepairRelayVoList(Set<Long> collect) {
        List<Repairrelay> list = repairrelayService.list(new QueryWrapper<Repairrelay>().lambda().in(Repairrelay::getRepairUserid, collect));
        return repairrelayService.viewConversion(list);
    }

    /**
     * 根据年份Id,月份获取当前派工人
     *
     * @param yearId
     * @param month
     * @return
     */
    @Override
    public Long getDispatchingId(Long yearId, String month) {
        List<Repairplandetail> list = repairplandetailService.list(new QueryWrapper<Repairplandetail>().lambda().eq(Repairplandetail::getYearId, yearId).eq(Repairplandetail::getMonth, month));
        if (null != list && list.size() > 0) {
            return list.get(0).getRespUser();
        }
        return null;
    }

    @Override
    public List<AuxiliarySingleVo> getAuxiliarySingle(String deptIds) {
        List<AuxiliarySingleVo> voList = new ArrayList<>();
        // 获取当前用户下部门所有成员
        List<Long> userList = new ArrayList<>();
        Map<Long, Long> userDeptMap = new HashMap<>(12);
        Map<Long, String> deptMap = new HashMap<>(12);
        Map<Long, String> userIdNameMap = new HashMap<>(12);
        if(StringUtils.isEmpty(deptIds)){
            List<User> result = departmentClient.getDeptUserList(null).getResult();
            // 用户id为k,部门id为v
            userDeptMap.putAll(result.stream().collect(Collectors.toMap(User::getId, User::getDepartmentId, (key1, key2) -> key2)));
            deptMap.putAll(result.stream().collect(Collectors.toMap(User::getDepartmentId, User::getDepartmentName, (key1, key2) -> key2)));
            userList.addAll(result.stream().map(User::getId).collect(Collectors.toList()));
            userIdNameMap.putAll(result.stream().collect(Collectors.toMap(User::getId, User::getRealName, (key1, key2) -> key2)));

        }else {
            Set<Long> longList = Arrays.stream(deptIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toSet());
            longList.forEach(i->{
                List<User> result = departmentClient.getDeptUserList(i).getResult();
                if(null!=result && result.size()>0){
                    userDeptMap.putAll(result.stream().collect(Collectors.toMap(User::getId, User::getDepartmentId, (key1, key2) -> key2)));
                    deptMap.putAll(result.stream().collect(Collectors.toMap(User::getDepartmentId, User::getDepartmentName, (key1, key2) -> key2)));
                    userList.addAll(result.stream().map(User::getId).collect(Collectors.toList()));
                    userIdNameMap.putAll(result.stream().collect(Collectors.toMap(User::getId, User::getRealName, (key1, key2) -> key2)));
                }

            });
        }
        StringBuilder stringBuilder = new StringBuilder();
        userList.forEach(info -> {
            stringBuilder.append(info).append(Constant.CSV);
        });
        String users = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
        // 获取对应用户状态
        Map<Long, String> singTypeMap = pdasignService.list(new QueryWrapper<Pdasign>().lambda().in(Pdasign::getSignUser, userList)
                .select(Pdasign::getSignUser, Pdasign::getSignType)).stream().collect(Collectors.toMap(Pdasign::getSignUser, Pdasign::getSignType, (item1, item2) -> item2));

        // 获取今天上传gps过的数据用户信息
        List<GpsUpload> nowUserInfoList = iGpsUploadService.getNowUserInfoList(users, DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayBeginTime()), DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayEndTime()));
        nowUserInfoList.forEach(info -> {
            AuxiliarySingleVo vo = new AuxiliarySingleVo();
            vo.setUserId(info.getUserId());
            vo.setUserName(info.getUserName());
            vo.setDeptId(userDeptMap.get(info.getUserId()));
            vo.setDeptName(deptMap.get(userDeptMap.get(info.getUserId())));
            vo.setLgtd(info.getLocationLongitude());
            vo.setLttd(info.getLocationLatitude());
            String s = singTypeMap.get(info.getUserId());
            if(SignTypeEnum.SIGN_TYPE_YES.getCode().equals(s)){
                vo.setSingType(SignTypeEnum.SIGN_TYPE_YES.getValue());
            }
            if(SignTypeEnum.SIGN_TYPE_NO.getCode().equals(s)){
                vo.setSingType(SignTypeEnum.SIGN_TYPE_NO.getValue());
            }

            voList.add(vo);
        });
        // 要求没有今日签到的 不显示坐标但是要显示人员
        Map<Long, String> collect1 = voList.stream().collect(Collectors.
                toMap(AuxiliarySingleVo::getUserId, AuxiliarySingleVo::getUserName, (item1, item2) -> item1));

        userIdNameMap.forEach((k,v)->{
            if(!collect1.containsKey(k)){
                AuxiliarySingleVo vo = new AuxiliarySingleVo();
                vo.setUserId(k);
                vo.setUserName(v);
                vo.setDeptId(userDeptMap.get(k));
                vo.setDeptName(deptMap.get(userDeptMap.get(k)));
                vo.setSingType("离线");
                voList.add(vo);
            }
        });
        return voList;
    }



    @Override
    public List<AuxiliarySingleVo> getAuxiliarySingle(Long deptId,String flag) {
        List<AuxiliarySingleVo> voList = new ArrayList<>();
        List<Long> userList = new ArrayList<>();
        // 获取对应部门所有成员
        if("1".equals(flag)){
            List<User> result = departmentClient.getDeptUserList(null).getResult();
            userList =  result.stream().map(User::getId).collect(Collectors.toList());
        }else {
            Long departmentId = deptId==null?SecurityUtils.getUser().getDepartmentId():deptId;
            userList =  departmentClient.getDeptUserList(departmentId).getResult().stream().map(User::getId).collect(Collectors.toList());
        }
        StringBuilder stringBuilder = new StringBuilder();
        userList.forEach(info -> {
            stringBuilder.append(info).append(Constant.CSV);
        });
        String users = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
        // 获取用户对应名称列表map
        Map<Long, String> result = userClent.getUserIdNameMap(users).getResult();
        // 获取用户对应头像列表map
        ResultRespone<Map<Long, String>> userAvatarPathList = userClent.getUserAvatarPathList(users);
        Map<Long, String> avatarMap = userAvatarPathList.getResult();

        // 获取对应用户状态
        Map<Long, String> singTypeMap = pdasignService.list(new QueryWrapper<Pdasign>().lambda().in(Pdasign::getSignUser, userList)
                .select(Pdasign::getSignUser, Pdasign::getSignType)).stream().collect(Collectors.toMap(Pdasign::getSignUser, Pdasign::getSignType, (item1, item2) -> item2));

        // 获取今天上传gps过的数据用户信息
        List<GpsUpload> nowUserInfoList = iGpsUploadService.getNowUserInfoList(users, DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayBeginTime()), DateTimeUtil.convertLDTToDate(DateTimeUtil.getTodayEndTime()));
        nowUserInfoList.forEach(info -> {
            AuxiliarySingleVo vo = new AuxiliarySingleVo();
            vo.setUserId(info.getUserId());
            vo.setUserName(info.getUserName());
            vo.setLgtd(info.getLocationLongitude());
            vo.setLttd(info.getLocationLatitude());
            String s = singTypeMap.get(info.getUserId());
            if(SignTypeEnum.SIGN_TYPE_YES.getCode().equals(s)){
                vo.setSingType(SignTypeEnum.SIGN_TYPE_YES.getValue());
            }
            if(SignTypeEnum.SIGN_TYPE_NO.getCode().equals(s)){
                vo.setSingType(SignTypeEnum.SIGN_TYPE_NO.getValue());
            }

            vo.setPath(avatarMap.get(info.getUserId()));
            voList.add(vo);
        });
        // 要求没有今日签到的 不显示坐标但是要显示人员
        Map<Long, String> collect1 = voList.stream().collect(Collectors.
                toMap(AuxiliarySingleVo::getUserId, AuxiliarySingleVo::getUserName, (item1, item2) -> item1));

        result.forEach((k,v)->{
            String avatar = avatarMap.get(k)==null?"":avatarMap.get(k);
            if(!collect1.containsKey(k)){
                AuxiliarySingleVo vo = new AuxiliarySingleVo();
                vo.setUserId(k);
                vo.setUserName(v);
                vo.setPath(avatar);
                vo.setSingType("离线");
                voList.add(vo);
            }
        });
        return voList;
    }


    @Override
    public Boolean terminationRepairOrder(String orderId) {

        if (!StringUtils.isEmpty(orderId)) {
            Repairorder repairorder = this.getById(Long.valueOf(orderId));
            if (null != repairorder) {
                // 判断当前工单是否为热线类型工单 或者工单手动置为可结束
                if (OrderSourceEnum.ORDER_SOURCE_HOTLINE.getCode().equals(repairorder.getOrderSource()) || IsArtificialEndFlagEnum.IS_ARTIFICIAL_END_FLAG_YES.getCode().equals(repairorder.getArtificialEndFlag())) {
                    // 抢维修工单已完成不能终止
                    if (!OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode().equals(repairorder.getState())) {
                        repairorder.setState(OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode());
                        // 对应个人任务状态也更改
                        List<Repairuser> list = repairuserService.list(new QueryWrapper<Repairuser>().lambda().in(Repairuser::getRepairId, orderId));
                        if (null != list && list.size() > 0) {
                            list.forEach(info -> {
                                info.setState(OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode());
                            });
                            repairuserService.updateBatchById(list);
                        }
                        this.updateById(repairorder);
                        return true;
                    } else {
                        throw new BusinessException(Constant.TASK_REPAIR_ORDER_COMPLETE_HOTLINE_CODE, Constant.TASK_REPAIR_ORDER_COMPLETE_HOTLINE);
                    }
                } else {
                    throw new BusinessException(Constant.TASK_REPAIR_ORDER_TERMINATION_HOTLINE_CODE, Constant.TASK_REPAIR_ORDER_TERMINATION_HOTLINE);
                }
            } else {
                throw new BusinessException(Constant.TASK_REPAIR_ORDER_NULL_HOTLINE_CODE, Constant.TASK_REPAIR_ORDER_NULL_HOTLINE);
            }

        } else {
            throw new BusinessException(Constant.TASK_REPAIR_ORDER_NULL_HOTLINE_CODE, Constant.TASK_REPAIR_ORDER_NULL_HOTLINE);

        }
    }


    @Override
    public RepairOrderDetailNewVo getRepairOrderDetailNewVo(Long orderId) {
        RepairOrderDetailNewVo vo = new RepairOrderDetailNewVo();
        Repairorder repairOrder = this.getById(orderId);
        if (null == repairOrder) {
            throw new BusinessException(Constant.TASK_REPAIR_ORDER_NULL_HOTLINE_CODE, Constant.TASK_REPAIR_ORDER_NULL_HOTLINE);
        }

        // 获取抢维修基础信息
        RepairOrderBaseInfoVo repairOrderBaseInfo = repairorderMapper.getRepairOrderBaseInfo(orderId);
        String state = repairOrderBaseInfo.getState();
        // 节点(1工单登记2维修/保养处理3维修审核4归档)
        vo.setNode("1");
        // 处理中/驳回状态
        if (OrderStateEnum.ORDER_STATE_BEING_PERFORMED.getCode().equals(state) || OrderStateEnum.ORDER_STATE_REJECTED.getCode().equals(state)) {
            vo.setNode("2");
        } else if (OrderStateEnum.ORDER_STATE_NOT_AUDIT.getCode().equals(state)) {
            vo.setNode("3");
        } else if (OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode().equals(state)) {
            // 判断当前工单状态是否为完成 4
            vo.setNode("4");
        }
        // 获取抢维修对应的用户个人工单
//        List<Repairuser> repairuserList = repairuserService.list(new QueryWrapper<Repairuser>().lambda().eq(Repairuser::getRepairId, orderId));
        List<RepairuserVo> repairuserVos = repairuserMapper.getrepairuserVoList(orderId);
        // 获取地址(解析)
        if (null != repairuserVos && repairuserVos.size() > 0) {
            repairOrderBaseInfo.setRepairUserVoList(repairuserVos);
            List<String> collect = repairuserVos.stream().map(RepairuserVo::getLngLats).filter(lngLats -> !StringUtils.isEmpty(lngLats)).collect(Collectors.toList());
            List<OrderAddressVo> orderAddresses = new ArrayList<>();
            if (collect.size() > 0) {
                collect.forEach(str -> {
                    orderAddresses.addAll(JSONArray.parseArray(str, OrderAddressVo.class));

                });
                repairOrderBaseInfo.setAddressVoList(orderAddresses);
            }

        }
        vo.setBaseInfoVo(repairOrderBaseInfo);
        // 判断当前工单是否为热线工单 orderSource 2为热线
        String orderSource = repairOrder.getOrderSource();
        if (OrderSourceEnum.ORDER_SOURCE_HOTLINE.getCode().equals(orderSource)) {
            vo.setHotlineInfoVo(repairorderMapper.getRepairOrderHotlineInfoVo(orderId));
            vo.setRepairRejectList(repairrejectService.list(new QueryWrapper<Repairreject>().lambda().eq(Repairreject::getRepairId, orderId)));
        }
        // 判断当前工单 为  维修/保养 maintenanceFlag 0否 1是
        String maintenanceFlag = repairOrder.getMaintenanceFlag();
        if (IsDispatchingEnum.IS_DISPATCHING_NO.getCode().equals(maintenanceFlag)) {
            List<RepairOrderRecordInfoVo> repairRecordInfo = repairrecordMapper.getRepairRecordInfo(orderId);
            if (!CollectionUtils.isEmpty(repairRecordInfo)) {
                repairRecordInfo.forEach(info -> {
                    if (null != info && info.getRecordId()!=null) {
                        Long recordId = info.getRecordId();
                        List<Repairgoods> list = repairgoodsService.list(new QueryWrapper<Repairgoods>().lambda().eq(Repairgoods::getRecordId, recordId));
                        info.setGoodsList(repairgoodsService.viewConversion(list));
                    }
                });
                repairRecordInfo.sort(Comparator.nullsLast(Comparator.comparing(RepairOrderRecordInfoVo::getCreateTime
                        ,Comparator.nullsLast(Comparator.comparing(e->e)))));
                vo.setRecordInfoVoList(repairRecordInfo);
            }

        } else {
            List<PipeMfRecord> list = pipeMfRecordService.list(new QueryWrapper<PipeMfRecord>().lambda().eq(PipeMfRecord::getOrderId, orderId));
            if (null != list && list.size() > 0) {
                List<PipeMfRecord> collect = list.stream().sorted(Comparator.comparing(PipeMfRecord::getCreateTime)).collect(Collectors.toList());
                vo.setPipeMfRecordList(collect);
            }
        }

        // 获取实时审核记录
        List<AuditVo> auditVoList = auditMapper.getAuditVoList(AuditTypeEnum.AUDIT_TYPE_REPAIR_RECORD.getCode(), orderId);
        List<Date> collect = auditVoList.stream().map(AuditVo::getAuditTime).collect(Collectors.toList());
        // 获取历史审核记录
        List<CheckhistoryVo> checkhistoryVos = checkhistoryMapper.getCheckHistoryVoList(AuditTypeEnum.AUDIT_TYPE_REPAIR_RECORD.getCode(), orderId);
        List<AuditVo> auditList = new ArrayList<>();
        List<AuditVo> hisAuditList = new ArrayList<>();
        if (null != checkhistoryVos && checkhistoryVos.size() > 0) {
            checkhistoryVos.forEach(info -> {
                AuditVo v = new AuditVo();
                v.setAuditNote(info.getAuditNotes());
                v.setAuditTime(info.getAuditTime());
                v.setAuditUser(info.getAuditUser());
                v.setAuditUserName(info.getAuditUserName());
                v.setAuditStateName(info.getAuditResultName());
                v.setAuditTimeStr(DateTimeUtil.getLocalDateTime(DateTimeUtil.fromLong2LocalDateTime(info.getAuditTime().getTime()), DateTimeUtil.FULL_FORMAT));
                v.setAuditPlanId(info.getCheckId());
                if (!collect.contains(info.getAuditTime())) {
                    hisAuditList.add(v);
                }

            });
        }
        if (auditVoList.size() > 0) {
            auditList.addAll(auditVoList);
        }
        if (hisAuditList.size() > 0) {
            auditList.addAll(hisAuditList);
        }
        auditList.sort(Comparator.nullsLast((o1, o2) -> {
            if (o1.getAuditTime() == null) {
                return 1;
            }
            if (o2.getAuditTime() == null) {
                return -1;
            }
            return o2.getAuditTime().compareTo(o1.getAuditTime());
        }));
//        List<AuditVo> collect1 = auditList.stream().sorted(Comparator.nullsFirst(Comparator.comparing(AuditVo::getAuditTime))).collect(Collectors.toList());
        vo.setAuditList(auditList);
        return vo;
    }

    @Override
    public List<RepairorderVo> getWorkOrdersByDevice(String equipmentCode) {
        // 精确查询 维修记录表或保养记录表
        List<Repairrecord> list = repairrecordService.list(new QueryWrapper<Repairrecord>().lambda().eq(Repairrecord::getRepairDevice, equipmentCode));
        List<PipeMfRecord> list1 = pipeMfRecordService.list(new QueryWrapper<PipeMfRecord>().lambda().eq(PipeMfRecord::getCode, equipmentCode));
        // 保存当前查询设备 涉及抢维修个人id列表
        Set<Long> repairUserIdSet = new HashSet<>();
        if(null!=list && list.size()>0){
            repairUserIdSet.addAll(list.stream().map(Repairrecord::getRepairUserid).collect(Collectors.toSet()));
        }
        if(null!=list1 && list1.size()>0){
            repairUserIdSet.addAll(list1.stream().map(PipeMfRecord::getRepairUserId).collect(Collectors.toSet()));
        }
        if(repairUserIdSet.size()>0){
            Set<Long> orderIds = repairuserService.listByIds(repairUserIdSet).stream().map(Repairuser::getRepairId).collect(Collectors.toSet());
            return this.viewConversion(this.listByIds(orderIds));
        }
        return null;
    }

    @Override
    public List<RepairOrderOverVo> getRepairOrderOverVo() {
        List<RepairOrderOverVo> voList = new ArrayList<>();
        // 查询抢维修工单状态为 4 处理完成
        List<Repairorder> list = this.list(new QueryWrapper<Repairorder>().lambda().eq(Repairorder::getState, OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode()));
        if(null!=list && list.size()>0){
            Set<Long> collect = list.stream().map(Repairorder::getId).collect(Collectors.toSet());
            // 按照工单id分组
            Map<Long, List<Repairuser>> rMap = repairuserService.list(new QueryWrapper<Repairuser>().lambda()
                    .in(Repairuser::getRepairId, collect).select(Repairuser::getRepairId,Repairuser::getId)).stream().collect(Collectors.groupingBy(Repairuser::getRepairId));
            rMap.forEach((k,v)->{

                Set<Long> repairUserIds = v.stream().map(Repairuser::getId).collect(Collectors.toSet());
                List<Repairrecord> list1 = repairrecordService.list(new QueryWrapper<Repairrecord>().lambda()
                        .in(Repairrecord::getRepairUserid, repairUserIds).select(Repairrecord::getId,Repairrecord::getLgtd,Repairrecord::getLttd));
                list1.forEach(r->{
                    RepairOrderOverVo vo = new RepairOrderOverVo();
                    vo.setOrderId(k);
                    vo.setX(r.getLgtd());
                    vo.setY(r.getLttd());
                    voList.add(vo);
                });
                List<PipeMfRecord> list2 = pipeMfRecordService.list(new QueryWrapper<PipeMfRecord>().lambda()
                        .in(PipeMfRecord::getRepairUserId, repairUserIds).select(PipeMfRecord::getId,PipeMfRecord::getX,PipeMfRecord::getY));
                list2.forEach(r->{
                    RepairOrderOverVo vo = new RepairOrderOverVo();
                    vo.setOrderId(k);
                    vo.setX(r.getX());
                    vo.setY(r.getY());
                    voList.add(vo);
                });

            });
            return voList;
        }
        return null;
    }

    @Override
    public Map<String, Object> getRepairOrderReport(String yearAndMonth) {
        return repairorderMapper.getRepairOrderReport(yearAndMonth);
    }


    public RepairOrderDetailNewVo getRepairOrderDetailNewVo_old(Long orderId) {
        RepairOrderDetailNewVo vo = new RepairOrderDetailNewVo();
        Repairorder repairOrder = this.getById(orderId);
        if (null == repairOrder) {
            throw new BusinessException(Constant.TASK_REPAIR_ORDER_NULL_HOTLINE_CODE, Constant.TASK_REPAIR_ORDER_NULL_HOTLINE);
        }

        // 获取抢维修基础信息
        RepairOrderBaseInfoVo repairOrderBaseInfo = repairorderMapper.getRepairOrderBaseInfo(orderId);
        String state = repairOrderBaseInfo.getState();
        // 节点(1工单登记2维修/保养处理3维修审核4归档)
        // 热线工单默认为2 工单处理
        if("2".equals(repairOrderBaseInfo.getOrderSource())){
            vo.setNode("2");
        }else {
            vo.setNode("1");
        }

        // 处理中/驳回状态
        if (OrderStateEnum.ORDER_STATE_BEING_PERFORMED.getCode().equals(state) || OrderStateEnum.ORDER_STATE_REJECTED.getCode().equals(state)) {
            vo.setNode("2");
        } else if (OrderStateEnum.ORDER_STATE_NOT_AUDIT.getCode().equals(state)) {
            vo.setNode("3");
        } else if (OrderStateEnum.ORDER_STATE_PROCESSING_COMPLETE.getCode().equals(state)) {
            // 判断当前工单状态是否为完成 4
            vo.setNode("4");
        }
        // 获取抢维修对应的用户个人工单
//        List<Repairuser> repairuserList = repairuserService.list(new QueryWrapper<Repairuser>().lambda().eq(Repairuser::getRepairId, orderId));
        List<RepairuserVo> repairuserVos = repairuserMapper.getrepairuserVoList(orderId);
        // 获取地址(解析)
        if (null != repairuserVos && repairuserVos.size() > 0) {
            repairOrderBaseInfo.setRepairUserVoList(repairuserVos);
            List<String> collect = repairuserVos.stream().map(RepairuserVo::getLngLats).filter(lngLats -> !StringUtils.isEmpty(lngLats)).collect(Collectors.toList());
            List<OrderAddressVo> orderAddresses = new ArrayList<>();
            if (collect.size() > 0) {
                collect.forEach(str -> {
                    orderAddresses.addAll(JSONArray.parseArray(str, OrderAddressVo.class));

                });
                repairOrderBaseInfo.setAddressVoList(orderAddresses);
            }

        }
        vo.setBaseInfoVo(repairOrderBaseInfo);
        // 判断当前工单是否为热线工单 orderSource 2为热线
        String orderSource = repairOrder.getOrderSource();
        if (OrderSourceEnum.ORDER_SOURCE_HOTLINE.getCode().equals(orderSource)) {
            vo.setHotlineInfoVo(repairorderMapper.getRepairOrderHotlineInfoVo(orderId));
            vo.setRepairRejectList(repairrejectService.list(new QueryWrapper<Repairreject>().lambda().eq(Repairreject::getRepairId, orderId)));
        }
        // 判断当前工单 为  维修/保养 maintenanceFlag 0否 1是
        String maintenanceFlag = repairOrder.getMaintenanceFlag();
        if (IsDispatchingEnum.IS_DISPATCHING_NO.getCode().equals(maintenanceFlag)) {
            List<RepairOrderRecordInfoVo> repairRecordInfo = repairrecordMapper.getRepairRecordInfo(orderId);
            if (null != repairRecordInfo && repairRecordInfo.size() > 0) {
                repairRecordInfo.forEach(info -> {
                    Long recordId = info.getRecordId();
                    if (null != recordId) {
                        List<Repairgoods> list = repairgoodsService.list(new QueryWrapper<Repairgoods>().lambda().eq(Repairgoods::getRecordId, recordId));
                        info.setGoodsList(repairgoodsService.viewConversion(list));
                    }
                });
                List<RepairOrderRecordInfoVo> collect = repairRecordInfo.stream().sorted(Comparator.comparing(RepairOrderRecordInfoVo::getCreateTime)).collect(Collectors.toList());
                vo.setRecordInfoVoList(collect);
            }

        } else {
            List<PipeMfRecord> list = pipeMfRecordService.list(new QueryWrapper<PipeMfRecord>().lambda().eq(PipeMfRecord::getOrderId, orderId));
            if (null != list && list.size() > 0) {
                List<PipeMfRecord> collect = list.stream().sorted(Comparator.comparing(PipeMfRecord::getCreateTime)).collect(Collectors.toList());
                vo.setPipeMfRecordList(collect);
            }
        }

        // 获取实时审核记录
        List<AuditVo> auditVoList = auditMapper.getAuditVoList(AuditTypeEnum.AUDIT_TYPE_REPAIR_RECORD.getCode(), orderId);
        List<Date> collect = auditVoList.stream().map(AuditVo::getAuditTime).collect(Collectors.toList());
        // 获取历史审核记录
        List<CheckhistoryVo> checkhistoryVos = checkhistoryMapper.getCheckHistoryVoList(AuditTypeEnum.AUDIT_TYPE_REPAIR_RECORD.getCode(), orderId);
        List<AuditVo> auditList = new ArrayList<>();
        List<AuditVo> hisAuditList = new ArrayList<>();
        if (null != checkhistoryVos && checkhistoryVos.size() > 0) {
            checkhistoryVos.forEach(info -> {
                AuditVo v = new AuditVo();
                v.setAuditNote(info.getAuditNotes());
                v.setAuditTime(info.getAuditTime());
                v.setAuditUser(info.getAuditUser());
                v.setAuditUserName(info.getAuditUserName());
                v.setAuditStateName(info.getAuditResultName());
                v.setAuditTimeStr(DateTimeUtil.getLocalDateTime(DateTimeUtil.fromLong2LocalDateTime(info.getAuditTime().getTime()), DateTimeUtil.FULL_FORMAT));
                v.setAuditPlanId(info.getCheckId());
                if (!collect.contains(info.getAuditTime())) {
                    hisAuditList.add(v);
                }

            });
        }
        if (auditVoList.size() > 0) {
            auditList.addAll(auditVoList);
        }
        if (hisAuditList.size() > 0) {
            auditList.addAll(hisAuditList);
        }
        List<AuditVo> collect1 = auditList.stream().sorted(Comparator.comparing(AuditVo::getAuditTime)).collect(Collectors.toList());
        vo.setAuditList(collect1);
        return vo;
    }

    private String sendOrderCode(Long userId) {
        StringBuilder deptCode = new StringBuilder("");
        // 获取用户对应的机构编码
        User user = userClent.getById(userId).getResult();
        if (null != user) {
            Long departmentId = user.getDepartmentId();
            if (null != departmentId) {
                Department department = departmentClient.getById(departmentId).getResult();
                deptCode.append(department.getCode());
            }
        }
        //生成一个序列号，每天从0开始自增
        deptCode.append(this.produceSerialNumber());
        return deptCode.toString();

    }


    private String produceSerialNumber() {

        //批次前缀
        String prefix = DateTimeUtil.getCurrentDate(DateTimeUtil.NUMBER_FORMAT);
        String pre = prefix.substring(0, 8);
        //使用redis生成唯一流水号
        Long sequence = stringRedisTemplate.opsForValue().increment(Constant.MESSAGE_BATCH_ROB_MAINTAIN_SEQUENCE + "_" + pre, 1);
        if (sequence == 1) {
            stringRedisTemplate.delete(stringRedisTemplate.keys(Constant.MESSAGE_BATCH_ROB_MAINTAIN_SEQUENCE + "_" + "*"));
            sequence = stringRedisTemplate.opsForValue().increment(Constant.MESSAGE_BATCH_ROB_MAINTAIN_SEQUENCE + "_" + pre, 1);
        }
        //批次后缀 取流水号最后5位 如果不足5位前面补0
        String suffix = String.format("%05d", sequence % 100000);
        return pre + suffix;
    }


    @Override
    public List<Map<String, Object>> getExportData(String dto, String templateFlag) {
        // 只导出数据
        List<Map<String, Object>> returnMap = new ArrayList<>();
        Map<String, Object> parentMap = new HashMap<>(12);
        Repairorder repairorder = JSONObject.parseObject(dto, Repairorder.class);
        Long id = repairorder.getId();
        if (!StringUtils.isEmpty(id)) {

            RepairOrderDetailNewVo repairOrderDetailNewVo = this.getRepairOrderDetailNewVo(id);
            RepairOrderHotlineInfoVo hotlineInfoVo = repairOrderDetailNewVo.getHotlineInfoVo();
            if (null != hotlineInfoVo) {
                List<RepairOrderHotlineInfoVo> hotlineInfoVoList = new ArrayList<>();
                hotlineInfoVoList.add(hotlineInfoVo);
                // 新增热线信息
                parentMap.put("hotline", hotlineInfoVoList);
                List<Repairreject> repairRejectList = repairOrderDetailNewVo.getRepairRejectList();
                if (null != repairRejectList) {
                    parentMap.put("reject", repairRejectList);
                }
            }

            RepairOrderBaseInfoVo baseInfoVo = repairOrderDetailNewVo.getBaseInfoVo();
            if (null != baseInfoVo) {
                List<RepairOrderBaseInfoVo> baseInfoVoList = new ArrayList<>();
                baseInfoVoList.add(baseInfoVo);
                // 新增抢维修基础信息
                parentMap.put("order", baseInfoVoList);
            }
            List<RepairOrderRecordInfoVo> recordInfoVoList = repairOrderDetailNewVo.getRecordInfoVoList();
            if (null != recordInfoVoList && recordInfoVoList.size() > 0) {
                // 新增抢维修处理信息
                parentMap.put("record", recordInfoVoList);
            }
            List<PipeMfRecord> pipeMfRecordList = repairOrderDetailNewVo.getPipeMfRecordList();
            if (null != pipeMfRecordList && pipeMfRecordList.size() > 0) {
                pipeMfRecordList.forEach(mf -> {
                    // 处理设施是否能启闭 / 设施维护保养效果 值
                    List<PipeMfEvaluate> pipeMfEvaluateList = mf.getPipeMfEvaluateList();
                    pipeMfEvaluateList.forEach(pi -> {
                        String mfEvaluateSerialNumber = pi.getMfEvaluateSerialNumber();
                        if ("2.1".equals(mfEvaluateSerialNumber)) {
                            mf.setExcelISPJ(IsRespectEnum.getCodeForValue(pi.getMfEvaluateFlag()));
                        }
                        if ("2.1".equals(mfEvaluateSerialNumber)) {
                            mf.setPJconten(pi.getMfEvaluateResult());
                        }
                    });

                });
                // 新增养护处理信息
                parentMap.put("mf", pipeMfRecordList);
            }
            List<AuditVo> auditList = repairOrderDetailNewVo.getAuditList();
            if (null != auditList && auditList.size() > 0) {
                // 新增审核信息
                parentMap.put("audit", auditList);
            }
            returnMap.add(parentMap);
        } else {
            throw new BusinessException(Constant.EXCEL_EXPORT_ORDER_PLAN_ID_NULL_ERROR_CODE, Constant.EXCEL_EXPORT_ORDER_PLAN_ID_NULL_ERROR);
        }
        return returnMap;
    }

    @Override
    public Boolean excelDataStorage(List<Object> dataList) {
        return null;
    }


}
