package com.ruoyi.cs.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.enums.ServiceResponseEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.securityContext.CsOrderMemberUserSecurityContext;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.cs.domain.*;
import com.ruoyi.cs.domain.dto.*;
import com.ruoyi.cs.domain.vo.*;
import com.ruoyi.cs.mapper.CsOrderMemberUserMapper;
import com.ruoyi.cs.mapper.CsResourceOrderApplyMapper;
import com.ruoyi.cs.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 资源、工单申请Service业务层处理
 *
 * @author ruoyi
 * @date 2024-04-23
 */
@Service
public class CsResourceOrderApplyServiceImpl implements ICsResourceOrderApplyService {
    @Resource
    private CsResourceOrderApplyMapper csResourceOrderApplyMapper;

    @Resource
    private ICsUserInfoService csUserInfoService;

    @Resource
    private ICsBusinessMappingService csBusinessMappingService;

    @Resource
    private ICsUserNetworkInfoService userNetworkInfoService;

    @Resource
    private ICsResApplySoftwareInfoService applySoftwareInfoService;

    @Resource
    private ICsAnnexService csAnnexService;

    @Resource
    private ICsAchievementInfoService achievementInfoService;

    @Resource
    private ICsAchievementInfoDetailsService achievementInfoDetailsService;

    @Resource
    private ICsApprovalConfigService approvalConfigService;

    @Resource
    private ICsApprovalCarbonCopyService approvalCarbonCopyService;

    @Resource
    private CsOrderMemberUserMapper csOrderMemberUserMapper;

    @Resource
    private ICsAccountExtensionInfoService accountExtensionInfoService;

