package com.ruoyi.postCheck.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.PostCheckedProblemEnum;
import com.ruoyi.common.constant.PostListEnum;
import com.ruoyi.common.constant.PostPlanEnum;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.SysDeptEnum;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.postCheck.domain.*;
import com.ruoyi.postCheck.domain.excel.problem.ProblemExportBean;
import com.ruoyi.postCheck.domain.excel.problem.ProblemImportBean;
import com.ruoyi.postCheck.domain.homePage.DeptProblemRectificationView;
import com.ruoyi.postCheck.domain.homePage.PostCheckedProblemView;
import com.ruoyi.postCheck.domain.homePage.PostCheckedUnCheckedView;
import com.ruoyi.postCheck.domain.homePage.PostTotalView;
import com.ruoyi.postCheck.domain.join.PostPlanJoinProblem;
import com.ruoyi.postCheck.domain.problemStatistics.*;
import com.ruoyi.postCheck.domain.tools.ProblemCategory;
import com.ruoyi.postCheck.mapper.*;
import com.ruoyi.postCheck.model.DeptDetaailViewModel;
import com.ruoyi.postCheck.service.IPostCheckedProblemRecordService;
import com.ruoyi.postCheck.service.IPostCheckedProblemService;
import com.ruoyi.postCheck.service.IPostPlanInfoService;
import com.ruoyi.postCheck.service.IPostPlanJoinProblemService;
import com.ruoyi.postCheck.util.excel.create.PostProblemCreateExcel;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 岗检问题表Service业务层处理
 *
 * @author csg
 * @date 2023-12-23
 */
@Service
@Slf4j
public class PostCheckedProblemServiceImpl extends ServiceImpl<PostCheckedProblemMapper, PostCheckedProblem> implements IPostCheckedProblemService {
    @Autowired
    private PostCheckedProblemMapper postCheckedProblemMapper;

    @Autowired
    private IPostCheckedProblemRecordService postCheckedProblemRecordService;


    @Autowired
    private PostPlanInfoMapper postPlanInfoMapper;
    @Autowired
    private PostPlanMapper postPlanMapper;
    @Autowired
    private PostAssessmentRatingMapper postAssessmentRatingMapper;
    @Autowired
    private PostAssessmentRulesMapper postAssessmentRulesMapper;
    @Autowired
    private IPostPlanJoinProblemService postPlanJoinProblemService;
    @Autowired
    private PostListMapper postListMapper;
    @Autowired
    private PostAssessmentRatingOtherMapper postAssessmentRatingOtherMapper;

    @Autowired
    private SysPostMapper sysPostMapper;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysPostService sysPostService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IPostPlanInfoService postPlanInfoService;


    /**
     * 查询岗检问题表
     *
     * @param id 岗检问题表主键
     * @return 岗检问题表
     */
    @Override
    public PostCheckedProblem selectPostCheckedProblemById(Long id) {
        PostCheckedProblem data = postCheckedProblemMapper.selectPostCheckedProblemById(id);
        if (data != null) {
            Long dataId = data.getId();
            PostCheckedProblemRecord param = new PostCheckedProblemRecord();
            param.setProblemId(dataId);
            List<PostCheckedProblemRecord> children = postCheckedProblemRecordService.selectPostCheckedProblemRecordList(param);
            data.setChildren(children);
        }
        return data;
    }

    /**
     * 查询岗检问题表列表
     *
     * @param postCheckedProblem 岗检问题表
     * @return 岗检问题表
     */
    @Override
    public List<PostCheckedProblem> selectPostCheckedProblemList(PostCheckedProblem postCheckedProblem) {
        List<PostCheckedProblem> list = postCheckedProblemMapper.selectPostCheckedProblemList(postCheckedProblem);
        for (PostCheckedProblem data : list) {
            Long dataId = data.getId();
            if (data == null)
                continue;
            PostCheckedProblemRecord param = new PostCheckedProblemRecord();
            param.setProblemId(dataId);
            List<PostCheckedProblemRecord> children = postCheckedProblemRecordService.selectPostCheckedProblemRecordList(param);
            data.setChildren(children);
        }
        return list;
    }


    /**
     * 岗检问题编号生成
     * GJ-MF5-2023-Z-000001
     * 编号规则	GJ-岗检	MF5-问题所属部门代码	2023-年份	Z-问题级别，Z-重要，Y-一般
     *
     * @param problemLevel 1一般、2 重要
     */
    private String createProblemNo(int problemLevel, Long deptId) {
        String problemNo = "GJ-";

        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        if (sysDept == null) {
            throw new BaseException("被检查部门id错误，请检查！");
        }
        //部门代码
        String deptCodePost = sysDept.getDeptCodePost();
        if (StringUtils.isBlank(deptCodePost)) {
            throw new BaseException("被检查部门代码为空，请检查！");
        }

        problemNo += deptCodePost + "-";

        String year = DateUtils.dateTimeNow(DateUtils.YYYY);
        problemNo += year + "-";
        //一般
        if (problemLevel == PostCheckedProblemEnum.LEVEL_Y.getValue()) {
            problemNo += "Y-";
        }
        //重要
        else if (problemLevel == PostCheckedProblemEnum.LEVEL_Z.getValue()) {
            problemNo += "Z-";
        } else {
            throw new BaseException("问题等级错误，请检查！");
        }

        Long problemNum = 1l;
        Page<PostCheckedProblem> page = new Page<>();
        page.setCurrent(1);
        page.setSize(20);
        LambdaQueryWrapper<PostCheckedProblem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(PostCheckedProblem::getCreateTime);

        Page<PostCheckedProblem> postCheckedProblemPage = postCheckedProblemMapper.selectPage(page, queryWrapper);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemPage.getRecords();
        if (CollectionUtils.isEmpty(postCheckedProblemList)) {
            problemNum = 1l;
        }
        //计算最大值
        else {
            List<String> problemNoList = postCheckedProblemList.stream().map(PostCheckedProblem::getProblemNo).collect(Collectors.toList());
            TreeSet<Long> lastNoSet = new TreeSet<>();
            for (String problemNoDB : problemNoList) {
                try {
                    if (StringUtils.isBlank(problemNoDB))
                        continue;
                    int index = problemNoDB.lastIndexOf("-");
                    if (index <= 0)
                        continue;
                    if (problemNoDB.length() - index < 0)
                        continue;
                    String no = problemNoDB.substring(index + 1);
                    long lastNo = Long.parseLong(no);
                    lastNoSet.add(lastNo);
                } catch (Exception e) {
//                    e.printStackTrace();
                }
            }

            if (CollectionUtils.isEmpty(lastNoSet)) {
                problemNum = 1l;
            } else {
                Long nextNo = lastNoSet.last() + 1;
                problemNum = nextNo;
            }
        }
//        return String.format("%0" + 6 + "d", problemNo);//6位字符串左补0
        return problemNo + String.format("%0" + 6 + "d", problemNum);//6位字符串左补0
//        return problemNo;
    }

