package com.njcn.device.userledger.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.bpm.enums.BpmProcessInstanceStatusEnum;
import com.njcn.bpm.enums.BpmTaskStatusEnum;
import com.njcn.common.pojo.constant.PatternRegex;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.device.device.mapper.DeviceMapper;
import com.njcn.device.line.mapper.LineDetailMapper;
import com.njcn.device.line.mapper.LineMapper;
import com.njcn.device.pq.pojo.param.TerminalCheckParam;
import com.njcn.device.pq.pojo.po.Device;
import com.njcn.device.pq.pojo.po.Line;
import com.njcn.device.pq.pojo.po.LineDetail;
import com.njcn.device.pq.pojo.po.SupervisionUserReportFile;
import com.njcn.device.substation.mapper.SubstationMapper;
import com.njcn.device.userledger.mapper.SupervisionUserReportFileMapper;
import com.njcn.device.userledger.mapper.UserReportNormalMapper;
import com.njcn.device.userledger.mapper.UserReportPOMapper;
import com.njcn.device.userledger.service.*;
import com.njcn.supervision.enums.FlowStatusEnum;
import com.njcn.supervision.enums.SupervisionResponseEnum;
import com.njcn.supervision.enums.UserNatureEnum;
import com.njcn.supervision.pojo.param.SensitiveUserParam;
import com.njcn.supervision.pojo.param.user.UserReportParam;
import com.njcn.supervision.pojo.po.user.*;
import com.njcn.supervision.pojo.vo.user.NewUserReportVO;
import com.njcn.supervision.pojo.vo.user.UserLedgerVO;
import com.njcn.supervision.pojo.vo.user.UserReportVO;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.user.api.UserFeignClient;
import com.njcn.user.pojo.po.Dept;
import com.njcn.user.pojo.vo.UserVO;
import com.njcn.web.constant.ValidMessage;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author wr
 * @description
 * @date 2026/3/3 16:19
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserLedgerServiceImpl extends ServiceImpl<UserReportPOMapper, UserReportPO> implements UserLedgerService {

    private final DeptFeignClient deptFeignClient;
    private final UserReportProjectPOService userReportProjectPOService;
    private final UserReportSubstationPOService userReportSubstationPOService;
    private final UserReportNormalMapper userReportNormalMapper;
    private final UserReportSensitivePOService userReportSensitivePOService;
    private final UserFeignClient userFeignClient;
    private final LineMapper substationMapper;
    private final LineDetailMapper lineDetailMapper;
    private final SupervisionUserReportFileService supervisionUserReportFileService;
    private final DeviceMapper deviceMapper;

    @Override
    public List<UserLedgerVO> selectUserList(UserReportParam userReportParam) {
        LambdaQueryWrapper<UserReportPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(userReportParam.getCity())) {
            lambdaQueryWrapper.in(UserReportPO::getCity, Stream.of(userReportParam.getCity()).collect(Collectors.toList()));
        }
        if (StrUtil.isNotBlank(userReportParam.getStationId())) {
            lambdaQueryWrapper.eq(UserReportPO::getStationId, userReportParam.getStationId());
        }
        if (ObjectUtil.isNotNull(userReportParam.getUserType())) {
            lambdaQueryWrapper.eq(UserReportPO::getUserType, userReportParam.getUserType());
        }
        lambdaQueryWrapper.eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
        List<UserReportPO> list = this.list(lambdaQueryWrapper);
        return BeanUtil.copyToList(list, UserLedgerVO.class);
    }

    @Override
    public UserLedgerVO selectUserInfo(String id) {
        LambdaQueryWrapper<UserReportPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserReportPO::getId, id).eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
        UserReportPO userReportPO = this.getById(id);
        if (Objects.nonNull(userReportPO)) {
            return BeanUtil.copyProperties(userReportPO, UserLedgerVO.class);
        }
        return null;
    }

    @Override
    public Boolean bindUserStation(String userId, String stationId) {
        UserReportPO userReportPO = new UserReportPO();
        userReportPO.setId(userId);
        userReportPO.setStationId(stationId);
        return this.updateById(userReportPO);
    }

    @Override
    public List<NewUserReportVO> getUserReportByIds(List<String> ids) {
        List<UserReportPO> userReportPOS = this.listByIds(ids);
        List<NewUserReportVO> info = new ArrayList<>();
        for (UserReportPO userReportNormalPO : userReportPOS) {
            NewUserReportVO newUserReportVO = new NewUserReportVO();

            BeanUtil.copyProperties(userReportNormalPO, newUserReportVO);
            info.add(newUserReportVO);
        }
        return info;
    }

    @Override
    public List<UserReportPO> getSensitiveUserByDept(SensitiveUserParam param) {
        QueryWrapper<UserReportPO> userReportVOQueryWrapper = new QueryWrapper<>();
        List<String> data = deptFeignClient.getDepSonIdtByDeptId(param.getDeptId()).getData();
        //此处仅查询敏感及重要用户
        userReportVOQueryWrapper.and(wrapper ->
                        wrapper.in("supervision_user_report.org_id", data)
                )
                .eq("supervision_user_report.state", DataStateEnum.ENABLE.getCode())
                .eq("supervision_user_report.user_type", UserNatureEnum.SENSITIVE_USER.getCode())
                .in("supervision_user_report.status", Arrays.asList(FlowStatusEnum.AUDIT.getCode(), FlowStatusEnum.APPROVE.getCode()));
        userReportVOQueryWrapper.like(StringUtils.isNotBlank(param.getProjectName()), "supervision_user_report.project_name", param.getProjectName());
        userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
        return this.baseMapper.selectList(userReportVOQueryWrapper);
    }

    @Override
    public Page<UserReportVO> getUserLedgerPage(UserReportParam.UserReportQueryParam userReportQueryParam) {
        //正则校验
        Pattern pattern = Pattern.compile(PatternRegex.ALL_CHAR_1_20);
        Matcher matcher = pattern.matcher(userReportQueryParam.getProjectName());
        if (StringUtils.isNotBlank(userReportQueryParam.getProjectName()) && !matcher.matches()) {
            throw new BusinessException(ValidMessage.SEARCH_DATA_ERROR);
        }
        QueryWrapper<UserReportVO> userReportVOQueryWrapper = new QueryWrapper<>();

        //此处仅查询敏感及重要用户
        userReportVOQueryWrapper
                .eq("supervision_user_report.state", DataStateEnum.ENABLE.getCode());

        if (Objects.nonNull(userReportQueryParam)) {
            if (StrUtil.isNotBlank(userReportQueryParam.getCity())) {
                //查询所有区域下的数据
                userReportVOQueryWrapper.in("supervision_user_report.city", userReportQueryParam.getCity());
            }
            if (Objects.nonNull(userReportQueryParam.getDataType())) {
                userReportVOQueryWrapper.eq("data_type", userReportQueryParam.getDataType());
            }
            userReportVOQueryWrapper.like(StringUtils.isNotBlank(userReportQueryParam.getProjectName()), "supervision_user_report.project_name", userReportQueryParam.getProjectName());
            if (StrUtil.isNotBlank(userReportQueryParam.getSearchBeginTime()) && StrUtil.isNotBlank(userReportQueryParam.getSearchEndTime())) {
                userReportVOQueryWrapper.and(wrapper -> wrapper.between("supervision_user_report.report_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                        .or()
                        .between("supervision_user_report.expected_production_date",
                                DateUtil.beginOfDay(DateUtil.parse(userReportQueryParam.getSearchBeginTime())),
                                DateUtil.endOfDay(DateUtil.parse(userReportQueryParam.getSearchEndTime())))
                );
            }
            userReportVOQueryWrapper.orderByDesc("supervision_user_report.Update_Time");
        }
        userReportVOQueryWrapper.orderByDesc("supervision_user_report.create_time");
        Page<UserReportVO> page;
        page = this.baseMapper.page(new Page<>(PageFactory.getPageNum(userReportQueryParam), PageFactory.getPageSize(userReportQueryParam)), userReportVOQueryWrapper);
        Map<String,String> atationMap = new HashMap<>();
        if(CollUtil.isNotEmpty(page.getRecords())){
           List<String> stationIds = page.getRecords().stream().map(UserReportVO::getStationId).filter(StrUtil::isNotBlank).distinct().collect(Collectors.toList());
          if(CollUtil.isNotEmpty(stationIds)){
              List<Line> stationList = substationMapper.selectBatchIds(stationIds);
              stationList.forEach(line -> atationMap.put(line.getId(), line.getName()));
          }

            List<String> ids = page.getRecords().stream().map(UserReportVO::getId).collect(Collectors.toList());
            List<SupervisionUserReportFile> supervisionUserReportFiles = supervisionUserReportFileService.lambdaQuery().in(SupervisionUserReportFile::getId,ids).list();
            Map<String,SupervisionUserReportFile> stringSupervisionUserReportFileMap = supervisionUserReportFiles.stream().collect(Collectors.toMap(SupervisionUserReportFile::getId, Function.identity()));
        page.getRecords().forEach(temp -> {
            temp.setStationId(atationMap.getOrDefault(temp.getStationId(),"/"));
            Integer needGovernance = 0;
            if (
                    CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_POWER_GRID.getCode(),
                            UserNatureEnum.EXTEND_POWER_GRID.getCode()
                    ).contains(temp.getUserType())) {
                //电网工程类用户额外数据
                needGovernance = userReportProjectPOService.getById(temp.getId()).getNeedGovernance();
            } else if (
                    CollectionUtil.newArrayList(
                            UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                            UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                            UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                    ).contains(temp.getUserType())) {
                //非线性负荷用户 & 新能源发电站用户

                needGovernance = userReportSubstationPOService.getById(temp.getId()).getNeedGovernance();
            } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(temp.getUserType())) {
                // 敏感及重要用户
                needGovernance = userReportSensitivePOService.getById(temp.getId()).getNeedGovernance();
            }
            temp.setNeedGovernance(needGovernance);
            //添加治理评估文件，需先判断入网评估是否审核通过
            boolean type = true;
            if (1 == temp.getNeedGovernance()) {
                List<UserReportNormalPO> list = userReportNormalMapper.selectList(new LambdaQueryWrapper<UserReportNormalPO>()
                        .eq(UserReportNormalPO::getUserReportId, temp.getId())
                        .eq(UserReportNormalPO::getState, DataStateEnum.ENABLE.getCode())
                        .ne(UserReportNormalPO::getStatus, BpmTaskStatusEnum.CANCEL.getStatus())
                        .eq(UserReportNormalPO::getType, 0)
                        .orderByDesc(UserReportNormalPO::getCreateTime)
                );
                if (CollUtil.isNotEmpty(list)) {
                    List<String> collect = list.stream().filter(x -> !Objects.equals(x.getStatus(), BpmTaskStatusEnum.APPROVE.getStatus()))
                            .map(UserReportNormalPO::getId)
                            .collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(collect)) {
                        type = false;
                    }
                } else {
                    type = false;
                }
            }
            temp.setType(type);
            if(stringSupervisionUserReportFileMap.containsKey(temp.getId())){
                SupervisionUserReportFile supervisionUserReportFile = stringSupervisionUserReportFileMap.get(temp.getId());
                temp.setCheckUrl(supervisionUserReportFile.getCheckUrl());
                //temp.setCheckHistoryUrl(supervisionUserReportFile.getCheckHistoryUrl());
                temp.setAssessUrl(supervisionUserReportFile.getAssessUrl());
                temp.setOtherUrl(supervisionUserReportFile.getOtherUrl());
            }

        });
        }
        return page;
    }

    @Override
    public UserReportVO.UserReportListVO getVOById(String id) {
        UserReportVO.UserReportListVO userReportVO = new UserReportVO.UserReportListVO();
        UserReportPO userReportPO = this.baseMapper.selectById(id);
        //复制基础信息
        BeanUtil.copyProperties(userReportPO, userReportVO);
        //处理特殊字段，用户名、部门名
        if (StrUtil.isNotBlank(userReportPO.getReporter())){
            UserVO userVO = userFeignClient.getUserById(userReportPO.getReporter()).getData();
            if(ObjUtil.isNotNull(userVO)){
                userReportVO.setReporter(userVO.getName());

            }
        }
        if (StrUtil.isNotBlank(userReportPO.getReporter())){
            Dept dept = deptFeignClient.getDeptById(userReportPO.getOrgId()).getData();
            if(ObjUtil.isNotNull(dept)){
                userReportVO.setOrgName(dept.getName());
            }
        }

        SupervisionUserReportFile supervisionUserReportFile = supervisionUserReportFileService.getOne(new LambdaQueryWrapper<SupervisionUserReportFile>().eq(SupervisionUserReportFile::getId,userReportPO.getId()));
        if(Objects.nonNull(supervisionUserReportFile)){
            userReportVO.setCheckUrl(supervisionUserReportFile.getCheckUrl());
            userReportVO.setAssessUrl(supervisionUserReportFile.getAssessUrl());
            userReportVO.setOtherUrl(supervisionUserReportFile.getOtherUrl());
        }
        /*
            根据用户性质获取自己特有的字段，此处需要特殊处理
            1、每个附件需要返回文件名称以及可以预览的url
            todo...by黄正剑
         */
        if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_POWER_GRID.getCode(),
                        UserNatureEnum.EXTEND_POWER_GRID.getCode()
                ).contains(userReportPO.getUserType())) {
            //电网工程类用户额外数据
            UserReportProjectPO byId = userReportProjectPOService.getById(id);
            userReportVO.setUserReportProjectPO(byId);

        } else if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                        UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                ).contains(userReportPO.getUserType())) {
            //非线性负荷用户 & 新能源发电站用户
            UserReportSubstationPO byId = userReportSubstationPOService.getById(id);
            userReportSubstationPOService.saveOrUpdate(byId);
            userReportVO.setUserReportSubstationPO(byId);
        } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(userReportPO.getUserType())) {
            // 敏感及重要用户
            UserReportSensitivePO byId = userReportSensitivePOService.getById(id);
            userReportVO.setUserReportSensitivePO(byId);
        }
        List<UserReportNormalPO> list = userReportNormalMapper.selectList(new LambdaQueryWrapper<UserReportNormalPO>()
                .eq(UserReportNormalPO::getUserReportId, id)
                .eq(UserReportNormalPO::getStatus, BpmTaskStatusEnum.APPROVE.getStatus())
                .eq(UserReportNormalPO::getState, DataStateEnum.ENABLE.getCode())
                .orderByDesc(UserReportNormalPO::getCreateTime)
        );
        Optional<String> netInReport = list.stream().filter(x -> 0 == x.getType()).map(UserReportNormalPO::getReportUrl).findFirst();
        Optional<String> governReport = list.stream().filter(x -> 1 == x.getType()).map(UserReportNormalPO::getReportUrl).findFirst();
        Optional<String> simulationReport = list.stream().filter(x -> 1 == x.getType()).map(UserReportNormalPO::getSimulationReportUrl).findFirst();
        userReportVO.setNetInReport(Collections.singletonList(netInReport.orElse(null)));
        userReportVO.setGovernReport(Collections.singletonList(governReport.orElse(null)));
        userReportVO.setSimulationReport(Collections.singletonList(simulationReport.orElse(null)));
        return userReportVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addUserReport(UserReportParam userReportParam) {
        UserReportPO userReportPO = new UserReportPO();
        BeanUtils.copyProperties(userReportParam, userReportPO);
        userReportPO.setState(DataStateEnum.ENABLE.getCode());
        if (Objects.equals(userReportParam.getSaveOrCheckflag(), "2")) {
            checkProjectName(userReportParam, !StringUtils.isEmpty(userReportParam.getId()));
        }
        //判断工程名称是否有重复的
        if (Objects.equals(userReportParam.getSaveOrCheckflag(), "1")) {
            userReportPO.setStatus(BpmTaskStatusEnum.WAIT.getStatus());
            checkProjectName(userReportParam, !StringUtils.isEmpty(userReportParam.getId()));
        } else {
            //常态化干扰源用户信息更新的用的
            if (!Objects.equals(userReportParam.getSaveOrCheckflag(), "0")) {
                userReportPO.setStatus(BpmTaskStatusEnum.RUNNING.getStatus());
            }
        }
        if (ObjectUtil.isNotNull(userReportParam.getDataType())) {
            userReportPO.setDataType(userReportParam.getDataType());
            if (userReportParam.getDataType() == 1) {
                if (UserNatureEnum.SENSITIVE_USER.getCode().equals(userReportParam.getUserType())) {
                    userReportPO.setStatus(BpmTaskStatusEnum.APPROVE.getStatus());
                }
            }
        } else {
            userReportPO.setDataType(0);
        }
        this.saveOrUpdate(userReportPO);

        //需要同步更新pq_line_detail 表里的obj_name字段
        if(Objects.nonNull(userReportParam.getDataType()) && userReportParam.getDataType() == 1){
            if(StrUtil.isNotBlank(userReportPO.getId())){
                List<LineDetail> lineDetailList = lineDetailMapper.selectList(new LambdaQueryWrapper<LineDetail>().eq(LineDetail::getId, userReportPO.getId()));
                if(CollUtil.isNotEmpty(lineDetailList)){
                   List<String> ids = lineDetailList.stream().map(LineDetail::getId).collect(Collectors.toList());
                    LineDetail lineDetail = new LineDetail();
                    lineDetail.setObjName(userReportPO.getProjectName());
                    lineDetailMapper.update(lineDetail,new LambdaUpdateWrapper<LineDetail>().in(LineDetail::getId,ids));
                }
            }
        }
        //处理需要上传的附件
        SupervisionUserReportFile supervisionUserReportFile = new SupervisionUserReportFile();
        supervisionUserReportFile.setId(userReportPO.getId());
        supervisionUserReportFile.setCheckUrl(userReportParam.getCheckUrl());
        supervisionUserReportFile.setAssessUrl(userReportParam.getAssessUrl());
        supervisionUserReportFile.setOtherUrl(userReportParam.getOtherUrl());
        supervisionUserReportFileService.saveOrUpdate(supervisionUserReportFile);

        userReportPO = this.getById(userReportPO.getId());
        if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_POWER_GRID.getCode(),
                        UserNatureEnum.EXTEND_POWER_GRID.getCode()
                ).contains(userReportPO.getUserType())) {
            //电网工程类用户额外数据
            UserReportProjectPO userReportProjectPO = userReportParam.getUserReportProjectPO();
            userReportProjectPO.setId(userReportPO.getId());
            userReportProjectPO.setState(DataStateEnum.ENABLE.getCode());
            userReportProjectPOService.saveOrUpdate(userReportProjectPO);
        } else if (
                CollectionUtil.newArrayList(
                        UserNatureEnum.BUILD_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.EXTEND_NON_LINEAR_LOAD.getCode(),
                        UserNatureEnum.BUILD_NEW_ENERGY_POWER_STATION.getCode(),
                        UserNatureEnum.EXTEND_NEW_ENERGY_POWER_STATION.getCode()
                ).contains(userReportPO.getUserType())) {
            //非线性负荷用户 & 新能源发电站用户
            UserReportSubstationPO userReportSubstationPO = userReportParam.getUserReportSubstationPO();
            userReportSubstationPO.setId(userReportPO.getId());
            userReportSubstationPO.setState(DataStateEnum.ENABLE.getCode());
            userReportSubstationPOService.saveOrUpdate(userReportSubstationPO);
        } else if (UserNatureEnum.SENSITIVE_USER.getCode().equals(userReportPO.getUserType())) {
            // 敏感及重要用户
            UserReportSensitivePO userReportSensitivePO = userReportParam.getUserReportSensitivePO();
            userReportSensitivePO.setId(userReportPO.getId());
            userReportSensitivePO.setState(DataStateEnum.ENABLE.getCode());
            userReportSensitivePOService.saveOrUpdate(userReportSensitivePO);
        }
        return userReportPO.getId();
    }

    @Override
    public Boolean deleteUserReport(List<String> supervisionId) {
        List<UserReportPO> userReportPOS = this.listByIds(supervisionId);
        if (CollUtil.isEmpty(userReportPOS)) {
            throw new BusinessException(SupervisionResponseEnum.EXISTENCE_OR_NOT);
        }
        //先判断是否是删除管理员，如果是就有全部删除权限，否则就只能删除带提交审批的
        List<String> deleteUser = userReportPOS.stream().map(UserReportPO::getCreateBy).distinct().collect(Collectors.toList());
        long statusCount = userReportPOS.stream().filter(x -> !BpmTaskStatusEnum.WAIT.getStatus().equals(x.getStatus())).count();
        //判断是否有权限操作
        if (CollUtil.isEmpty(deleteUser)) {
            throw new BusinessException(SupervisionResponseEnum.EXISTENCE_OR_NOT);
        }
        //如果为空则需要判断信息，先判断全部数据是否都是自己创建的，然后判断是否是都是带提交数据
        if (CollUtil.isEmpty(deleteUser)) {
            long count = deleteUser.stream().filter(x -> !RequestUtil.getUserIndex().equals(x)).count();
            if (count > 0) {
                throw new BusinessException(SupervisionResponseEnum.NO_POWER);
            } else {
                if (statusCount > 0) {
                    throw new BusinessException(SupervisionResponseEnum.DELETE_TO_BE_SUBMITTED);
                }
            }
        }
        return this.update(new LambdaUpdateWrapper<UserReportPO>().set(UserReportPO::getState, DataStateEnum.DELETED.getCode())
                .in(UserReportPO::getId, supervisionId));
    }

    @Override
    public UserReportVO getUserReportById(String id) {
        QueryWrapper<UserReportVO> userReportVOQueryWrapper = new QueryWrapper<>();
        userReportVOQueryWrapper.eq("supervision_user_report.id", id);
        return this.baseMapper.getUserReportById(userReportVOQueryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean userCheckUpload(TerminalCheckParam terminalCheckParam) {
        SupervisionUserReportFile supervisionUserReportFile = new SupervisionUserReportFile();
        supervisionUserReportFile.setId(terminalCheckParam.getObjId());
        supervisionUserReportFile.setCheckUrl(terminalCheckParam.getCheckUrl());
        supervisionUserReportFileService.saveOrUpdate(supervisionUserReportFile);
        Device device = new Device();
        device.setId(terminalCheckParam.getDevId());
        device.setThisTimeCheck(terminalCheckParam.getThisCheckTime());
        device.setNextTimeCheck(terminalCheckParam.getNextCheckTime());
        deviceMapper.updateById(device);
        return true;
    }

    /**
     * 判断工程名称是否重复，如果重复则提示用户XXX已经创建该工程
     *
     * @param userReportParam 用户申请数据
     * @param isExcludeSelf   是否排除自己，一般新增不排除，更新时需要排除自己
     */
    protected void checkProjectName(UserReportParam userReportParam, boolean isExcludeSelf) {
        if (!StringUtils.isEmpty(userReportParam.getProjectName())) {
            LambdaQueryWrapper<UserReportPO> userReportPOLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userReportPOLambdaQueryWrapper
                    .eq(UserReportPO::getProjectName, userReportParam.getProjectName())
                    .in(UserReportPO::getStatus, CollectionUtil.newArrayList(BpmProcessInstanceStatusEnum.AWAIT.getStatus(), BpmProcessInstanceStatusEnum.RUNNING.getStatus(), BpmProcessInstanceStatusEnum.APPROVE.getStatus()))
                    .eq(UserReportPO::getState, DataStateEnum.ENABLE.getCode());
            //更新的时候，需排除当前记录
            if (isExcludeSelf) {
                if (userReportParam instanceof UserReportParam.UserReportUpdate) {
                    userReportPOLambdaQueryWrapper.ne(UserReportPO::getId, ((UserReportParam.UserReportUpdate) userReportParam).getId());
                } else {
                    userReportPOLambdaQueryWrapper.ne(UserReportPO::getId, (userReportParam).getId());
                }
            }
            List<UserReportPO> userReportPOList = this.baseMapper.selectList(userReportPOLambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(userReportPOList)) {
                //过滤已取消的申请
                userReportPOList = userReportPOList.stream()
                        .filter(userReportPO -> !userReportPO.getStatus().equals(FlowStatusEnum.CANCEL.getCode()))
                        .collect(Collectors.toList());
                //如果还存在，则说明有人申请过了
                if (CollectionUtil.isNotEmpty(userReportPOList)) {
                    UserVO userVO = userFeignClient.getUserById(userReportPOList.get(0).getReporter()).getData();
                    throw new BusinessException(userReportParam.getProjectName().concat(",该工程已被:").concat(userVO.getName()).concat("申请"));
                }
            }
        }

    }
}
