package com.ruoyi.postCheck.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.PostCheckedProblemEnum;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.postCheck.domain.PostAssessmentRating;
import com.ruoyi.postCheck.domain.PostAssessmentRules;
import com.ruoyi.postCheck.domain.PostList;
import com.ruoyi.postCheck.domain.PostPlan;
import com.ruoyi.postCheck.domain.PostPlanInfo;
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.CheckedProblemDeptDetaailView;
import com.ruoyi.postCheck.domain.problemStatistics.CoverageRateView;
import com.ruoyi.postCheck.domain.problemStatistics.DutyTypeProblemStatisticsView;
import com.ruoyi.postCheck.domain.problemStatistics.FunctionDeptProblemContrastView;
import com.ruoyi.postCheck.domain.problemStatistics.HistoryProblemNumberView;
import com.ruoyi.postCheck.domain.problemStatistics.ProblemAttributeCategoryView;
import com.ruoyi.postCheck.domain.problemStatistics.ProblemLevelView;
import com.ruoyi.postCheck.domain.tools.ProblemCategory;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingMapper;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingOtherMapper;
import com.ruoyi.postCheck.mapper.PostAssessmentRulesMapper;
import com.ruoyi.postCheck.mapper.PostListMapper;
import com.ruoyi.postCheck.mapper.PostPlanInfoMapper;
import com.ruoyi.postCheck.mapper.PostPlanMapper;
import com.ruoyi.postCheck.service.IPostPlanJoinProblemService;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.UserPostAuthority;
import com.ruoyi.system.service.ISysPostService;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.postCheck.mapper.PostCheckedProblemMapper;
import com.ruoyi.postCheck.domain.PostCheckedProblem;
import com.ruoyi.postCheck.service.IPostCheckedProblemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.FacesWebRequest;


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

    /**
     * 查询岗检问题表
     *
     * @param id 岗检问题表主键
     * @return 岗检问题表
     */
    @Override
    public PostCheckedProblem selectPostCheckedProblemById(Long id) {
        return postCheckedProblemMapper.selectPostCheckedProblemById(id);
    }

    /**
     * 查询岗检问题表列表
     *
     * @param postCheckedProblem 岗检问题表
     * @return 岗检问题表
     */
    @Override
    public List<PostCheckedProblem> selectPostCheckedProblemList(PostCheckedProblem postCheckedProblem) {
        return postCheckedProblemMapper.selectPostCheckedProblemList(postCheckedProblem);
    }

    /**
     * 新增岗检问题表
     *
     * @param postCheckedProblemList 前端提交的岗检问题集合，一次提交多个问题
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPostCheckedProblem(List<PostCheckedProblem> postCheckedProblemList) {
        if (CollectionUtils.isEmpty(postCheckedProblemList)) {
            return 0;
        }

        PostCheckedProblem data = postCheckedProblemList.get(0);
        Long planInfoId = data.getPlanInfoId();
        PostPlanJoinProblem param = new PostPlanJoinProblem();
        param.setPlanInfoId(planInfoId);
        List<PostPlanJoinProblem> list = postPlanJoinProblemService.selectPostPlanJoinProblemList(param);
        if (CollectionUtils.isEmpty(list)) {
            return 0;
        }
        PostPlanJoinProblem postPlanJoinProblem = list.get(0);
        Long checkGroupId = postPlanJoinProblem.getCheckGroupId();
        Long checkTeamId = postPlanJoinProblem.getCheckTeamId();
        Long checkedDeptId = postPlanJoinProblem.getCheckedDeptId();
        Date checkTime = postPlanJoinProblem.getCheckTime();

        int count = 0;
        for (PostCheckedProblem postCheckedProblem : postCheckedProblemList) {
            count++;
            postCheckedProblem.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
            postCheckedProblem.setCreateDefault();

            postCheckedProblem.setProblemNo("GJ-" + DateUtils.getTime());
            postCheckedProblem.setCheckWorkgroupId(checkGroupId);
            postCheckedProblem.setCheckGroupId(checkTeamId);
            postCheckedProblem.setCheckedDeptId(checkedDeptId);
            //检查时间取值=岗检计划的开始时间
            postCheckedProblem.setCheckTime(checkTime);
            postCheckedProblem.setStatus(PostCheckedProblemEnum.ADD.getValue());

            int insertCount = postCheckedProblemMapper.insertPostCheckedProblem(postCheckedProblem);
            if (insertCount == 0) {
                throw new BaseException("第" + count + "行更新失败请检查！");
            }
        }
        return 1;
    }

    /**
     * 修改岗检问题表
     *
     * @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++;
            //只允许新增状态单据修改
            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("当前状态无法修改，请检查！");
            }

            // postCheckedProblem.setUpdateTime(DateUtils.getNowDate());

            postCheckedProblem.setUpdateDefault();
            postCheckedProblem.setStatus(PostCheckedProblemEnum.ADD.getValue());
            int updateCount = postCheckedProblemMapper.updatePostCheckedProblem(postCheckedProblem);
            if (updateCount == 0) {
                throw new BaseException("第" + count + "行更新失败请检查！");
            }
        }
        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();


        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 status = dataDB.getStatus();
            if (status != null && status != PostCheckedProblemEnum.ADD.getValue()) {
                errorMsg += "【第" + index + "行】当前状态无法指定整改责任人，请检查！";
                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);
        }
        if (StringUtils.isNotBlank(errorMsg)) {
            throw new BaseException(errorMsg);
        }


        PostCheckedProblem updateData = new PostCheckedProblem();
        updateData.setStatus(PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue());//待填写方案
        updateData.setRectificationResponsibleUserId(rectificationResponsibleUserId);//整改责任人
        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, Long rectificationResponsibleUserId, Date rectificationPeriod) {
    public int updateRectificationMeasure(Long id, String problemCause, Integer isImmediatelyCorrected, String rectificationMeasure, Date rectificationPeriod) {

//        if (id == null || StringUtils.isBlank(problemCause) || isImmediatelyCorrected == null || StringUtils.isBlank(rectificationMeasure) || rectificationResponsibleUserId == null || rectificationPeriod == null) {
        if (id == null || StringUtils.isBlank(problemCause) || isImmediatelyCorrected == null || StringUtils.isBlank(rectificationMeasure) || rectificationPeriod == 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 status = dataDB.getStatus();
        if (status != PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + status + "】");
        }

        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),

        return postCheckedProblemMapper.updatePostCheckedProblem(data);
    }

    /**
     * 指定专业部门的审核人：整改责任人填写
     *
     * @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 status = dataDB.getStatus();
        if (status != PostCheckedProblemEnum.ADD.getValue()
                && status != PostCheckedProblemEnum.EDIT_WAIT_ONR.getValue()
                && status != PostCheckedProblemEnum.DEPT_WAIT.getValue()
        ) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + status + "】");
        }
        Long rectificationResponsibleUserId = dataDB.getRectificationResponsibleUserId();
        if (!rectificationResponsibleUserId.equals(userId)) {
            throw new BaseException("请切换整改责任人账号操作！");
        }


        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setSpecialityDepartmentReviewerId(specialityDepartmentReviewerId);
//        data.setStatus(PostCheckedProblemEnum);
        return postCheckedProblemMapper.updatePostCheckedProblem(data);
    }


    /**
     * 审核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) {
//            return 0;
            throw new BaseException("参数不全，请检查！");
        }

        //状态错误
        if (status != PostCheckedProblemEnum.DEPT_PASS.getValue() && status != PostCheckedProblemEnum.DEPT_BACK.getValue()) {
//            return 0;
            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()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + 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());
        //通过
        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());
        }


        return postCheckedProblemMapper.updatePostCheckedProblem(data);
    }

    /**
     * 审核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) {
//            return 0;
            throw new BaseException("参数不全，请检查！");
        }

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


        //驳回时必须填写原因
        if (status == PostCheckedProblemEnum.ZHUAN_ZY_BACK.getValue() && StringUtils.isBlank(reason)) {
//            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.ZHUAN_ZY_WAIT.getValue()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + 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());
        }

        return postCheckedProblemMapper.updatePostCheckedProblem(data);
    }

    /**
     * 实施整改：上传实施照片
     *
     * @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 status = dataDb.getStatus();
        if (status != PostCheckedProblemEnum.EDIT_WAIT_TWO.getValue()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + status + "】");
        }

        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);
        data.setStatus(PostCheckedProblemEnum.EDIT_TWO_OVER.getValue());

        return postCheckedProblemMapper.updatePostCheckedProblem(data);
    }

    /**
     * 指定复查人
     *
     * @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 status = dataDb.getStatus();
        if (status != PostCheckedProblemEnum.EDIT_WAIT_TWO.getValue()
                && status != PostCheckedProblemEnum.EDIT_TWO_OVER.getValue()
        ) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + status + "】");
        }
        Long rectificationResponsibleUserId = dataDb.getRectificationResponsibleUserId();
        if (!rectificationResponsibleUserId.equals(userId)) {
            throw new BaseException("请切换整改责任人账号操作！");
        }

        PostCheckedProblem data = new PostCheckedProblem();
        data.setId(id);
        data.setReviewDepartmentReviewerId(reviewDepartmentReviewerId);
        data.setStatus(PostCheckedProblemEnum.FU_CHA_WAIT.getValue());
        return postCheckedProblemMapper.updatePostCheckedProblem(data);
    }

    /**
     * 审核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) {
//            return 0;
            throw new BaseException("参数不全，请检查！");
        }

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


        //驳回时必须填写原因
        if (status == PostCheckedProblemEnum.FU_CHA_BACK.getValue() && StringUtils.isBlank(reason)) {
//            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.FU_CHA_WAIT.getValue()) {
            throw new BaseException("当前状态不允许此操作，请检查！【" + status + "】");
        }

        //复查部门的审核人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);
        return postCheckedProblemMapper.updatePostCheckedProblem(data);
    }

    /**
     * 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() {
        PostTotalView postTotalView = new PostTotalView();
        // 1
        List<PostList> postLists = postListMapper.selectList(Wrappers.lambdaQuery());
        postTotalView.setListCount(postLists.size());
        // 2
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.lambdaQuery());
        postTotalView.setProblemCount(postCheckedProblems.size());
        // 3
        Integer checkedPostCount = postCheckedProblemMapper.selectCheckedPostCount(1);
        postTotalView.setCheckedPostCount(checkedPostCount);
        Integer uncheckedPostCount = postCheckedProblemMapper.selectCheckedPostCount(2);
        postTotalView.setUncheckedPostCount(uncheckedPostCount);
        return postTotalView;
    }

    @Override
    public PostCheckedProblemView checkedProblem() {
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.lambdaQuery());
        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() == 3)
                    problemEffective++;
                if (postCheckedProblem.getProblemAttribute() != null && postCheckedProblem.getProblemAttribute() == 2)
                    problemSuitable++;
            }
        PostCheckedProblemView post = new PostCheckedProblemView();
        post.setProblemTotal(postCheckedProblems.size());
        post.setProblemComplete(problemComplete);
        post.setProblemSuitable(problemSuitable);
        post.setProblemEffective(problemEffective);
        return post;
    }

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

    @Override
    public Map<Integer, BigDecimal> problemRectification() {
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.lambdaQuery());
        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) {
                if (postCheckedProblem.getProblemAttribute() != null && postCheckedProblem.getProblemAttribute() == 1) {
                    problemComplete++;
                    if (postCheckedProblem.getIsImmediatelyCorrected() != null && postCheckedProblem.getIsImmediatelyCorrected() == 1) {
                        overproblemComplete++;
                    }
                }
                if (postCheckedProblem.getProblemAttribute() != null && postCheckedProblem.getProblemAttribute() == 3) {
                    problemEffective++;
                    if (postCheckedProblem.getIsImmediatelyCorrected() != null && postCheckedProblem.getIsImmediatelyCorrected() == 1) {
                        overproblemEffective++;
                    }
                }
                if (postCheckedProblem.getProblemAttribute() != null && postCheckedProblem.getProblemAttribute() == 2) {
                    problemSuitable++;
                    if (postCheckedProblem.getIsImmediatelyCorrected() != null && postCheckedProblem.getIsImmediatelyCorrected() == 1) {
                        overproblemSuitable++;
                    }
                }
                total++;
                if (postCheckedProblem.getIsImmediatelyCorrected() != null && postCheckedProblem.getIsImmediatelyCorrected() == 1) {
                    overtotal++;
                }
            }
        Map<Integer, BigDecimal> map = new HashMap<>();
        map.put(1, new BigDecimal(overproblemComplete).divide(new BigDecimal(problemComplete), 4, RoundingMode.HALF_UP));
        map.put(2, new BigDecimal(overproblemSuitable).divide(new BigDecimal(problemSuitable), 4, RoundingMode.HALF_UP));
        map.put(3, new BigDecimal(overproblemEffective).divide(new BigDecimal(problemEffective), 4, RoundingMode.HALF_UP));
        map.put(4, new BigDecimal(overtotal).divide(new BigDecimal(total), 4, RoundingMode.HALF_UP));
        return map;

    }

    @Override
    public List<DeptProblemRectificationView> deptProblemRectification() {
        List<DeptProblemRectificationView> dataList = new ArrayList<>();
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.lambdaQuery());
        if (!postCheckedProblems.isEmpty()) {
            Map<Long, List<PostCheckedProblem>> postMapListMap = postCheckedProblems.stream().collect(Collectors.groupingBy(PostCheckedProblem::getCheckedDeptId));
            for (Map.Entry<Long, List<PostCheckedProblem>> entry : postMapListMap.entrySet()) {
                DeptProblemRectificationView data1 = new DeptProblemRectificationView();
                data1.setDeptId(entry.getKey());
                data1.setDeptName(postAssessmentRatingMapper.getSysDeptName(entry.getKey()));
                Integer problemTotal = 0;
                Integer problemComplete = 0;
                for (PostCheckedProblem postCheckedProblem : entry.getValue()) {
                    problemTotal++;
                    if (postCheckedProblem.getIsRectificationCompleted() != null && postCheckedProblem.getIsRectificationCompleted() == 1) {
                        problemComplete++;
                    }
                }
                data1.setProblemTotal(problemTotal);
                data1.setProblemComplete(problemComplete);
                data1.setProblemRectificationRate(new BigDecimal(problemComplete).divide(new BigDecimal(problemTotal), 4, RoundingMode.HALF_UP));
                dataList.add(data1);
            }
        }
        return dataList;
    }

    @Override
    public List<PostCheckedUnCheckedView> postChecked(Integer i) {
        return postListMapper.postChecked(i);
    }

    @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) {
//         查询问题表
//        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())
        );
//        @ApiModelProperty("总数量")
        int problemTotal = 0;
//        @ApiModelProperty("完整性数量")
        int problemComplete = 0;
//        @ApiModelProperty("适宜性数量")
        int problemSuitable = 0;
//        @ApiModelProperty("有效性数量")
        int problemEffective = 0;
//        @ApiModelProperty("职责权限问题")
        int problemCategoryOne = 0;
//        @ApiModelProperty("工作内容问题")
        int problemCategoryTwo = 0;
//        @ApiModelProperty("工作标准问题")
        int problemCategoryThree = 0;
//        @ApiModelProperty("考核奖励问题")
        int problemCategoryFour = 0;
//        @ApiModelProperty("任职资格问题")
        int problemCategoryFive = 0;
//        @ApiModelProperty("其他")
        int problemCategorySix = 0;
        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
            for (PostCheckedProblem postCheckedProblem : postCheckedProblems) {
                problemTotal++;
                if (postCheckedProblem.getProblemAttribute() == 1) {
                    problemComplete++;
                }
                if (postCheckedProblem.getProblemAttribute() == 2) {
                    problemEffective++;
                }
                if (postCheckedProblem.getProblemAttribute() == 3) {
                    problemSuitable++;
                }
                if (postCheckedProblem.getProblemCategory() == null)
                    continue;
                if (postCheckedProblem.getProblemCategory().equals("1"))
                    problemCategoryOne++;
                if (postCheckedProblem.getProblemCategory().equals("2"))
                    problemCategoryTwo++;
                if (postCheckedProblem.getProblemCategory().equals("3"))
                    problemCategoryThree++;
                if (postCheckedProblem.getProblemCategory().equals("4"))
                    problemCategoryFour++;
                if (postCheckedProblem.getProblemCategory().equals("5"))
                    problemCategoryFive++;
                if (postCheckedProblem.getProblemCategory().equals("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);
    }

    @Override
    public List<CoverageRateView> coverageRateView(Integer type) {
        //         查询问题表
//        select * from "public"."post_checked_problem";
//        status = 40    状态：1-待指定整改人（问题录入完成时）；2-待填写方案（部门管理员指定整改人后）；3-方案填写完成；10-部门审核通过；11-部门审核驳回；20-专业部门人审核（非必填）通过；21-专业部门人审核驳回（非必填）；30-整改人待上传实施（整改人上传实施图片）；31-上传实施照片完成；40-复查部门人审核通过；41-复查部门人审核驳回
//        is_rectification_completed = 1 整改情况-是否完成(1-Yes；2-No；)
        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());
        // 查询职能问题数量
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
        );
        List<CoverageRateView> list = new ArrayList<>();
        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
            CoverageRateView data = new CoverageRateView();
            data.setProblemTotal(postCheckedProblems.size());
            List<PostCheckedProblem> collect = postCheckedProblems.stream().filter(d -> d.getIsRectificationCompleted() != null && d.getIsRectificationCompleted().equals(1)).collect(Collectors.toList());
            data.setProblemComplete(collect.size());
            list.add(data);
        }
        return list;
    }

    @Override
    public List<DutyTypeProblemStatisticsView> dutyTypeProblemStatisticsView(Integer type) {
        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());
        // 查询职能问题数量
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
        );
        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) {
        //         查询问题表
//        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());
        // 查询职能问题数量
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
        );
        List<ProblemLevelView> list = new ArrayList<>();
        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
            List<PostCheckedProblem> collect = postCheckedProblems.stream().filter(d -> d.getProblemLevel() != null && d.getProblemLevel().equals("2")).collect(Collectors.toList());
            ProblemLevelView data = new ProblemLevelView();
            data.setProblemLeveOne(collect.size());
            data.setProblemLeveTwo(postCheckedProblems.size() - collect.size());
            list.add(data);
        }

        return list;
    }

    @Override
    public List<ProblemAttributeCategoryView> problemAttributeCategoryView(Integer type) {
        //         查询问题表
//        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());
        // 查询职能问题数量
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
        );
        List<ProblemAttributeCategoryView> list = new ArrayList<>();
        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
            Map<String, List<PostCheckedProblem>> collect = postCheckedProblems.stream().collect(Collectors.groupingBy(PostCheckedProblem::getProblemCategory));
//           问题类别（职责权限问题、工作内容问题、工作标准问题、考核奖励问题、任职资格问题、其他）
            for (Map.Entry<String, List<PostCheckedProblem>> stringListEntry : collect.entrySet()) {
                List<PostCheckedProblem> value = stringListEntry.getValue();
                if (value != null && value.size() > 0) {

                    ProblemAttributeCategoryView data = new ProblemAttributeCategoryView();
                    if (stringListEntry.getKey().equals("1")) {
                        data.setProblemCategoryType(1);
                        data.setProblemCategoryTypeView("职责权限问题");
                    }
                    if (stringListEntry.getKey().equals("2")) {
                        data.setProblemCategoryType(2);
                        data.setProblemCategoryTypeView("工作内容问题");
                    }
                    if (stringListEntry.getKey().equals("3")) {
                        data.setProblemCategoryType(3);
                        data.setProblemCategoryTypeView("工作标准问题");
                    }
                    if (stringListEntry.getKey().equals("4")) {
                        data.setProblemCategoryType(4);
                        data.setProblemCategoryTypeView("考核奖励问题");
                    }
                    if (stringListEntry.getKey().equals("5")) {
                        data.setProblemCategoryType(5);
                        data.setProblemCategoryTypeView("任职资格问题");
                    }
                    if (stringListEntry.getKey().equals("6")) {
                        data.setProblemCategoryType(6);
                        data.setProblemCategoryTypeView("其他");
                    }
//        @ApiModelProperty("完整性数量")
                    int problemComplete = 0;
//        @ApiModelProperty("适宜性数量")
                    int problemSuitable = 0;
//        @ApiModelProperty("有效性数量")
                    int problemEffective = 0;

                    for (PostCheckedProblem postCheckedProblem : value) {
                        if (postCheckedProblem.getProblemAttribute() == 1) {
                            problemComplete++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 2) {
                            problemEffective++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 3) {
                            problemSuitable++;
                        }
                    }
                    data.setProblemComplete(problemComplete);// 完整性数量
                    data.setProblemSuitable(problemSuitable);// 适宜性数量
                    data.setProblemEffective(problemEffective);// 有效性数量
                    list.add(data);
                }
            }
        }


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


        return list;
    }

    @Override
    public List<HistoryProblemNumberView> historyProblemNumberView(Integer type) {
        //         查询问题表
//        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());
        // 查询职能问题数量
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
        );
        List<HistoryProblemNumberView> list = new ArrayList<>();
        if (postCheckedProblems != null && postCheckedProblems.size() > 0) {
            SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd");
            Map<String, List<PostCheckedProblem>> collect = postCheckedProblems.stream().collect(Collectors.groupingBy(d -> adf.format(d.getCreateTime()), Collectors.toList()));
            HistoryProblemNumberView data = new HistoryProblemNumberView();
            data.setCheckYear(new Date());
            //        @ApiModelProperty("总数量")
            int problemTotal = 0;
//        @ApiModelProperty("完整性数量")
            int problemComplete = 0;
//        @ApiModelProperty("适宜性数量")
            int problemSuitable = 0;
//        @ApiModelProperty("有效性数量")
            int problemEffective = 0;
//        @ApiModelProperty("职责权限问题")
            int problemCategoryOne = 0;
//        @ApiModelProperty("工作内容问题")
            int problemCategoryTwo = 0;
//        @ApiModelProperty("工作标准问题")
            int problemCategoryThree = 0;
//        @ApiModelProperty("考核奖励问题")
            int problemCategoryFour = 0;
//        @ApiModelProperty("任职资格问题")
            int problemCategoryFive = 0;
//        @ApiModelProperty("其他")
            int problemCategorySix = 0;
            for (Map.Entry<String, List<PostCheckedProblem>> stringListEntry : collect.entrySet()) {
                List<PostCheckedProblem> value = stringListEntry.getValue();
                if (value != null && value.size() > 0) {
                    for (PostCheckedProblem postCheckedProblem : value) {
                        problemTotal++;
                        if (postCheckedProblem.getProblemAttribute() == 1) {
                            problemComplete++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 2) {
                            problemEffective++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 3) {
                            problemSuitable++;
                        }
                        if (postCheckedProblem.getProblemCategory() == null)
                            continue;
                        if (postCheckedProblem.getProblemCategory().equals("1"))
                            problemCategoryOne++;
                        if (postCheckedProblem.getProblemCategory().equals("2"))
                            problemCategoryTwo++;
                        if (postCheckedProblem.getProblemCategory().equals("3"))
                            problemCategoryThree++;
                        if (postCheckedProblem.getProblemCategory().equals("4"))
                            problemCategoryFour++;
                        if (postCheckedProblem.getProblemCategory().equals("5"))
                            problemCategoryFive++;
                        if (postCheckedProblem.getProblemCategory().equals("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(Integer type) {
        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());
        // 查询职能问题数量
        List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                .in(PostCheckedProblem::getCheckedDeptId, deptIds)
        );

        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));// 部门名称
                int problemTotal = 0;
//    @ApiModelProperty("一般")
                Integer problemLeveOne = 0;
//    @ApiModelProperty("重要")
                Integer problemLeveTwo = 0;
                for (PostCheckedProblem postCheckedProblem : value) {
                    problemTotal++;
                    if (postCheckedProblem.getProblemLevel().equals("1")){
                        problemLeveOne++;
                    }
                    if (postCheckedProblem.getProblemLevel().equals("2")){
                        problemLeveTwo++;
                    }
                }
                data1.setProblemTotal(problemTotal); //问题数量
                data1.setProblemLeveTwo(problemLeveTwo); //重要问题
                data1.setProblemLeveOne(problemLeveOne); //一般问题
                Map<Integer, List<PostCheckedProblem>> dutyMap = value.stream().collect(Collectors.groupingBy(PostCheckedProblem::getDutyType));


                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();
                    for (PostCheckedProblem postCheckedProblem : postCheckedProblemList) {
                        if (postCheckedProblem.getProblemAttribute() == 1) {
                            problemComplete++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 2) {
                            problemEffective++;
                        }
                        if (postCheckedProblem.getProblemAttribute() == 3) {
                            problemSuitable++;
                        }
                    }
                    child1.setProblemComplete(problemComplete);
                    child1.setProblemEffective(problemEffective);
                    child1.setProblemSuitable(problemSuitable);
                }
                list.add(data1);
            }
        }


//        data1.setDeptId(1l); //部门ID
//        data1.setDeptName("测试部门名称1");// 部门名称
//        data1.setProblemTotal(10); //问题数量
//        data1.setProblemLeveTwo(2); //重要问题
//        data1.setProblemLeveOne(8); //一般问题
//        data1.setStatisticsTime(new Date());// 统计时间
//
//        List<CheckedProblemDeptDetaailView.ProblemAttributeInner> children1 = new ArrayList<>();
//        CheckedProblemDeptDetaailView.ProblemAttributeInner child1 = new CheckedProblemDeptDetaailView.ProblemAttributeInner();
//        child1.setProblemComplete(1); //child1.set完整性数量
//        child1.setProblemSuitable(2); //child1.set适宜性数量
//        child1.setProblemEffective(3);//child1.set有效性数量
//        //children1.add(child1);
//        //data1.setChildren(children1);
//        data1.getChildren().add(child1);


        return null;
    }
}

