package cn.iocoder.yudao.module.server.service.workorderInfos;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.infra.dal.mysql.file.FileMapper;
import cn.iocoder.yudao.module.infra.framework.file.core.client.FileClient;
import cn.iocoder.yudao.module.infra.framework.file.core.utils.FileTypeUtils;
import cn.iocoder.yudao.module.infra.service.file.FileConfigService;
import cn.iocoder.yudao.module.server.dal.dataobject.techorg.TechOrgDO;
import cn.iocoder.yudao.module.server.dal.dataobject.workorderLog.WorkorderLogDO;
import cn.iocoder.yudao.module.server.dal.dataobject.workorderType.WorkorderTypeDO;
import cn.iocoder.yudao.module.server.dal.dataobject.workorderFile.WorkorderFileDO;
import cn.iocoder.yudao.module.server.dal.mysql.techorg.TechOrgMapper;
import cn.iocoder.yudao.module.server.dal.mysql.workorderLog.WorkorderLogMapper;
import cn.iocoder.yudao.module.server.dal.mysql.workorderType.WorkorderTypeMapper;
import cn.iocoder.yudao.module.server.dal.mysql.workorderFile.WorkorderFileMapper;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.UserRoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.DeptMapper;
import cn.iocoder.yudao.module.system.dal.mysql.permission.UserRoleMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.iocoder.yudao.module.server.controller.admin.workorderInfos.vo.*;
import cn.iocoder.yudao.module.server.dal.dataobject.workorderInfos.WorkorderInfosDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.server.dal.mysql.workorderInfos.WorkorderInfosMapper;

import static cn.hutool.core.date.DatePattern.PURE_DATE_PATTERN;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.server.enums.ErrorCodeConstants.*;

/**
 * 工单 Service 实现类
 *
 * @author wyj
 */
@Service
@Validated
@Slf4j
public class WorkorderInfosServiceImpl implements WorkorderInfosService {

    private static final Map<Long, String> ROLE_STATUS_MAP = ImmutableMap.of(
            161L, "22",  // 用户退回
            162L, "52",  // 运维商退回
            163L, "32",  // 大数据中心退回
            164L, "42"   // 政务公开处退回
    );

    /**
     * 上传文件的前缀，是否包含日期（yyyyMMdd）
     * <p>
     * 目的：按照日期，进行分目录
     */
    static boolean PATH_PREFIX_DATE_ENABLE = true;
    /**
     * 上传文件的后缀，是否包含时间戳
     * <p>
     * 目的：保证文件的唯一性，避免覆盖
     * 定制：可按需调整成 UUID、或者其他方式
     */
    static boolean PATH_SUFFIX_TIMESTAMP_ENABLE = true;

    @Resource
    private WorkorderInfosMapper workorderInfosMapper;

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private WorkorderTypeMapper workorderTypeMapper;

    @Resource
    private FileConfigService fileConfigService;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private WorkorderFileMapper workorderFileMapper;

    @Resource
    private WorkorderLogMapper workorderLogMapper;

    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private TechOrgMapper techOrgMapper;

    @Override
    @Transactional
    public Long createWorkorderInfos(WorkorderInfosSaveReqVO createReqVO) {
        // 插入
        WorkorderInfosDO workorderInfos = BeanUtils.toBean(createReqVO, WorkorderInfosDO.class);
        workorderInfos.setRejectReason("");
        workorderInfosMapper.insert(workorderInfos);
        //修改工单附件表的工单id
        List<HashMap> files = createReqVO.getRequiredInfoFj();
        for (HashMap file : files) {
            Long id = Long.valueOf(file.get("id").toString());
            LambdaUpdateWrapper<WorkorderFileDO> wrapper = new LambdaUpdateWrapper<>();
            wrapper.eq(WorkorderFileDO::getId, id)
                    .set(WorkorderFileDO::getWorkorderId, workorderInfos.getId());
            workorderFileMapper.update(wrapper);
        }
        //保存工单日志
        WorkorderLogDO workorderLogDO = new WorkorderLogDO();
        workorderLogDO.setWorkorderId(workorderInfos.getId());
        workorderLogDO.setStatus("10");
        workorderLogMapper.insert(workorderLogDO);
        if ("push".equals(createReqVO.getType())) {
//            WorkorderLogDO workorderLogDO2 = new WorkorderLogDO();
//            workorderLogDO2.setWorkorderId(workorderInfos.getId());
//            workorderLogDO2.setStatus("10");
//            workorderLogMapper.insert(workorderLogDO2);
            //更新工单表中工单状态
            //判断工单类型
            WorkorderTypeDO workorderTypeDO = workorderTypeMapper.selectById(workorderInfos.getCategoryId());

            LambdaUpdateWrapper<WorkorderInfosDO> wrapper = new LambdaUpdateWrapper<>();
            if (workorderTypeDO.getProcessType() != 3) {
                //策略类、操作类工单
                workorderInfos.setStatus("21");
                wrapper.eq(WorkorderInfosDO::getId, workorderInfos.getId())
                        .set(WorkorderInfosDO::getStatus, "21");
            } else {
                //运维商流程，协助工单
                workorderInfos.setStatus("21");
                wrapper.eq(WorkorderInfosDO::getId, workorderInfos.getId())
                        .set(WorkorderInfosDO::getStatus, "21");//51
            }
            workorderInfosMapper.update(wrapper);
        }
        // 返回
        return workorderInfos.getId();
    }