    /**
     * 新增岗检问题表
     * 注意：若是批量导入的方法调用此方法新增问题需要，提前设置岗检计划ID到参数中，且需要以部门为单位进行分开调用才行，否则检查岗检工作和检查小组将不准确
     *
     * @param postCheckedProblemList 前端提交的岗检问题集合，一次提交多个问题
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPostCheckedProblem(List<PostCheckedProblem> postCheckedProblemList) {
        if (CollectionUtils.isEmpty(postCheckedProblemList)) {
            throw new BaseException("参数为空，请检查！");
        } else {
            //过滤空数据行
            StringBuffer errorMsg = new StringBuffer();
            int index = 0;
            Iterator<PostCheckedProblem> iterator = postCheckedProblemList.iterator();
            while (iterator.hasNext()) {
                index++;
                PostCheckedProblem postCheckedProblem = iterator.next();
                boolean frist = true;
                Long checkedPostId = postCheckedProblem.getCheckedPostId();
                Date checkTime = postCheckedProblem.getCheckTime();
                String checkUserName = postCheckedProblem.getCheckUserName();
                Integer problemLevel = postCheckedProblem.getProblemLevel();
                Integer dutyType = postCheckedProblem.getDutyType();
                Integer problemAttribute = postCheckedProblem.getProblemAttribute();
                Integer problemCategory = postCheckedProblem.getProblemCategory();
//                String description = postCheckedProblem.getDescription();
                if (checkedPostId == null
                        && checkTime == null
                        && StringUtils.isBlank(checkUserName)
                        && (problemLevel == null || problemLevel == 0)
                        && (dutyType == null || dutyType == 0)
                        && (problemAttribute == null || problemAttribute == 0)
                        && (problemCategory == null || problemCategory == 0)) {
                    iterator.remove();
                    continue;
                }

                if (checkedPostId == null) {
                    if (frist) {
                        frist = false;
                        errorMsg.append("第").append(index).append("行必数据不完整，详细信息如下：");
                    }
                    errorMsg.append("涉及岗位、");
                }
                if (checkTime == null) {
                    if (frist) {
                        frist = false;
                        errorMsg.append("第").append(index).append("行必数据不完整，详细信息如下：");
                    }
                    errorMsg.append("检查时间、");
                }
                if (StringUtils.isBlank(checkUserName)) {
                    if (frist) {
                        frist = false;
                        errorMsg.append("第").append(index).append("行必数据不完整，详细信息如下：");
                    }
                    errorMsg.append("检查人员");
                }

                if (problemLevel == null || problemLevel == 0) {
                    if (frist) {
                        frist = false;
                        errorMsg.append("第").append(index).append("行必数据不完整，详细信息如下：");
                    }
                    errorMsg.append("问题级别、");
                }
                if (dutyType == null || dutyType == 0) {
                    if (frist) {
                        frist = false;
                        errorMsg.append("第").append(index).append("行必数据不完整，详细信息如下：");
                    }
                    errorMsg.append("职责类别、");
                }
                if (problemAttribute == null || problemAttribute == 0) {
                    if (frist) {
                        frist = false;
                        errorMsg.append("第").append(index).append("行必数据不完整，详细信息如下：");
                    }
                    errorMsg.append("问题属性、");
                }
                if (problemCategory == null || problemCategory == 0) {
                    if (frist) {
                        frist = false;
                        errorMsg.append("第").append(index).append("行必数据不完整，详细信息如下：");
                    }
                    errorMsg.append("问题类别、");
                }
            }

            if (errorMsg.length() > 0) {
                throw new BaseException("错误 " + errorMsg.toString());
            }
        }

        //过滤空参后，再判断一次参数
        if (CollectionUtils.isEmpty(postCheckedProblemList)) {
            throw new BaseException("过滤空行后，未发现有效数据，请检查！");
        }

        //关联取出，检查工作组、小组、受检部门
        PostCheckedProblem data = postCheckedProblemList.get(0);
        Long planInfoId = data.getPlanInfoId();
        PostPlanJoinProblem param = new PostPlanJoinProblem();
        param.setPlanInfoId(planInfoId);
        List<PostPlanJoinProblem> planList = postPlanJoinProblemService.selectPostPlanJoinProblemList(param);
        if (CollectionUtils.isEmpty(planList)) {
            throw new BaseException("岗检计划匹配失败，请检查！");
        }
        PostPlanJoinProblem postPlanJoinProblem = planList.get(0);
        Long checkGroupId = postPlanJoinProblem.getCheckGroupId();
        Long checkTeamId = postPlanJoinProblem.getCheckTeamId();
        Long checkedDeptId = postPlanJoinProblem.getCheckedDeptId();

        SysDept sysDept = sysDeptService.selectDeptById(checkedDeptId);
        String checkedDeptName = sysDept.getDeptName();


        int count = 0;
        for (PostCheckedProblem postCheckedProblem : postCheckedProblemList) {
            count++;
            Date checkTime = postCheckedProblem.getCheckTime();
            Long checkedPostId = postCheckedProblem.getCheckedPostId();

            if (checkTime == null) {
                throw new BaseException("检查时间为空，请检查！");
            }
            if (checkedPostId == null) {
                throw new BaseException("涉及岗位为空，请检查！");
            }
            SysPost sysPost = sysPostService.selectPostById(checkedPostId);
            String checkedPostName = sysPost.getPostName();


            postCheckedProblem.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
            postCheckedProblem.setCreateDefault();


            String problemNo = createProblemNo(postCheckedProblem.getProblemLevel(), checkedDeptId);
            log.info("【岗检问题】新增：设置岗检编号，新的岗检编号={}", problemNo);
            postCheckedProblem.setProblemNo(problemNo);


            postCheckedProblem.setCheckWorkgroupId(checkGroupId);
            postCheckedProblem.setCheckGroupId(checkTeamId);
            postCheckedProblem.setCheckedDeptId(checkedDeptId);
            postCheckedProblem.setCheckedDeptName(checkedDeptName);
            postCheckedProblem.setCheckedPostName(checkedPostName);
            //检查时间取值=岗检计划的开始时间
//            postCheckedProblem.setCheckTime(checkTime);
            postCheckedProblem.setStatus(PostCheckedProblemEnum.ADD.getValue());


            //TODO 临时：待前端修改后需要去掉
//            postCheckedProblem.setProblemLevel(1); //问题等级:1一般、2 重要
//            postCheckedProblem.setDutyType(1); //职责类别：1-业务职责；2-党建及党风廉政；3-安全环保职责；4-合规保密职；
//            postCheckedProblem.setProblemAttribute(1); //问题属性：完整问题、有效性问题、适宜性问题
//            postCheckedProblem.setProblemCategory(1); //问题类别：职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他


            int insertCount = postCheckedProblemMapper.insertPostCheckedProblem(postCheckedProblem);
            if (insertCount == 0) {
                throw new BaseException("第" + count + "行更新失败请检查！");
            }
            //TODO 添加问题操作记录：1、创建
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(postCheckedProblem.getId());
            problemRecord.setContent("录入问题");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return 1;
    }


    /**
     * 问题批量导入
     *
     * @param filePath 文件的路径（相对路径+文件名）
     * @return
     */
    @Override
    public String batchImportProblem(String filePath) {
        String errMsg = "";
        String localPath = RuoYiConfig.getProfile();
        // 文件绝对磁盘路径（含文件名称）
        String downloadPath = localPath + filePath;
        File file = new File(downloadPath);
        List<ProblemImportBean> dataList = null;
        try {
            InputStream inputStream = new FileInputStream(file);
            ExcelUtil excelUtil = new ExcelUtil(ProblemImportBean.class);
            dataList = excelUtil.importExcel(inputStream, 1);
        } catch (Exception e) {
            errMsg = e.getMessage();
            e.printStackTrace();
        }
        if (CollectionUtils.isEmpty(dataList)) {
            return "读取文件失败，未加载到数据！" + errMsg;
        }

        //填充和验证后的问题清单
        dataList = importDataMatchingAndCheck(dataList);


        for (ProblemImportBean data : dataList) {
            Integer no = data.getNo();
            Long checkedDeptId = data.getCheckedDeptId();

            //复制属性值
            PostCheckedProblem postCheckedProblem = new PostCheckedProblem();
            BeanUtils.copyProperties(data, postCheckedProblem);


            String problemNo = createProblemNo(postCheckedProblem.getProblemLevel(), checkedDeptId);
            log.info("【岗检问题】新增：设置岗检编号，新的岗检编号={}", problemNo);

            postCheckedProblem.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
            postCheckedProblem.setStatus(PostCheckedProblemEnum.ADD.getValue());
            postCheckedProblem.setCreateDefault();
            postCheckedProblem.setProblemNo(problemNo);


            log.info("序号{}行 问题内容 -> {}", no, JSON.toJSONString(postCheckedProblem));

            int insertCount = postCheckedProblemMapper.insertPostCheckedProblem(postCheckedProblem);
            if (insertCount == 0) {
                throw new BaseException("全部失败，序号" + no + "行-插入数据库失败，请刷新后再试！");
            }
            //TODO 添加问题操作记录：1、创建
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(postCheckedProblem.getId());
            problemRecord.setContent("问题清单批量导入");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return "SUCCESS";
    }

    /**
     * 导入文件的中数据匹配（部门ID、岗位ID、工作组ID、检查小组ID、检查时间、检查人姓名）与合法校验
     *
     * @param dataList
     * @return
     */
    public List<ProblemImportBean> importDataMatchingAndCheck(List<ProblemImportBean> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            throw new BaseException("读取文件失败，未加载到数据！");
        }

        if (dataList.size() > 1000) {
            throw new BaseException("注意：一次仅可以导入1000条，请在模板标注范围内录入数据！");
        }

        //岗检系统中部门信息
        SysDept sysDeptParam = new SysDept();
        sysDeptParam.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        List<SysDept> sysDeptList = sysDeptService.selectDeptList(sysDeptParam);
        Map<String, List<SysDept>> deptListMap = sysDeptList.stream().collect(Collectors.groupingBy(SysDept::getDeptName));

        //岗位信息
        SysPost postParam = new SysPost();
        List<SysPost> sysPostList = sysPostService.selectPostList(postParam);
        Map<Long, List<SysPost>> postDeptListMap = sysPostList.stream().collect(Collectors.groupingBy(SysPost::getDeptId));

        //当年的岗检计划
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostPlanInfo shouldCheckedParam = new PostPlanInfo();
        shouldCheckedParam.setPlanStatus(PostPlanEnum.STATUS_PASS.getValue());
        shouldCheckedParam.setParams(params);
        List<PostPlanInfo> postPlanInfoList = postPlanInfoService.selectShouldCheckedList(shouldCheckedParam);

        StringBuffer resultBuf = new StringBuffer();
        List<ProblemImportBean> resultList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            ProblemImportBean data = dataList.get(i);
            Integer no = data.getNo();

            String checkUserName = data.getCheckUserName();
            Date checkTime = data.getCheckTime();

            String checkedDeptName = data.getCheckedDeptName();//受检部门
            String checkedPostName = data.getCheckedPostName();//受检岗位
            Integer problemLevel = data.getProblemLevel();//问题级别
            Integer dutyType = data.getDutyType();//职责类别
            Integer problemAttribute = data.getProblemAttribute();//问题属性
            Integer problemCategory = data.getProblemCategory();//问题类别
            String description = data.getDescription();//问题描述

            int emptyCount = 0;
            int notEmptyCount = 0;

            if (StringUtils.isBlank(checkedDeptName)) {
                emptyCount++;
            } else {
                notEmptyCount++;
            }
            if (StringUtils.isBlank(checkedPostName)) {
                emptyCount++;
            } else {
                notEmptyCount++;
            }

            if (problemLevel == null) {
                emptyCount++;
            } else {
                notEmptyCount++;
            }

            if (dutyType == null) {
                emptyCount++;
            } else {
                notEmptyCount++;
            }

            if (problemAttribute == null) {
                emptyCount++;
            } else {
                notEmptyCount++;
            }

            if (problemCategory == null) {
                emptyCount++;
            } else {
                notEmptyCount++;
            }

            if (StringUtils.isBlank(description)) {
                emptyCount++;
            } else {
                notEmptyCount++;
            }

            //有效数据行：全部列都有值
            if (emptyCount == 0) {
                if (!deptListMap.containsKey(checkedDeptName)) {
                    resultBuf.append("序号").append(no).append("行的受检部门无法与系统匹配，请检查！");
                    continue;
                }
                List<SysDept> deptList = deptListMap.get(checkedDeptName);
                Long deptId = deptList.get(0).getDeptId();
                int type = deptList.get(0).getType();//Version-部门类型：1-职能；2-生产


                List<SysPost> postDeptList = postDeptListMap.get(deptId);
                Map<String, List<SysPost>> postNameListMap = postDeptList.stream().collect(Collectors.groupingBy(SysPost::getPostName));
                if (!postNameListMap.containsKey(checkedPostName)) {
                    resultBuf.append("序号").append(no).append("行的受检岗位无法与系统匹配，请检查！");
                    continue;
                }
                List<SysPost> postList = postNameListMap.get(checkedPostName);
                Long postId = postList.get(0).getPostId();
                data.setCheckedDeptId(deptId);//受检部门ID
//                data.setCheckedDeptType(type);//部门类型
                data.setCheckedPostId(postId);//受检岗位ID

                //岗检计划
                Long checkWorkgroupId = null;
                Long checkTeamId = null;
                Date checkedTime = null;
                String checkedUserName = null;
                boolean hasPlan = false;//匹配到计划
                boolean hasUploadPlan = false;//匹配到计划，但未完成确认，需要先在岗记录上传页面操作岗检完成确认

                for (PostPlanInfo postPlanInfo : postPlanInfoList) {
                    Long checkedPostId = postPlanInfo.getCheckedPostId();
                    Integer status = postPlanInfo.getStatus();//岗检状态：1-未检；2-已检；
                    //不是当前岗位计划
                    if (checkedPostId.longValue() != postId.longValue()) {
                        continue;
                    }
                    //岗检记录上传：未上传确认
                    if (status != PostPlanEnum.INFO_STATUS_YES.getValue()) {
                        hasUploadPlan = true;
                        continue;
                    }

                    hasPlan = true;
                    checkWorkgroupId = postPlanInfo.getCheckGroupId();
                    checkTeamId = postPlanInfo.getCheckTeamId();
                    checkedTime = postPlanInfo.getCheckTime();
                    checkedUserName = postPlanInfo.getCheckedUserName();
                    break;
                }

                //系统中未发现该岗位的检查计划，请检查！
                if (!hasPlan && !hasUploadPlan) {
                    resultBuf.append("序号").append(no).append("行-").append("系统中未发现该岗位的检查计划，请检查！");
                    continue;
                }
                //发现了合适的岗检计划，放行
                else if (hasPlan) {
                    data.setCheckWorkgroupId(checkWorkgroupId);//工作组
                    data.setCheckGroupId(checkTeamId);//检查小组
                    //检查时间优先使用文件设置的值
                    if (checkTime == null) {
                        data.setCheckTime(checkedTime);
                    }
                    //检查人员优先使用文件设置的值
                    if (StringUtils.isBlank(checkUserName)) {
                        data.setCheckUserName(checkedUserName);
                    }
                }
                //发现了未上传的计划
                else if (hasUploadPlan) {
                    resultBuf.append("序号").append(no).append("行-").append("请先在岗检记录上传页面操作岗检完成确认，后再导入问题清单，请检查！");
                    continue;
                }


                resultList.add(data);
                continue;
            }
            //空数据行：跳过
            if (notEmptyCount == 0) {
                continue;
            }
            //错误数据行：有些列是空的有些列是有值的
            if (emptyCount != 0 && notEmptyCount != 0) {
                resultBuf.append("序号").append(no).append("行的数据不完整，请检查！");
                continue;
            }
        }

        //如果有错误信息，本次导入全部失败！
        if (resultBuf.length() >= 1) {
            throw new BaseException("失败：信息如下：" + resultBuf.toString());
        }

        //如果有错误信息，本次导入全部失败！
        if (CollectionUtils.isEmpty(resultList)) {
            throw new BaseException("未读取到有效数据，导入文件是否与模板格式一致，请检查！");
        }