    /**
     * 查询资源、工单申请
     *
     * @param applyId 资源、工单申请主键
     * @return 资源、工单申请
     */
    @Override
    public CsResourceOrderApply selectCsResourceOrderApplyByApplyId(String applyId) {
        return csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);
    }

    /**
     * 查询资源、工单申请列表
     *
     * @param csResourceOrderApply 资源、工单申请
     * @return 资源、工单申请
     */
    @Override
    public List<ResourceOrderApplyVO> selectCsResourceOrderApplyList(CsResourceOrderApply csResourceOrderApply) {
        List<ResourceOrderApplyVO> csResourceOrderApplies = csResourceOrderApplyMapper.selectCsResourceOrderApplyList(csResourceOrderApply);
        //塞入列表数据
        return csResourceOrderApplies;
    }

    /**
     * 新增资源、工单申请
     *
     * @param csResourceOrderApply 资源、工单申请
     * @return 结果
     */
    @Override
    public int insertCsResourceOrderApply(CsResourceOrderApply csResourceOrderApply) {
        csResourceOrderApply.setResourceClassId(IdUtils.fastSimpleUUID());
        csResourceOrderApply.setCreateAt(DateUtils.getNowDate());
        csResourceOrderApply.setDelFlag("0");
        return csResourceOrderApplyMapper.insertCsResourceOrderApply(csResourceOrderApply);
    }

    /**
     * 修改资源、工单申请
     *
     * @param csResourceOrderApply 资源、工单申请
     * @return 结果
     */
    @Override
    public int updateCsResourceOrderApply(CsResourceOrderApply csResourceOrderApply) {
        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(csResourceOrderApply);
    }

    /**
     * 批量删除资源、工单申请
     *
     * @param applyIds 需要删除的资源、工单申请主键
     * @return 结果
     */
    @Override
    public int deleteCsResourceOrderApplyByApplyIds(String[] applyIds) {
        return csResourceOrderApplyMapper.deleteCsResourceOrderApplyByApplyIds(applyIds);
    }

    /**
     * 删除资源、工单申请信息
     *
     * @param applyId 资源、工单申请主键
     * @return 结果
     */
    @Override
    public int deleteCsResourceOrderApplyByApplyId(String applyId) {
        return csResourceOrderApplyMapper.deleteCsResourceOrderApplyByApplyId(applyId);
    }

    //申请状态：0-待确认，1-盖章材料待上传，2-待审批，3-审批拒绝，4-待审核，5-审核拒绝，6-待分配，7-进行中，8-驳回，9-已完成
    //资源申请流程： 2-待审批 --> 0-待确认 --> 1-盖章材料待上传 --> 6-待分配 --> 4-待审核 --> 7-进行中 --> 9-已完成
    //              3-审批拒绝                                             5-审核拒绝

    /**
     * 新增 -构造资源申请基础信息--待审批2
     *
     * @param resourceDTO 资源申请信息
     * @param applyId     申请id
     * @param nowDate     时间
     * @return 待新增资源申请对象
     */
    private CsResourceOrderApply buildResourceApplyBasicData(CsResourceOrderApplyADDDTO resourceDTO, String applyId, Date nowDate) {
        CsResourceOrderApply addApply = BeanUtil.toBean(resourceDTO, CsResourceOrderApply.class);
        addApply.setApplyId(applyId);
        addApply.setApplyNumber('R' + IdUtil.getSnowflakeNextIdStr());
        addApply.setApplyStatus("2");
        addApply.setStatus("0");
        addApply.setIsDraft("0");
        addApply.setCreateAt(nowDate);
        CsOrderMemberUser csOrderMemberUser = csOrderMemberUserMapper.selectCsUserInfoByMemberUserId(CsOrderMemberUserSecurityContext.getMemberUserId());
        if (!ObjectUtils.isEmpty(csOrderMemberUser)) {
            addApply.setOrderTitle(csOrderMemberUser.getRealName() + "申请的" + resourceDTO.getResourceClassName() + "资源");
        }
        return addApply;
    }

    /**
     * 新增资源申请
     *
     * @param resourceDTO 资源申请信息
     * @return 新增结果
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int insertApplyForResource(CsResourceOrderApplyADDDTO resourceDTO) {
        //构造资源申请基础信息
        String applyId = IdUtils.fastSimpleUUID();
        Date nowDate = DateUtils.getNowDate();
        CsResourceOrderApply addApply = buildResourceApplyBasicData(resourceDTO, applyId, nowDate);
        String memberUserId = CsOrderMemberUserSecurityContext.getMemberUserId();
        addApply.setMemberUserId(memberUserId);
        //批量新增使用人员
        List<CsUserInfoDTO> userDTOList = resourceDTO.getUserInfoList();
        if (!CollectionUtil.isEmpty(userDTOList)) {
            int inUserList = csUserInfoService.batchInsertCsUserInfo(userDTOList, applyId, nowDate);
        }
        //批量新增业务映射
        List<CsBusinessMappingDTO> businessMappingList = resourceDTO.getBusinessMappingList();
        if (!CollectionUtil.isEmpty(businessMappingList)) {
            int inMappingList = csBusinessMappingService.batchInsertBusinessMapping(businessMappingList, applyId, nowDate);
        }
        //批量新增申请表
        List<CsAnnexAddApplyDTO> applyFileList = resourceDTO.getApplyFileList();
        if (!CollectionUtil.isEmpty(applyFileList)) {
            int inApplyFileList = csAnnexService.batchInsertResourceApplyFiles(applyFileList, addApply);
        }
        // 网络资源申请直接待审核
        if (resourceDTO.getNetworkType() != null && !resourceDTO.getNetworkType().equals("")) {
            addApply.setApplyStatus("4");
        }
        //新增申请
        return csResourceOrderApplyMapper.insertCsResourceOrderApply(addApply);
    }

    /**
     * 资源申请信息详情
     *
     * @param applyId 申请ID
     * @return
     */
    @Override
    public CsResourceOrderApplyVO applyForResourceDetail(String applyId) {
        //用户信息
        CsResourceOrderApply csResourceOrderApply = csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);


        if (ObjectUtils.isEmpty(csResourceOrderApply)) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        CsResourceOrderApplyVO applyDetail = BeanUtil.toBean(csResourceOrderApply, CsResourceOrderApplyVO.class);
        //查询当前申请的使用人员信息
        List<CsUserInfoVO> userInfoVOS = csUserInfoService.selectApplyUserInfoList(applyId);
        if (CollectionUtil.isNotEmpty(userInfoVOS)) {
            applyDetail.setUserInfoList(userInfoVOS);
        }

        //云计算业务映射
        if (applyDetail.getResourceClassId() != null && applyDetail.getResourceClassId().equals("2")) {
            List<CsBusinessMappingVO> mappingVOS = csBusinessMappingService.selectApplyBusinessMappingList(applyId, "0");
            if (CollectionUtil.isNotEmpty(mappingVOS)) {
                applyDetail.setBusinessMappingList(mappingVOS);
            }
        }

        //用户端网络信息列表
        List<CsUserNetworkInfoVO> csUserNetworkInfoVOS = userNetworkInfoService.selectUserNetworkInfoVOList(applyId, "0");
        if (CollectionUtil.isNotEmpty(csUserNetworkInfoVOS)) {
            applyDetail.setUserNetworkInfoList(csUserNetworkInfoVOS);
        }

        //软件信息applySoftwareInfoService
        CsResApplySoftwareInfoVO csResApplySoftwareInfoVO = applySoftwareInfoService.selectVO(applyId);
        if (ObjectUtil.isNotEmpty(csResApplySoftwareInfoVO)) {
            applyDetail.setSoftWareInfo(csResApplySoftwareInfoVO);
        }

        //申请表列表List<CsAnnexAddApplyDTO> applyFileList
        List<CsAnnexApplyVO> applyFileList = csAnnexService.getApplyFileList(applyId, applyDetail.getApplyType());
        if (CollectionUtil.isNotEmpty(applyFileList)) {
            for (CsAnnexApplyVO csAnnexApplyVO : applyFileList) {
                csAnnexApplyVO.setName(csAnnexApplyVO.getAnnexName());
                csAnnexApplyVO.setUrl(csAnnexApplyVO.getAnnexUrl());
            }
            applyDetail.setApplyFileList(applyFileList);
        }

        return applyDetail;
    }

    /**
     * 管理补充资源申请信息-->待确认
     *
     * @param editDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int updateApplyForResource(CsResourceOrderApplyEditDTO editDTO) {
        //修改申请主要信息
        String applyId = editDTO.getApplyId();
        CsResourceOrderApply csResourceOrderApply = csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);
        if (ObjectUtils.isEmpty(csResourceOrderApply)) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        if (!csResourceOrderApply.getApplyStatus().equals("2")) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_EDIT_WITH_STATUS);
        }
        csResourceOrderApply = BeanUtil.toBean(editDTO, CsResourceOrderApply.class);
        Date nowDate = new Date();

        //使用人员信息覆盖
        List<CsUserInfoDTO> editDTOUserList = editDTO.getUserInfoList();
        if (!CollectionUtil.isEmpty(editDTOUserList)) {
            int coverUserList = csUserInfoService.batchCoverCsUserInfo(editDTOUserList, applyId, nowDate);
        }
        //云计算业务映射覆盖
//        if(editDTO.getResourceClassId().equals("2")){
        List<CsBusinessMappingDTO> mappingList = editDTO.getBusinessMappingList();
        if (!CollectionUtil.isEmpty(mappingList)) {
            int coverMappingList = csBusinessMappingService.batchCoverBusinessMapping(mappingList, applyId, nowDate, "0");
        }
//        }


        /* 新增补充信息 */
        //用户端网络信息
        List<CsUserNetworkInfoAddDTO> userNetworkInfoAddList = editDTO.getUserNetworkInfoList();
        if (!CollectionUtil.isEmpty(userNetworkInfoAddList)) {
            int insertUserNetwork = userNetworkInfoService.batchCoverUserNetwork(userNetworkInfoAddList, applyId, nowDate, "0");
        }
        //软件信息
        CsResApplySoftwareInfoADDDTO softWareInfoDto = editDTO.getSoftWareInfo();
        if (!ObjectUtils.isEmpty(softWareInfoDto)) {
            int inserSoftWareInfo = applySoftwareInfoService.insertCoverCsApplySoftwareInfo(softWareInfoDto, applyId);
        }

        //申请表列表覆盖
        List<CsAnnexAddApplyDTO> applyFileList = editDTO.getApplyFileList();
        if (!CollectionUtil.isEmpty(applyFileList)) {
            int coverAnnexList = csAnnexService.batchCoverAnnexList(applyFileList, applyId, csResourceOrderApply.getProjectName(), csResourceOrderApply.getApplyType());
        }

        //0-待确认
        csResourceOrderApply.setApplyStatus("0");
        csResourceOrderApply.setUpdateAt(nowDate);
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(csResourceOrderApply);
    }

    /**
     * 用户PC——查询资源、工单申请列表
     *
     * @param paramDto 资源、工单申请
     * @return
     */
    @Override
    public List<MemberCsResourceOrderApplyVO> selectOrderApplyListForMember(MemberResOrderApplyQueryDTO paramDto) {
        paramDto.setMemberUserId(CsOrderMemberUserSecurityContext.getMemberUserId());
        return csResourceOrderApplyMapper.selectCsResourceOrderApplyListForMember(paramDto);
    }

    /**
     * 用户确认资源申请信息-->待上传盖章
     *
     * @param editDTO
     * @return
     */
    @Override
    public int checkApplyForResource(CsResourceOrderApplyEditDTO editDTO) {
        String applyId = editDTO.getApplyId();
        CsResourceOrderApply csResourceOrderApply = csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);
        if (ObjectUtils.isEmpty(csResourceOrderApply)) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        if (!csResourceOrderApply.getMemberUserId().equals(CsOrderMemberUserSecurityContext.getMemberUserId())) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_RIGHTS);
        }
        if (csResourceOrderApply.getNetworkType() != null && !csResourceOrderApply.getApplyStatus().equals("0") && csResourceOrderApply.getNetworkType().equals("")) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_CHECK_WITH_STATUS);
        }
        //1-待上传盖章材料
        csResourceOrderApply.setApplyStatus("1");

        // 网络资源申请直接待审核
        if (csResourceOrderApply.getNetworkType() != null && !csResourceOrderApply.getNetworkType().equals("")) {
            csResourceOrderApply.setApplyStatus("4");
        }

        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(csResourceOrderApply);
    }

    /**
     * 上传盖章材料 --> 待分配
     *
     * @param editDTO
     * @return
     */
    @Override
    public int uploadFileForResource(CsResourceOrderApplyEditDTO editDTO) {
        String applyId = editDTO.getApplyId();
        CsResourceOrderApply csResourceOrderApply = csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);
        if (ObjectUtils.isEmpty(csResourceOrderApply)) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        if (!csResourceOrderApply.getMemberUserId().equals(CsOrderMemberUserSecurityContext.getMemberUserId())) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_RIGHTS);
        }
        if (!csResourceOrderApply.getApplyStatus().equals("1")) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_UPLOAD_WITH_STATUS);
        }
        //申请表列表覆盖
        List<CsAnnexAddApplyDTO> applyFileList = editDTO.getApplyFileList();
        if (CollectionUtil.isNotEmpty(applyFileList)) {
            csAnnexService.batchCoverAnnexList(applyFileList, applyId, 
                    csResourceOrderApply.getProjectName(), editDTO.getApplyType());
        }
        //4-待审核
        csResourceOrderApply.setIsUpload("1");
        csResourceOrderApply.setUploadUrl(editDTO.getUploadUrl());
        csResourceOrderApply.setApplyStatus("4");
        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(csResourceOrderApply);
    }


    /**
     * 用户 待确认/审核拒绝状态 编辑资源申请基础信息
     *
     * @param editDTO 资源申请基础信息
     * @return
     */
    @Override
    public int editBaseInfoApplyForMember(CsResourceOrderApplyEditDTOForMember editDTO) {
        //修改申请主要信息
        String applyId = editDTO.getApplyId();
        CsResourceOrderApply csResourceOrderApply = csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);
        if (ObjectUtils.isEmpty(csResourceOrderApply)) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        String memberUserId = CsOrderMemberUserSecurityContext.getMemberUserId();
        if (!memberUserId.equals(csResourceOrderApply.getMemberUserId())) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_EDIT_WITH_UID);
        }
        String oldApplyStatus = csResourceOrderApply.getApplyStatus();
        if (!oldApplyStatus.equals("0") && !oldApplyStatus.equals("5")) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_EDIT_WITH_STATUS);
        }
        csResourceOrderApply = BeanUtil.toBean(editDTO, CsResourceOrderApply.class);
        Date nowDate = new Date();

        //使用人员信息覆盖
        List<CsUserInfoDTO> editDTOUserList = editDTO.getUserInfoList();
        if (!CollectionUtil.isEmpty(editDTOUserList)) {
            int coverUserList = csUserInfoService.batchCoverCsUserInfo(editDTOUserList, applyId, nowDate);
        }
        //云计算业务映射覆盖
