package com.ruoyi.postCheck.service.impl;

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.service.impl.ServiceImpl;
import com.ruoyi.common.constant.PostAssessmentRatingOtherEnum;
import com.ruoyi.common.constant.PostAssessmentRulesEnum;
import com.ruoyi.common.core.domain.entity.SysDept;
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.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.postCheck.domain.PostAssessmentRatingOther;
import com.ruoyi.postCheck.domain.PostAssessmentRatingOtherInfo;
import com.ruoyi.postCheck.domain.PostAssessmentRules;
import com.ruoyi.postCheck.domain.tools.PostAssessmentRatingOtherInfoDept;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingMapper;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingOtherInfoMapper;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingOtherMapper;
import com.ruoyi.postCheck.mapper.PostAssessmentRulesMapper;
import com.ruoyi.postCheck.service.IPostAssessmentRatingOtherService;
import com.ruoyi.system.service.ISysDeptService;
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.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 打分表(职能互评生产日常)Service业务层处理
 *
 * @author csg
 * @date 2024-01-01
 */
@Service
public class PostAssessmentRatingOtherServiceImpl extends ServiceImpl<PostAssessmentRatingOtherMapper, PostAssessmentRatingOther> implements IPostAssessmentRatingOtherService {
    @Autowired
    private PostAssessmentRulesMapper postAssessmentRulesMapper;
    @Autowired
    private PostAssessmentRatingOtherInfoMapper postAssessmentRatingOtherInfoMapper;
    @Autowired
    private PostAssessmentRatingMapper postAssessmentRatingMapper;
    @Autowired
    private PostAssessmentRatingOtherMapper postAssessmentRatingOtherMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询打分表(职能互评生产日常)
     *
     * @param id 打分表(职能互评生产日常)主键
     * @return 打分表(职能互评生产日常)
     */
    @Override
    public PostAssessmentRatingOther selectPostAssessmentRatingOtherById(Long id) {
        //打分任务：该评分记录
        PostAssessmentRatingOther data = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherById(id);
        if (data == null) {
            throw new BaseException("该打分任务不存在，请刷新页面再试！");
        }

        //打分明细：12个部门的明细，每个部门有4项/3项
        PostAssessmentRatingOtherInfo postAssessmentRatingOtherInfoParam = new PostAssessmentRatingOtherInfo();
        postAssessmentRatingOtherInfoParam.setRatingOtherId(data.getId());
        List<PostAssessmentRatingOtherInfo> assessmentRatingOtherInfoList = postAssessmentRatingOtherInfoMapper.selectPostAssessmentRatingOtherInfoList(postAssessmentRatingOtherInfoParam);
        if (CollectionUtils.isEmpty(assessmentRatingOtherInfoList)) {
            throw new BaseException("该打分任务下没有设置明细，请联系管理员！");
        }

        //为打分任务设置Children
        //按项目分组
        Map<Integer, List<PostAssessmentRatingOtherInfo>> dutyTypeMap = assessmentRatingOtherInfoList.stream().collect(Collectors.groupingBy(PostAssessmentRatingOtherInfo::getDutyType));

        //为打分任务，添加分组后的打分项目
        for (Map.Entry<Integer, List<PostAssessmentRatingOtherInfo>> dutyTypeEntyr : dutyTypeMap.entrySet()) {
            Integer dutyType = dutyTypeEntyr.getKey();
            String rule = "";
            Integer scoreWeight = 100;

            //其中一个打分项目的12个部门得分
            List<PostAssessmentRatingOtherInfoDept> deptChildren = new ArrayList<>();

            //一个项目的所有部门打分记录
            List<PostAssessmentRatingOtherInfo> dutyTypeDeptChildren = dutyTypeEntyr.getValue();
            //为一个项目设置所有部门的打分记录：按前端约定的格式组装数据
            for (PostAssessmentRatingOtherInfo dutyTypeDeptChild : dutyTypeDeptChildren) {
                rule = dutyTypeDeptChild.getRule();//每一项都一样。覆盖取到一个即可
                scoreWeight = dutyTypeDeptChild.getScoreWeight();//每一项都一样。覆盖取到一个即可
                deptChildren.add(new PostAssessmentRatingOtherInfoDept(dutyTypeDeptChild.getId(), dutyTypeDeptChild.getByDeptId(), dutyTypeDeptChild.getByDeptName(), dutyTypeDeptChild.getByDeptScore()));
            }
            /*
            最后版本 - 查询SQL添加排序规则（按 评分分类 部门排序号 和 部门ID 进行综合排序），也可以实现效果：ORDER BY info.duty_type,	sd.order_num, info.by_dept_id
            //注意：很关键，前端没有按部门ID校正部门的排序，导致分数放的不正确，为了让前端更轻松，后端强制校位部门的顺序（即：相同部门在不同打分分类下出现的顺序是固定的）
            // 排序：被排序部门的中文名称升序
            Collections.sort(deptChildren, new Comparator<PostAssessmentRatingOtherInfoDept>() {
                @Override
                public int compare(PostAssessmentRatingOtherInfoDept o1, PostAssessmentRatingOtherInfoDept o2) {
                    return o1.getByDeptName().compareTo(o2.getByDeptName());//字符串字典正序
//                    return o2.getByDeptName().compareTo(o1.getByDeptName());//字符串字典倒序
                }
            });
*/
            PostAssessmentRatingOtherInfo child = new PostAssessmentRatingOtherInfo();
            child.setDutyType(dutyType);
            child.setRule(rule);
            child.setScoreWeight(scoreWeight);
            child.setChildren(deptChildren);

            data.getChildren().add(child);
        }

        //按被评分部门分组打分明细
//        Map<Long, List<PostAssessmentRatingOtherInfo>> assessmentRatingOtherInfoMap = assessmentRatingOtherInfoList.stream().collect(Collectors.groupingBy(PostAssessmentRatingOtherInfo::getByDeptId));

        //遍历分组Map（key是被评分部门ID）设置每个部门的打分明细（value是单个被评分部门的打分项4个/3个）

        /*
        List<PostAssessmentRatingOtherInfoDept> deptChildren1 = new ArrayList<>();
        deptChildren1.add(new PostAssessmentRatingOtherInfoDept(1l, 10l, "部门名称1", new BigDecimal("51")));
        deptChildren1.add(new PostAssessmentRatingOtherInfoDept(1l, 20l, "部门名称2", new BigDecimal("52")));
        deptChildren1.add(new PostAssessmentRatingOtherInfoDept(1l, 30l, "部门名称3", new BigDecimal("53")));
        deptChildren1.add(new PostAssessmentRatingOtherInfoDept(1l, 40l, "部门名称4", new BigDecimal("54")));
        deptChildren1.add(new PostAssessmentRatingOtherInfoDept(1l, 50l, "部门名称5", new BigDecimal("55")));
        deptChildren1.add(new PostAssessmentRatingOtherInfoDept(1l, 60l, "部门名称6", new BigDecimal("56")));

        List<PostAssessmentRatingOtherInfoDept> deptChildren2 = new ArrayList<>();
        deptChildren2.add(new PostAssessmentRatingOtherInfoDept(1l, 10l, "部门名称1", new BigDecimal("31")));
        deptChildren2.add(new PostAssessmentRatingOtherInfoDept(1l, 20l, "部门名称2", new BigDecimal("32")));
        deptChildren2.add(new PostAssessmentRatingOtherInfoDept(1l, 30l, "部门名称3", new BigDecimal("33")));
        deptChildren2.add(new PostAssessmentRatingOtherInfoDept(1l, 40l, "部门名称4", new BigDecimal("34")));
        deptChildren2.add(new PostAssessmentRatingOtherInfoDept(1l, 50l, "部门名称5", new BigDecimal("35")));
        deptChildren2.add(new PostAssessmentRatingOtherInfoDept(1l, 60l, "部门名称6", new BigDecimal("36")));

        List<PostAssessmentRatingOtherInfoDept> deptChildren3 = new ArrayList<>();
        deptChildren3.add(new PostAssessmentRatingOtherInfoDept(1l, 10l, "部门名称1", new BigDecimal("21")));
        deptChildren3.add(new PostAssessmentRatingOtherInfoDept(1l, 20l, "部门名称2", new BigDecimal("22")));
        deptChildren3.add(new PostAssessmentRatingOtherInfoDept(1l, 30l, "部门名称3", new BigDecimal("23")));
        deptChildren3.add(new PostAssessmentRatingOtherInfoDept(1l, 40l, "部门名称4", new BigDecimal("24")));
        deptChildren3.add(new PostAssessmentRatingOtherInfoDept(1l, 50l, "部门名称5", new BigDecimal("25")));
        deptChildren3.add(new PostAssessmentRatingOtherInfoDept(1l, 60l, "部门名称6", new BigDecimal("26")));

        List<PostAssessmentRatingOtherInfo> dataCheilren = new ArrayList<>();
        for (int i = 1; i <= 3; i++) {
            PostAssessmentRatingOtherInfo info = new PostAssessmentRatingOtherInfo();
            info.setByDeptId((long) (i + 99));
            info.setByDeptName("部门名称" + i);
            info.setDutyType(i);
            if (i == 1) {
                info.setScoreWeight(50);
                info.getChildren().addAll(deptChildren1);
            } else if (i == 2) {
                info.setScoreWeight(30);
                info.getChildren().addAll(deptChildren2);
            } else if (i == 3) {
                info.setScoreWeight(20);
                info.getChildren().addAll(deptChildren3);
            }
            info.setRule("Rule" + i);

            dataCheilren.add(info);
        }
        data.getChildren().addAll(dataCheilren);
        */

        //相同批次下所有评分记录
//        List<PostAssessmentRatingOther> batchAssessmentRatingOtherList = postAssessmentRatingOtherMapper.selectList(Wrappers.<PostAssessmentRatingOther>lambdaQuery()
//                .eq(PostAssessmentRatingOther::getBatchId, data.getBatchId())
//        );

//        if (batchAssessmentRatingOtherList.isEmpty()) {
//            return new PostAssessmentRatingOther();
//        }

        //data.getType() 互评/日常分表 1-是职能管理部门；2-生产运营部门；
        //type 考核规则->评分分类/项目/专业：1-岗检考核规则；2-职能部门互评表；；3-生产部门日常得分；
//        Long type = 2L;//职能
//        if (data.getType() == 2) {
//            type = 3L;//生产
//        }
        //考核规则（职能/生产）
//        List<PostAssessmentRules> postAssessmentRules = postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
//                .eq(PostAssessmentRules::getType, type)
//        );

 /*       List<PostAssessmentRatingOtherInfo> children = new ArrayList<>();

        for (PostAssessmentRules postAssessmentRule : postAssessmentRules) {
            // "评分分类/项目/专业：职责类别：1-业务职责；2-党建及党风廉政；3-安全环保职责；4-合规与保密职责；5-任职资格与能力素质要求；6-岗位责任制文件完整性与适宜性；
            // 10-工作态度；11-部门协作；12-廉洁从业；13-主要工作完成情况；
            // 20-HSE；21-生产；22-设备；")
            Integer dutyType = postAssessmentRule.getDutyType();//类型
            Integer scoreWeight = postAssessmentRule.getFullScore();//权重


            //打分表明细里面放的为各个部门的评分结果
            List<PostAssessmentRatingOtherInfoDept> deptChildren = new ArrayList<>();

            for (PostAssessmentRatingOther postAssessmentRatingOther : batchAssessmentRatingOtherList) {
                //根据 打分表ID + 评分分类/项目/专业 查询打分明细，即：打分页面的一行，例如：主要工作完成情况->A部门90分，B部门91分，C部门92分……（一般为13个）
                List<PostAssessmentRatingOtherInfo> dutyTypeAssessmentRatingOtherInfoList = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                        .eq(PostAssessmentRatingOtherInfo::getRatingOtherId, postAssessmentRatingOther.getId())
                        .eq(PostAssessmentRatingOtherInfo::getDutyType, dutyType)
                );

                BigDecimal distance = new BigDecimal("0");
//                Integer distance = 0;
                if (dutyTypeAssessmentRatingOtherInfoList.isEmpty()) {
                    continue;
                }
                distance = dutyTypeAssessmentRatingOtherInfoList.get(0).getByDeptScore();
                deptChildren.add(new PostAssessmentRatingOtherInfoDept(dutyTypeAssessmentRatingOtherInfoList.get(0).getId(), postAssessmentRatingOther.getDeptId(), postAssessmentRatingMapper.getSysDeptName(postAssessmentRatingOther.getDeptId()), distance));
            }

            PostAssessmentRatingOtherInfo child = new PostAssessmentRatingOtherInfo();
            child.setDutyType(dutyType);
            child.setScoreWeight(scoreWeight);
            child.setChildren(deptChildren);
            children.add(child);
        }
        data.setChildren(children);
        */
        return data;
    }

/*
    public PostAssessmentRatingOther back_selectPostAssessmentRatingOtherById(Long id) {
        //该评分记录
        PostAssessmentRatingOther data = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherById(id);
        //相同批次下所有评分记录
        List<PostAssessmentRatingOther> batchAssessmentRatingOtherList = postAssessmentRatingOtherMapper.selectList(Wrappers.<PostAssessmentRatingOther>lambdaQuery()
                .eq(PostAssessmentRatingOther::getBatchId, data.getBatchId())
        );

        if (batchAssessmentRatingOtherList.isEmpty()) {
            return new PostAssessmentRatingOther();
        }

        //data.getType() 互评/日常分表 1-是职能管理部门；2-生产运营部门；
        //type 考核规则->评分分类/项目/专业：1-岗检考核规则；2-职能部门互评表；；3-生产部门日常得分；
        Long type = 2L;//职能
        if (data.getType() == 2) {
            type = 3L;//生产
        }
        //考核规则（职能/生产）
        List<PostAssessmentRules> postAssessmentRules = postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
                .eq(PostAssessmentRules::getType, type)
        );

        List<PostAssessmentRatingOtherInfo> children = new ArrayList<>();

        for (PostAssessmentRules postAssessmentRule : postAssessmentRules) {
            // "评分分类/项目/专业：职责类别：1-业务职责；2-党建及党风廉政；3-安全环保职责；4-合规与保密职责；5-任职资格与能力素质要求；6-岗位责任制文件完整性与适宜性；
            // 10-工作态度；11-部门协作；12-廉洁从业；13-主要工作完成情况；
            // 20-HSE；21-生产；22-设备；")
            Integer dutyType = postAssessmentRule.getDutyType();//类型
            Integer scoreWeight = postAssessmentRule.getFullScore();//权重


            //打分表明细里面放的为各个部门的评分结果
            List<PostAssessmentRatingOtherInfoDept> deptChildren = new ArrayList<>();

            for (PostAssessmentRatingOther postAssessmentRatingOther : batchAssessmentRatingOtherList) {
                //根据 打分表ID + 评分分类/项目/专业 查询打分明细，即：打分页面的一行，例如：主要工作完成情况->A部门90分，B部门91分，C部门92分……（一般为13个）
                List<PostAssessmentRatingOtherInfo> dutyTypeAssessmentRatingOtherInfoList = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                        .eq(PostAssessmentRatingOtherInfo::getRatingOtherId, postAssessmentRatingOther.getId())
                        .eq(PostAssessmentRatingOtherInfo::getDutyType, dutyType)
                );

                BigDecimal distance = new BigDecimal("0");
                if (dutyTypeAssessmentRatingOtherInfoList.isEmpty()) {
                    continue;
                }
                distance = dutyTypeAssessmentRatingOtherInfoList.get(0).getByDeptScore();
                deptChildren.add(new PostAssessmentRatingOtherInfoDept(dutyTypeAssessmentRatingOtherInfoList.get(0).getId(), postAssessmentRatingOther.getDeptId(), postAssessmentRatingMapper.getSysDeptName(postAssessmentRatingOther.getDeptId()), distance));
            }

            PostAssessmentRatingOtherInfo child = new PostAssessmentRatingOtherInfo();
            child.setDutyType(dutyType);
            child.setScoreWeight(scoreWeight);
            child.setChildren(deptChildren);
            children.add(child);
        }
        data.setChildren(children);
        return data;
    }
*/