        return resultList;
    }

    /**
     * 整改方案/整改实施导入：用户通过岗检问题导出，导出文件，在导出文件的基础上填充问题的方案和整改信息后将表格重新导入到系统中
     *
     * @param filePath 文件的路径（相对路径+文件名）
     * @return
     */
    @Override
    public String batchImportRectification(String filePath) {
        String errMsg = "";
        String localPath = RuoYiConfig.getProfile();
        String downloadPath = localPath + filePath;// 文件绝对磁盘路径（含文件名称）
        List<ProblemExportBean> dataList = null;
        try {
            FileInputStream inputStream = new FileInputStream(downloadPath);
            PostProblemCreateExcel<ProblemExportBean> excelBeanExcelUtil = new PostProblemCreateExcel<>(ProblemExportBean.class);
            dataList = excelBeanExcelUtil.importExcel(inputStream, 1);
        } catch (Exception e) {
            errMsg = e.getMessage();
            e.printStackTrace();
        }
        if (CollectionUtils.isEmpty(dataList)) {
            return "读取文件失败，未加载到数据！" + errMsg;
        }

        //填充和验证后的问题清单
        dataList = importDataRectificationMatchingAndCheck(dataList);

        for (ProblemExportBean data : dataList) {
            Integer no = data.getNo();
            boolean programmeFlag = data.isProgrammeFlag();
            //复制属性值
            PostCheckedProblem problem = new PostCheckedProblem();
            BeanUtils.copyProperties(data, problem);
            //待部门审核
            problem.setStatus(PostCheckedProblemEnum.DEPT_WAIT.getValue());
            problem.setUpdateDefault();


            //TODO 更新业务职责的状态=待审核：只要部门修改数据，人力资源都需要重新审核单据
            //1、按区域类型+主表id批量更新明细表状态、审核人、审核时间、未通过理由
            LambdaUpdateWrapper<PostCheckedProblem> updateWrapper = new LambdaUpdateWrapper<>();
            //条件
            updateWrapper.eq(PostCheckedProblem::getId, problem.getId());

            //需要更新的字段
            //1-方案
            updateWrapper.set(PostCheckedProblem::getStatus, problem.getStatus());
            updateWrapper.set(PostCheckedProblem::getProblemCause, problem.getProblemCause());//原因
            updateWrapper.set(PostCheckedProblem::getIsImmediatelyCorrected, problem.getIsImmediatelyCorrected());//立行立改
            updateWrapper.set(PostCheckedProblem::getRectificationMeasure, problem.getRectificationMeasure());//整改措施/建议
            updateWrapper.set(PostCheckedProblem::getRectificationPeriod, problem.getRectificationPeriod());//整改期限
            //2-专业审核人ID
            updateWrapper.set(PostCheckedProblem::getSpecialityDepartmentReviewerId, problem.getSpecialityDepartmentReviewerId());
            updateWrapper.set(PostCheckedProblem::getSpecialityDepartmentReviewerName, problem.getSpecialityDepartmentReviewerName()); //专业部门审核人姓名
            //实施
            updateWrapper.set(PostCheckedProblem::getIsRectificationCompleted, problem.getIsRectificationCompleted());//整改情况
            updateWrapper.set(PostCheckedProblem::getRectificationCompletionTime, problem.getRectificationCompletionTime());//整改完成时间
            updateWrapper.set(PostCheckedProblem::getReviewDepartmentReviewerId, problem.getReviewDepartmentReviewerId());//复查人ID
            updateWrapper.set(PostCheckedProblem::getReviewDepartmentReviewerName, problem.getReviewDepartmentReviewerName());//复查部门审核人姓名
            //3-更新为空的字段
            updateWrapper.set(PostCheckedProblem::getDeptApproveUserId, null);//部门审核人ID
            updateWrapper.set(PostCheckedProblem::getDeptApproveUserName, null);//部门审核人
            updateWrapper.set(PostCheckedProblem::getDeptApproveTime, null);//部门审核时间
            updateWrapper.set(PostCheckedProblem::getSpecialityDepartmentReviewTime, null);//专业审核人审核时间
            updateWrapper.set(PostCheckedProblem::getReviewDepartmentReviewerTime, null);//复查人审核时间
            updateWrapper.set(PostCheckedProblem::getReviewConclusion, null);//复查结论
            updateWrapper.set(PostCheckedProblem::getReason, null);//未通过理由

            int insertCount = postCheckedProblemMapper.update(null, updateWrapper);
            if (insertCount == 0) {
                throw new BaseException("全部失败，序号" + no + "行-更新数据库失败，请刷新后再试！");
            }
            //TODO 添加问题操作记录：1、创建
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(problem.getId());
            //true：仅为方案导入
            if (programmeFlag) {
                problemRecord.setContent("问题方案批量导入");
            }
            //false：方案 + 实施 导入
            else {
                problemRecord.setContent("问题方案/实施批量导入");
            }
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return "SUCCESS";
    }


    /**
     * 导入方案/实施文件的中数据匹配（问题编号 专业部门 专业审核人 复查部门 复查人）与合法校验
     *
     * @param dataList
     * @return
     */
    public List<ProblemExportBean> importDataRectificationMatchingAndCheck(List<ProblemExportBean> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            throw new BaseException("读取文件失败，未加载到数据！");
        }

        if (dataList.size() > 1000) {
            throw new BaseException("注意：一次仅可以导入1000条，请在模板标注范围内录入数据！");
        }


        List<String> problemNoList = dataList.stream().map(ProblemExportBean::getProblemNo).collect(Collectors.toList());
        LambdaQueryWrapper<PostCheckedProblem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PostCheckedProblem::getProblemNo, problemNoList);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectList(queryWrapper);
        Map<String, List<PostCheckedProblem>> problemListProblemNoMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getProblemNo));

        //岗检系统中部门信息
        SysDept sysDeptParam = new SysDept();
        sysDeptParam.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        List<SysDept> sysDeptList = sysDeptService.selectDeptList(sysDeptParam);
        Map<String, List<SysDept>> deptListMap = sysDeptList.stream().collect(Collectors.groupingBy(SysDept::getDeptName));

        List<SysUser> sysUserList = sysUserService.postUserList(null, null, null, null, null, null, null);
        Map<String, List<SysUser>> userListDeptMap = sysUserList.stream().collect(Collectors.groupingBy(SysUser::getDeptName));

        StringBuffer resultBuf = new StringBuffer();
        List<ProblemExportBean> resultList = new ArrayList<>();
        for (int i = 0; i < dataList.size(); i++) {
            ProblemExportBean data = dataList.get(i);
            Integer no = data.getNo();
            String problemNo = data.getProblemNo();

            if (!problemListProblemNoMap.containsKey(problemNo)) {
                resultBuf.append("序号").append(no).append("行").append("问题编号无法与系统匹配，请检查！");
                continue;
            } else {
                PostCheckedProblem problem = problemListProblemNoMap.get(problemNo).get(0);
                Integer status = problem.getStatus();
                data.setId(problem.getId());
                if (status == PostCheckedProblemEnum.ADD.getValue()) {
                    resultBuf.append("序号").append(no).append("行").append("无法填写方案/措施，因为管理员尚未指定整改责任人，请检查！");
                    continue;
                } else if (status != PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue()
                        && status != PostCheckedProblemEnum.DEPT_WAIT.getValue()
                        && status != PostCheckedProblemEnum.DEPT_BACK.getValue()
                        && status != PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue()
                        && status != PostCheckedProblemEnum.FU_CHA_BACK.getValue()) {
                    resultBuf.append("序号").append(no).append("行").append("当前状态无法填写方案/措施（仅有待审核或者驳回时可填写），请检查！");
                    continue;
                }
            }
            //专业审核部门
            String specialityDepartment = data.getSpecialityDepartment();
            String specialityDepartmentReviewerName = data.getSpecialityDepartmentReviewerName() != null ? data.getSpecialityDepartmentReviewerName().replaceAll("\\s*", "") : null;
            data.setSpecialityDepartmentReviewerName(specialityDepartmentReviewerName);
            //复查部门
            String reviewDepartment = data.getReviewDepartment();
            String reviewDepartmentReviewerName = data.getReviewDepartmentReviewerName() != null ? data.getReviewDepartmentReviewerName().replaceAll("\\s*", "") : null;
            data.setReviewDepartmentReviewerName(reviewDepartmentReviewerName);
            //方案
            String problemCause = data.getProblemCause();
            Integer isImmediatelyCorrected = data.getIsImmediatelyCorrected();
            String rectificationMeasure = data.getRectificationMeasure();
            Date rectificationPeriod = data.getRectificationPeriod();
            //实施
            Integer isRectificationCompleted = data.getIsRectificationCompleted();
            Date rectificationCompletionTime = data.getRectificationCompletionTime();


            if (StringUtils.isNotEmpty(specialityDepartment) && !deptListMap.containsKey(specialityDepartment)) {
                resultBuf.append("序号").append(no).append("行").append("专业审核部门无法与系统匹配，请检查！");
                continue;
            }
            if (StringUtils.isNotEmpty(reviewDepartment) && !deptListMap.containsKey(reviewDepartment)) {
                resultBuf.append("序号").append(no).append("行").append("复查部门无法与系统匹配，请检查！");
                continue;
            }


            //true：仅为方案导入
            //false：方案 + 实施 导入
            boolean programmeFlag = true;
            int notEmptyCountFA = 0;
            if (StringUtils.isNotBlank(problemCause)) {
                notEmptyCountFA++;
            }
            if (isImmediatelyCorrected != null) {
                notEmptyCountFA++;
            }
            if (StringUtils.isNotBlank(rectificationMeasure)) {
                notEmptyCountFA++;
            }
            if (rectificationPeriod != null) {
                notEmptyCountFA++;
            }
            //无效：空行
            if (notEmptyCountFA == 0) {
                resultBuf.append("序号").append(no).append("行").append("无效数据方案信息未填写，请检查！");
                continue;
            }
            //无效：数据不完整
            else if (notEmptyCountFA != 4) {
                resultBuf.append("序号").append(no).append("行").append("无效数据方案信息填写不完整，请检查！");
                continue;
            }


            int notEmptyCountSS = 0;
            if (isRectificationCompleted != null) {
                notEmptyCountSS++;
            }
            if (rectificationCompletionTime != null) {
                notEmptyCountSS++;
            }
            if (StringUtils.isNotBlank(reviewDepartment)) {
                notEmptyCountSS++;
            }
            if (StringUtils.isNotBlank(reviewDepartmentReviewerName)) {
                notEmptyCountSS++;
            }

            //实施
            if (notEmptyCountSS == 4) {
                programmeFlag = true;
            }
            //无效：数据不完整
            else if (notEmptyCountSS != 0) {
                resultBuf.append("序号").append(no).append("行").append("无效数据实施信息填写不完整，请检查！");
                continue;
            }
            data.setProgrammeFlag(programmeFlag);

            //查找专业审核人
            if (StringUtils.isNotEmpty(specialityDepartmentReviewerName) && StringUtils.isNotEmpty(specialityDepartment) && deptListMap.containsKey(specialityDepartment)) {
                List<SysUser> userList = userListDeptMap.get(specialityDepartment);
                boolean userHas = false;
                for (SysUser user : userList) {
                    String nickName = user.getNickName().replaceAll("\\s*", "");
                    if (specialityDepartmentReviewerName.equals(nickName)) {
                        data.setSpecialityDepartmentReviewerId(user.getUserId());
                        userHas = true;
                        break;
                    }
                }
                if (!userHas) {
                    resultBuf.append("序号").append(no).append("行").append("系统中专业审核人不存在，请检查！");
                    continue;
                }
            }
            //查找复查人
            if (StringUtils.isNotEmpty(reviewDepartmentReviewerName) && StringUtils.isNotEmpty(reviewDepartment) && deptListMap.containsKey(reviewDepartment)) {
                List<SysUser> userList = userListDeptMap.get(reviewDepartment);
                boolean userHas = false;
                for (SysUser user : userList) {
                    String nickName = user.getNickName().replaceAll("\\s*", "");
                    if (reviewDepartmentReviewerName.equals(nickName)) {
                        data.setReviewDepartmentReviewerId(user.getUserId());
                        userHas = true;
                        break;
                    }
                }
                if (!userHas) {
                    resultBuf.append("序号").append(no).append("行").append("系统中复查人不存在，请检查！");
                    continue;
                }
            }

            resultList.add(data);
        }

        //如果有错误信息，本次导入全部失败！
        if (resultBuf.length() >= 1) {
            throw new BaseException("失败：信息如下：" + resultBuf.toString());
        }

        //如果有错误信息，本次导入全部失败！
        if (CollectionUtils.isEmpty(resultList)) {
            throw new BaseException("未读取到有效数据，导入文件是否与模板格式一致，请检查！");
        }


        return resultList;
    }

    /**
     * 修改岗检问题表
     *
     * @param postCheckedProblemList 岗检问题集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePostCheckedProblem(List<PostCheckedProblem> postCheckedProblemList) {
        if (CollectionUtils.isEmpty(postCheckedProblemList)) {
            return 0;
        }
        int count = 0;
        for (PostCheckedProblem postCheckedProblem : postCheckedProblemList) {
            count++;

            Date checkTime = postCheckedProblem.getCheckTime();
            Long checkedPostId = postCheckedProblem.getCheckedPostId();

            if (checkTime == null) {
                throw new BaseException("检查时间为空，请检查！");
            }

            if (checkedPostId == null) {
                throw new BaseException("涉及岗位为空，请检查！");
            }

            //只允许新增状态单据修改
            PostCheckedProblem dataDb = postCheckedProblemMapper.selectById(postCheckedProblem.getId());
            if (dataDb == null) {
                throw new BaseException("id错误或为空，请检查！");
            }
            Integer status = dataDb.getStatus();
            if (status != null && status != PostCheckedProblemEnum.ADD.getValue()) {
                throw new BaseException("当前状态无法修改，请检查！");
            }

            SysPost sysPost = sysPostService.selectPostById(checkedPostId);
            String checkedPostName = sysPost.getPostName();

            postCheckedProblem.setUpdateDefault();
            postCheckedProblem.setStatus(PostCheckedProblemEnum.ADD.getValue());
            postCheckedProblem.setCheckedDeptId(null);
            postCheckedProblem.setCheckedDeptName(null);
//            postCheckedProblem.setCheckedDeptName(checkedDeptName);部门是允许修改的
            postCheckedProblem.setCheckedPostName(checkedPostName);
            int updateCount = postCheckedProblemMapper.updatePostCheckedProblem(postCheckedProblem);
            if (updateCount == 0) {
                throw new BaseException("第" + count + "行更新失败请检查！");
            }
            //TODO 添加问题操作记录：2、修改
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(postCheckedProblem.getId());
            problemRecord.setContent("修改问题");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return 1;
    }
/*
    public void jobInspectionScore(List<PostCheckedProblem> postCheckedProblemList) {
        *//**
     * 业务职责有效性 1
     * 党建及党风廉政建设职责有效性 2
     * 安全环保职责有效性 3
     * 合规与保密职责有效性 4
     * 任职资格与能力素质要求符合性 5
     * 岗位责任制文件完整性与适宜性 6
     *//*
        if (postCheckedProblemList.isEmpty()) {
            return;
        }
        Long planInfoId = postCheckedProblemList.get(0).getPlanInfoId();
        Long departmentId = postCheckedProblemList.get(0).getCheckedDeptId();
        List<PostAssessmentRules> postAssessmentRules = postAssessmentRulesMapper.selectList(Wrappers.query());
        PostPlanInfo postPlanInfo = postPlanInfoMapper.selectById(planInfoId);
        PostPlan postPlan = postPlanMapper.selectById(postPlanInfo.getPostPlanId());
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .eq(PostCheckedProblem::getCheckedDeptId, departmentId)
                .between(PostCheckedProblem::getCreateTime, postPlan.getStartTime(), postPlan.getEndTime())

        );
        List<PostAssessmentRating> postAssessmentRatings = postAssessmentRatingMapper.selectList(Wrappers.<PostAssessmentRating>lambdaQuery()
                .eq(PostAssessmentRating::getPlanId, postPlanInfo.getPostPlanId())
                .eq(PostAssessmentRating::getDeptId, postPlanInfo.getCheckedDeptId())
        );
        if (postAssessmentRatings.isEmpty()) {
            return;
        }
        BigDecimal score = new BigDecimal("100");
        for (PostCheckedProblem postCheckedProblem : postCheckedProblems) {
            Optional<PostAssessmentRules> first = postAssessmentRules.stream().filter(d -> d.getDutyType().equals(postCheckedProblem.getDutyType())).findFirst();
            if (first.isPresent() && score.compareTo(new BigDecimal("0")) > 0) {
                // 计算岗检得分
                if (postCheckedProblem.getProblemLevel().equals("1")) {
                    score = score.subtract(first.get().getProblemLevelOne());
                } else if (postCheckedProblem.getProblemLevel().equals("2")) {
                    score = score.subtract(first.get().getProblemLevelTwo());
                }
            }
        }

        // todo 公式计算
        if (postCheckedProblems.size() > 0) {
            BigDecimal bigDecimal = new BigDecimal("1");
            List<PostPlanInfo> postPlanInfos = postPlanInfoMapper.selectList(Wrappers.<PostPlanInfo>lambdaQuery()
                    .eq(PostPlanInfo::getPostPlanId, postPlan.getId())
            );
            if (postPlanInfos.size() <= 0) {
                score = new BigDecimal("0");
            } else {
                BigDecimal divide = new BigDecimal(postCheckedProblems.size()).divide(new BigDecimal(postPlanInfos.size()).multiply(new BigDecimal("6")));
                if (divide.compareTo(new BigDecimal("0")) <= 0 || divide.compareTo(new BigDecimal("1")) > 0) {
                    score = new BigDecimal("0");
                } else {
                    score = bigDecimal.subtract(divide);
                }
            }
        } else {
            score = new BigDecimal("0");
        }
        postAssessmentRatingMapper.update(null, Wrappers.<PostAssessmentRating>lambdaUpdate()
                .set(PostAssessmentRating::getPositionScore, score)
                .eq(PostAssessmentRating::getDeptId, departmentId)
                .eq(PostAssessmentRating::getPlanId, postPlan.getId())
        );
    }
    */


    /**
     * 批量删除岗检问题表
     *
     * @param ids 需要删除的岗检问题表主键
     * @return 结果
     */
    @Override
    public int deletePostCheckedProblemByIds(Long[] ids) {
        return postCheckedProblemMapper.deletePostCheckedProblemByIds(ids);
    }

    /**
     * 删除岗检问题表信息
     *
     * @param id 岗检问题表主键
     * @return 结果
     */
    @Override
    public int deletePostCheckedProblemById(Long id) {
        return postCheckedProblemMapper.deletePostCheckedProblemById(id);
    }

    /**
     * 管理员批量设置整改责任人
     *
     * @param ids                            多个主键英文逗号拼接
     * @param rectificationResponsibleUserId 整改责任人ID
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int setRectificationResponsibleUserId(String ids, Long rectificationResponsibleUserId) {
        if (StringUtils.isBlank(ids) || rectificationResponsibleUserId == null) {
//            return 0;
            throw new BaseException("参数不全，请检查！");
        }
        //TODO 审核权限：管理员操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();

        // 判断审核的权限
        if (!SecurityUtils.isAdmin(userId)) {
            throw new BaseException("请切换管理员操作！");
        }


        String[] idArr = ids.split(",");
        if (idArr.length == 0) {
            throw new BaseException("id错误或为空，请检查！");
        }


        String errorMsg = "";
        List<PostCheckedProblem> dataList = new ArrayList<>(idArr.length);
        int index = 0;
        for (String idStr : idArr) {
            index++;
            Long id = Long.parseLong(idStr);

            PostCheckedProblem dataDB = postCheckedProblemMapper.selectById(id);
            if (dataDB == null) {
                errorMsg += "【第" + index + "行】id错误或为空，请检查！";
                continue;
            }
            Integer statusDB = dataDB.getStatus();
            if (statusDB != null && statusDB != PostCheckedProblemEnum.ADD.getValue()) {
                errorMsg += "【第" + index + "行】当前状态不允许此操作，请检查！【" + statusDB + ":" + PostCheckedProblemEnum.getStatusStr(statusDB) + "】";
                continue;
            }

//            Long checkedDeptId = dataDB.getCheckedDeptId();//责任部门ID
//            if (!checkedDeptId.equals(deptId)) {
//                errorMsg += "【第" + index + "行】请切换问题责任部门经理操作01！";
//                continue;
//            }

            // 当前登录用户是否为部门经理级别
//            boolean userHaveAuthority = sysPostService.userHaveAuthority(deptId);
//            if (!userHaveAuthority) {
//                errorMsg += "【第" + index + "行】请切换问题责任部门经理操作02！";
//                continue;
//            }

            dataList.add(dataDB);

            //TODO 添加问题操作记录：3、批量指定责任人
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("批量指定责任人");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new BaseException(errorMsg);
        }

        SysUser sysUser = sysUserService.selectUserById(rectificationResponsibleUserId);
        String rectificationResponsibleName = sysUser.getNickName();

        PostCheckedProblem updateData = new PostCheckedProblem();
        updateData.setStatus(PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue());//待填写方案
        updateData.setRectificationResponsibleUserId(rectificationResponsibleUserId);//整改责任人
        updateData.setRectificationResponsibleName(rectificationResponsibleName);//整改责任人
        LambdaUpdateWrapper<PostCheckedProblem> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(PostCheckedProblem::getId, idArr);
        int updateCount = postCheckedProblemMapper.update(updateData, updateWrapper);
        if (updateCount != idArr.length) {
            throw new BaseException("更新行数与请求行数不匹配，请检查！");
        }
        return updateCount;


        /*
        int count = 0;
        for (String idStr : idArr) {
            index++;
            Long id = Long.parseLong(idStr);

            PostCheckedProblem dataDB = postCheckedProblemMapper.selectById(id);
            if (dataDB == null) {
                throw new BaseException("id错误或为空，请检查！");
            }
            Integer status = dataDB.getStatus();
            if (status != null && status != PostCheckedProblemEnum.ADD.getValue()) {
                throw new BaseException("当前状态无法指定整改责任人，请检查！");
            }

            Long checkedDeptId = dataDB.getCheckedDeptId();//责任部门ID
            if (!checkedDeptId.equals(deptId)) {
                throw new BaseException("请切换问题责任部门经理操作【第" + index + "行】！");
            }

            // 当前登录用户是否为部门经理级别
            boolean userHaveAuthority = sysPostService.userHaveAuthority(deptId);
            if (!userHaveAuthority) {
                throw new BaseException("请切换问题责任部门经理操作【第" + index + "行】！");
            }


            PostCheckedProblem data = new PostCheckedProblem();
            data.setId(id);
            data.setStatus(PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue());//待填写方案
            data.setRectificationResponsibleUserId(rectificationResponsibleUserId);
            count += postCheckedProblemMapper.updatePostCheckedProblem(data);
        }
        return count;
        * */
    }

    /**
     * 填写方案：整改责任人填写方案
     *
     * @param id                     问题主键
     * @param problemCause           问题原因
     * @param isImmediatelyCorrected 是否立行立改(1-Yes；2-No；)
     * @param rectificationMeasure   整改措施/建议
     *                               param rectificationResponsibleUserId 整改责任人ID
     * @param rectificationPeriod    整改期限
     * @return
     */
    @Override
    public int updateRectificationMeasure(Long id, String problemCause, Integer isImmediatelyCorrected, String rectificationMeasure, Date rectificationPeriod) {

        if (id == null || StringUtils.isBlank(problemCause) || isImmediatelyCorrected == null || StringUtils.isBlank(rectificationMeasure) || rectificationPeriod == null) {
            throw new BaseException("参数不全，请检查！");
        }
        //TODO 审核权限：部门经理操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        PostCheckedProblem dataDB = postCheckedProblemMapper.selectById(id);
        if (dataDB == null) {
            throw new BaseException("id错误或为空，请检查！");
        }

        //以下状态时，才可以进行：问题录入、待填写方案、部门待审核、部门驳回、专业部门驳回、复查驳回
        Integer statusDB = dataDB.getStatus();
        if (statusDB != PostCheckedProblemEnum.ADD.getValue()
                && statusDB != PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue()
                && statusDB != PostCheckedProblemEnum.DEPT_WAIT.getValue()
                && statusDB != PostCheckedProblemEnum.DEPT_BACK.getValue()
                && statusDB != PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue()
                && statusDB != PostCheckedProblemEnum.FU_CHA_BACK.getValue()

        ) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + statusDB + ":" + PostCheckedProblemEnum.getStatusStr(statusDB) + "】");
        }

        Long rectificationResponsibleUserId = dataDB.getRectificationResponsibleUserId();
        if (!rectificationResponsibleUserId.equals(userId)) {
            throw new BaseException("请切换整改责任人账号操作！");
        }

        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setProblemCause(problemCause);
        data.setIsImmediatelyCorrected(isImmediatelyCorrected);
        data.setRectificationMeasure(rectificationMeasure);