//        if(editDTO.getResourceClassId().equals("2")){
        List<CsBusinessMappingDTO> mappingList = editDTO.getBusinessMappingList();
        if (!CollectionUtil.isEmpty(mappingList)) {
            int coverMappingList = csBusinessMappingService.batchCoverBusinessMapping(mappingList, applyId, nowDate, "0");
        }
//        }
        //申请表列表覆盖
        List<CsAnnexAddApplyDTO> applyFileList = editDTO.getApplyFileList();
        if (!CollectionUtil.isEmpty(applyFileList)) {
            int coverAnnexList = csAnnexService.batchCoverAnnexList(applyFileList, applyId, csResourceOrderApply.getProjectName(), csResourceOrderApply.getApplyType());
        }
        if (oldApplyStatus.equals("5")) {
            csResourceOrderApply.setApplyStatus("0");
        }
        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(csResourceOrderApply);
    }


    /**
     * 管理员审核资源申请信息-->待分配6/审核拒绝5
     *
     * @param checkDTO
     * @return
     */
    @Override
    public int checkApplyForResourceAndManager(CsResourceOrderApplyManageCheckDTO checkDTO) {
        String applyId = checkDTO.getApplyId();
        CsResourceOrderApply csResourceOrderApply = csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);
        if (ObjectUtils.isEmpty(csResourceOrderApply)) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_NOT_FIND);
        }
        if (!csResourceOrderApply.getApplyStatus().equals("4")) {
            throw new ServiceException(ServiceResponseEnum.RESOURCE_APPLY_CANNOT_MANAGER_CHECK_WITH_STATUS);
        }
        if (checkDTO.getCheckType().equals("0")) {//通过
            csResourceOrderApply.setApplyStatus("6");//6-待分配

            // 网络资源申请通过直接完成
            // if (csResourceOrderApply.getNetworkType() != null && !csResourceOrderApply.getNetworkType().equals("")) {
            //     csResourceOrderApply.setApplyStatus("9");
            // }

        } else {//拒绝
            csResourceOrderApply.setApplyStatus("5");//5-审核拒绝
            if (StringUtils.isBlank(checkDTO.getRefuseReason())) {
                throw new ServiceException(ServiceResponseEnum.REFUSE_REASON_IS_NULL);
            }
            csResourceOrderApply.setRefuseReason(checkDTO.getRefuseReason());
        }
        csResourceOrderApply.setUpdateAt(DateUtils.getNowDate());
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(csResourceOrderApply);
    }

    /**
     * 新增工单
     *
     * @param orderDTO 工单申请信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public int insertApplyForOrder(CsOrderApplyAddDTO orderDTO) {
        // 构造工单申请基础信息
        String applyId = IdUtils.fastSimpleUUID();
        Date nowDate = DateUtils.getNowDate();
        String nowDateString = DateUtils.getTime();

        CsResourceOrderApply addApply = buildOrderApplyBasicData(orderDTO, applyId, nowDate);
        String memberUserId = CsOrderMemberUserSecurityContext.getMemberUserId();
        addApply.setMemberUserId(memberUserId);

        if (StringUtils.isNotBlank(orderDTO.getApplicationArea())) {
            // 新增科研成果
            CsAchievementInfo csAchievementInfo = new CsAchievementInfo();
            csAchievementInfo.setAchievementInfoId(IdUtils.fastSimpleUUID());
            csAchievementInfo.setApplicationArea(orderDTO.getApplicationArea());
            csAchievementInfo.setPlatformSoftware(orderDTO.getPlatformSoftware());
            csAchievementInfo.setSoftwareName(orderDTO.getSoftwareName());
            csAchievementInfo.setIsPublicize(orderDTO.getIsPublicize());
            csAchievementInfo.setResId(applyId);
            achievementInfoService.insertCsAchievementInfo(csAchievementInfo);
        }

        // 批量新增科研成果-论文成果
        List<CsAchievementPaperDetailsDTO> paperAchievementList = orderDTO.getPaperAchievementList();
        if (!CollectionUtil.isEmpty(paperAchievementList)) {
            achievementInfoService.batchInsertPaperAchievementList(paperAchievementList, applyId, nowDate);
        }

        // 批量新增科研成果-专利成果
        List<CsAchievementPatentDetailsDTO> patentAchievementList = orderDTO.getPatentAchievementList();
        if (!CollectionUtil.isEmpty(patentAchievementList)) {
            achievementInfoService.batchInsertPatentAchievementList(patentAchievementList, applyId, nowDate);
        }

        // 批量新增科研成果-奖项成果
        List<CsAchievementPrizeDetailsDTO> prizeAchievementList = orderDTO.getPrizeAchievementList();
        if (!CollectionUtil.isEmpty(prizeAchievementList)) {
            achievementInfoService.batchInsertPrizeAchievementList(prizeAchievementList, applyId, nowDate);
        }

        // 批量新增科研成果-其他成果
        List<CsAchievementOtherDetailsDTO> otherAchievementList = orderDTO.getOtherAchievementList();
        if (!CollectionUtil.isEmpty(otherAchievementList)) {
            achievementInfoService.batchInsertOtherAchievementList(otherAchievementList, applyId, nowDate);
        }

        // 批量新增科研成果-预约成果
        List<CsAchievementReservationDetailsDTO> reservationAchievementList = orderDTO.getReservationAchievementList();
        if (!CollectionUtil.isEmpty(reservationAchievementList)) {
            achievementInfoService.batchInsertReservationAchievementList(reservationAchievementList, applyId, nowDate);
        }

        // 批量新增账户延期人员信息列表
        List<CsAccountExtensionInfoDTO> accountExtensionInfoList = orderDTO.getAccountExtensionInfoList();
        if (!CollectionUtil.isEmpty(accountExtensionInfoList)) {
            accountExtensionInfoService.batchInsertCsAccountExtensionInfo(accountExtensionInfoList, applyId, nowDate);
        }

        // 批量新增附件
        List<CsAnnex> csAnnexList = orderDTO.getCsAnnexList();
        if (!CollectionUtil.isEmpty(csAnnexList)) {
            csAnnexService.batchInsertCsAnnexList(csAnnexList, applyId, nowDateString);
        }
        // 新增工单
        return csResourceOrderApplyMapper.insertCsResourceOrderApply(addApply);
    }

    /**
     * 编辑工单
     *
     * @param orderDTO 工单申请信息
     * @return
     */
    @Override
    public int editApplyForOrder(CsOrderApplyEditDTO orderDTO) {
        // 构造工单申请基础信息
        String applyId = orderDTO.getApplyId();
        Date nowDate = DateUtils.getNowDate();
        String nowDateString = DateUtils.getTime();

        CsResourceOrderApply addApply = BeanUtil.toBean(orderDTO, CsResourceOrderApply.class);
        CsAchievementInfo achievementInfo = BeanUtil.toBean(orderDTO, CsAchievementInfo.class);


        // 新增
        List<CsAchievementPaperDetailsDTO> insertPaperList = new ArrayList<>();
        List<CsAchievementPatentDetailsDTO> insertPatentList = new ArrayList<>();
        List<CsAchievementPrizeDetailsDTO> insertPrizeList = new ArrayList<>();
        List<CsAchievementOtherDetailsDTO> insertOtherList = new ArrayList<>();
        List<CsAchievementReservationDetailsDTO> insertReservationList = new ArrayList<>();
        // 修改
        List<CsAchievementInfoDetails> updateList = new ArrayList<>();

        // 批量修改科研成果-论文成果
        List<CsAchievementPaperDetailsDTO> paperAchievementList = orderDTO.getPaperAchievementList();
        if (!CollectionUtil.isEmpty(paperAchievementList)) {
            for (CsAchievementPaperDetailsDTO paperDetailsDTO : paperAchievementList) {
                if (StringUtils.isBlank(paperDetailsDTO.getInfoDetailsId())) {
                    insertPaperList.add(paperDetailsDTO);
                } else {
                    CsAchievementInfoDetails achievementInfoDetails = BeanUtil.toBean(paperDetailsDTO, CsAchievementInfoDetails.class);
                    if ("1".equals(achievementInfoDetails.getDelFlag())) {
                        achievementInfoDetails.setStatus("3");
                    }
                    achievementInfoDetails.setUpdateAt(nowDate);
                    updateList.add(achievementInfoDetails);
                }
            }
            if (insertPaperList.size() > 0) {
                achievementInfoService.batchInsertPaperAchievementList(insertPaperList, applyId, nowDate);
            }
        } else {
            achievementInfoDetailsService.bachDeleteCsAchievementInfoDetailsByResId(applyId, "0");
        }

        // 批量修改科研成果-专利成果
        List<CsAchievementPatentDetailsDTO> patentAchievementList = orderDTO.getPatentAchievementList();
        if (!CollectionUtil.isEmpty(patentAchievementList)) {
            for (CsAchievementPatentDetailsDTO patentDetailsDTO : patentAchievementList) {
                if (StringUtils.isBlank(patentDetailsDTO.getInfoDetailsId())) {
                    insertPatentList.add(patentDetailsDTO);
                } else {
                    CsAchievementInfoDetails achievementInfoDetails = BeanUtil.toBean(patentDetailsDTO, CsAchievementInfoDetails.class);
                    if ("1".equals(achievementInfoDetails.getDelFlag())) {
                        achievementInfoDetails.setStatus("3");
                    }
                    achievementInfoDetails.setUpdateAt(nowDate);
                    updateList.add(achievementInfoDetails);
                }
            }
            if (insertPatentList.size() > 0) {
                achievementInfoService.batchInsertPatentAchievementList(insertPatentList, applyId, nowDate);
            }
        } else {
            achievementInfoDetailsService.bachDeleteCsAchievementInfoDetailsByResId(applyId, "1");
        }

        // 批量修改科研成果-奖项成果
        List<CsAchievementPrizeDetailsDTO> prizeAchievementList = orderDTO.getPrizeAchievementList();
        if (!CollectionUtil.isEmpty(prizeAchievementList)) {
            for (CsAchievementPrizeDetailsDTO prizeDetailsDTO : prizeAchievementList) {
                if (StringUtils.isBlank(prizeDetailsDTO.getInfoDetailsId())) {
                    insertPrizeList.add(prizeDetailsDTO);
                } else {
                    CsAchievementInfoDetails achievementInfoDetails = BeanUtil.toBean(prizeDetailsDTO, CsAchievementInfoDetails.class);
                    if ("1".equals(achievementInfoDetails.getDelFlag())) {
                        achievementInfoDetails.setStatus("3");
                    }
                    achievementInfoDetails.setUpdateAt(nowDate);
                    updateList.add(achievementInfoDetails);
                }
            }
            if (insertPrizeList.size() > 0) {
                achievementInfoService.batchInsertPrizeAchievementList(insertPrizeList, applyId, nowDate);
            }
        } else {
            achievementInfoDetailsService.bachDeleteCsAchievementInfoDetailsByResId(applyId, "2");
        }

        // 批量修改科研成果-其他成果
        List<CsAchievementOtherDetailsDTO> otherAchievementList = orderDTO.getOtherAchievementList();
        if (!CollectionUtil.isEmpty(otherAchievementList)) {
            for (CsAchievementOtherDetailsDTO otherDetailsDTO : otherAchievementList) {
                if (StringUtils.isBlank(otherDetailsDTO.getInfoDetailsId())) {
                    insertOtherList.add(otherDetailsDTO);
                } else {
                    CsAchievementInfoDetails achievementInfoDetails = BeanUtil.toBean(otherDetailsDTO, CsAchievementInfoDetails.class);
                    if ("1".equals(achievementInfoDetails.getDelFlag())) {
                        achievementInfoDetails.setStatus("3");
                    }
                    achievementInfoDetails.setUpdateAt(nowDate);
                    updateList.add(achievementInfoDetails);
                }
            }
            if (insertOtherList.size() > 0) {
                achievementInfoService.batchInsertOtherAchievementList(insertOtherList, applyId, nowDate);
            }
        } else {
            achievementInfoDetailsService.bachDeleteCsAchievementInfoDetailsByResId(applyId, "3");
        }

        // 批量修改科研成果-预约成果
        List<CsAchievementReservationDetailsDTO> reservationAchievementList = orderDTO.getReservationAchievementList();
        if (!CollectionUtil.isEmpty(reservationAchievementList)) {
            for (CsAchievementReservationDetailsDTO reservationDetailsDTO : reservationAchievementList) {
                if (StringUtils.isBlank(reservationDetailsDTO.getInfoDetailsId())) {
                    insertReservationList.add(reservationDetailsDTO);
                } else {
                    CsAchievementInfoDetails achievementInfoDetails = BeanUtil.toBean(reservationDetailsDTO, CsAchievementInfoDetails.class);
                    if ("1".equals(achievementInfoDetails.getDelFlag())) {
                        achievementInfoDetails.setStatus("3");
                    }
                    achievementInfoDetails.setUpdateAt(nowDate);
                    updateList.add(achievementInfoDetails);
                }
            }
            if (insertReservationList.size() > 0) {
                achievementInfoService.batchInsertReservationAchievementList(insertReservationList, applyId, nowDate);
            }
        } else {
            achievementInfoDetailsService.bachDeleteCsAchievementInfoDetailsByResId(applyId, "4");
        }

        List<CsAnnex> csAnnexList = orderDTO.getCsAnnexList();
        if (csAnnexList != null && !csAnnexList.isEmpty()) {
            // 新增
            List<CsAnnex> insertAnnexList = new ArrayList<>();
            // 修改
            List<CsAnnex> updateAnnexList = new ArrayList<>();
            for (CsAnnex csAnnex : csAnnexList) {
                if (csAnnex.getAnnexId() != null) {
                    updateAnnexList.add(csAnnex);
                } else {
                    insertAnnexList.add(csAnnex);
                }
            }

            if (insertAnnexList.size() > 0) {
                csAnnexService.batchInsertCsAnnexList(insertAnnexList, applyId, nowDateString);
            }
            if (updateAnnexList.size() > 0) {
                csAnnexService.batchUpdateCsAnnexList(updateAnnexList);
            }

        }

        if (updateList.size() > 0) {
            // 批量修改科研成果-成果
            achievementInfoService.batchUpdateAchievementDetailsList(updateList);
        }

        if (StringUtils.isBlank(achievementInfo.getAchievementInfoId())) {
            // 新增科研成果
            achievementInfo.setAchievementInfoId(IdUtils.fastSimpleUUID());
            achievementInfo.setResId(applyId);
            achievementInfoService.insertCsAchievementInfo(achievementInfo);
        } else {
            // 修改科研成果信息
            achievementInfo.setResId(applyId);
            achievementInfoService.updateCsAchievementInfoByResId(achievementInfo);
        }

        //覆盖延期账户
        accountExtensionInfoService.covertCsAccountExtensionInfo(orderDTO.getAccountExtensionInfoList(), applyId, nowDate);

        // 修改工单申请
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(addApply);
    }

    /**
     * 处理工单
     *
     * @param orderDTO 工单申请信息
     * @return
     */
    @Override
    public int handleApplyForOrder(CsOrderApplyEditDTO orderDTO) {
        CsResourceOrderApply updateApply = new CsResourceOrderApply();
        updateApply.setApplyId(orderDTO.getApplyId());
        updateApply.setApplyStatus(orderDTO.getApplyStatus());
        updateApply.setUpdateAt(DateUtils.getNowDate());
        updateApply.setRefuseReason(orderDTO.getRefuseReason());

        // 修改工单申请
        return csResourceOrderApplyMapper.updateCsResourceOrderApply(updateApply);
    }

    /**
     * 新增 -构造工单申请基础信息
     *
     * @param orderDTO 工单申请信息
     * @param applyId  申请id
     * @param nowDate  时间
     * @return 新增工单申请对象
     */
    private CsResourceOrderApply buildOrderApplyBasicData(CsOrderApplyAddDTO orderDTO, String applyId, Date nowDate) {
        CsResourceOrderApply addApply = BeanUtil.toBean(orderDTO, CsResourceOrderApply.class);
        addApply.setApplyId(applyId);
        addApply.setApplyNumber(IdUtil.getSnowflakeNextIdStr());
        addApply.setApplyStatus("4");
        addApply.setStatus("0");
        addApply.setCreateAt(nowDate);
        return addApply;
    }

    /**
     * 工单申请信息详情
     *
     * @param applyId 申请ID
     * @return
     */
    @Override
    public CsOrderApplyVO applyForOrderDetail(String applyId) {
        CsResourceOrderApply csResourceOrderApply = csResourceOrderApplyMapper.selectCsResourceOrderApplyByApplyId(applyId);
        CsOrderApplyVO applyDetail = BeanUtil.toBean(csResourceOrderApply, CsOrderApplyVO.class);

        if (ObjectUtils.isEmpty(csResourceOrderApply)) {
            throw new ServiceException(ServiceResponseEnum.ORDER_APPLY_NOT_FIND);
        }

        CsAchievementInfo csAchievementInfo = achievementInfoService.selectCsAchievementInfoByResId(applyId);
        if (csAchievementInfo != null) {
            applyDetail.setAchievementInfoId(csAchievementInfo.getAchievementInfoId());
            applyDetail.setApplicationArea(csAchievementInfo.getApplicationArea());
            applyDetail.setPlatformSoftware(csAchievementInfo.getPlatformSoftware());
            applyDetail.setSoftwareName(csAchievementInfo.getSoftwareName());
            applyDetail.setIsPublicize(csAchievementInfo.getIsPublicize());
            applyDetail.setResId(csAchievementInfo.getResId());
        }

        // 查询当前申请的科研成果-论文成果
        List<CsAchievementPaperDetailsVO> paperDetailsVOList = achievementInfoDetailsService.selectPaperAchievementList(applyId);
        if (!CollectionUtil.isEmpty(paperDetailsVOList)) {
            applyDetail.setPaperAchievementList(paperDetailsVOList);
        }

        // 查询当前申请的科研成果-专利成果
        List<CsAchievementPatentDetailsVO> patentDetailsVOList = achievementInfoDetailsService.selectPatentAchievementList(applyId);
        if (!CollectionUtil.isEmpty(patentDetailsVOList)) {
            applyDetail.setPatentAchievementList(patentDetailsVOList);
        }

        // 查询当前申请的科研成果-奖项成果
        List<CsAchievementPrizeDetailsVO> prizeDetailsVOList = achievementInfoDetailsService.selectPrizeAchievementList(applyId);
        if (!CollectionUtil.isEmpty(prizeDetailsVOList)) {
            applyDetail.setPrizeAchievementList(prizeDetailsVOList);
        }

        // 查询当前申请的科研成果-其他成果
        List<CsAchievementOtherDetailsVO> otherDetailsVOList = achievementInfoDetailsService.selectOtherAchievementList(applyId);
        if (!CollectionUtil.isEmpty(otherDetailsVOList)) {
            applyDetail.setOtherAchievementList(otherDetailsVOList);
        }

        // 查询当前申请的科研成果-预约成果
        List<CsAchievementReservationDetailsVO> reservationDetailsVOList = achievementInfoDetailsService.selectReservationAchievementList(applyId);
        if (!CollectionUtil.isEmpty(reservationDetailsVOList)) {
            applyDetail.setReservationAchievementList(reservationDetailsVOList);
        }

        // 查询当前申请的延期人员信息列表
        List<CsAccountExtensionInfoVO> accountExtensionInfoList = accountExtensionInfoService.selectCsAccountExtensionInfoList(applyId);
        if (!CollectionUtil.isEmpty(accountExtensionInfoList)) {
            applyDetail.setAccountExtensionInfoList(accountExtensionInfoList);
        }


        CsAnnex csAnnex = new CsAnnex();
        csAnnex.setResId(applyId);
        csAnnex.setDelFlag("0");
        applyDetail.setCsAnnexList(csAnnexService.selectCsAnnexList(csAnnex));

        return applyDetail;
    }

    /**
     * 用户PC——查询我的工单列表
     *
     * @param myOrderQuery 工单
     * @return 资源、工单申请集合
     */
    @Override
    public List<MemberMyOrderQueryVo> selectMyOrderApplyListForMember(MemberMyOrderQueryDTO myOrderQuery) {
        myOrderQuery.setMemberUserId(CsOrderMemberUserSecurityContext.getMemberUserId());
        // myOrderQuery.setMemberUserId("ad86230aaf7f4104ba7b6c9abdb39f8f");
        return csResourceOrderApplyMapper.selectMyOrderApplyListForMember(myOrderQuery);
    }

    /**
     * xcx——查询资源、工单申请列表
     *
     * @param paramDto 资源、工单申请
     * @return 资源、工单申请集合
     */
    @Override
    public List<XcxCsOrderApplyVO> selectOrderApplyListForXcx(XcxApprovalListDTO paramDto) {
        paramDto.setSysUid(SecurityUtils.getUserId());
        return csResourceOrderApplyMapper.selectOrderApplyListForXcx(paramDto);
    }

    /**
     * xcx——工单详情
     *
     * @param paramDto
     * @return
     */
    @Override
    public XcxResOrderApplyDetailVO selectOrderApplyDetailForXcx(XcxApprovalListDTO paramDto) {
        String applyId = paramDto.getFormId();
        CsResourceOrderApplyVO csResourceOrderApplyVO = applyForResourceDetail(applyId);
        XcxResOrderApplyDetailVO result = BeanUtil.toBean(csResourceOrderApplyVO, XcxResOrderApplyDetailVO.class);
        Long userId = SecurityUtils.getUserId();
        //获取用户当前申请的未审核节点的数据
        CsApprovalRecordVO approvalNode = approvalConfigService.getUserNodeInfoForXcx(csResourceOrderApplyVO.getApplyId(), csResourceOrderApplyVO.getApplyType(), userId);
        if (ObjectUtils.isEmpty(approvalNode)) {
            //获取流程最新节点的数据
            CsApprovalRecordVO newNodeInfoForXcx = approvalConfigService.getNewNodeInfoForXcx(csResourceOrderApplyVO.getApplyId(), csResourceOrderApplyVO.getApplyType());
            approvalNode = new CsApprovalRecordVO();
            approvalNode.setApproverResult(newNodeInfoForXcx.getApproverResult());
            approvalNode.setApproverOpinions(newNodeInfoForXcx.getApproverOpinions());
        }
        result.setApprovalNode(approvalNode);
        return result;
    }

    /**
     * xcx——消息列表
     *
     * @return
     */
    @Override
    public PageInfo<XcxCsOrderApplyVO> getMsgList(Integer pageNum, Integer pageSize) {
        //全部已读

        int i = approvalCarbonCopyService.updateReadForXcx();
        PageHelper.startPage(pageNum, pageSize);
        List<XcxCsOrderApplyVO> xcxCsOrderApplyVOS = csResourceOrderApplyMapper.selectXcxMsgList(SecurityUtils.getUserId());

        return new PageInfo<>(xcxCsOrderApplyVOS);
    }

    /**
     * 查询管理端资源、工单相关统计
     *
     * @param beginAt 开始时间
     * @param endAt   结束时间
     * @return 资源、工单数量集合
     */
    @Override
    public Map<String, Object> selectResourceOrderStatistics(String beginAt, String endAt) {
        return csResourceOrderApplyMapper.selectResourceOrderStatistics(beginAt, endAt);
    }

    @Override
    public Map<String,Object> getSatisfactionStatistics(SatisfactionStatisticsDTO dto) {
        Map<String,Object> resultMap = new HashMap<>();
        AnalysisLineVO analysisVO = new AnalysisLineVO();
        List<String> list = new ArrayList<>();
        list.add("五星");
        list.add("四星");
        list.add("三星");
        list.add("二星");
        list.add("一星");
        list.add("未评分");
        resultMap.put("evaluateStarList",list);
        List<String> timeList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        Map<String, String> lastMap = new HashMap<>();
        List<AnalysisLineVO.DataList> dataList = new ArrayList<>();
        List<String> xAxisData = new ArrayList<>();
        AnalysisLineVO.DataList list1 = new AnalysisLineVO.DataList();
        list1.setYAxisData(new ArrayList<>());
        AnalysisLineVO.DataList list2 = new AnalysisLineVO.DataList();
        list2.setYAxisData(new ArrayList<>());
        if (StringUtils.isEmpty(dto.getType())) {
            dto.setType("1");
        }
        if ("1".equals(dto.getType())) {
            if (StringUtils.isEmpty(dto.getYear())) {
                dto.setYear(DateUtils.dateTimeNow("YYYY"));
            }
            //获取当年的
            List<LabelAndValueVO> labelAndValueVOList = csResourceOrderApplyMapper.getSatisfactionStatistics(dto);
            map = labelAndValueVOList.stream().collect(Collectors.toMap(LabelAndValueVO::getLabel, LabelAndValueVO::getValue));
            list1.setName(dto.getYear());
            timeList.add(dto.getYear()+"年");
            list1.setType("column");
            dto.setYear(String.valueOf(Integer.parseInt(dto.getYear()) - 1));
            List<LabelAndValueVO> lastLabelAndValueVOList = csResourceOrderApplyMapper.getSatisfactionStatistics(dto);
            lastMap = lastLabelAndValueVOList.stream().collect(Collectors.toMap(LabelAndValueVO::getLabel, LabelAndValueVO::getValue));
            list2.setName(dto.getYear());
            timeList.add(dto.getYear()+"年");
            list2.setType("column");
        } else if ("2".equals(dto.getType())) {
            if (StringUtils.isEmpty(dto.getYear())) {
                dto.setYear(DateUtils.dateTimeNow("YYYY"));
            }
            if (StringUtils.isEmpty(dto.getMonth())) {
                dto.setMonth(DateUtils.dateTimeNow("MM"));
            }
            //获取当年的
            List<LabelAndValueVO> labelAndValueVOList = csResourceOrderApplyMapper.getSatisfactionStatistics(dto);
            map = labelAndValueVOList.stream().collect(Collectors.toMap(LabelAndValueVO::getLabel, LabelAndValueVO::getValue));
            list1.setName(dto.getMonth() + "月");
            timeList.add(dto.getMonth()+"月");
            list1.setType("column");
            dto.setMonth(String.valueOf(Integer.parseInt(dto.getMonth()) - 1));
            List<LabelAndValueVO> lastLabelAndValueVOList = csResourceOrderApplyMapper.getSatisfactionStatistics(dto);
            lastMap = lastLabelAndValueVOList.stream().collect(Collectors.toMap(LabelAndValueVO::getLabel, LabelAndValueVO::getValue));
            list2.setName(dto.getMonth() + "月");
            timeList.add(dto.getMonth()+"月");
            list2.setType("column");
        }
        for (String s : list) {
            xAxisData.add(s);
            if (CollectionUtil.isNotEmpty(map)) {
                String value = map.get(s);
                if (StringUtils.isNotEmpty(value)) {
                    list1.getYAxisData().add(value);
                } else {
                    list1.getYAxisData().add("0");
                }
            } else {
                list1.getYAxisData().add("0");
            }
            if (CollectionUtil.isNotEmpty(lastMap)) {
                String value = lastMap.get(s);
                if (StringUtils.isNotEmpty(value)) {
                    list2.getYAxisData().add(value);
                } else {
                    list2.getYAxisData().add("0");
                }
            } else {
                list2.getYAxisData().add("0");
            }
        }
        dataList.add(list1);
        dataList.add(list2);
        analysisVO.setXAxisData(xAxisData);
        analysisVO.setDataList(dataList);
        resultMap.put("timeList",timeList);
        resultMap.put("nowList",list2.getYAxisData());
        resultMap.put("lastList",list1.getYAxisData());
        return resultMap;
    }

    @Override
    public Map<String,Object> getWorOrderSubmissionStatistics(SatisfactionStatisticsDTO dto) {
        Map<String,Object> resultMap = new HashMap<>();
        List<String> timeList = new ArrayList<>();
        List<SatisfactionStatisticsVO> list = new ArrayList<>();
        Map<String, List<WorOrderSubmissionStatisticsDTO>> map = new HashMap<>();
        Map<String, List<WorOrderSubmissionStatisticsDTO>> lastMap = new HashMap<>();
        if (StringUtils.isEmpty(dto.getType())) {
            dto.setType("1");
        }
        if ("1".equals(dto.getType())) {
            if (StringUtils.isEmpty(dto.getYear())) {
                dto.setYear(DateUtils.dateTimeNow("YYYY"));
            }
            timeList.add(dto.getYear()+"年");
            //获取当年的
            List<WorOrderSubmissionStatisticsDTO> submissionStatisticsList = csResourceOrderApplyMapper.getWorOrderSubmissionStatistics(dto);
            map = submissionStatisticsList.stream().collect(Collectors.groupingBy(WorOrderSubmissionStatisticsDTO::getCompanyName));
            dto.setYear(String.valueOf(Integer.parseInt(dto.getYear()) - 1));
            timeList.add(dto.getYear()+"年");
            List<WorOrderSubmissionStatisticsDTO> lastLabelAndValueVOList = csResourceOrderApplyMapper.getWorOrderSubmissionStatistics(dto);
            lastMap = lastLabelAndValueVOList.stream().collect(Collectors.groupingBy(WorOrderSubmissionStatisticsDTO::getCompanyName));
        } else if ("2".equals(dto.getType())) {
            if (StringUtils.isEmpty(dto.getYear())) {
                dto.setYear(DateUtils.dateTimeNow("YYYY"));
            }
            if (StringUtils.isEmpty(dto.getMonth())) {
                dto.setMonth(DateUtils.dateTimeNow("MM"));
            }
            timeList.add(dto.getMonth()+"月");
            //获取当月的
            List<WorOrderSubmissionStatisticsDTO> submissionStatisticsList = csResourceOrderApplyMapper.getWorOrderSubmissionStatistics(dto);
            map = submissionStatisticsList.stream().collect(Collectors.groupingBy(WorOrderSubmissionStatisticsDTO::getCompanyName));
            //获取上个月
            dto.setMonth(String.valueOf(Integer.parseInt(dto.getMonth()) - 1));
            timeList.add(dto.getMonth()+"月");
            List<WorOrderSubmissionStatisticsDTO> lastSubmissionStatisticsList = csResourceOrderApplyMapper.getWorOrderSubmissionStatistics(dto);
            lastMap = lastSubmissionStatisticsList.stream().collect(Collectors.groupingBy(WorOrderSubmissionStatisticsDTO::getCompanyName));
        }
        for (Map.Entry<String, List<WorOrderSubmissionStatisticsDTO>> entry : map.entrySet()) {
            SatisfactionStatisticsVO statisticsVO = new SatisfactionStatisticsVO();
            statisticsVO.setName(entry.getKey());
            Map<String, String> orderSubmissionMap = new HashMap<>();
            List<WorOrderSubmissionStatisticsDTO> orderSubmissionStatisticsDTOS = lastMap.get(entry.getKey());
            if (!CollectionUtil.isEmpty(orderSubmissionStatisticsDTOS)) {
                orderSubmissionMap = orderSubmissionStatisticsDTOS.stream().collect(Collectors.toMap(WorOrderSubmissionStatisticsDTO::getDeptName, WorOrderSubmissionStatisticsDTO::getNum));
            }
            List<String> xAxisData = new ArrayList<>();
            List<String> list1 = new ArrayList<>();
            List<String> list2 = new ArrayList<>();
            for (WorOrderSubmissionStatisticsDTO submissionStatisticsDTO : entry.getValue()) {
                xAxisData.add(submissionStatisticsDTO.getDeptName());
                list1.add(StringUtils.isNotEmpty(submissionStatisticsDTO.getNum()) ? submissionStatisticsDTO.getNum() : "0");
                statisticsVO.setDataList2(list1);
                if (!CollectionUtil.isEmpty(orderSubmissionMap)) {
                    list2.add(StringUtils.isNotEmpty(orderSubmissionMap.get(submissionStatisticsDTO.getDeptName())) ? orderSubmissionMap.get(submissionStatisticsDTO.getDeptName()) : "0");
                } else {
                    list2.add("0");
                }
                statisticsVO.setDataList2(list2);
                statisticsVO.setDataList1(list1);
            }
            statisticsVO.setXAxisData(xAxisData);
            list.add(statisticsVO);
        }
        if(CollectionUtil.isNotEmpty(list)){
            resultMap.put("classList",list.get(0).getXAxisData());
            resultMap.put("nowList",list.get(0).getDataList1());
            resultMap.put("lastList",list.get(0).getDataList2());
        }else{
            resultMap.put("classList",new ArrayList());
            resultMap.put("nowList",new ArrayList());
            resultMap.put("lastList",new ArrayList());
        }
        resultMap.put("timeList",timeList);
        return resultMap;
    }

    @Override
    public List<ExportOrderResponseTimeStatisticsVO> exportOrderResponseTimeStatistics(SatisfactionStatisticsDTO dto) {
        List<CsResourceOrderApply> list = csResourceOrderApplyMapper.exportOrderResponseTimeStatistics(dto);
        return list.stream().map(item -> {
            ExportOrderResponseTimeStatisticsVO exportOrderResponseTimeStatisticsVO = new ExportOrderResponseTimeStatisticsVO();
            BeanUtils.copyProperties(item, exportOrderResponseTimeStatisticsVO);
            return exportOrderResponseTimeStatisticsVO;
        }).collect(Collectors.toList());
    }

    @Override
    public List<CsResourceOrderApply> exportWorkOrderProcessingTime(SatisfactionStatisticsDTO dto) {
        List<CsResourceOrderApply> list = csResourceOrderApplyMapper.exportWorkOrderProcessingTime(dto);
        return Collections.emptyList();
    }