    /**
     * 查询打分表(职能互评生产日常)列表
     *
     * @param postAssessmentRatingOther 打分表(职能互评生产日常)
     * @return 打分表(职能互评生产日常)
     */
    @Override
    public List<PostAssessmentRatingOther> selectPostAssessmentRatingOtherList(PostAssessmentRatingOther postAssessmentRatingOther) {

        //该部门的打分任务表
        List<PostAssessmentRatingOther> dataList = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherList(postAssessmentRatingOther);
        if (dataList.isEmpty()) {
            return new ArrayList<>();
        }

        //任务表的下的打分明细
        List<Long> dataIdList = dataList.stream().map(PostAssessmentRatingOther::getId).collect(Collectors.toList());
        List<PostAssessmentRatingOtherInfo> dataChildren = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                .in(PostAssessmentRatingOtherInfo::getRatingOtherId, dataIdList)
        );

        //为打分任务添加打分明细：每个明细项目仅按类型装载一个明细即可
        for (PostAssessmentRatingOther data : dataList) {
            //过滤当前部门的打分明细
            List<PostAssessmentRatingOtherInfo> childrenAllDept = dataChildren.stream().filter(a -> a.getRatingOtherId().equals(data.getId())).collect(Collectors.toList());
            //按项目分组
            Map<Integer, List<PostAssessmentRatingOtherInfo>> dutyTypeMap = childrenAllDept.stream().collect(Collectors.groupingBy(PostAssessmentRatingOtherInfo::getDutyType));
            //为打分任务，添加分组后的打分项目
            for (Map.Entry<Integer, List<PostAssessmentRatingOtherInfo>> dutyTypeEntyr : dutyTypeMap.entrySet()) {
                Integer dutyType = dutyTypeEntyr.getKey();
                PostAssessmentRatingOtherInfo childrenTemp = dutyTypeEntyr.getValue().get(0);
                PostAssessmentRatingOtherInfo child = new PostAssessmentRatingOtherInfo();
                child.setDutyType(dutyType);
                child.setRule(childrenTemp.getRule());
                child.setScoreWeight(childrenTemp.getScoreWeight());
                data.getChildren().add(child);
            }
        }
        return dataList;
    }

    /**
     * 新增打分表(职能互评生产日常)
     *
     * @param postAssessmentRatingOther 打分表(职能互评生产日常)
     * @return 结果
     */
    @Override
    public int insertPostAssessmentRatingOther(PostAssessmentRatingOther postAssessmentRatingOther) {
        //TODO 自增主键修改为-MyBatis-Plus雪花算法(截取5位解决VUE精度丢失BUG)-系统登录日志
//        if (postAssessmentRatingOther.getId() == null)
        postAssessmentRatingOther.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
        // postAssessmentRatingOther.setCreateTime(DateUtils.getNowDate());
        postAssessmentRatingOther.setCreateDefault();
        postAssessmentRatingOther.setStatus(PostAssessmentRatingOtherEnum.STATUS_ING.getValue()); // 去创建自己的枚举类
        postAssessmentRatingOther.setCreateUserId(SecurityUtils.getUserId());
        return postAssessmentRatingOtherMapper.insertPostAssessmentRatingOther(postAssessmentRatingOther);
    }

    /**
     * 修改打分表(职能互评生产日常)
     *
     * @param postAssessmentRatingOther 打分表(职能互评生产日常)
     * @return 结果
     */
    @Override
    public int updatePostAssessmentRatingOther(PostAssessmentRatingOther postAssessmentRatingOther) {
        // postAssessmentRatingOther.setUpdateTime(DateUtils.getNowDate());
        postAssessmentRatingOther.setUpdateDefault();
        return postAssessmentRatingOtherMapper.updatePostAssessmentRatingOther(postAssessmentRatingOther);
    }

    /**
     * 批量删除打分表(职能互评生产日常)
     *
     * @param ids 需要删除的打分表(职能互评生产日常)主键
     * @return 结果
     */
    @Override
    public int deletePostAssessmentRatingOtherByIds(Long[] ids) {
        return postAssessmentRatingOtherMapper.deletePostAssessmentRatingOtherByIds(ids);
    }

    /**
     * 删除打分表(职能互评生产日常)信息
     *
     * @param id 打分表(职能互评生产日常)主键
     * @return 结果
     */
    @Override
    public int deletePostAssessmentRatingOtherById(Long id) {
        return postAssessmentRatingOtherMapper.deletePostAssessmentRatingOtherById(id);
    }

    /**
     * 管理员创建
     * V2：职能部门互评
     * 互评批次：管理员启动互评任务，初始化13个部门互相打分的记录
     *
     * @param postAssessmentRatingOther
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchAddRatingOther(PostAssessmentRatingOther postAssessmentRatingOther) {

        Integer type = postAssessmentRatingOther.getType();//类型：1-职能互评；2-生产日常；
        Date startTime = postAssessmentRatingOther.getStartTime();//评分开始时间（管理员创建的）
        Integer deptType = null;
        String deptTypeView = "";
        if (type == PostAssessmentRatingOtherEnum.TYPE_ZN_HP.getValue()) {
            deptTypeView = "职能部门互评";
            deptType = SysDeptEnum.TYPE_ZN.getValue();
        } else if (type == PostAssessmentRatingOtherEnum.TYPE_SC_RC.getValue()) {
            deptTypeView = "生产部门日常评分";
            deptType = SysDeptEnum.TYPE_SC.getValue();
        } else {
            deptTypeView = "【type = " + type + "】";
            deptType = SysDeptEnum.TYPE_OTHER.getValue();
        }
        if (type == null || startTime == null) {
            return 0;
        }

        if (type != PostAssessmentRatingOtherEnum.TYPE_ZN_HP.getValue()) {
            return 0;
        }

        //检查评分记录是否已经存在，1个年度只允许一次
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, startTime);
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostAssessmentRatingOther postAssessmentRatingOtherParam = new PostAssessmentRatingOther();
        postAssessmentRatingOtherParam.setType(type);
        postAssessmentRatingOtherParam.setParams(params);
        List<PostAssessmentRatingOther> postAssessmentRatingOtherList = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherList(postAssessmentRatingOtherParam);
        if (!CollectionUtils.isEmpty(postAssessmentRatingOtherList)) {
            throw new BaseException(year + "年度已创建过" + deptTypeView + "不可以重复创建，请检查！");
        }


        //初始化13个职能部门评分
        List<PostAssessmentRules> rulesList = rulesList = postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
                .eq(PostAssessmentRules::getType, PostAssessmentRulesEnum.TYPE_ZN.getValue())
                .orderByDesc(PostAssessmentRules::getCreateTime)
        );
        /*
        // 类型：1-职能互评；
        if (type == PostAssessmentRatingOtherEnum.TYPE_ZN_HP.getValue()) {
            rulesList = postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
                    .eq(PostAssessmentRules::getType, PostAssessmentRulesEnum.TYPE_ZN.getValue())
                    .orderByDesc(PostAssessmentRules::getCreateTime)
            );
        }
        //类型：2-生产日常；
        else if (type == PostAssessmentRatingOtherEnum.TYPE_SC_RC.getValue()) {
            rulesList = postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
                    .eq(PostAssessmentRules::getType, PostAssessmentRulesEnum.TYPE_SC.getValue())
                    .orderByDesc(PostAssessmentRules::getCreateTime)
            );

        }
        */
        if (CollectionUtils.isEmpty(rulesList)) {
            throw new BaseException(deptTypeView + "未添加考核评比规则，请检查！");
        }

        //利用Set集合进行去重，按创建时间取最近的
        Set<Integer> dutyTypeSet = new HashSet<>();
        Iterator<PostAssessmentRules> rulesIterator = rulesList.iterator();
        while (rulesIterator.hasNext()) {
            PostAssessmentRules rules = rulesIterator.next();
            Integer dutyType = rules.getDutyType();
            if (!dutyTypeSet.add(dutyType)) {
                rulesIterator.remove();
            }
        }


        //1、查询职能/生产部门列表
        SysDept deptParam = new SysDept();
        deptParam.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());//部门状态（0正常 1停用）
        deptParam.setType(deptType);//1 职能部门 2 生产部门 3 其他
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(deptParam);
        if (CollectionUtils.isEmpty(deptList)) {
            throw new BaseException(deptTypeView + "系统管理->部门管理中未设置部门类型，请检查！");
        }


        String batchId = IdWorker.getIdStr().substring(4);//批次ID

        //循环13个部门插入待打分的任务：例如：A部门为其他12个部门打分的主表 + 打分明细表(不含自己的其他12个部门)、B部门为其他12个部门打分的主表 + 打分明细表(不含自己的其他12个部门)、……
        for (SysDept dept : deptList) {
            Long deptId = dept.getDeptId();
            String deptName = dept.getDeptName();
            //A部门打分任务主表
            PostAssessmentRatingOther postAssessmentRatingOtherOther = new PostAssessmentRatingOther();
            postAssessmentRatingOtherOther.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
            postAssessmentRatingOtherOther.setType(type);
            postAssessmentRatingOtherOther.setBatchId(batchId);
            postAssessmentRatingOtherOther.setStartTime(startTime);
            postAssessmentRatingOtherOther.setStatus(PostAssessmentRatingOtherEnum.STATUS_ING.getValue());////状态：1-进行中；2-已完成
            postAssessmentRatingOtherOther.setDeptId(deptId);//打分部门ID
            postAssessmentRatingOtherOther.setDeptName(deptName);//打分部门名称
            postAssessmentRatingOtherOther.setCreateDefault();
            postAssessmentRatingOtherOther.setCreateUserId(SecurityUtils.getLoginUser().getUserId());
            int insert = postAssessmentRatingOtherMapper.insert(postAssessmentRatingOtherOther);
            if (insert == 0) {
                throw new BaseException(deptTypeView + "失败，请稍后重试！");
            }

            //A部门为其他12个部门打分的明细：根据规则
            //1、过滤得到其他12个部门：当前部门外的另外的12个部门
            List<SysDept> otherDeptList = deptList.stream().filter(a -> a.getDeptId() != deptId).collect(Collectors.toList());
            //2、分别为12个部门按规则插入打分明细
            for (SysDept otherDept : otherDeptList) {
                //2.1、B、C、D、E、F……（另外的12个部门）部门按考核评比规则插入打分明细
                for (PostAssessmentRules postAssessmentRule : rulesList) {
                    PostAssessmentRatingOtherInfo info = new PostAssessmentRatingOtherInfo();
                    info.setRatingOtherId(postAssessmentRatingOtherOther.getId());//A打分任务表ID
                    info.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
                    info.setByDeptName(otherDept.getDeptName());//被评分部门名称（其他12个部门的）
                    info.setByDeptId(otherDept.getDeptId());//被评分部门ID（其他12个部门的）
                    info.setDutyType(postAssessmentRule.getDutyType());//规则类型
                    info.setScoreWeight(postAssessmentRule.getFullScore());//满分/权重
                    info.setRule(postAssessmentRule.getRule());//考核规则/评分标准
//                    info.setByDeptScore();//打分分数
                    info.setCreateDefault();
                    int insertInfo = postAssessmentRatingOtherInfoMapper.insert(info);
                    if (insertInfo == 0) {
                        throw new BaseException(deptTypeView + "失败，请稍后重试！");
                    }
                }
            }
        }

        return 1;
    }

    /**
     * V2：管理员创建生产部门的日常评分，只创建一条，后续三大部门对所有的生产部门（13个）进行评分
     *
     * @param postAssessmentRatingOther
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addRatingOtherSC(PostAssessmentRatingOther postAssessmentRatingOther) {

        Integer type = postAssessmentRatingOther.getType();//类型：1-职能互评；2-生产日常；
        Date startTime = postAssessmentRatingOther.getStartTime();//评分开始时间（管理员创建的）
        Integer deptType = null;
        String deptTypeView = "";
        if (type == PostAssessmentRatingOtherEnum.TYPE_ZN_HP.getValue()) {
            deptTypeView = "职能部门互评";
            deptType = SysDeptEnum.TYPE_ZN.getValue();
        } else if (type == PostAssessmentRatingOtherEnum.TYPE_SC_RC.getValue()) {
            deptTypeView = "生产部门日常评分";
            deptType = SysDeptEnum.TYPE_SC.getValue();
        } else {
            deptTypeView = "【type = " + type + "】";
            deptType = SysDeptEnum.TYPE_OTHER.getValue();
        }
        if (type == null || startTime == null) {
            return 0;
        }

        if (type != PostAssessmentRatingOtherEnum.TYPE_SC_RC.getValue()) {
            return 0;
        }

        //检查评分记录是否已经存在，1个年度只允许一次
        String year = DateUtils.parseDateToStr(DateUtils.YYYY, startTime);
        Map<String, Object> params = new HashMap<>();
        params.put("beginTime", year + "-01-01");
        params.put("endTime", year + "-12-31");
        PostAssessmentRatingOther postAssessmentRatingOtherParam = new PostAssessmentRatingOther();
        postAssessmentRatingOtherParam.setType(type);
        postAssessmentRatingOtherParam.setParams(params);
        List<PostAssessmentRatingOther> postAssessmentRatingOtherList = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherList(postAssessmentRatingOtherParam);
        if (!CollectionUtils.isEmpty(postAssessmentRatingOtherList)) {
            throw new BaseException(year + "年度已创建过" + deptTypeView + "不可以重复创建，请检查！");
        }


        //初始化13个生产部门评分，只有1条
        List<PostAssessmentRules> rulesList = postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
                .eq(PostAssessmentRules::getType, PostAssessmentRulesEnum.TYPE_SC.getValue())
                .orderByDesc(PostAssessmentRules::getCreateTime)
        );


        if (CollectionUtils.isEmpty(rulesList)) {
            throw new BaseException(deptTypeView + "未添加考核评比规则，请检查！");
        }

        //利用Set集合进行去重，按创建时间取最近的
        Set<Integer> dutyTypeSet = new HashSet<>();
        Iterator<PostAssessmentRules> rulesIterator = rulesList.iterator();
        while (rulesIterator.hasNext()) {
            PostAssessmentRules rules = rulesIterator.next();
            Integer dutyType = rules.getDutyType();
            if (!dutyTypeSet.add(dutyType)) {
                rulesIterator.remove();
            }
        }


        //1、查询生产部门
        SysDept deptParam = new SysDept();
        deptParam.setStatus(SysDeptEnum.STATUS_VALID.getValue().toString());//部门状态（0正常 1停用）
        deptParam.setType(deptType);//1 职能部门 2 生产部门 3 其他
        List<SysDept> deptList = sysDeptService.selectDeptListByCondition(deptParam);
        if (CollectionUtils.isEmpty(deptList)) {
            throw new BaseException(deptTypeView + "系统管理->部门管理中未设置部门类型，请检查！");
        }


        String batchId = IdWorker.getIdStr().substring(4);//批次ID
        Long deptId = SecurityUtils.getDeptId();
        SysDept sysDept = sysDeptService.selectDeptById(deptId);
        String deptName = sysDept.getDeptName();
        //A部门打分任务主表
        PostAssessmentRatingOther postAssessmentRatingOtherOther = new PostAssessmentRatingOther();
        postAssessmentRatingOtherOther.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
        postAssessmentRatingOtherOther.setType(type);
        postAssessmentRatingOtherOther.setBatchId(batchId);
        postAssessmentRatingOtherOther.setStartTime(startTime);
        postAssessmentRatingOtherOther.setStatus(PostAssessmentRatingOtherEnum.STATUS_ING.getValue());////状态：1-进行中；2-已完成
        postAssessmentRatingOtherOther.setDeptId(deptId);//打分部门ID
        postAssessmentRatingOtherOther.setDeptName(deptName);//打分部门名称
        postAssessmentRatingOtherOther.setCreateDefault();
        postAssessmentRatingOtherOther.setCreateUserId(SecurityUtils.getLoginUser().getUserId());
        int insert = postAssessmentRatingOtherMapper.insert(postAssessmentRatingOtherOther);
        if (insert == 0) {
            throw new BaseException(deptTypeView + "失败，请稍后重试！");
        }

        //分别为13个部门按规则插入打分明细
        for (SysDept otherDept : deptList) {
            //2.1、B、C、D、E、F……（另外的12个部门）部门按考核评比规则插入打分明细
            for (PostAssessmentRules postAssessmentRule : rulesList) {
                PostAssessmentRatingOtherInfo info = new PostAssessmentRatingOtherInfo();
                info.setRatingOtherId(postAssessmentRatingOtherOther.getId());//A打分任务表ID
                info.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
                info.setByDeptName(otherDept.getDeptName());//被评分部门名称（其他12个部门的）
                info.setByDeptId(otherDept.getDeptId());//被评分部门ID（其他12个部门的）
                info.setDutyType(postAssessmentRule.getDutyType());//规则类型
                info.setScoreWeight(postAssessmentRule.getFullScore());//满分/权重
//                    info.setByDeptScore();//打分分数
                info.setCreateDefault();
                int insertInfo = postAssessmentRatingOtherInfoMapper.insert(info);
                if (insertInfo == 0) {
                    throw new BaseException(deptTypeView + "失败，请稍后重试！");
                }
            }
        }

        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchAddRatingOtherUpdate(PostAssessmentRatingOther postAssessmentRatingOther) {
//        List<PostAssessmentRatingOther> postAssessmentRatingOthers = postAssessmentRatingOtherMapper.selectList(Wrappers.<PostAssessmentRatingOther>lambdaQuery()
//                .eq(PostAssessmentRatingOther::getBatchId, postAssessmentRatingOther.getBatchId())
//        );
//        if (postAssessmentRatingOthers.isEmpty()) {
//            throw new RuntimeException("提交失败");
//        }
        //打分记录
//        List<Long> collect = postAssessmentRatingOthers.stream().map(PostAssessmentRatingOther::getId).collect(Collectors.toList());
//        PostAssessmentRatingOther postAssessmentRatingOther1 = postAssessmentRatingOtherMapper.selectOne(Wrappers.<PostAssessmentRatingOther>lambdaQuery()
//                .eq(PostAssessmentRatingOther::getId, postAssessmentRatingOther.getId()));


        //标记状态=已打分
        postAssessmentRatingOtherMapper.update(null,
                Wrappers.<PostAssessmentRatingOther>lambdaUpdate().
                        set(PostAssessmentRatingOther::getStatus, PostAssessmentRatingOtherEnum.STATUS_FINISH.getValue()).
                        set(PostAssessmentRatingOther::getUpdateTime, DateUtils.getNowDate()).
                        set(PostAssessmentRatingOther::getUpdateBy, SecurityUtils.getLoginUser().getUsername()).
                        eq(PostAssessmentRatingOther::getId, postAssessmentRatingOther.getId())
        );


        //打分明细：数据库中
        List<PostAssessmentRatingOtherInfo> info = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                .eq(PostAssessmentRatingOtherInfo::getRatingOtherId, postAssessmentRatingOther.getId())
        );

        //打分项目:页面提交的
        List<PostAssessmentRatingOtherInfo> children = postAssessmentRatingOther.getChildren();
        children.forEach(child -> {
            //页面提交的打分记录：打分项目中的各个部门（除自己外的12个部门）得分
            List<PostAssessmentRatingOtherInfoDept> dept = child.getChildren();
            dept.forEach(y -> {
                //数据库中的 得分部门ID = 页面提交的 && 打分项目 = 页面提交的
                List<PostAssessmentRatingOtherInfo> collect1 = info.stream().filter(d -> d.getByDeptId().equals(y.getByDeptId()) && d.getDutyType().equals(child.getDutyType())).collect(Collectors.toList());
                for (PostAssessmentRatingOtherInfo postAssessmentRatingOtherInfo : collect1) {
                    postAssessmentRatingOtherInfo.setUpdateDefault();
                    postAssessmentRatingOtherInfo.setByDeptScore(y.getByDeptScore());
                    postAssessmentRatingOtherInfoMapper.updateById(postAssessmentRatingOtherInfo);
                }
            });
        });
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int productionDepartmentSub(List<PostAssessmentRatingOther> postAssessmentRatingOtherList) {

        //根据打分明细表的主键，查询主表的ID，下一步再更新主表的打分状态为已完成打分
        PostAssessmentRatingOther postAssessmentRatingOther = postAssessmentRatingOtherList.get(0);
        List<PostAssessmentRatingOtherInfo> children1 = postAssessmentRatingOther.getChildren();
        PostAssessmentRatingOtherInfo child1 = children1.get(0);
        Long childId = child1.getId();
        PostAssessmentRatingOtherInfo postAssessmentRatingOtherInfo = postAssessmentRatingOtherInfoMapper.selectById(childId);


        //标记状态=已打分
        postAssessmentRatingOtherMapper.update(null,
                Wrappers.<PostAssessmentRatingOther>lambdaUpdate().
                        set(PostAssessmentRatingOther::getStatus, PostAssessmentRatingOtherEnum.STATUS_FINISH.getValue()).
                        set(PostAssessmentRatingOther::getUpdateTime, DateUtils.getNowDate()).
                        set(PostAssessmentRatingOther::getUpdateBy, SecurityUtils.getLoginUser().getUsername()).
                        eq(PostAssessmentRatingOther::getId, postAssessmentRatingOtherInfo.getRatingOtherId())
        );


        for (PostAssessmentRatingOther assessmentRatingOther : postAssessmentRatingOtherList) {
            List<PostAssessmentRatingOtherInfo> children = assessmentRatingOther.getChildren();
            children.forEach(child -> {
                PostAssessmentRatingOtherInfo info = new PostAssessmentRatingOtherInfo();
                info.setId(child.getId());
                info.setByDeptScore(child.getByDeptScore());
                info.setUpdateDefault();
                postAssessmentRatingOtherInfoMapper.updateById(info);
            });
        }
        return 1;
    }

}