//        data.setRectificationResponsibleUserId(rectificationResponsibleUserId);
        data.setRectificationPeriod(rectificationPeriod);
        data.setStatus(PostCheckedProblemEnum.DEPT_WAIT.getValue());//DEPT_WAIT("待部门审核", 10),

        int update = postCheckedProblemMapper.updatePostCheckedProblem(data);
        if (update > 0) {
            //TODO 添加问题操作记录：4、责任人填写方案
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("责任人填写方案");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }

        return update;
    }

    /**
     * 指定专业部门的审核人：整改责任人填写
     *
     * @param id                             问题主键ID
     * @param specialityDepartmentReviewerId 专业部门的审核人ID
     * @return
     */
    @Override
    public int setSpecialityDepartmentReviewerId(Long id, Long specialityDepartmentReviewerId) {
        if (id == null || specialityDepartmentReviewerId == null) {
//            return 0;
            throw new BaseException("参数不全，请检查！");
        }
        //TODO 审核权限：部门经理操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        PostCheckedProblem dataDB = postCheckedProblemMapper.selectById(id);
        if (dataDB == null) {
            throw new BaseException("id错误或为空，请检查！");
        }


        //以下状态时，才可以进行：问题录入、待填写方案、部门待审核、部门待审核、部门驳回、专业部门驳回、复查驳回
        Integer statusDB = dataDB.getStatus();
        if (statusDB != PostCheckedProblemEnum.ADD.getValue()
                && statusDB != PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue()
                && statusDB != PostCheckedProblemEnum.DEPT_WAIT.getValue()
                && statusDB != PostCheckedProblemEnum.DEPT_BACK.getValue()
                && statusDB != PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue()
                && statusDB != PostCheckedProblemEnum.FU_CHA_BACK.getValue()
        ) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + statusDB + "】");
        }

        Long rectificationResponsibleUserId = dataDB.getRectificationResponsibleUserId();
        if (!rectificationResponsibleUserId.equals(userId)) {
            throw new BaseException("请切换整改责任人账号操作！");
        }

        SysUser sysUser = sysUserService.selectUserById(specialityDepartmentReviewerId);
        String specialityDepartmentReviewerName = sysUser.getNickName();
        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setSpecialityDepartmentReviewerId(specialityDepartmentReviewerId);
        data.setSpecialityDepartmentReviewerName(specialityDepartmentReviewerName);