    @Override
    public void updateWorkorderInfos(WorkorderInfosSaveReqVO updateReqVO) {
        // 校验存在
        validateWorkorderInfosExists(updateReqVO.getId());
        //删除之前工单的旧附件
        LambdaQueryWrapper<WorkorderFileDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkorderFileDO::getWorkorderId, updateReqVO.getId());
        workorderFileMapper.delete(wrapper);
        // 更新
        WorkorderInfosDO updateObj = BeanUtils.toBean(updateReqVO, WorkorderInfosDO.class);
        workorderInfosMapper.updateById(updateObj);
        //修改工单附件表的工单id
        List<HashMap> files = updateReqVO.getRequiredInfoFj();
        for (HashMap file : files) {
            Long id = Long.valueOf(file.get("id").toString());
            LambdaUpdateWrapper<WorkorderFileDO> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(WorkorderFileDO::getId, id)
                    .set(WorkorderFileDO::getWorkorderId, updateReqVO.getId())
                    .set(WorkorderFileDO::getDeleted, 0);
            workorderFileMapper.update(updateWrapper);
            workorderFileMapper.restoreById(id);
        }
        //保存工单日志
        if ("push".equals(updateReqVO.getType())) {
//            WorkorderLogDO workorderLogDO2 = new WorkorderLogDO();
//            workorderLogDO2.setWorkorderId(updateObj.getId());
//            workorderLogDO2.setStatus("10");
//            workorderLogMapper.insert(workorderLogDO2);
            //更新工单表中工单状态
            //判断工单类型
            WorkorderTypeDO workorderTypeDO = workorderTypeMapper.selectById(updateReqVO.getCategoryId());
            LambdaUpdateWrapper<WorkorderInfosDO> wrapper3 = new LambdaUpdateWrapper<>();
            if (workorderTypeDO.getProcessType() != 3) {
                //策略类、操作类工单
                updateObj.setStatus("21");
                wrapper3.eq(WorkorderInfosDO::getId, updateObj.getId())
                        .set(WorkorderInfosDO::getStatus, "21")
                        .set(WorkorderInfosDO::getRejectReason, "");
            } else {
                //运维商流程，协助工单   注释
                updateObj.setStatus("21");
                wrapper3.eq(WorkorderInfosDO::getId, updateObj.getId())
                        .set(WorkorderInfosDO::getStatus, "21")
                        .set(WorkorderInfosDO::getRejectReason, "");//51
            }
            //判断是否为退回的工单，要重新提交，是的话要添加一条工单日志
            WorkorderInfosDO infosDO = workorderInfosMapper.selectById(updateReqVO.getId());
            if (StrUtil.isNotEmpty(infosDO.getRejectReason())) {
                //添加一条工单日志
                WorkorderLogDO workorderLogDO = new WorkorderLogDO();
                workorderLogDO.setWorkorderId(infosDO.getId());
                workorderLogDO.setStatus("51");
                workorderLogMapper.insert(workorderLogDO);
            }
            workorderInfosMapper.update(wrapper3);
        }
    }

    @Override
    public void closeWorkorderInfos(Long id) {
        LambdaUpdateWrapper<WorkorderInfosDO> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(WorkorderInfosDO::getId, id)
                .set(WorkorderInfosDO::getStatus, "0");
        workorderInfosMapper.update(wrapper);
        //添加一条工单日志
        //添加一条工单日志
        WorkorderLogDO workorderLogDO = new WorkorderLogDO();
        workorderLogDO.setWorkorderId(id);
        workorderLogDO.setStatus("0");
        workorderLogMapper.insert(workorderLogDO);
    }

    @Override
    public void deleteWorkorderInfos(Long id) {
        // 校验存在
        validateWorkorderInfosExists(id);
        // 删除
        workorderInfosMapper.deleteById(id);
    }

    private void validateWorkorderInfosExists(Long id) {
        if (workorderInfosMapper.selectById(id) == null) {
            throw exception(WORKORDER_INFOS_NOT_EXISTS);
        }
    }

    @Override
    public WorkorderInfosRespVO getWorkorderInfos(Long id) {
        WorkorderInfosDO workorderInfosDO = workorderInfosMapper.selectById(id);
        //查询工单附件
        LambdaQueryWrapper<WorkorderFileDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkorderFileDO::getWorkorderId, workorderInfosDO.getId());
        List<WorkorderFileDO> workorderFileDOS = workorderFileMapper.selectList(wrapper);
        WorkorderInfosRespVO workorderInfosRespVO = BeanUtils.toBean(workorderInfosDO, WorkorderInfosRespVO.class);
        workorderInfosRespVO.setRequiredInfo(workorderFileDOS);
        workorderInfosRespVO.setCategoryId(workorderInfosDO.getCategoryId());
        workorderInfosRespVO.setTechOperatorId(workorderInfosDO.getTechOperatorId());
        workorderInfosRespVO.setUserId(workorderInfosDO.getUserId());
        workorderInfosRespVO.setUploadinfo(workorderInfosDO.getRequiredInfo());
        //查询创建人
        AdminUserDO adminUserDO = adminUserMapper.selectByIdWithoutPermission(Long.valueOf(workorderInfosDO.getCreator()));
        workorderInfosRespVO.setCreator(adminUserDO.getNickname());
        //查询工单分类
        WorkorderTypeDO workorderTypeDO = workorderTypeMapper.selectById(workorderInfosRespVO.getCategoryId());
        workorderInfosRespVO.setCategory(workorderTypeDO.getName());
        //获取实施运维商部门名称
//        DeptDO deptDO = deptMapper.selectById(workorderInfosDO.getTechOperatorId());
        DeptDO deptDO = deptMapper.selectByIdWithoutPermission(workorderInfosDO.getTechOperatorId());
        workorderInfosRespVO.setTechOperator(deptDO.getName());
        //获取部门用户