//    /**
//     * 行政村通响数据统计
//     *
//     * @param platformId
//     * @return
//     */
//    public AnalysisLineVO villageRespond(String platformId) {
//        AnalysisLineVO analysisVO = new AnalysisLineVO();
//        List<String> xAxisData = new ArrayList<>();
//        List<AnalysisLineVO.DataList> dataList = new ArrayList<>();
//        List<AreaNameBO> areaNameList = new ArrayList<>();
//        if (StringUtils.isEmpty(platformId)) {
//            PlatformInfoBO platformInfo = getThisPlatformInfo();
//            if (StringUtils.isNull(platformInfo) || StringUtils.isEmpty(platformInfo.getAreaCode())) {
//                return analysisVO;
//            }
//            areaNameList = dataWebMapper.selectAreaByParentCode(platformInfo.getAreaCode());
//        } else {
//            PlatformInfoBO platform = dataWebMapper.selectPlatformById(platformId);
//            if (StringUtils.isNull(platform) || StringUtils.isEmpty(platform.getAreaCode())) {
//                return analysisVO;
//            }
//            areaNameList = dataWebMapper.selectAreaByParentCode(platform.getAreaCode());
//        }
//        if (!CollectionUtil.isEmpty(areaNameList)) {
//            AnalysisLineVO.DataList list1 = new AnalysisLineVO.DataList();
//            list1.setName("行政村总数");
//            list1.setType("bar");
//            list1.setYAxisData(new ArrayList<>());
//            dataList.add(list1);
//            AnalysisLineVO.DataList list2 = new AnalysisLineVO.DataList();
//            list2.setName("设备覆盖数");
//            list2.setType("bar");
//            list2.setYAxisData(new ArrayList<>());
//            dataList.add(list2);
//            AnalysisLineVO.DataList list3 = new AnalysisLineVO.DataList();
//            list3.setName("设备通响数");
//            list3.setType("bar");
//            list3.setYAxisData(new ArrayList<>());
//            dataList.add(list3);
//            for (AreaNameBO areaNameBO : areaNameList) {
//                xAxisData.add(areaNameBO.getAreaName());
//                String areaCodePrefix = getAreaCodePrefixByLevel(areaNameBO.getAreaCode(), areaNameBO.getAreaLevel());
//                int areaNum = dataWebMapper.areaNumByLevel(areaCodePrefix, areaNameBO.getAreaLevel());
//                LabelAndValueBO valueBO = dataWebMapper.villageRespond(areaCodePrefix, areaNameBO.getAreaLevel());
//                list1.getYAxisData().add(String.valueOf(areaNum));
//                list2.getYAxisData().add(String.valueOf(valueBO.getLabel()));
//                list3.getYAxisData().add(String.valueOf(valueBO.getValue()));
//            }
//        }
//        analysisVO.setXAxisData(xAxisData);
//        analysisVO.setDataList(dataList);
//        return analysisVO;
//    }

    /**
     * 查询工单列表
     *
     * @param csResourceOrderApply 资源、工单申请
     * @return 资源、工单申请集合
     */
    @Override
    public List<ResourceOrderApplyListVO> selectResourceOrderApplyList(CsResourceOrderApply csResourceOrderApply) {
        List<ResourceOrderApplyListVO> vos = csResourceOrderApplyMapper.selectResourceOrderApplyList(csResourceOrderApply);
        if (CollectionUtil.isNotEmpty(vos)){
            vos.forEach(l -> {
                l.setCsAnnexApplyVO(csAnnexService.getApplyFileList(l.getApplyId(),l.getApplyType()));
            });
        }
        return vos;
    }

    /**
     * 查询工单数量统计信息
     *
     * @param params
     * @return
     */
    @Override
    public Map<String,Object> searchResourceOrderApplyStatisticsInfo(Map<String,Object> params){
        if(params.get("quarter") != null && params.get("quarter") != ""){
            if("1".equals(String.valueOf(params.get("quarter")))){// 如果是第一季度，则代表月份为1，2，3
                params.put("quarter","1,2,3");
            }
            if("2".equals(String.valueOf(params.get("quarter")))){// 如果是第二季度，则代表月份为4，5，6
                params.put("quarter","4,5,6");
            }
            if("3".equals(String.valueOf(params.get("quarter")))){// 如果是第三季度，则代表月份为7，8，9
                params.put("quarter","7,8,9");
            }
            if("4".equals(String.valueOf(params.get("quarter")))){// 如果是第四季度，则代表月份为10，11，12
                params.put("quarter","10,11,12");
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        String applyStatus = "";
        params.put("applyStatus",applyStatus);
        resultMap.put("resourceOrderApplyCount",csResourceOrderApplyMapper.searchResourceOrderApplyCountByCondition(params));// 全部工单
        applyStatus = "2";// 2-待审批
        params.put("applyStatus",applyStatus);
        resultMap.put("dspResourceOrderApplyCount",csResourceOrderApplyMapper.searchResourceOrderApplyCountByCondition(params));// 待审批工单
        applyStatus = "3";// 3-待审核
        params.put("applyStatus",applyStatus);
        resultMap.put("dshResourceOrderApplyCount",csResourceOrderApplyMapper.searchResourceOrderApplyCountByCondition(params));// 待审核工单
        applyStatus = "6";// 6-待分配
        params.put("applyStatus",applyStatus);
        resultMap.put("dfpResourceOrderApplyCount",csResourceOrderApplyMapper.searchResourceOrderApplyCountByCondition(params));// 待分配工单
        applyStatus = "9";// 9-待评价
        params.put("applyStatus",applyStatus);
        resultMap.put("dpjResourceOrderApplyCount",csResourceOrderApplyMapper.searchResourceOrderApplyCountByCondition(params));// 待评价工单
        applyStatus = "7";// 7-进行中
        params.put("applyStatus",applyStatus);
        resultMap.put("jxzResourceOrderApplyCount",csResourceOrderApplyMapper.searchResourceOrderApplyCountByCondition(params));// 进行中工单
        return resultMap;
    }

    /**
     * 查询部门列表
     *
     * @return
     */
    @Override
    public List<Map<String,Object>> searchDeptList(){
        return csResourceOrderApplyMapper.searchDeptList();
    }

}