//        data.setStatus(PostCheckedProblemEnum);
        int update = postCheckedProblemMapper.updatePostCheckedProblem(data);
        if (update > 0) {
            //TODO 添加问题操作记录：5、指定专业部门审核人
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("指定专业部门审核人");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return update;
    }


    /**
     * 审核1：部门经理审核
     *
     * @param id
     * @param status 10-部门审核通过；11-部门审核驳回；
     * @param reason 未通过理由
     * @return
     */
    @Override
    public int setDeptApproveTime(Long id, Integer status, String reason) {
        if (id == null || status == null) {
            throw new BaseException("参数不全，请检查！");
        }

        //状态错误
        if (status != PostCheckedProblemEnum.DEPT_PASS.getValue() && status != PostCheckedProblemEnum.DEPT_BACK.getValue()) {
            throw new BaseException("状态参数错误，请检查！【" + status + "】");
        }

        //驳回时必须填写原因
        if (status == PostCheckedProblemEnum.DEPT_BACK.getValue() && StringUtils.isBlank(reason)) {
            throw new BaseException("未通过理由为空，请检查！");
        }

        //TODO 审核权限：部门经理操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        PostCheckedProblem dataDb = postCheckedProblemMapper.selectById(id);
        if (dataDb == null) {
            throw new BaseException("id错误或为空，请检查！");
        }

        //以下状态时，才可以进行部门审核：部门待审核、部门驳回、专业部门驳回、复查驳回
        Integer statusDB = dataDb.getStatus();
        if (statusDB != PostCheckedProblemEnum.DEPT_WAIT.getValue()
//                && statusDB != PostCheckedProblemEnum.DEPT_BACK.getValue()
//                && statusDB != PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue()
//                && statusDB != PostCheckedProblemEnum.FU_CHA_BACK.getValue()
        ) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + statusDB + ":" + PostCheckedProblemEnum.getStatusStr(statusDB) + "】");
        }

        Long checkedDeptId = dataDb.getCheckedDeptId();//责任部门ID
        if (!checkedDeptId.equals(deptId)) {
            throw new BaseException("请切换问题责任部门经理操作01！");
        }

        // 当前登录用户是否为部门经理级别
        boolean userHaveAuthority = sysPostService.userHaveAuthority(deptId);
        if (!userHaveAuthority) {
            throw new BaseException("请切换问题责任部门经理操作02！");
        }


        //专业部门的审核人ID
        Long specialityDepartmentReviewerId = dataDb.getSpecialityDepartmentReviewerId();

        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setReason(reason);
        data.setDeptApproveTime(new Date());
        data.setDeptApproveUserId(userId);//审核人：部门经理ID
        data.setDeptApproveUserName(loginUser.getUser().getNickName());//审核人：部门经理姓名
        //通过
        if (status == PostCheckedProblemEnum.DEPT_PASS.getValue()) {
            // ZHUAN_ZY_WAIT("待专业部门人审核（非必填）", 20),
            if (specialityDepartmentReviewerId != null) {
                data.setStatus(PostCheckedProblemEnum.ZHUAN_ZY_WAIT.getValue());
            }
            //EDIT_WAIT("待整改人待上传实施（整改人上传实施图片）", 30),
            else {
                data.setStatus(PostCheckedProblemEnum.EDIT_WAIT_TWO.getValue());
            }
        }
        //驳回
        else if (status == PostCheckedProblemEnum.DEPT_BACK.getValue()) {
            data.setStatus(PostCheckedProblemEnum.DEPT_BACK.getValue());
        }


        int update = postCheckedProblemMapper.updatePostCheckedProblem(data);
        if (update > 0) {
            //TODO 添加问题操作记录：6、部门经理审核
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("部门经理审核");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return update;
    }

    /**
     * 审核2：专业部门审核人审核
     *
     * @param id
     * @param status 20-专业部门人审核（非必填）通过；21-专业部门人审核驳回（非必填）；
     * @param reason 未通过理由
     * @return
     */
    @Override
    public int setSpecialityDepartmentReviewTime(Long id, Integer status, String reason) {
        if (id == null || status == null) {
            throw new BaseException("参数不全，请检查！");
        }

        //状态错误
        if (status != PostCheckedProblemEnum.ZHUAN_ZY_PASS.getValue() && status != PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue()) {
            throw new BaseException("状态参数错误，请检查！【" + status + "】");
        }


        //驳回时必须填写原因
        if (status == PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue() && StringUtils.isBlank(reason)) {
            throw new BaseException("未通过理由为空，请检查！");
        }

        //TODO 审核权限：部门经理操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        PostCheckedProblem dataDb = postCheckedProblemMapper.selectById(id);
        if (dataDb == null) {
            throw new BaseException("id错误或为空，请检查！");
        }

        Integer statusDB = dataDb.getStatus();
        if (statusDB != PostCheckedProblemEnum.ZHUAN_ZY_WAIT.getValue()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + statusDB + ":" + PostCheckedProblemEnum.getStatusStr(statusDB) + "】");
        }

        Long specialityDepartmentReviewerId = dataDb.getSpecialityDepartmentReviewerId();
        if (!specialityDepartmentReviewerId.equals(userId)) {
            throw new BaseException("请切换专业部门审核人操作！");
        }


        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setReason(reason);
        data.setSpecialityDepartmentReviewTime(new Date());

        if (status == PostCheckedProblemEnum.ZHUAN_ZY_PASS.getValue()) {
            data.setStatus(PostCheckedProblemEnum.EDIT_WAIT_TWO.getValue());
        } else if (status == PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue()) {
            data.setStatus(PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue());
        }

        int update = postCheckedProblemMapper.updatePostCheckedProblem(data);
        if (update > 0) {
            //TODO 添加问题操作记录：7、专业部门审核
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("专业部门审核");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return update;
    }

    /**
     * 实施整改：上传实施照片
     *
     * @param id                          问题主键ID
     * @param isRectificationCompleted    整改情况-是否完成(1-Yes；2-No；)
     * @param rectificationCompletionTime 整改完成时间
     * @param rectificationCompletionImg  整改完成图片磁盘路径
     * @return
     */
    @Override
    public int updateRectificationCompletionImg(Long id, Integer isRectificationCompleted, Date rectificationCompletionTime, String rectificationCompletionImg) {

        if (id == null || isRectificationCompleted == null || StringUtils.isBlank(rectificationCompletionImg)) {
//            return 0;
            throw new BaseException("参数不全，请检查！");
        }
        if (rectificationCompletionTime == null)
            rectificationCompletionTime = new Date();


        //TODO 审核权限：部门经理操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        PostCheckedProblem dataDb = postCheckedProblemMapper.selectById(id);
        if (dataDb == null) {
            throw new BaseException("id错误或为空，请检查！");
        }
        Integer statusDB = dataDb.getStatus();
        if (statusDB != PostCheckedProblemEnum.EDIT_WAIT_TWO.getValue()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + statusDB + ":" + PostCheckedProblemEnum.getStatusStr(statusDB) + "】");
        }

        Long rectificationResponsibleUserId = dataDb.getRectificationResponsibleUserId();
        if (!rectificationResponsibleUserId.equals(userId)) {
            throw new BaseException("请切换整改责任人账号操作！");
        }


        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setIsRectificationCompleted(isRectificationCompleted);
        data.setRectificationCompletionTime(rectificationCompletionTime);
        data.setRectificationCompletionImg(rectificationCompletionImg);


        //复查人ID
        Long reviewDepartmentReviewerId = dataDb.getReviewDepartmentReviewerId();
        if (reviewDepartmentReviewerId == null) {
            data.setStatus(PostCheckedProblemEnum.EDIT_TWO_OVER.getValue());
        } else {
            //如果已经设置好了复查人将状态修改为40-待复查人审核
            data.setStatus(PostCheckedProblemEnum.FU_CHA_WAIT.getValue());
        }


        int update = postCheckedProblemMapper.updatePostCheckedProblem(data);
        if (update > 0) {
            //TODO 添加问题操作记录：8、责任人上传实施照片
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("责任人上传实施照片");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return update;
    }

    /**
     * 指定复查人
     *
     * @param id                         问题主键ID
     * @param reviewDepartmentReviewerId 复查人ID
     * @return
     */
    @Override
    public int setReviewDepartmentReviewerId(Long id, Long reviewDepartmentReviewerId) {
        if (id == null || reviewDepartmentReviewerId == null) {
//            return 0;
            throw new BaseException("参数不全，请检查！");
        }

        //TODO 审核权限：部门经理操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        PostCheckedProblem dataDb = postCheckedProblemMapper.selectById(id);
        if (dataDb == null) {
            throw new BaseException("id错误或为空，请检查！");
        }
        Integer statusDB = dataDb.getStatus();
        if (statusDB != PostCheckedProblemEnum.EDIT_WAIT_TWO.getValue()
                && statusDB != PostCheckedProblemEnum.EDIT_TWO_OVER.getValue()
        ) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + statusDB + ":" + PostCheckedProblemEnum.getStatusStr(statusDB) + "】");
        }
        Long rectificationResponsibleUserId = dataDb.getRectificationResponsibleUserId();
        if (!rectificationResponsibleUserId.equals(userId)) {
            throw new BaseException("请切换整改责任人账号操作！");
        }

        SysUser sysUser = sysUserService.selectUserById(reviewDepartmentReviewerId);
        String reviewDepartmentReviewerName = sysUser.getNickName();

        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setReviewDepartmentReviewerId(reviewDepartmentReviewerId);
        data.setReviewDepartmentReviewerName(reviewDepartmentReviewerName);//复查人姓名
        data.setStatus(PostCheckedProblemEnum.FU_CHA_WAIT.getValue());
        int update = postCheckedProblemMapper.updatePostCheckedProblem(data);
        if (update > 0) {
            //TODO 添加问题操作记录：9、指定复查人
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("指定复查人");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return update;
    }

    /**
     * 审核3：复查部门的审核人复查
     *
     * @param id               问题主键ID
     * @param status           30-复查部门人审核通过；31-复查部门人审核驳回
     * @param reviewConclusion 复查结论
     * @param reason           未通过理由
     */
    @Override
    public int setReviewDepartmentReviewerTime(Long id, Integer status, String reviewConclusion, String reason) {
        if (id == null || status == null) {
            throw new BaseException("参数不全，请检查！");
        }

        //状态错误
        if (status != PostCheckedProblemEnum.FU_CHA_PASS.getValue() && status != PostCheckedProblemEnum.FU_CHA_BACK.getValue()) {
            throw new BaseException("状态参数错误，请检查！【" + status + "】");
        }


        //驳回时必须填写原因
        if (status == PostCheckedProblemEnum.FU_CHA_BACK.getValue() && StringUtils.isBlank(reason)) {
            throw new BaseException("未通过理由为空，请检查！");
        }

        //TODO 审核权限：部门经理操作
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long userId = loginUser.getUserId();
        Long deptId = loginUser.getDeptId();
        PostCheckedProblem dataDb = postCheckedProblemMapper.selectById(id);
        if (dataDb == null) {
            throw new BaseException("id错误或为空，请检查！");
        }
        Integer statusDB = dataDb.getStatus();
        if (statusDB != PostCheckedProblemEnum.FU_CHA_WAIT.getValue()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + status + ":" + PostCheckedProblemEnum.getStatusStr(statusDB) + "】");
        }

        //复查部门的审核人ID
        Long reviewDepartmentReviewerId = dataDb.getReviewDepartmentReviewerId();
        if (!reviewDepartmentReviewerId.equals(userId)) {
            throw new BaseException("请切换复查人账号操作！");
        }

        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setReviewConclusion(reviewConclusion);
        data.setReason(reason);
        data.setReviewDepartmentReviewerTime(new Date());
        data.setStatus(status);
        int update = postCheckedProblemMapper.updatePostCheckedProblem(data);
        if (update > 0) {
            //TODO 添加问题操作记录：10、复查
            PostCheckedProblemRecord problemRecord = new PostCheckedProblemRecord();
            problemRecord.setProblemId(id);
            problemRecord.setContent("复查");
            postCheckedProblemRecordService.insertPostCheckedProblemRecord(problemRecord);
        }
        return update;
    }

    /**
     * 1、责任制清单：post_list表
     * 2、检查出的问题：post_checked_problem表
     * 3、岗检数量-已查：post_plan t1 inner join post_plan_info t2 两张表连接，t2.status(岗检状态：1-未检；2-已检；)
     * 4、岗检数量-未查：post_plan t1 inner join post_plan_info t2 两张表连接，t2.status(岗检状态：1-未检；2-已检；)
     */
    @Override
    public PostTotalView totalView() {

        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
//        Map<String, Object> params = new HashMap<>();
        String beginTime = year + "-01-01";
        String endTime = year + "-12-31";


        PostTotalView postTotalView = new PostTotalView();
        // 1-listCount             责任制清单数量
        List<PostList> postLists = postListMapper.selectList(Wrappers.lambdaQuery());
        postTotalView.setListCount(postLists.size());

        // 2-problemCount          检查出的问题数量
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.lambdaQuery());
        postTotalView.setProblemCount(postCheckedProblems.size());

        // 3-checkedPostCount      岗检数量-已查
        Integer checkedPostCount = postCheckedProblemMapper.selectCheckedPostCount(PostPlanEnum.INFO_STATUS_YES.getValue(), beginTime, endTime);
        postTotalView.setCheckedPostCount(checkedPostCount);

        //4-uncheckedPostCount    岗检数量-未查
        Integer uncheckedPostCount = postCheckedProblemMapper.selectCheckedPostCount(PostPlanEnum.INFO_STATUS_NO.getValue(), beginTime, endTime);
        postTotalView.setUncheckedPostCount(uncheckedPostCount);
        return postTotalView;
    }

    @Override
    public PostCheckedProblemView checkedProblem() {
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        String beginTime = year + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";
        Date beginTimeDate = DateUtils.parseDate(beginTime);
        Date endTimeDate = DateUtils.parseDate(endTime);

        LambdaQueryWrapper<PostCheckedProblem> problemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        problemLambdaQueryWrapper.between(PostCheckedProblem::getCheckTime, beginTimeDate, endTimeDate);
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(problemLambdaQueryWrapper);
        Integer problemComplete = 0;
        Integer problemSuitable = 0;
        Integer problemEffective = 0;
        //（1-完整问题；2-有效性问题；3-适宜性问题；）
        if (!postCheckedProblems.isEmpty()) {
            for (PostCheckedProblem postCheckedProblem : postCheckedProblems) {
                if (postCheckedProblem.getProblemAttribute() != null && postCheckedProblem.getProblemAttribute() == 1)
                    problemComplete++;

                if (postCheckedProblem.getProblemAttribute() != null && postCheckedProblem.getProblemAttribute() == 2)
                    problemEffective++;

                if (postCheckedProblem.getProblemAttribute() != null && postCheckedProblem.getProblemAttribute() == 3)
                    problemSuitable++;

            }
        }
        PostCheckedProblemView post = new PostCheckedProblemView();
        post.setProblemComplete(problemComplete);
        post.setProblemEffective(problemEffective);
        post.setProblemSuitable(problemSuitable);
        post.setProblemTotal(postCheckedProblems.size());
        return post;
    }

    @Override
    public Integer userTotal() {
        return postListMapper.userTotal();
    }

    @Override
    public LinkedHashMap<Integer, Double> problemRectification() {
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        String beginTime = year + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";
        Date beginTimeDate = DateUtils.parseDate(beginTime);
        Date endTimeDate = DateUtils.parseDate(endTime);

        LambdaQueryWrapper<PostCheckedProblem> problemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        problemLambdaQueryWrapper.between(PostCheckedProblem::getCheckTime, beginTimeDate, endTimeDate);
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(problemLambdaQueryWrapper);
        Integer problemComplete = 0;//完整问题
        Integer overProblemComplete = 0;

        Integer problemSuitable = 0;//有效性问题
        Integer overProblemSuitable = 0;

        Integer problemEffective = 0;//适宜性问题
        Integer overProblemEffective = 0;

        Integer total = 0;
        Integer overTotal = 0;
        //（1-完整问题；2-有效性问题；3-适宜性问题；4 总数）
        if (!postCheckedProblems.isEmpty()) {
            for (PostCheckedProblem postCheckedProblem : postCheckedProblems) {
                total++;
                Integer problemAttribute = postCheckedProblem.getProblemAttribute();
                Integer status = postCheckedProblem.getStatus();//复查通过
                Integer isRectificationCompleted = postCheckedProblem.getIsRectificationCompleted();//整改情况-是否完成(1-Yes；2-No；)

                //完整问题
                if (problemAttribute != null && problemAttribute == 1) {
                    problemComplete++;
                    if (status != null && status == PostCheckedProblemEnum.FU_CHA_PASS.getValue() && isRectificationCompleted != null && isRectificationCompleted == 1) {
                        overProblemComplete++;
                        overTotal++;
                    }
                }
                if (problemAttribute != null && problemAttribute == 3) {
                    problemEffective++;
                    if (status != null && status == PostCheckedProblemEnum.FU_CHA_PASS.getValue() && isRectificationCompleted != null && isRectificationCompleted == 1) {
                        overProblemEffective++;
                        overTotal++;
                    }
                }
                if (problemAttribute != null && problemAttribute == 2) {
                    problemSuitable++;
                    if (status != null && status == PostCheckedProblemEnum.FU_CHA_PASS.getValue() && isRectificationCompleted != null && isRectificationCompleted == 1) {
                        overProblemSuitable++;
                        overTotal++;
                    }
                }

//                if (status != null && status == 1) {
//                    overTotal++;
//                }
            }
        }


        //注意：前端解析是按顺序进行的，所以必须用有顺序的LinkedHashMap，且put顺序不能随意调整
        LinkedHashMap<Integer, Double> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put(1, problemComplete == 0 ? 0 : new BigDecimal(overProblemComplete).divide(new BigDecimal(problemComplete), 4, RoundingMode.HALF_UP).doubleValue());
        linkedHashMap.put(2, problemSuitable == 0 ? 0 : new BigDecimal(overProblemSuitable).divide(new BigDecimal(problemSuitable), 4, RoundingMode.HALF_UP).doubleValue());
        linkedHashMap.put(3, problemEffective == 0 ? 0 : new BigDecimal(overProblemEffective).divide(new BigDecimal(problemEffective), 4, RoundingMode.HALF_UP).doubleValue());
        linkedHashMap.put(4, total == 0 ? 0 : new BigDecimal(overTotal).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP).doubleValue());
        return linkedHashMap;

//        problemComplete = 1;
//        problemSuitable = 2;
//        problemEffective = 3;
//        total = 6;
//        Map<Integer, BigDecimal> map = new HashMap<>();
//        map.put(1, problemComplete == 0 ? new BigDecimal(0) : new BigDecimal(overproblemComplete).divide(new BigDecimal(problemComplete), 4, RoundingMode.HALF_UP));
//        map.put(2, problemSuitable == 0 ? new BigDecimal(0) : new BigDecimal(overproblemSuitable).divide(new BigDecimal(problemSuitable), 4, RoundingMode.HALF_UP));
//        map.put(3, problemEffective == 0 ? new BigDecimal(0) : new BigDecimal(overproblemEffective).divide(new BigDecimal(problemEffective), 4, RoundingMode.HALF_UP));
//        map.put(4, total == 0 ? new BigDecimal(0) : new BigDecimal(overtotal).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP));
    }

    @Override
    public List<DeptProblemRectificationView> deptProblemRectification() {
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        String beginTime = year + "-01-01 00:00:00";
        String endTime = year + "-12-31 23:59:59";
        Date beginTimeDate = DateUtils.parseDate(beginTime);
        Date endTimeDate = DateUtils.parseDate(endTime);

        LambdaQueryWrapper<PostCheckedProblem> problemLambdaQueryWrapper = new LambdaQueryWrapper<>();
        problemLambdaQueryWrapper.between(PostCheckedProblem::getCheckTime, beginTimeDate, endTimeDate);
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(problemLambdaQueryWrapper);
        List<DeptProblemRectificationView> dataList = new ArrayList<>();
        if (!postCheckedProblems.isEmpty()) {
            Map<Long, List<PostCheckedProblem>> deptProblemListMap = postCheckedProblems.stream().collect(Collectors.groupingBy(PostCheckedProblem::getCheckedDeptId));
            for (Map.Entry<Long, List<PostCheckedProblem>> deptProblemListEntry : deptProblemListMap.entrySet()) {
                DeptProblemRectificationView dataView = new DeptProblemRectificationView();
                dataView.setDeptId(deptProblemListEntry.getKey());//deptId
                dataView.setDeptName(postAssessmentRatingMapper.getSysDeptName(deptProblemListEntry.getKey()));
                Integer problemTotal = 0;
                Integer problemComplete = 0;
                //遍历部门下的问题
                for (PostCheckedProblem postCheckedProblem : deptProblemListEntry.getValue()) {
                    problemTotal++;

                    Integer status = postCheckedProblem.getStatus();//复查通过
                    Integer isRectificationCompleted = postCheckedProblem.getIsRectificationCompleted();//整改情况-是否完成(1-Yes；2-No；)
                    if (status != null && status == PostCheckedProblemEnum.FU_CHA_PASS.getValue() && isRectificationCompleted != null && isRectificationCompleted == 1) {
                        problemComplete++;
                    }
                }
                dataView.setProblemTotal(problemTotal);
                dataView.setProblemComplete(problemComplete);
                dataView.setProblemRectificationRate(problemTotal == null ? 0 : new BigDecimal(problemComplete).divide(new BigDecimal(problemTotal), 4, RoundingMode.HALF_UP).doubleValue());
                dataList.add(dataView);
            }
        }
        return dataList;
    }

    @Override
    public List<PostCheckedUnCheckedView> postChecked(Integer status) {
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, new Date());
        String beginTime = year + "-01-01";
        String endTime = year + "-12-31";
        return postListMapper.postChecked(status, beginTime, endTime);
    }

    @Override
    public Integer getPostCountByDeptId(Long deptId) {
        return postListMapper.getPostCountByDeptId(deptId);
    }

    /**
     * 按问题属性分组统计问题类别
     *
     * @return
     */
    @Override
    public List<ProblemCategory> problemCategoryByAttribute() {
////        @ApiModelProperty("职责权限问题")
//        private Integer problemCategoryOne;
////        @ApiModelProperty("工作内容问题")
//        private Integer problemCategoryTwo;
////        @ApiModelProperty("工作标准问题")
//        private Integer problemCategoryThree;
////        @ApiModelProperty("考核奖励问题")
//        private Integer problemCategoryFour;
////        @ApiModelProperty("任职资格问题")
//        private Integer problemCategoryFive;
////        @ApiModelProperty("其他")
//        private Integer problemCategorySix;
////        @ApiModelProperty("总数量")
//        private Integer problemTotal;

        List<ProblemCategory> list = postCheckedProblemMapper.problemCategoryByAttribute();
        ProblemCategory totalData = new ProblemCategory();
        totalData.setProblemAttribute(999);
        totalData.setProblemAttributeView("总计");
        int problemCategoryOne = 0;
        int problemCategoryTwo = 0;
        int problemCategoryThree = 0;
        int problemCategoryFour = 0;
        int problemCategoryFive = 0;
        int problemCategorySix = 0;
        for (ProblemCategory data : list) {
//            Integer problemAttribute = data.getProblemAttribute();
//            switch (problemAttribute) {
//                case 1: {
//                    setProblemAttributeView("完整问题");
//
//                    break;
//                }
//                case 2: {
//                    setProblemAttributeView("有效性问题");
//
//                    break;
//                }
//                case 3: {
//                    setProblemAttributeView("适宜性问题");
//
//                    break;
//                }
//
//                default:
//                    setProblemAttributeView("Other");
//                    break;
//            }

            problemCategoryOne += data.getProblemCategoryOne();
            problemCategoryTwo += data.getProblemCategoryTwo();
            problemCategoryThree += data.getProblemCategoryThree();
            problemCategoryFour += data.getProblemCategoryFour();
            problemCategoryFive += data.getProblemCategoryFive();
            problemCategorySix += data.getProblemCategorySix();
        }
        totalData.setProblemCategoryOne(problemCategoryOne);
        totalData.setProblemCategoryTwo(problemCategoryTwo);
        totalData.setProblemCategoryThree(problemCategoryThree);
        totalData.setProblemCategoryFour(problemCategoryFour);
        totalData.setProblemCategoryFive(problemCategoryFive);
        totalData.setProblemCategorySix(problemCategorySix);
        list.add(totalData);
        return list;
    }

    @Override
    public List<Map<String, Object>> getDeptIdListByType(Integer type) {
        return postAssessmentRatingOtherMapper.getDeptIdListByType(type);
    }

    @Override
    public void functionDeptProblemContrast(FunctionDeptProblemContrastView data, String year) {
//         查询问题表
//        select * from "public"."post_checked_problem";
//        GROUP BY problem_attribute -- 问题属性（1-完整问题；2-有效性问题；3-适宜性问题；）
//        GROUP BY problem_category -- 问题类别（职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他）
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .eq(PostCheckedProblem::getCheckedDeptId, data.getDeptId())
                .like(PostCheckedProblem::getCheckTime, year)
        );