//        DeptDO userDept = deptMapper.selectById(workorderInfosDO.getUserId());
        DeptDO userDept = deptMapper.selectByIdWithoutPermission(workorderInfosDO.getUserId());
        workorderInfosRespVO.setUser(userDept.getName());
        //查询工单实施情况
        LambdaQueryWrapper<WorkorderLogDO> workorderLogWrapper = new LambdaQueryWrapper<>();
        workorderLogWrapper.eq(WorkorderLogDO::getWorkorderId, id)
                .eq(WorkorderLogDO::getStatus, "70");
        WorkorderLogDO workorderLogDO = workorderLogMapper.selectOne(workorderLogWrapper);
        if (workorderLogDO != null) {
            workorderInfosRespVO.setFinishText(workorderLogDO.getFinishText());
        }
        return workorderInfosRespVO;
    }

    @Override
    public PageResult<WorkorderInfosRespVO> getWorkorderInfosPage(WorkorderInfosPageReqVO pageReqVO) {
        List<Long> idList = null;
        PageResult<WorkorderInfosDO> result = new PageResult<>();
        LambdaQueryWrapper<WorkorderLogDO> workorderLogWrapper = new LambdaQueryWrapper<>();
        // 获取当前用户对象
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        ArrayList<WorkorderInfosRespVO> WorkorderInfosRespVOList = new ArrayList<WorkorderInfosRespVO>();
        if ("user".equals(pageReqVO.getType())) {
            long deptId = Long.parseLong(loginUser.getInfo().get("deptId"));
            pageReqVO.setUserId(deptId);
            result = workorderInfosMapper.selectPage3(pageReqVO);
        } else if ("dsjzx".equals(pageReqVO.getType())) {
            workorderLogWrapper.in(WorkorderLogDO::getStatus, "31", "32");
            List<WorkorderLogDO> workorderLogDOS = workorderLogMapper.selectList(workorderLogWrapper);
            idList = workorderLogDOS.stream()
                    .map(WorkorderLogDO::getWorkorderId) // 提取每个对象的 id
                    .collect(Collectors.toList()); // 收集为 List
            if(pageReqVO.getStatus() == null) {
                pageReqVO.setStatus("31");
            }
            if(idList.size() == 0) {
                return new PageResult<WorkorderInfosRespVO>(WorkorderInfosRespVOList, (long) 0);
            }
            List<Long> finalIdList = idList;
            List<Long> matchedIds = workorderInfosMapper.selectList(
                    new LambdaQueryWrapper<WorkorderInfosDO>()
                            .select(WorkorderInfosDO::getId)
                            .and(wrapper -> wrapper
                                    .in(WorkorderInfosDO::getId, finalIdList)
                                    .or()
                                    .in(pageReqVO.getStatus() != null, WorkorderInfosDO::getStatus, pageReqVO.getStatus())
                            )
            ).stream().map(WorkorderInfosDO::getId).collect(Collectors.toList());
            if(matchedIds.size() == 0) {
                return new PageResult<WorkorderInfosRespVO>(WorkorderInfosRespVOList, 0L);
            }
            result = workorderInfosMapper.selectPage2(pageReqVO, matchedIds);
        } else if ("zwgk".equals(pageReqVO.getType())) {
            workorderLogWrapper.in(WorkorderLogDO::getStatus, "41", "42");
            List<WorkorderLogDO> workorderLogDOS = workorderLogMapper.selectList(workorderLogWrapper);
            idList = workorderLogDOS.stream()
                    .map(WorkorderLogDO::getWorkorderId) // 提取每个对象的 id
                    .collect(Collectors.toList()); // 收集为 List
//            if(!"search".equals(pageReqVO.getSearch())){
                pageReqVO.setStatus("41");
//            }
            if(idList.size() == 0) {
                return new PageResult<WorkorderInfosRespVO>(WorkorderInfosRespVOList, (long) 0);
            }
            List<Long> finalIdList = idList;
            List<Long> matchedIds = workorderInfosMapper.selectList(
                    new LambdaQueryWrapper<WorkorderInfosDO>()
                            .select(WorkorderInfosDO::getId)
                            .and(wrapper -> wrapper
                                    .in(WorkorderInfosDO::getId, finalIdList)
                                    .or()
                                    .in(pageReqVO.getStatus() != null, WorkorderInfosDO::getStatus, pageReqVO.getStatus())
                            )
            ).stream().map(WorkorderInfosDO::getId).collect(Collectors.toList());
            if(matchedIds.size() == 0) {
                return new PageResult<WorkorderInfosRespVO>(WorkorderInfosRespVOList, 0L);
            }
//            List<WorkorderInfosDO> workorderInfosDOS = workorderInfosMapper.selectList(new LambdaQueryWrapper<WorkorderInfosDO>().select(WorkorderInfosDO::getId).in(WorkorderInfosDO::getId, matchedIds));
//            if("search".equals(pageReqVO.getSearch())) {
//                result = workorderInfosMapper.selectPage2(pageReqVO, matchedIds);
//            }
            result = workorderInfosMapper.selectPage2(pageReqVO, matchedIds);
        } else if ("yws".equals(pageReqVO.getType())) {
            long deptId = Long.parseLong(loginUser.getInfo().get("deptId"));
            List<Long> matchedIds = workorderInfosMapper.selectList(
                    new LambdaQueryWrapper<WorkorderInfosDO>()
                            .select(WorkorderInfosDO::getId)
                            .and(wrapper -> wrapper
                                    .eq(WorkorderInfosDO::getTechOperatorId, deptId)
                                    .or()
                                    .eq(WorkorderInfosDO::getCreator, loginUser.getId().toString())
                            )
            ).stream().map(WorkorderInfosDO::getId).collect(Collectors.toList());

            if(matchedIds.size() == 0) {
                return new PageResult<WorkorderInfosRespVO>(WorkorderInfosRespVOList, 0L);
            }
//            if(pageReqVO.getTechOperatorId() == null) {
//                pageReqVO.setTechOperatorId(deptId);
//            }
//            if(pageReqVO.getCategoryId() ==null  && pageReqVO.getUserId() == null && pageReqVO.getStatus() == null && StrUtil.isEmpty(pageReqVO.getRequirement()) && pageReqVO.getOrderTime() == null) {
//                pageReqVO.setCreator(loginUser.getId().toString());
//            }
            result = workorderInfosMapper.selectPage4(pageReqVO,matchedIds);
        } else {
            result = workorderInfosMapper.selectPage(pageReqVO);
        }
        LambdaQueryWrapper<WorkorderInfosDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkorderInfosDO::getCreator, loginUser.getId().toString());
        List<WorkorderInfosDO> workorderInfosDOS = workorderInfosMapper.selectList(wrapper);
        List<WorkorderInfosDO> list = result.getList();