//        @ApiModelProperty("总数量")
        int problemTotal = 0;

        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
            for (PostCheckedProblem postCheckedProblem : postCheckedProblems) {
                problemTotal++;
            }
        }
        data.setProblemTotal(problemTotal);
    }

    /**
     * @param type
     * @param year
     * @param selType 1 公司 2 部门 3 关键岗位
     * @return
     */
    @Override
    public Object coverageRateView(Integer type, String year, String selType) {
        Map<String, Object> map = new HashMap<>();
        if (selType.equals("1")) {
            // 查询总人数
            int mantotal = postCheckedProblemMapper.selectAllMans();
            // 被检查总人数
            int cmantotal = postCheckedProblemMapper.selectCheaAllMans(year);

            // 查询岗位数
            int postTolat = postCheckedProblemMapper.selectPostTolat();
            int cpostTolat = postCheckedProblemMapper.selectCheatPostTolat(year);
            map.put("mantotal", mantotal);
            map.put("cmantotal", cmantotal);
            map.put("postTolat", postTolat);
            map.put("cpostTolat", cpostTolat);
        } else if (selType.equals("2")) {
            // 查询总岗位人数
            int deptTotal = postCheckedProblemMapper.selectAllMansByDeptType(type);
            int cdeptTotal = postCheckedProblemMapper.selectCheatAllMansByDeptType(type, year);
            // 查询部门岗位数
            int deptPostTotal = postCheckedProblemMapper.seletctPostTolatByDeptType(type);
            int cdeptPostTotal = postCheckedProblemMapper.seletctCheatPostTolatByDeptType(type, year);
            map.put("mantotal", deptTotal);
            map.put("cmantotal", cdeptTotal);
            map.put("postTolat", deptPostTotal);
            map.put("cpostTolat", cdeptPostTotal);
        } else if (selType.equals("3")) {
            // 关键岗位总人数
            int keyTotal = postCheckedProblemMapper.selectAllKeyMans(type);
            int ckeyTotal = postCheckedProblemMapper.selectCheatAllKeyMans(type, year);


            // 查询关键岗位数
            int keyPostTotal = postCheckedProblemMapper.seletctKeyPostTolat(type);
            int ckeyPostTotal = postCheckedProblemMapper.seletctCheatKeyPostTolat(type, year);
            map.put("mantotal", keyTotal);
            map.put("cmantotal", ckeyTotal);
            map.put("postTolat", keyPostTotal);
            map.put("cpostTolat", ckeyPostTotal);
        }
        return map;
    }

    @Override
    public List<DutyTypeProblemStatisticsView> dutyTypeProblemStatisticsView(Integer type, String year, String deptId) {
        List<Map<String, Object>> deptIdListByType = postAssessmentRatingOtherMapper.getDeptIdListByType(type);
        if (deptIdListByType == null || deptIdListByType.size() == 0) {
            return new ArrayList<>();
        }
        List<String> deptIds = deptIdListByType.stream().map(d -> d.get("deptId").toString()).distinct().collect(Collectors.toList());
        // 查询职能问题数量
        if (!deptId.equals("0")) {
            deptIds.clear();
            deptIds.add(deptId);
        }
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
                .like(PostCheckedProblem::getCheckTime, year)
        );
        List<DutyTypeProblemStatisticsView> list = new ArrayList<>();
        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
//            @ApiModelProperty("业务职责")
            Integer dutyTypeOne = 0;

//            @ApiModelProperty("党建及党风廉政")
            Integer dutyTypeTwo = 0;

//            @ApiModelProperty("安全环保职责")
            Integer dutyTypeThree = 0;

//            @ApiModelProperty("合规保密职")
            Integer dutyTypeFour = 0;
            for (PostCheckedProblem postCheckedProblem : postCheckedProblems) {
                if (postCheckedProblem.getDutyType() == 1)
                    dutyTypeOne++;
                if (postCheckedProblem.getDutyType() == 2)
                    dutyTypeTwo++;
                if (postCheckedProblem.getDutyType() == 3)
                    dutyTypeThree++;
                if (postCheckedProblem.getDutyType() == 4)
                    dutyTypeFour++;
            }
            DutyTypeProblemStatisticsView data = new DutyTypeProblemStatisticsView();
            data.setDutyTypeOne(dutyTypeOne);
            data.setDutyTypeTwo(dutyTypeTwo);
            data.setDutyTypeThree(dutyTypeThree);
            data.setDutyTypeFour(dutyTypeFour);
            list.add(data);
        }


        return list;
    }

    @Override
    public List<ProblemLevelView> problemLevelView(Integer type, String year, String deptId) {
        //         查询问题表
//        select * from "public"."post_checked_problem";
//        group by problem_level   问题等级（一般、重要）
        List<Map<String, Object>> deptIdListByType = postAssessmentRatingOtherMapper.getDeptIdListByType(type);
        if (deptIdListByType == null || deptIdListByType.size() == 0) {
            return new ArrayList<>();
        }
        List<String> deptIds = deptIdListByType.stream().map(d -> d.get("deptId").toString()).distinct().collect(Collectors.toList());
        // 查询职能问题数量
        if (!deptId.equals("0")) {
            deptIds.clear();
            deptIds.add(deptId);
        }
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
                .like(PostCheckedProblem::getCheckTime, year)
        );
        List<ProblemLevelView> list = new ArrayList<>();
//        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
        List<PostCheckedProblem> problemLeveOneList = postCheckedProblemList.stream().filter(d -> d.getProblemLevel() != null && d.getProblemLevel().equals(1)).collect(Collectors.toList());
        ProblemLevelView data = new ProblemLevelView();
        data.setProblemLeveOne(problemLeveOneList.size());
        data.setProblemLeveTwo(postCheckedProblemList.size() - problemLeveOneList.size());
        list.add(data);
//        }

        return list;
    }

    @Override
    public List<ProblemAttributeCategoryView> problemAttributeCategoryView(Integer type, String year, Long deptId) {
        //         查询问题表
//        select * from "public"."post_checked_problem";
//        GROUP BY problem_attribute -- 问题属性（1-完整问题；2-有效性问题；3-适宜性问题；）
//        GROUP BY problem_category -- 问题类别（职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他）

        //查部门：职能/生产
        List<SysDept> deptList = new ArrayList<>();
        if (deptId != 0) {
            SysDept sysDept = new SysDept();
            sysDept.setDeptId(deptId);
            deptList.add(sysDept);
        } else {
            SysDept sysDept = new SysDept();
            sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
            sysDept.setType(type);
            deptList = sysDeptService.selectDeptListByCondition(sysDept);
        }
        List<Long> deptIdList = deptList.stream().map(d -> d.getDeptId()).distinct().collect(Collectors.toList());

        //1、查全部问题（职能/生产）
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                        .in(PostCheckedProblem::getCheckedDeptId, deptIdList)//受检部门ID
//                .like(PostCheckedProblem::getCheckTime, year)//检查时间
                        .between(PostCheckedProblem::getCheckTime, DateUtils.parseDate(year + "-01-01"), DateUtils.parseDate(year + "-12-31"))//检查时间
        );
        if (CollectionUtils.isEmpty(postCheckedProblemList)) {
            return new ArrayList<>();
        }

        //全部列别都需要设置默认值，不能空
        //问题类别：1-职责权限问题、2-工作内容问题、3-工作标准问题、4-考核奖励问题、5-任职资格问题、6-其他
        for (int i = 1; i <= 6; i++) {
            PostCheckedProblem data = new PostCheckedProblem();
            data.setProblemCategory(i);

            for (PostCheckedProblem problem : postCheckedProblemList) {
                Integer categoryType = problem.getProblemCategory();
                if (categoryType == i) {
                    data = null;
                    continue;
                }
            }

            if (data != null) {
                postCheckedProblemList.add(data);
            }
        }

        //2、按类别分组
        Map<Integer, List<PostCheckedProblem>> categoryListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getProblemCategory));


        List<ProblemAttributeCategoryView> dataList = new ArrayList<>();
//           问题类别（职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他）
        for (Map.Entry<Integer, List<PostCheckedProblem>> categoryListEntry : categoryListMap.entrySet()) {

            //问题类别：1-职责权限问题、2-工作内容问题、3-工作标准问题、4-考核奖励问题、5-任职资格问题、6-其他
            Integer categoryType = categoryListEntry.getKey();

            //当前“问题类别”中的所有问题，再按问题属性（1-完整问题；2-有效性问题；3-适宜性问题；）统计数量即可
            List<PostCheckedProblem> categoryList = categoryListEntry.getValue();


            ProblemAttributeCategoryView data = new ProblemAttributeCategoryView();
            data.setProblemCategoryType(categoryType);
            data.setProblemTotal(categoryList.size());//后期添加未和前端对接
            if (categoryType == 1) {
                data.setProblemCategoryTypeView("职责权限问题");
                data.setProblemCategoryOne(categoryList.size());//后期添加未和前端对接
            } else if (categoryType == 2) {
                data.setProblemCategoryTypeView("工作内容问题");
                data.setProblemCategoryTwo(categoryList.size());//后期添加未和前端对接
            } else if (categoryType == 3) {
                data.setProblemCategoryTypeView("工作标准问题");
                data.setProblemCategoryThree(categoryList.size());//后期添加未和前端对接
            } else if (categoryType == 4) {
                data.setProblemCategoryTypeView("考核奖励问题");
                data.setProblemCategoryFour(categoryList.size());//后期添加未和前端对接
            } else if (categoryType == 5) {
                data.setProblemCategoryTypeView("任职资格问题");
                data.setProblemCategoryFive(categoryList.size());//后期添加未和前端对接
            } else if (categoryType == 6) {
                data.setProblemCategoryTypeView("其他");
                data.setProblemCategorySix(categoryList.size());//后期添加未和前端对接
            }

            //完整性数量
            int problemComplete = 0;
            //适宜性数量
            int problemSuitable = 0;
            //有效性数量
            int problemEffective = 0;

            for (PostCheckedProblem postCheckedProblem : categoryList) {
                Integer problemAttribute = postCheckedProblem.getProblemAttribute();
                if (problemAttribute != null && problemAttribute == 1) {
                    problemComplete++;
                } else if (problemAttribute != null && problemAttribute == 2) {
                    problemEffective++;
                } else if (problemAttribute != null && problemAttribute == 3) {
                    problemSuitable++;
                }
            }
            data.setProblemComplete(problemComplete);// 完整性数量
            data.setProblemSuitable(problemSuitable);// 适宜性数量
            data.setProblemEffective(problemEffective);// 有效性数量
            dataList.add(data);
        }


//        data.set完成性
//        data.set适宜性
//        data.set有效性
//        data.set职责权限
//        data.set工作内容
//        data.set工作标准
//        data.set考核奖励
//        data.set任职资格
//        data.set其他


        return dataList;
    }

    @Override
    public List<HistoryProblemNumberView> historyProblemNumberView(Integer type, String year, String deptId) {
        //         查询问题表
//        select * from "public"."post_checked_problem";
//        GROUP BY problem_attribute -- 问题属性（1-完整问题；2-有效性问题；3-适宜性问题；）
//        GROUP BY problem_category -- 问题类别（职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他）


        List<Map<String, Object>> deptIdListByType = postAssessmentRatingOtherMapper.getDeptIdListByType(type);
        if (deptIdListByType == null || deptIdListByType.size() == 0) {
            return new ArrayList<>();
        }
        List<String> deptIds = deptIdListByType.stream().map(d -> d.get("deptId").toString()).distinct().collect(Collectors.toList());
        // 查询职能问题数量
        if (!deptId.equals("0")) {
            deptIds.clear();
            deptIds.add(deptId);
        }
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
                .like(PostCheckedProblem::getCheckTime, year)

        );
        List<HistoryProblemNumberView> list = new ArrayList<>();