//        list.addAll(workorderInfosDOS);
        int tmp = 0;
        for (int i = 0; i <= list.size()-1; i++) {
            WorkorderInfosDO workorderInfosDO = list.get(i);
            //查询对应的用户部门名称
            WorkorderInfosRespVO workorderInfosRespVO = BeanUtils.toBean(workorderInfosDO, WorkorderInfosRespVO.class);
            Long deptId = workorderInfosDO.getUserId();
//            DeptDO deptDO = deptMapper.selectById(deptId);
            DeptDO deptDO = deptMapper.selectByIdWithoutPermission(deptId);
            workorderInfosRespVO.setUser(deptDO.getName());
            //查询对应的运维商名称
            Long techOperatorId = workorderInfosDO.getTechOperatorId();
//            deptDO = deptMapper.selectById(techOperatorId);
            deptDO = deptMapper.selectByIdWithoutPermission(techOperatorId);

            workorderInfosRespVO.setTechOperator(deptDO.getName());
            workorderInfosRespVO.setDeptId(deptDO.getId());
            //查询对应的工单分类
            Long categoryId = workorderInfosDO.getCategoryId();
            WorkorderTypeDO workorderTypeDO = workorderTypeMapper.selectById(categoryId);
            workorderInfosRespVO.setCategory(workorderTypeDO.getName());
            workorderInfosRespVO.setCreator(workorderInfosDO.getCreator());
            WorkorderInfosRespVOList.add(workorderInfosRespVO);
        }
        return new PageResult<WorkorderInfosRespVO>(WorkorderInfosRespVOList, (long) result.getTotal());
    }

    @Override
    public List<DeptDO> getBelongingUser(DeptDO deptDO) {
        LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeptDO::getParentId, 100)
                .eq(DeptDO::getStatus, 0);
        return deptMapper.selectList(wrapper);
    }

    @Override
    public List<DeptDO> getWorkorderBelongingUser() {
        // 获取当前用户对象
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        //获取当前用户角色
        LambdaQueryWrapper<UserRoleDO> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(UserRoleDO::getUserId,loginUser.getId());
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectList(userWrapper);
        // 判断列表中是否有管理员角色
        boolean containsIdOne = userRoleDOS.stream()
                .anyMatch(userRoleDO -> userRoleDO.getRoleId() == 1L);
        //根据当前用户对象所属部门去技术运维表中查询
        LambdaQueryWrapper<TechOrgDO> wrapper = new LambdaQueryWrapper<>();
        if(!containsIdOne) {
            wrapper.eq(TechOrgDO::getTechOrgId,Long.parseLong(loginUser.getInfo().get("deptId")));
        }
        List<TechOrgDO> techOrgDOS = techOrgMapper.selectList(wrapper);
        ArrayList<DeptDO> resultList = new ArrayList<>();
        for (TechOrgDO techOrgDO : techOrgDOS) {
            Long websiteDept = techOrgDO.getWebsiteDept();//用户部门id
//            DeptDO deptDO = deptMapper.selectById(websiteDept);
            DeptDO deptDO = deptMapper.selectByIdWithoutPermission(websiteDept);
            resultList.add(deptDO);
        }
        return resultList;
    }

    @Override
    @SneakyThrows
    public Integer createFile(byte[] content, String name, String directory, String type, String uploadType) {
        // 1.1 处理 type 为空的情况
        if (StrUtil.isEmpty(type)) {
            type = FileTypeUtils.getMineType(content, name);
        }
        // 1.2 处理 name 为空的情况
        if (StrUtil.isEmpty(name)) {
            name = DigestUtil.sha256Hex(content);
        }
        if (StrUtil.isEmpty(FileUtil.extName(name))) {
            // 如果 name 没有后缀 type，则补充后缀
            String extension = FileTypeUtils.getExtension(type);
            if (StrUtil.isNotEmpty(extension)) {
                name = name + extension;
            }
        }

        // 2.1 生成上传的 path，需要保证唯一
        String path = generateUploadPath(name, directory);
        // 2.2 上传到文件存储器
        FileClient client = fileConfigService.getMasterFileClient();
        Assert.notNull(client, "客户端(master) 不能为空");
        String url = client.upload(content, path, type);
        // 3. 保存到数据库
        WorkorderFileDO workorderFileDO = new WorkorderFileDO();
        workorderFileDO.setWorkorderId(1L);
        workorderFileDO.setName(name);
        workorderFileDO.setUrl(url);
        workorderFileDO.setType(type);
        workorderFileDO.setSize(Long.parseLong(String.valueOf(content.length)));
        workorderFileMapper.insert(workorderFileDO);
        return workorderFileDO.getId().intValue();
    }

    @Override
    @Transactional
    public void checkWorkorderInfos(WorkorderInfosSaveReqVO updateReqVO) {
        WorkorderLogDO workorderLogDO = new WorkorderLogDO();
        LambdaUpdateWrapper<WorkorderInfosDO> infosWrapper = new LambdaUpdateWrapper<>();
        //查询工单流程类型
        WorkorderTypeDO workorderTypeDO = workorderTypeMapper.selectById(updateReqVO.getCategoryId());
        infosWrapper.eq(WorkorderInfosDO::getId, updateReqVO.getId());
        if ("1".equals(updateReqVO.getAuditResult())) {
            //同意
            //根据用户角色判断流程
            List<String> list = checkProcessType(updateReqVO, workorderTypeDO.getProcessType());
            infosWrapper.set(WorkorderInfosDO::getStatus, list.get(0));
            infosWrapper.set(WorkorderInfosDO::getAttachment, updateReqVO.getAttachment());
            workorderLogDO.setStatus(list.get(1));
        } else {
            //驳回
            // 获取当前用户对象
            LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
            LambdaQueryWrapper<UserRoleDO> userRoleWrapper = new LambdaQueryWrapper<>();
            userRoleWrapper.eq(UserRoleDO::getUserId, loginUser.getId());
            List<UserRoleDO> userRoleDOList = userRoleMapper.selectList(userRoleWrapper);
            //直接修改工单表中的状态
            Integer deptId = updateReqVO.getRejectTo();
//            DeptDO deptDO = deptMapper.selectById(deptId);
            DeptDO deptDO = deptMapper.selectByIdWithoutPermission(Long.parseLong(deptId+""));
            LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DeptDO::getId, deptDO.getParentId());
            deptDO = deptMapper.selectOne(wrapper);
            switch (deptDO.getId().intValue()) {
                case 100:
                    //驳回到用户
                    infosWrapper.set(WorkorderInfosDO::getStatus, "21");
                    break;
                case 110:
                    //驳回到运维商，判断驳回的运维商是否为工单发起人
                    WorkorderInfosDO infosDO = workorderInfosMapper.selectById(updateReqVO.getId());
//                    AdminUserDO adminUserDO = adminUserMapper.selectById(infosDO.getCreator());
                    AdminUserDO adminUserDO = adminUserMapper.selectByIdWithoutPermission(Long.parseLong(infosDO.getCreator()));
                    if (adminUserDO.getDeptId().intValue() == updateReqVO.getRejectTo()) {
                        //驳回的运维商为工单发起人
                        infosWrapper.set(WorkorderInfosDO::getRejectReason, updateReqVO.getAuditOpinion());
                    }
                    infosWrapper.set(WorkorderInfosDO::getStatus, "51");
                    break;
                case 101:
                    //驳回到大数据中心
                    infosWrapper.set(WorkorderInfosDO::getStatus, "31");
                    break;
                default:
                    log.info("未查询到驳回人员");
                    return;
            }
            for (UserRoleDO userRoleDO : userRoleDOList) {
                String status = ROLE_STATUS_MAP.get(userRoleDO.getRoleId());
                if(StrUtil.isNotEmpty(status)) {
                    workorderLogDO.setStatus(status);
                    break;
                }
            }
        }
        //更新工单表
        workorderInfosMapper.update(infosWrapper);
        //添加工单流转日志

        workorderLogDO.setWorkorderId(updateReqVO.getId());
        workorderLogDO.setReviewComments(updateReqVO.getAuditOpinion());
        workorderLogDO.setFinishText(updateReqVO.getFinishText());
        workorderLogMapper.insert(workorderLogDO);
    }

    @Override
    public HashMap<String, Long> getCardList() {
        HashMap<String, Long> map = new HashMap<>();
        //根据用户角色查询信息
        // 获取当前用户对象
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<UserRoleDO> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.eq(UserRoleDO::getUserId, loginUser.getId());
        List<UserRoleDO> userRoleDO = userRoleMapper.selectList(userRoleWrapper);
        //查询条件
        LambdaQueryWrapper<WorkorderInfosDO> pendingWrapper = new LambdaQueryWrapper<>();//待处理工单
        LambdaQueryWrapper<WorkorderInfosDO> finishWrapper = new LambdaQueryWrapper<>();//已完成工单
        LambdaQueryWrapper<WorkorderInfosDO> yearWrapper = new LambdaQueryWrapper<>();//年度工单
        LambdaQueryWrapper<WorkorderInfosDO> allWrapper = new LambdaQueryWrapper<>();//全部工单
        // 获取当前年的第一天 00:00:00
        Date startOfYear = DateUtil.beginOfYear(DateUtil.date());
        // 获取当前年的最后一天 23:59:59
        Date endOfYear = DateUtil.endOfYear(DateUtil.date());
        boolean found = false;
        Long pendingCount = 0L;
        Long finidshCount = 0L;
        Long yearCount = 0L;
        Long count = 0L;
        for (UserRoleDO roleDO : userRoleDO) {
            if (found) break; // 如果已找到，退出循环
            switch (roleDO.getRoleId().intValue()){
                case 161:
                    //用户、查询待处理工单
                    pendingWrapper.eq(WorkorderInfosDO::getUserId,loginUser.getInfo().get("deptId"))
//                            .ne(WorkorderInfosDO::getStatus, "0")
                            .ne(WorkorderInfosDO::getStatus, "70");
                    //查询已完成工单 70
                    finishWrapper.eq(WorkorderInfosDO::getUserId,loginUser.getInfo().get("deptId"))
                            .eq(WorkorderInfosDO::getStatus,"70");
                    //查询年度工单量
                    yearWrapper.eq(WorkorderInfosDO::getUserId,loginUser.getInfo().get("deptId"))
//                            .ne(WorkorderInfosDO::getStatus,"0")
                            .between(WorkorderInfosDO::getOrderTime, startOfYear, endOfYear);
                    //查询所有工单
                    allWrapper.eq(WorkorderInfosDO::getUserId,loginUser.getInfo().get("deptId"));
//                            .ne(WorkorderInfosDO::getStatus,"0");
                    found = true;
                    pendingCount = workorderInfosMapper.selectCount(pendingWrapper);
                    finidshCount = workorderInfosMapper.selectCount(finishWrapper);
                    yearCount = workorderInfosMapper.selectCount(yearWrapper);
                    count = workorderInfosMapper.selectCount(allWrapper);
                    break;
                case 162:
                    //运维商、查询待处理工单、自己发起的和自己处理的工单
                    pendingWrapper.nested(w -> w.eq(WorkorderInfosDO::getCreator, loginUser.getId())
                            .or()
                            .eq(WorkorderInfosDO::getTechOperatorId, loginUser.getInfo().get("deptId")))
                            .nested(w -> w.ne(WorkorderInfosDO::getStatus, "0")
                                    .ne(WorkorderInfosDO::getStatus, "70"));
                    //查询已完成工单 70
                    finishWrapper.nested(w -> w.eq(WorkorderInfosDO::getCreator, loginUser.getId())
                            .or()
                            .eq(WorkorderInfosDO::getTechOperatorId, loginUser.getInfo().get("deptId")))
                            .eq(WorkorderInfosDO::getStatus, "70");
                    //查询年度工单量
                    yearWrapper.nested(w -> w.eq(WorkorderInfosDO::getTechOperatorId, loginUser.getInfo().get("deptId"))
                            .or()
                            .eq(WorkorderInfosDO::getCreator, loginUser.getId()))
//                            .ne(WorkorderInfosDO::getStatus, "0")
                            .between(WorkorderInfosDO::getOrderTime, startOfYear, endOfYear);
                    //查询所有工单,自己发起的或者自己处理的
                    allWrapper.nested(w -> w.eq(WorkorderInfosDO::getTechOperatorId, loginUser.getInfo().get("deptId"))
                            .or()
                            .eq(WorkorderInfosDO::getCreator, loginUser.getId()));
//                            .ne(WorkorderInfosDO::getStatus, "0");
                    found = true;
                    pendingCount = workorderInfosMapper.selectCount(pendingWrapper);
                    finidshCount = workorderInfosMapper.selectCount(finishWrapper);
                    yearCount = workorderInfosMapper.selectCount(yearWrapper);
                    count = workorderInfosMapper.selectCount(allWrapper);
                    break;
                case 163:
                    //大数据中心三处、待处理工单查询处于31或者32状态的工单、查询工单日志表中处理过的工单
                    LambdaQueryWrapper<WorkorderInfosDO> wrapper = new LambdaQueryWrapper<>();
                    wrapper.select(WorkorderInfosDO::getId)
                            .eq(WorkorderInfosDO::getStatus,"31")
                            .or().eq(WorkorderInfosDO::getStatus,"32");
                    List<WorkorderInfosDO> workorderList = workorderInfosMapper.selectList(wrapper);
                    //查询工单日志表中处理过的工单
                    LambdaQueryWrapper<WorkorderLogDO> wrapperLog = new LambdaQueryWrapper<>();
                    wrapperLog.select(WorkorderLogDO::getWorkorderId)
                            .eq(WorkorderLogDO::getStatus,"31")
                            .or().eq(WorkorderLogDO::getStatus,"32");
                    List<WorkorderLogDO> workorderLogList = workorderLogMapper.selectList(wrapperLog);
                    //收集id
                    List<Long> resultIds = Stream.concat(
                            workorderList.stream().map(WorkorderInfosDO::getId),
                            workorderLogList.stream().map(WorkorderLogDO::getWorkorderId)
                    )
                            .distinct()  // 去重
                            .collect(Collectors.toList());
                    pendingWrapper.in(WorkorderInfosDO::getId,resultIds)
                            .ne(WorkorderInfosDO::getStatus,"70")
                            .ne(WorkorderInfosDO::getStatus,"0");


                    //查询已完成工单 70、查询工单日志表中处理过的工单
                    wrapperLog = new LambdaQueryWrapper<>();
                    wrapperLog.select(WorkorderLogDO::getWorkorderId)
                            .eq(WorkorderLogDO::getStatus,"31")
                            .or().eq(WorkorderLogDO::getStatus,"32");
                    workorderLogList = workorderLogMapper.selectList(wrapperLog);
                    List<Long> finishresultIds = workorderLogList.stream()
                            .map(WorkorderLogDO::getWorkorderId)
                            .collect(Collectors.toList());
                    finishWrapper.in(WorkorderInfosDO::getId,finishresultIds)
                            .eq(WorkorderInfosDO::getStatus,"70");

                    //查询年度工单量
                    yearWrapper.in(WorkorderInfosDO::getId,resultIds)
//                            .ne(WorkorderInfosDO::getStatus, "0")
                            .between(WorkorderInfosDO::getOrderTime,startOfYear,endOfYear);
                    //查询所有工单
                    allWrapper.in(WorkorderInfosDO::getId,resultIds);
//                            .ne(WorkorderInfosDO::getStatus, "0");
                    found = true;
                    if(resultIds.size() > 0) {
                        pendingCount = workorderInfosMapper.selectCount(pendingWrapper);
                        yearCount = workorderInfosMapper.selectCount(yearWrapper);
                        count = workorderInfosMapper.selectCount(allWrapper);
                    }
                    if(finishresultIds.size()>0) {
                        finidshCount = workorderInfosMapper.selectCount(finishWrapper);
                    }
                    break;
                case 164:
                    //政务公开
                    wrapper = new LambdaQueryWrapper<>();
                    wrapper.select(WorkorderInfosDO::getId)
                            .eq(WorkorderInfosDO::getStatus,"41")
                            .or().eq(WorkorderInfosDO::getStatus,"42");
                    workorderList = workorderInfosMapper.selectList(wrapper);
                    //查询工单日志表中处理过的工单
                    wrapperLog = new LambdaQueryWrapper<>();
                    wrapperLog.select(WorkorderLogDO::getWorkorderId)
                            .eq(WorkorderLogDO::getStatus,"41")
                            .or().eq(WorkorderLogDO::getStatus,"42");
                    workorderLogList = workorderLogMapper.selectList(wrapperLog);
                    //收集id
                    resultIds = Stream.concat(
                            workorderList.stream().map(WorkorderInfosDO::getId),
                            workorderLogList.stream().map(WorkorderLogDO::getWorkorderId)
                    )
                            .distinct()  // 去重
                            .collect(Collectors.toList());
                    pendingWrapper.in(WorkorderInfosDO::getId,resultIds)
                            .ne(WorkorderInfosDO::getStatus,"70")
                            .ne(WorkorderInfosDO::getStatus,"0");


                    //查询已完成工单 70、查询工单日志表中处理过的工单
                    wrapperLog = new LambdaQueryWrapper<>();
                    wrapperLog.select(WorkorderLogDO::getWorkorderId)
                            .eq(WorkorderLogDO::getStatus,"41")
                            .or().eq(WorkorderLogDO::getStatus,"42");
                    workorderLogList = workorderLogMapper.selectList(wrapperLog);
                    finishresultIds = workorderLogList.stream()
                            .map(WorkorderLogDO::getWorkorderId)
                            .collect(Collectors.toList());
                    finishWrapper.in(WorkorderInfosDO::getId,finishresultIds)
                            .eq(WorkorderInfosDO::getStatus,"70");

                    //查询年度工单量
                    yearWrapper.in(WorkorderInfosDO::getId,resultIds)
//                            .ne(WorkorderInfosDO::getStatus, "0")
                            .between(WorkorderInfosDO::getOrderTime,startOfYear,endOfYear);
                    //查询所有工单
                    allWrapper.in(WorkorderInfosDO::getId,resultIds);
//                            .ne(WorkorderInfosDO::getStatus, "0");
                    found = true;
                    if(resultIds.size() > 0) {
                        pendingCount = workorderInfosMapper.selectCount(pendingWrapper);
                        yearCount = workorderInfosMapper.selectCount(yearWrapper);
                        count = workorderInfosMapper.selectCount(allWrapper);
                    }
                    if(finishresultIds.size()>0) {
                        finidshCount = workorderInfosMapper.selectCount(finishWrapper);
                    }
                    break;
                case 1:
                    //管理员、查询待处理工单
                    pendingWrapper.ne(WorkorderInfosDO::getStatus,"70")
                            .ne(WorkorderInfosDO::getStatus,"0");
                    //查询已完成工单 70
                    finishWrapper.eq(WorkorderInfosDO::getStatus,"70");
                    //查询年度工单量 .ne(WorkorderInfosDO::getStatus, "0")
                    yearWrapper
                            .between(WorkorderInfosDO::getOrderTime,startOfYear,endOfYear);
                    //查询所有工单、没有条件，管理员查询全部工单
//                    allWrapper.ne(WorkorderInfosDO::getStatus, "0");
                    found = true;
                    pendingCount = workorderInfosMapper.selectCount(pendingWrapper);
                    finidshCount = workorderInfosMapper.selectCount(finishWrapper);
                    yearCount = workorderInfosMapper.selectCount(yearWrapper);
                    count = workorderInfosMapper.selectCount(allWrapper);
                    break;
            }
        }

//        pendingCount = workorderInfosMapper.selectCount(pendingWrapper);
//        finidshCount = workorderInfosMapper.selectCount(finishWrapper);
//        yearCount = workorderInfosMapper.selectCount(yearWrapper);
//        count = workorderInfosMapper.selectCount(allWrapper);
        map.put("pendingCount",pendingCount);

        map.put("finidshCount",finidshCount);

        map.put("yearCount",yearCount);
        //查询所有工单

        map.put("allCount",count);
        return map;
    }


    @Override
    public List<DeptWorkorderVO> getDeptWorkorder() {
        // 获取当前用户对象
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<UserRoleDO> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(UserRoleDO::getUserId,loginUser.getId());
        List<UserRoleDO> userRoleDOS = userRoleMapper.selectList(userWrapper);

        List<DeptDO> deptList = null;
        List<WorkorderInfosDO> workorderList = new ArrayList<>();
        List<DeptWorkorderVO> result = new ArrayList<>();
        // 判断列表中是否有管理员角色
        boolean containsIdOne = userRoleDOS.stream()
                .anyMatch(userRoleDO -> userRoleDO.getRoleId() == 1L);
        // 判断列表中是否有工单用户角色
        boolean workorderContainsIdOne = userRoleDOS.stream()
                .anyMatch(userRoleDO -> userRoleDO.getRoleId() == 161L);
        // 判断列表中是否有工单审核三处角色
        boolean workorderCheck = userRoleDOS.stream()
                .anyMatch(userRoleDO -> userRoleDO.getRoleId() == 163L);
        // 判断列表中是否有工单审核政务公开角色
        boolean workorderCheckZWGK = userRoleDOS.stream()
                .anyMatch(userRoleDO -> userRoleDO.getRoleId() == 164L);
        if(containsIdOne) {
            //获取所有部门
            LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DeptDO::getParentId,100);
            deptList = deptMapper.selectList(wrapper);
            //查询所有工单
            LambdaQueryWrapper<WorkorderInfosDO> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.ne(WorkorderInfosDO::getStatus,"0");
            workorderList = workorderInfosMapper.selectList(wrapper1);
        }else if(workorderContainsIdOne){
            //查询当前工单用户所有工单
            LambdaQueryWrapper<WorkorderInfosDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WorkorderInfosDO::getUserId,loginUser.getInfo().get("deptId"))
                    .ne(WorkorderInfosDO::getStatus,"0");
            workorderList = workorderInfosMapper.selectList(wrapper);
        }else if(workorderCheck) {
            //获取所有部门
            LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DeptDO::getParentId,100);
            deptList = deptMapper.selectList(wrapper);
            //查询自己处理的工单
            //查询日志表中
            LambdaQueryWrapper<WorkorderLogDO> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(WorkorderLogDO::getStatus,"31","32");
            List<WorkorderLogDO> workorderLogDOList = workorderLogMapper.selectList(wrapper1);
            // 提取 id 到 List<Long>
            List<Long> idList = workorderLogDOList.stream()
                    .map(WorkorderLogDO::getWorkorderId)  // 提取每个 TechOrgDO 的 id
                    .collect(Collectors.toList());  // 收集到 List
            //查询工单表中处于审核状态的工单
            LambdaQueryWrapper<WorkorderInfosDO> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.in(WorkorderInfosDO::getStatus,"31","32");
            List<WorkorderInfosDO> workorderInfosDOList = workorderInfosMapper.selectList(wrapper2);
            // 提取 id 到 List<Long>
            List<Long> idList2 = workorderInfosDOList.stream()
                    .map(WorkorderInfosDO::getId)  // 提取每个 TechOrgDO 的 id
                    .collect(Collectors.toList());  // 收集到 List
            List<Long> result2 = Stream.concat(idList.stream(), idList2.stream())
                    .distinct()
                    .collect(Collectors.toList());
            if(result2.size() == 0) {
                return result;
            }
            //查询最后需要的工单
            LambdaQueryWrapper<WorkorderInfosDO> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.in(WorkorderInfosDO::getId,result2)
                    .ne(WorkorderInfosDO::getStatus,"0");
            workorderList =workorderInfosMapper.selectList(wrapper3);
        }else if(workorderCheckZWGK) {
            //获取所有部门
            LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DeptDO::getParentId,100);
            deptList = deptMapper.selectList(wrapper);
            //查询自己处理的工单
            //查询日志表中
            LambdaQueryWrapper<WorkorderLogDO> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.in(WorkorderLogDO::getStatus,"41","42");
            List<WorkorderLogDO> workorderLogDOList = workorderLogMapper.selectList(wrapper1);
            // 提取 id 到 List<Long>
            List<Long> idList = workorderLogDOList.stream()
                    .map(WorkorderLogDO::getWorkorderId)  // 提取每个 TechOrgDO 的 id
                    .collect(Collectors.toList());  // 收集到 List
            //查询工单表中处于审核状态的工单
            LambdaQueryWrapper<WorkorderInfosDO> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.in(WorkorderInfosDO::getStatus,"41","42");
            List<WorkorderInfosDO> workorderInfosDOList = workorderInfosMapper.selectList(wrapper2);
            // 提取 id 到 List<Long>
            List<Long> idList2 = workorderInfosDOList.stream()
                    .map(WorkorderInfosDO::getId)  // 提取每个 TechOrgDO 的 id
                    .collect(Collectors.toList());  // 收集到 List
            List<Long> result2 = Stream.concat(idList.stream(), idList2.stream())
                    .distinct()
                    .collect(Collectors.toList());
            if(result2.size() == 0) {
                return result;
            }
            //查询最后需要的工单
            LambdaQueryWrapper<WorkorderInfosDO> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.in(WorkorderInfosDO::getId,result2)
                    .ne(WorkorderInfosDO::getStatus,"0");
            workorderList =workorderInfosMapper.selectList(wrapper3);
        }else {
            //查询涉及到自己的工单比如创建人、处理人是自己
            LambdaQueryWrapper<WorkorderInfosDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WorkorderInfosDO::getCreator,loginUser.getId())
                    .or()
                    .eq(WorkorderInfosDO::getTechOperatorId,loginUser.getInfo().get("deptId"));
            workorderList = workorderInfosMapper.selectList(wrapper);
            // 提取 id 到 List<Long>
            List<Long> idList = workorderList.stream()
                    .map(WorkorderInfosDO::getUserId)  // 提取每个 TechOrgDO 的 id
                    .collect(Collectors.toList());  // 收集到 List
            if(idList.size() == 0) {
                return result;
            }
            //获取部门
            LambdaQueryWrapper<DeptDO> wrapper2 = new LambdaQueryWrapper<>();
            wrapper2.in(DeptDO::getId,idList);
            deptList = deptMapper.selectList(wrapper2);
        }
        if(workorderContainsIdOne) {
            List<Long> categoryIds = workorderList.stream()
                    .map(WorkorderInfosDO::getCategoryId)
                    .collect(Collectors.toList());
            if(categoryIds.size() > 0) {
                LambdaQueryWrapper<WorkorderTypeDO> wrapper = new LambdaQueryWrapper<>();
                wrapper.in(WorkorderTypeDO::getId,categoryIds);
                List<WorkorderTypeDO> workorderTypeDOS = workorderTypeMapper.selectList(wrapper);
                // 使用 Stream 按工单名称统计工单数量，确保未匹配的部门返回 0
                List<WorkorderInfosDO> resultList = workorderList;
                result = workorderTypeDOS.stream()
                        .map(dept -> {
                            long count = resultList.stream()
                                    .filter(workorder ->
                                            workorder.getUserId() != null &&
                                                    workorder.getCategoryId().equals(dept.getId()))
                                    .count();

                            return new DeptWorkorderVO(dept.getName(), count);
                        })
                        .collect(Collectors.toList());
            }

        }else {
            // 使用 Stream 按部门名称统计工单数量，确保未匹配的部门返回 0
            List<WorkorderInfosDO> resultList = workorderList;
            result = deptList.stream()
                    .map(dept -> {
                        long count = resultList.stream()
                                .filter(workorder ->
                                        workorder.getUserId() != null &&
                                                workorder.getUserId().equals(dept.getId()))
                                .count();

                        return new DeptWorkorderVO(dept.getName(), count);
                    })
                    .collect(Collectors.toList());
        }
        return result;
    }


    @Override
    public PageResult<WorkorderInfosRespVO> getPendingWorkorder(WorkorderInfosPageReqVO pageReqVO) {
        //获取待处理工单列表
        List<WorkorderInfosRespVO> resultList = new ArrayList<WorkorderInfosRespVO>();
        //根据用户角色查询信息
        // 获取当前用户对象
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<UserRoleDO> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.eq(UserRoleDO::getUserId, loginUser.getId());
        List<UserRoleDO> userRoleDO = userRoleMapper.selectList(userRoleWrapper);
        PageResult<WorkorderInfosDO> workorderList = null;
        LambdaQueryWrapper<WorkorderInfosDO> wrapper = new LambdaQueryWrapper<>();
        boolean found = false;
        for (UserRoleDO roleDO : userRoleDO) {
            if (found) break; // 如果已找到，退出循环
            switch (roleDO.getRoleId().intValue()){
                case 161:
                    //用户、查询待处理工单
                    wrapper.eq(WorkorderInfosDO::getUserId,loginUser.getInfo().get("deptId"))
                            .ne(WorkorderInfosDO::getStatus, "0")
                            .ne(WorkorderInfosDO::getStatus, "70")
                            .orderByDesc(WorkorderInfosDO::getOrderTime);
                    workorderList = workorderInfosMapper.selectPage(pageReqVO,wrapper);
                    found = true;
                    break;
                case 162:
                    //运维商、查询待处理工单、自己发起的和自己处理的工单
                    wrapper.nested(w -> w.eq(WorkorderInfosDO::getCreator, loginUser.getId())
                            .or()
                            .eq(WorkorderInfosDO::getTechOperatorId, Long.parseLong(loginUser.getInfo().get("deptId"))))
                            .nested(w -> w.ne(WorkorderInfosDO::getStatus, "0")
                                    .ne(WorkorderInfosDO::getStatus, "70"))
                            .orderByDesc(WorkorderInfosDO::getOrderTime);
                    workorderList = workorderInfosMapper.selectPage(pageReqVO,wrapper);
                    found = true;
                    break;
                case 163:
                    //大数据中心三处、待处理工单查询处于31或者32状态的工单、查询工单日志表中处理过的工单
                    wrapper.select(WorkorderInfosDO::getId)
                            .eq(WorkorderInfosDO::getStatus,"31")
                            .or().eq(WorkorderInfosDO::getStatus,"32");
                    List<WorkorderInfosDO> workorderLists = workorderInfosMapper.selectList(wrapper);
                    //查询工单日志表中处理过的工单
                    LambdaQueryWrapper<WorkorderLogDO> wrapperLog = new LambdaQueryWrapper<>();
                    wrapperLog.select(WorkorderLogDO::getWorkorderId)
                            .eq(WorkorderLogDO::getStatus,"31")
                            .or().eq(WorkorderLogDO::getStatus,"32");
                    List<WorkorderLogDO> workorderLogList = workorderLogMapper.selectList(wrapperLog);
                    //收集id
                    List<Long> resultIds = Stream.concat(
                            workorderLists.stream().map(WorkorderInfosDO::getId),
                            workorderLogList.stream().map(WorkorderLogDO::getWorkorderId)
                    )
                            .distinct()  // 去重
                            .collect(Collectors.toList());
                    if(resultIds.size() == 0) {
                        return new PageResult<WorkorderInfosRespVO>(resultList, (long) 0);
                    }
                    wrapper = new LambdaQueryWrapper<>();
                    wrapper.in(WorkorderInfosDO::getId,resultIds)
                            .ne(WorkorderInfosDO::getStatus,"70")
                            .ne(WorkorderInfosDO::getStatus,"0")
                            .orderByDesc(WorkorderInfosDO::getOrderTime);
                    workorderList = workorderInfosMapper.selectPage(pageReqVO,wrapper);
                    found = true;
                    break;
                case 164:
                    //政务公开
                    wrapper.select(WorkorderInfosDO::getId)
                            .eq(WorkorderInfosDO::getStatus,"41")
                            .or().eq(WorkorderInfosDO::getStatus,"42");
                    workorderLists = workorderInfosMapper.selectList(wrapper);
                    //查询工单日志表中处理过的工单
                    wrapperLog = new LambdaQueryWrapper<>();
                    wrapperLog.select(WorkorderLogDO::getWorkorderId)
                            .eq(WorkorderLogDO::getStatus,"41")
                            .or().eq(WorkorderLogDO::getStatus,"42");
                    workorderLogList = workorderLogMapper.selectList(wrapperLog);
                    //收集id
                    resultIds = Stream.concat(
                            workorderLists.stream().map(WorkorderInfosDO::getId),
                            workorderLogList.stream().map(WorkorderLogDO::getWorkorderId)
                    )
                            .distinct()  // 去重
                            .collect(Collectors.toList());
                    if(resultIds.size() == 0) {
                        return new PageResult<WorkorderInfosRespVO>(resultList, (long) 0);
                    }
                    wrapper = new LambdaQueryWrapper<>();
                    wrapper.in(WorkorderInfosDO::getId,resultIds)
                            .ne(WorkorderInfosDO::getStatus,"70")
                            .ne(WorkorderInfosDO::getStatus,"0")
                            .orderByDesc(WorkorderInfosDO::getOrderTime);
                    workorderList = workorderInfosMapper.selectPage(pageReqVO,wrapper);
                    found = true;
                    break;
                case 1:
                    //管理员、查询待处理工单
                    workorderList = workorderInfosMapper.pendingWorkorderSelectPage(pageReqVO);
                    found = true;
                    break;
            }
        }

        List<WorkorderInfosDO> list = workorderList.getList();
        for (WorkorderInfosDO infosDO : list) {
            WorkorderInfosRespVO vo = BeanUtils.toBean(infosDO, WorkorderInfosRespVO.class);
            //查询工单分类
            WorkorderTypeDO workorderTypeDO = workorderTypeMapper.selectById(vo.getCategoryId());
            vo.setCategory(workorderTypeDO.getName());
            //查询部门用户
//            DeptDO deptDO = deptMapper.selectById(vo.getUserId());
            DeptDO deptDO = deptMapper.selectByIdWithoutPermission(vo.getUserId());
            vo.setUser(deptDO.getName());
            //查询运维商
//            DeptDO deptDO1 = deptMapper.selectById(vo.getTechOperatorId());
            DeptDO deptDO1 = deptMapper.selectByIdWithoutPermission(vo.getTechOperatorId());
            vo.setTechOperator(deptDO1.getName());
            resultList.add(vo);
        }
        return new PageResult<WorkorderInfosRespVO>(resultList, (long) workorderList.getTotal());
    }

    private List<String> checkProcessType(WorkorderInfosSaveReqVO workorderInfosSaveReqVO, Integer type) {
        // 获取当前用户对象
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        LambdaQueryWrapper<UserRoleDO> userRoleWrapper = new LambdaQueryWrapper<>();
        userRoleWrapper.eq(UserRoleDO::getUserId, loginUser.getId());
        List<UserRoleDO> userRoleDOList = userRoleMapper.selectList(userRoleWrapper);
        String status = "";
        String statusLog = "";
        boolean tmp = false;
        for (UserRoleDO userRoleDO : userRoleDOList) {
            switch (userRoleDO.getRoleId().intValue()) {
                case 161:
                    //用户确认
                    if (type != 3) {
                        statusLog = "21";
                        status = "31";
                        tmp = true;
                        break;
                    }else {//新增的
                        statusLog = "21";
                        status = "51";
                        tmp = true;
                        break;
                    }
                case 163:
                    //大数据中心
                    statusLog = "31";
                    if (type == 1) {
                        status = "41";
                    } else {
                        status = "60";
                    }
                    tmp = true;
                    break;
                case 164:
                    //政务公开处
                    statusLog = "41";
                    status = "60";
                    tmp = true;
                    break;
                case 162:
                    //运维商
                    if (workorderInfosSaveReqVO.getStatus().equals("60")) {
                        statusLog = "70";
                        status = "70";
                    } else if (type != 3) {
                        statusLog = "51";
                        status = "21";
                    } else {
                        statusLog = "51";
                        status = "31";
                    }
                    tmp = true;
                    break;
//                default:
//                    log.info("未查询到对应角色信息");
            }
            if(tmp) {
                break;
            }
        }

        ArrayList<String> list = new ArrayList<>();
        list.add(status);
        list.add(statusLog);
        return list;
    }

    @VisibleForTesting
    String generateUploadPath(String name, String directory) {
        // 1. 生成前缀、后缀
        String prefix = null;
        if (PATH_PREFIX_DATE_ENABLE) {
            prefix = LocalDateTimeUtil.format(LocalDateTimeUtil.now(), PURE_DATE_PATTERN);
        }
        String suffix = null;
        if (PATH_SUFFIX_TIMESTAMP_ENABLE) {
            suffix = String.valueOf(System.currentTimeMillis());
        }

        // 2.1 先拼接 suffix 后缀
        if (StrUtil.isNotEmpty(suffix)) {
            String ext = FileUtil.extName(name);
            if (StrUtil.isNotEmpty(ext)) {
                name = FileUtil.mainName(name) + StrUtil.C_UNDERLINE + suffix + StrUtil.DOT + ext;
            } else {
                name = name + StrUtil.C_UNDERLINE + suffix;
            }
        }
        // 2.2 再拼接 prefix 前缀
        if (StrUtil.isNotEmpty(prefix)) {
            name = prefix + StrUtil.SLASH + name;
        }
        // 2.3 最后拼接 directory 目录
        if (StrUtil.isNotEmpty(directory)) {
            name = directory + StrUtil.SLASH + name;
        }
        return name;
    }
}