//        if (postCheckedProblemList != null && postCheckedProblemList.size() > 0) {
        SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, List<PostCheckedProblem>> postCheckedProblemListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(d -> adf.format(d.getCreateTime()), Collectors.toList()));
        HistoryProblemNumberView data = new HistoryProblemNumberView();
        data.setCheckYear(new Date());

        //总数量
        int problemTotal = 0;

        //完整性数量
        int problemComplete = 0;
        //适宜性数量
        int problemSuitable = 0;
        //有效性数量
        int problemEffective = 0;

        //职责权限问题
        int problemCategoryOne = 0;
        //工作内容问题
        int problemCategoryTwo = 0;
        //工作标准问题
        int problemCategoryThree = 0;
        //考核奖励问题
        int problemCategoryFour = 0;
        //任职资格问题
        int problemCategoryFive = 0;
        //其他

        int problemCategorySix = 0;
        for (Map.Entry<String, List<PostCheckedProblem>> stringListEntry : postCheckedProblemListMap.entrySet()) {
            List<PostCheckedProblem> value = stringListEntry.getValue();
            if (value != null && value.size() > 0) {
                for (PostCheckedProblem postCheckedProblem : value) {
                    Integer categoryType = postCheckedProblem.getProblemCategory();

                    problemTotal++;
                    if (postCheckedProblem.getProblemAttribute() == 1) {
                        problemComplete++;
                    }
                    if (postCheckedProblem.getProblemAttribute() == 2) {
                        problemEffective++;
                    }
                    if (postCheckedProblem.getProblemAttribute() == 3) {
                        problemSuitable++;
                    }
                    if (categoryType == null)
                        continue;
                    if (categoryType == 1)
                        problemCategoryOne++;
                    if (categoryType == 2)
                        problemCategoryTwo++;
                    if (categoryType == 3)
                        problemCategoryThree++;
                    if (categoryType == 4)
                        problemCategoryFour++;
                    if (categoryType == 5)
                        problemCategoryFive++;
                    if (categoryType == 6)
                        problemCategorySix++;
                }
            }
        }
        data.setProblemTotal(problemTotal);
        data.setProblemComplete(problemComplete);
        data.setProblemSuitable(problemSuitable);
        data.setProblemEffective(problemEffective);
        data.setProblemCategoryOne(problemCategoryOne);
        data.setProblemCategoryTwo(problemCategoryTwo);
        data.setProblemCategoryThree(problemCategoryThree);
        data.setProblemCategoryFour(problemCategoryFour);
        data.setProblemCategoryFive(problemCategoryFive);
        data.setProblemCategorySix(problemCategorySix);
        list.add(data);
//        }
        return list;
    }

    @Override
    public List<CheckedProblemDeptDetaailView> deptDetaailView(DeptDetaailViewModel type) {
        List<Map<String, Object>> deptIdListByType = postAssessmentRatingOtherMapper.getDeptIdListByType(type.getType());
        if (deptIdListByType == null || deptIdListByType.size() == 0) {
            return new ArrayList<>();
        }
        List<String> deptIds = deptIdListByType.stream().map(d -> d.get("deptId").toString()).distinct().collect(Collectors.toList());
        // 查询职能问题数量
        LambdaQueryWrapper<PostCheckedProblem> postCheckedProblemLambdaQueryWrapper = Wrappers.<PostCheckedProblem>lambdaQuery();
        postCheckedProblemLambdaQueryWrapper.in(PostCheckedProblem::getCheckedDeptId, deptIds);
        if (type.getParams() != null && type.getParams().get("beginTime") != null)
            postCheckedProblemLambdaQueryWrapper.like(PostCheckedProblem::getCreateTime, type.getParams());
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(postCheckedProblemLambdaQueryWrapper);

        List<CheckedProblemDeptDetaailView> list = new ArrayList<>();

        //TODO 第一步：得到各个部门ID、部门名称、问题总数量、重要问题数量、一般问题数量、统计时间
        //TODO 第二步：得到4个职责类别的问题数量及整改完成数量(1-业务职责；2-党建及党风廉政；3-安全环保职责；4-合规保密职；)
        //TODO 第三步：设置部门的整改率：遍历职责类别计算整改率
        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
            Map<Long, List<PostCheckedProblem>> deptMap = postCheckedProblems.stream().collect(Collectors.groupingBy(PostCheckedProblem::getCheckedDeptId));
            for (Map.Entry<Long, List<PostCheckedProblem>> longListEntry : deptMap.entrySet()) {
                Long key = longListEntry.getKey();
                List<PostCheckedProblem> value = longListEntry.getValue();
                CheckedProblemDeptDetaailView data1 = new CheckedProblemDeptDetaailView();
                data1.setDeptId(key); //部门ID
                data1.setDeptName(postAssessmentRatingMapper.getSysDeptName(key));// 部门名称
                if (type.getDeptName() != null && !data1.getDeptName().contains(type.getDeptName())) {
                    continue;
                }
                int problemTotal = 0;
//    @ApiModelProperty("一般")
                Integer problemLeveOne = 0;
//    @ApiModelProperty("重要")
                Integer problemLeveTwo = 0;

                Integer rate = 0;
                for (PostCheckedProblem postCheckedProblem : value) {
                    problemTotal++;
                    if (postCheckedProblem.getProblemLevel().equals("1")) {
                        problemLeveOne++;
                    }
                    if (postCheckedProblem.getProblemLevel().equals("2")) {
                        problemLeveTwo++;
                    }
                    if (postCheckedProblem.getIsRectificationCompleted() != null && postCheckedProblem.getIsRectificationCompleted() == 1) {
                        rate++;
                    }
                }
                if (rate == 0 || problemTotal == 0) {
                    data1.setRate(new BigDecimal("0"));
                } else {
                    data1.setRate(new BigDecimal(rate).divide(new BigDecimal(problemTotal), 4, RoundingMode.HALF_UP));
                }
                data1.setStatisticsTime(new Date());
                data1.setProblemTotal(problemTotal); //问题数量
                data1.setProblemLeveTwo(problemLeveTwo); //重要问题
                data1.setProblemLeveOne(problemLeveOne); //一般问题
                Map<Integer, List<PostCheckedProblem>> dutyMap = value.stream().collect(Collectors.groupingBy(PostCheckedProblem::getDutyType));

                List<CheckedProblemDeptDetaailView.ProblemAttributeInner> innerList = new ArrayList<>();
                for (Map.Entry<Integer, List<PostCheckedProblem>> integerListEntry : dutyMap.entrySet()) {
                    //        @ApiModelProperty("完整性数量")
                    int problemComplete = 0;
//        @ApiModelProperty("适宜性数量")
                    int problemSuitable = 0;
//        @ApiModelProperty("有效性数量")
                    int problemEffective = 0;
                    Integer duty = integerListEntry.getKey();
                    CheckedProblemDeptDetaailView.ProblemAttributeInner child1 = new CheckedProblemDeptDetaailView.ProblemAttributeInner();
                    child1.setDutyType(duty);
                    List<PostCheckedProblem> postCheckedProblemList = integerListEntry.getValue();
//                    @ApiModelProperty("已完成完整性数量")
                    int problemCompleteChecked = 0;
//                    @ApiModelProperty("已完成适宜性数量")
                    int problemSuitableChecked = 0;
//                    @ApiModelProperty("已完成有效性数量")
                    int problemEffectiveChecked = 0;
                    for (PostCheckedProblem postCheckedProblem : postCheckedProblemList) {
                        if (postCheckedProblem.getProblemAttribute() == 1) {
                            problemComplete++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 2) {
                            problemEffective++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 3) {
                            problemSuitable++;
                        }
                        if (postCheckedProblem.getIsRectificationCompleted() != null && postCheckedProblem.getIsRectificationCompleted() == 1) {
                            if (postCheckedProblem.getProblemAttribute() == 1) {
                                problemCompleteChecked++;
                            }
                            if (postCheckedProblem.getProblemAttribute() == 2) {
                                problemEffectiveChecked++;
                            }
                            if (postCheckedProblem.getProblemAttribute() == 3) {
                                problemSuitableChecked++;
                            }
                        }
                    }
                    child1.setProblemComplete(problemComplete);
                    child1.setProblemEffective(problemEffective);
                    child1.setProblemSuitable(problemSuitable);
                    child1.setProblemCompleteChecked(problemCompleteChecked);
                    child1.setProblemEffectiveChecked(problemEffectiveChecked);
                    child1.setProblemSuitableChecked(problemSuitableChecked);
                    innerList.add(child1);
                }
                data1.setChildren(innerList);
                list.add(data1);

            }
        }
        return list;
    }


    /**
     * 统计问题整改率
     *
     * @param type 1-职能；2-生产；
     * @param year 年份，例如：2024
     * @return
     */
    @Override
    public List<FunctionDeptProblemContrastView> deptProblemRectificationRate(Integer type, String year) {
//         查询问题表
//        select * from "public"."post_checked_problem";
//        GROUP BY problem_attribute -- 问题属性（1-完整问题；2-有效性问题；3-适宜性问题；）
//        GROUP BY problem_category -- 问题类别（职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他）

        List<FunctionDeptProblemContrastView> dataListTemp = new ArrayList<>();

        //查询部门
        SysDept sysDept = new SysDept();
        sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        sysDept.setType(type);
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(sysDept);
        List<Long> deptIdList = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());


        //查询问题
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostCheckedProblem checkedProblem = new PostCheckedProblem();
        checkedProblem.setParams(params);
        checkedProblem.setCheckedDeptIdList(deptIdList);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectPostCheckedProblemList(checkedProblem);
        Map<Long, List<PostCheckedProblem>> problemListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getCheckedDeptId));


        //按部门计算整改率
        Double deptProblemRectificationRateTatol = 0.0;
        for (Map.Entry<Long, List<PostCheckedProblem>> problemEntry : problemListMap.entrySet()) {
            Long checkedDeptId = problemEntry.getKey();
            List<PostCheckedProblem> problemList = problemEntry.getValue();
            List<PostCheckedProblem> finishList = problemList.stream().filter(problem -> problem.getStatus() == PostCheckedProblemEnum.FU_CHA_PASS.getValue()).collect(Collectors.toList());
            String checkedDeptName = problemList.get(0).getCheckedDeptName();

            int problemFinishCount = finishList.size();
            int problemTotal = problemList.size();
            Double deptProblemRectificationRate = 0.0;
            try {
                deptProblemRectificationRate = Arith.div(problemFinishCount, problemTotal, 2);
            } catch (Exception e) {
                e.printStackTrace();
            }
            deptProblemRectificationRateTatol += deptProblemRectificationRate;

            FunctionDeptProblemContrastView data = new FunctionDeptProblemContrastView();
            data.setDeptId(checkedDeptId);
            data.setDeptName(checkedDeptName);
            data.setDeptProblemRectificationRate(deptProblemRectificationRate);
            dataListTemp.add(data);
        }

        //补充数据，不存在问题的部门也要一起返回到前端
        List<FunctionDeptProblemContrastView> dataList = new ArrayList<>();

        Map<Long, List<FunctionDeptProblemContrastView>> checkedDeptIdListMap = dataListTemp.stream().collect(Collectors.groupingBy(a -> a.getDeptId()));

        for (SysDept dept : deptList) {
            Long deptId = dept.getDeptId();
            String deptName = dept.getDeptName();

            FunctionDeptProblemContrastView data = null;
            if (checkedDeptIdListMap.containsKey(deptId)) {
                data = checkedDeptIdListMap.get(deptId).get(0);
            } else {
                data = new FunctionDeptProblemContrastView();
                data.setDeptId(deptId);
                data.setDeptName(deptName);
                data.setDeptProblemRectificationRate(0.0);
            }

            dataList.add(data);
        }


        FunctionDeptProblemContrastView data = new FunctionDeptProblemContrastView();
        data.setDeptId(null);
        data.setDeptName("全部");
        data.setDeptProblemRectificationRate(deptProblemRectificationRateTatol);
        dataList.add(0, data);


        return dataList;
    }

    /**
     * 岗检问题职责类别整改占比
     *
     * @param type
     * @param year
     * @param deptId
     * @return
     */
    @Override
    public DutyTypeProblemStatisticsView deptProblemDutyTypeRectificationRate(Integer type, String year, Long deptId) {
        if (deptId == null || deptId == 0)
            deptId = null;

        //查询部门
        SysDept sysDept = new SysDept();
        sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        sysDept.setType(type);
        sysDept.setDeptId(deptId);
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(sysDept);
        List<Long> deptIdList = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());


        //查询问题
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostCheckedProblem checkedProblem = new PostCheckedProblem();
        checkedProblem.setParams(params);
        checkedProblem.setCheckedDeptIdList(deptIdList);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectPostCheckedProblemList(checkedProblem);
        Map<Integer, List<PostCheckedProblem>> problemListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getDutyType));

        //岗检问题整改率
        //业务职责
        Double dutyTypeOneRate = 0.0;
        //党建及党风廉政
        Double dutyTypeTwoRate = 0.0;
        //安全环保职责
        Double dutyTypeThreeRate = 0.0;
        //合规保密职
        Double dutyTypeFourRate = 0.0;
        //任职资格与能力素质要求
        Double dutyTypeFiveRate = 0.0;
        //岗位责任制文件完整性与适宜性
        Double dutyTypeSixRate = 0.0;

        //按职责类别计算整改率
        for (Map.Entry<Integer, List<PostCheckedProblem>> problemEntry : problemListMap.entrySet()) {
            Integer dutyType = problemEntry.getKey();
            List<PostCheckedProblem> problemList = problemEntry.getValue();
            List<PostCheckedProblem> finishList = problemList.stream().filter(problem -> problem.getStatus() == PostCheckedProblemEnum.FU_CHA_PASS.getValue()).collect(Collectors.toList());
            Integer problemTotal = problemList.size();
            if (dutyType == 1) {
                try {
                    dutyTypeOneRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (dutyType == 2) {
                try {
                    dutyTypeTwoRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (dutyType == 3) {
                try {
                    dutyTypeThreeRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (dutyType == 4) {
                try {
                    dutyTypeFourRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (dutyType == 5) {
                try {
                    dutyTypeFiveRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (dutyType == 6) {
                try {
                    dutyTypeSixRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }

       /* List<DutyTypeProblemStatisticsView> list = new ArrayList<>();

        // 业务职责
        Integer dutyTypeOne = 0;
        //党建及党风廉政
        Integer dutyTypeTwo = 0;
        //安全环保职责
        Integer dutyTypeThree = 0;
        //合规保密职
        Integer dutyTypeFour = 0;
        //任职资格与能力素质要求
        Integer dutyTypeFive = 0;
        //岗位责任制文件完整性与适宜性
        Integer dutyTypeSix = 0;

        Integer problemTotal = postCheckedProblemList.size();
        for (PostCheckedProblem postCheckedProblem : postCheckedProblemList) {
            if (postCheckedProblem.getDutyType() == 1)
                dutyTypeOne++;
            if (postCheckedProblem.getDutyType() == 2)
                dutyTypeTwo++;
            if (postCheckedProblem.getDutyType() == 3)
                dutyTypeThree++;
            if (postCheckedProblem.getDutyType() == 4)
                dutyTypeFour++;
            if (postCheckedProblem.getDutyType() == 5)
                dutyTypeFive++;
            if (postCheckedProblem.getDutyType() == 6)
                dutyTypeSix++;
        }


        //岗检问题整改率
        //业务职责
        Double dutyTypeOneRate = 0.0;
        //党建及党风廉政
        Double dutyTypeTwoRate = 0.0;
        //安全环保职责
        Double dutyTypeThreeRate = 0.0;
        //合规保密职
        Double dutyTypeFourRate = 0.0;
        //任职资格与能力素质要求
        Double dutyTypeFiveRate = 0.0;
        //岗位责任制文件完整性与适宜性
        Double dutyTypeSixRate = 0.0;

        try {
            dutyTypeOneRate = Arith.div(dutyTypeOne, problemTotal, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            dutyTypeTwoRate = Arith.div(dutyTypeTwo, problemTotal, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            dutyTypeThreeRate = Arith.div(dutyTypeThree, problemTotal, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            dutyTypeFourRate = Arith.div(dutyTypeFour, problemTotal, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            dutyTypeFiveRate = Arith.div(dutyTypeFive, problemTotal, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            dutyTypeSixRate = Arith.div(dutyTypeSix, problemTotal, 2);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        DutyTypeProblemStatisticsView data = new DutyTypeProblemStatisticsView();
        data.setDutyTypeOneRate(dutyTypeOneRate);
        data.setDutyTypeTwoRate(dutyTypeTwoRate);
        data.setDutyTypeThreeRate(dutyTypeThreeRate);
        data.setDutyTypeFourRate(dutyTypeFourRate);
        data.setDutyTypeFiveRate(dutyTypeFiveRate);
        data.setDutyTypeSixRate(dutyTypeSixRate);
//        list.add(data);
        return data;
    }

    /**
     * 岗检问题级别整改占比
     *
     * @param type
     * @param year
     * @param deptId
     * @return
     */
    @Override
    public ProblemLevelView deptProblemLevelRectificationRate(Integer type, String year, Long deptId) {


        if (deptId == null || deptId == 0)
            deptId = null;

        //查询部门
        SysDept sysDept = new SysDept();
        sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        sysDept.setType(type);
        sysDept.setDeptId(deptId);
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(sysDept);
        List<Long> deptIdList = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());


        //查询问题
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostCheckedProblem checkedProblem = new PostCheckedProblem();
        checkedProblem.setParams(params);
        checkedProblem.setCheckedDeptIdList(deptIdList);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectPostCheckedProblemList(checkedProblem);

        Map<Integer, List<PostCheckedProblem>> problemListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getProblemLevel));


        //一般问题整改率")
        double problemLeveOneRate = 0.0;
        //重要问题整改率")
        double problemLeveTwoRate = 0.0;

        //按职责类别计算整改率
        for (Map.Entry<Integer, List<PostCheckedProblem>> problemEntry : problemListMap.entrySet()) {
            //问题等级：1一般、2 重要
            Integer problemLevel = problemEntry.getKey();
            List<PostCheckedProblem> problemList = problemEntry.getValue();
            List<PostCheckedProblem> finishList = problemList.stream().filter(problem -> problem.getStatus() == PostCheckedProblemEnum.FU_CHA_PASS.getValue()).collect(Collectors.toList());
            Integer problemTotal = problemList.size();
            if (problemLevel == 1) {
                try {
                    problemLeveOneRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemLevel == 2) {
                try {
                    problemLeveTwoRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            }
        }

        ProblemLevelView data = new ProblemLevelView();
        data.setProblemLeveOneRate(problemLeveOneRate);
        data.setProblemLeveTwoRate(problemLeveTwoRate);
        return data;
    }


    /**
     * 岗检问题属性整改占比
     *
     * @param type
     * @param year
     * @param deptId
     * @return
     */
    @Override
    public ProblemAttributeCategoryView problemAttributeRate(Integer type, String year, Long deptId) {
        if (deptId == null || deptId == 0)
            deptId = null;

        //查询部门
        SysDept sysDept = new SysDept();
        sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        sysDept.setType(type);
        sysDept.setDeptId(deptId);
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(sysDept);
        List<Long> deptIdList = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());


        //查询问题
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostCheckedProblem checkedProblem = new PostCheckedProblem();
        checkedProblem.setParams(params);
        checkedProblem.setCheckedDeptIdList(deptIdList);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectPostCheckedProblemList(checkedProblem);

        // 1-完整问题
        // 2-有效性问题
        // 3-适宜性问题
        Map<Integer, List<PostCheckedProblem>> problemListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getProblemAttribute));


        //完整性数量
        double problemCompleteRate = 0.0;
        //适宜性数量
        double problemSuitableRate = 0.0;
        //有效性数量
        double problemEffectiveRate = 0.0;


        //按职责类别计算整改率
        for (Map.Entry<Integer, List<PostCheckedProblem>> problemEntry : problemListMap.entrySet()) {
            //问题等级：1一般、2 重要
            Integer problemAttribute = problemEntry.getKey();
            List<PostCheckedProblem> problemList = problemEntry.getValue();
            List<PostCheckedProblem> finishList = problemList.stream().filter(problem -> problem.getStatus() == PostCheckedProblemEnum.FU_CHA_PASS.getValue()).collect(Collectors.toList());
            Integer problemTotal = problemList.size();
            if (problemAttribute == 1) {
                try {
                    problemCompleteRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemAttribute == 2) {
                try {
                    problemSuitableRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemAttribute == 3) {
                try {
                    problemEffectiveRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            }
        }

        ProblemAttributeCategoryView data = new ProblemAttributeCategoryView();
        data.setProblemCompleteRate(problemCompleteRate);
        data.setProblemSuitableRate(problemSuitableRate);
        data.setProblemEffectiveRate(problemEffectiveRate);
        return data;
    }

    /**
     * 岗检问题类别整改占比
     *
     * @param type
     * @param year
     * @param deptId
     * @return
     */
    @Override
    public ProblemAttributeCategoryView problemCategoryRate(Integer type, String year, Long deptId) {
        if (deptId == null || deptId == 0)
            deptId = null;

        //查询部门
        SysDept sysDept = new SysDept();
        sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        sysDept.setType(type);
        sysDept.setDeptId(deptId);
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(sysDept);
        List<Long> deptIdList = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());


        //查询问题
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostCheckedProblem checkedProblem = new PostCheckedProblem();
        checkedProblem.setParams(params);
        checkedProblem.setCheckedDeptIdList(deptIdList);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectPostCheckedProblemList(checkedProblem);

        // 职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他
        Map<Integer, List<PostCheckedProblem>> problemListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getProblemCategory));

        //职责权限问题
        double problemCategoryOneRate = 0.0;
        //工作内容问题
        double problemCategoryTwoRate = 0.0;
        //工作标准问题
        double problemCategoryThreeRate = 0.0;
        //考核奖励问题
        double problemCategoryFourRate = 0.0;
        //任职资格问题
        double problemCategoryFiveRate = 0.0;
        //其他
        double problemCategorySixRate = 0.0;


        //按职责类别计算整改率
        for (Map.Entry<Integer, List<PostCheckedProblem>> problemEntry : problemListMap.entrySet()) {
            //问题等级：1一般、2 重要
            Integer problemCategory = problemEntry.getKey();
            List<PostCheckedProblem> problemList = problemEntry.getValue();
            List<PostCheckedProblem> finishList = problemList.stream().filter(problem -> problem.getStatus() == PostCheckedProblemEnum.FU_CHA_PASS.getValue()).collect(Collectors.toList());
            Integer problemTotal = problemList.size();
            if (problemCategory == 1) {
                try {
                    problemCategoryOneRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemCategory == 2) {
                try {
                    problemCategoryTwoRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemCategory == 3) {
                try {
                    problemCategoryThreeRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemCategory == 4) {
                try {
                    problemCategoryFourRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemCategory == 5) {
                try {
                    problemCategoryFiveRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            } else if (problemCategory == 6) {
                try {
                    problemCategorySixRate = Arith.div(finishList.size(), problemTotal, 2);
                } catch (Exception e) {

                }
            }
        }

        ProblemAttributeCategoryView data = new ProblemAttributeCategoryView();
        data.setProblemCategoryOneRate(problemCategoryOneRate);
        data.setProblemCategoryTwoRate(problemCategoryTwoRate);
        data.setProblemCategoryThreeRate(problemCategoryThreeRate);
        data.setProblemCategoryFourRate(problemCategoryFourRate);
        data.setProblemCategoryFiveRate(problemCategoryFiveRate);
        data.setProblemCategorySixRate(problemCategorySixRate);
        return data;
    }

    /**
     * 各部门整改率对比排名
     *
     * @param type
     * @param year
     * @return
     */
    @Override
    public List<CheckedProblemDeptRateView> deptRate(Integer type, String year) {
//         查询问题表
//        select * from "public"."post_checked_problem";
//        GROUP BY problem_attribute -- 问题属性（1-完整问题；2-有效性问题；3-适宜性问题；）
//        GROUP BY problem_category -- 问题类别（职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他）

        List<CheckedProblemDeptRateView> dataListTemp = new ArrayList<>();

        //查询部门
        SysDept sysDept = new SysDept();
        sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        sysDept.setType(type);
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(sysDept);
        List<Long> deptIdList = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());


        //查询问题
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostCheckedProblem checkedProblem = new PostCheckedProblem();
        checkedProblem.setParams(params);
        checkedProblem.setCheckedDeptIdList(deptIdList);
        List<PostCheckedProblem> postCheckedProblemList = postCheckedProblemMapper.selectPostCheckedProblemList(checkedProblem);
        Map<Long, List<PostCheckedProblem>> problemListMap = postCheckedProblemList.stream().collect(Collectors.groupingBy(PostCheckedProblem::getCheckedDeptId));


        //按部门计算整改率
        for (Map.Entry<Long, List<PostCheckedProblem>> problemEntry : problemListMap.entrySet()) {
            Long checkedDeptId = problemEntry.getKey();
            List<PostCheckedProblem> problemList = problemEntry.getValue();
            List<PostCheckedProblem> finishList = problemList.stream().filter(problem -> problem.getStatus() == PostCheckedProblemEnum.FU_CHA_PASS.getValue()).collect(Collectors.toList());
            String checkedDeptName = problemList.get(0).getCheckedDeptName();

            int problemFinishCount = finishList.size();
            int problemTotal = problemList.size();
            Double deptProblemRectificationRate = 0.0;
            try {
                deptProblemRectificationRate = Arith.div(problemFinishCount, problemTotal, 2);
            } catch (Exception e) {
                e.printStackTrace();
            }

            CheckedProblemDeptRateView data = new CheckedProblemDeptRateView();
            data.setDeptId(checkedDeptId);
            data.setDeptName(checkedDeptName);
            data.setProblemCount(problemTotal);
            data.setProblemFinishCount(problemFinishCount);
            data.setProblemRate(deptProblemRectificationRate);
            dataListTemp.add(data);
        }

        //按部门整改率倒叙
        dataListTemp = dataListTemp.stream().sorted(Comparator.comparingDouble(CheckedProblemDeptRateView::getProblemRate).reversed()).collect(Collectors.toList());

        //设置排名
        List<CheckedProblemDeptRateView> dataList = new ArrayList<>();
        Integer rating = 0;
        Double lastRate = 0.0;
        for (int i = 0; i < dataListTemp.size(); i++) {
            CheckedProblemDeptRateView postAssessmentRating = dataListTemp.get(i);

            Double problemRate = postAssessmentRating.getProblemRate();//整改率


            //分数相等排名不增加
            if (problemRate.compareTo(lastRate) == 0) {
                if (rating == 0) {
                    rating++;
                }
                postAssessmentRating.setRating(rating);
            }
            //增加排名
            else {
                rating++;
                postAssessmentRating.setRating(rating);
            }
            lastRate = problemRate;


            dataList.add(postAssessmentRating);
        }


        //补充数据，不存在问题的部门也要一起返回到前端
        Map<Long, List<CheckedProblemDeptRateView>> checkedDeptIdListMap = dataList.stream().collect(Collectors.groupingBy(a -> a.getDeptId()));
        for (SysDept dept : deptList) {
            Long deptId = dept.getDeptId();
            String deptName = dept.getDeptName();
            if (!checkedDeptIdListMap.containsKey(deptId)) {
                CheckedProblemDeptRateView data = new CheckedProblemDeptRateView();
                data.setDeptId(deptId);
                data.setDeptName(deptName);
                data.setProblemCount(0);
                dataList.add(data);
            }
        }


        return dataList;
    }

    /**
     * 近三年岗检问题整改率对比
     *
     * @param type
     * @param year
     * @return
     */
    @Override
    public List<CheckedProblemYearsRatelView> lastThreeYearsRatelView(Integer type, String year) {

        List<CheckedProblemYearsRatelView> dataList = new ArrayList<>();

        //查询部门
        SysDept sysDept = new SysDept();
        sysDept.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());
        sysDept.setType(type);
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(sysDept);
        List<Long> deptIdList = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());


        int yearInt = Integer.parseInt(year);
        for (int i = 2; i >= 0; i--) {
            //查询问题
            Map<String, Object> params = new HashMap<>();
            params.put("beginTime", (yearInt - i) + "-01-01");
            params.put("endTime", (yearInt - i) + "-12-31");
            PostCheckedProblem checkedProblem = new PostCheckedProblem();
            checkedProblem.setParams(params);
            checkedProblem.setCheckedDeptIdList(deptIdList);
            List<PostCheckedProblem> problemOneList = postCheckedProblemMapper.selectPostCheckedProblemList(checkedProblem);//总问题数量
            List<PostCheckedProblem> finishOneList = problemOneList.stream().filter(problem -> problem.getStatus() == PostCheckedProblemEnum.FU_CHA_PASS.getValue()).collect(Collectors.toList());//已整改的问题数量
            //整改率
            Double finishOneRate = 0.0;
            try {
                finishOneRate = Arith.div(finishOneList.size(), problemOneList.size(), 2);
            } catch (Exception e) {
            }

            CheckedProblemYearsRatelView data = new CheckedProblemYearsRatelView();
            data.setYearView((yearInt - i) + "年");
            data.setProblemRate(finishOneRate);
            dataList.add(data);
        }

        return dataList;

    }
}

