package com.ruoyi.postCheck.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.postCheck.domain.PostAssessmentRatingOther;
import com.ruoyi.postCheck.domain.PostAssessmentRatingOtherInfo;
import com.ruoyi.postCheck.domain.PostAssessmentRules;
import com.ruoyi.postCheck.domain.PostCheckedProblem;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingOtherInfoMapper;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingOtherMapper;
import com.ruoyi.postCheck.mapper.PostAssessmentRulesMapper;
import com.ruoyi.postCheck.mapper.PostCheckedProblemMapper;
import com.ruoyi.postCheck.mapper.PostPlanInfoMapper;
import com.ruoyi.postCheck.mapper.PostPlanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingMapper;
import com.ruoyi.postCheck.domain.PostAssessmentRating;
import com.ruoyi.postCheck.service.IPostAssessmentRatingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 考核评比Service业务层处理
 *
 * @author csg
 * @date 2023-12-21
 */
@Service
public class PostAssessmentRatingServiceImpl extends ServiceImpl<PostAssessmentRatingMapper, PostAssessmentRating> implements IPostAssessmentRatingService {
    @Autowired
    private PostAssessmentRatingOtherMapper postAssessmentRatingOtherMapper;
    @Autowired
    private PostAssessmentRatingOtherInfoMapper postAssessmentRatingOtherInfoMapper;
    @Autowired
    private PostAssessmentRatingMapper postAssessmentRatingMapper;
    @Autowired
    private PostCheckedProblemMapper postCheckedProblemMapper;
    @Autowired
    private PostPlanInfoMapper postPlanInfoMapper;
    @Autowired
    private PostPlanMapper postPlanMapper;
    @Autowired
    private PostAssessmentRulesMapper postAssessmentRulesMapper;
    /**
     * 查询考核评比
     *
     * @param id 考核评比主键
     * @return 考核评比
     */
    @Override
    public PostAssessmentRating selectPostAssessmentRatingById(Long id) {
        return postAssessmentRatingMapper.selectPostAssessmentRatingById(id);
    }

    /**
     * 查询考核评比列表
     *
     * @param postAssessmentRating 考核评比
     * @return 考核评比
     */
    @Override
    public List<PostAssessmentRating> selectPostAssessmentRatingList(PostAssessmentRating postAssessmentRating) {
        // type 1 是职能管理部门， 2 生产运营部门
        Integer type;
        if (postAssessmentRating.getType() == 2){
            type = 3;
        } else {
            type = 2;
        }
        List<PostAssessmentRating> postAssessmentRatings = new ArrayList<>();
        List<Map<String, Object>> deptIdListByType = postAssessmentRatingOtherMapper.getDeptIdListByType(postAssessmentRating.getType());
        List<PostAssessmentRules> postAssessmentRules = postAssessmentRulesMapper.selectList(Wrappers.lambdaQuery());
        for (Map<String, Object> map : deptIdListByType) {
            PostAssessmentRating post = new PostAssessmentRating();
            post.setDeptId(Long.parseLong(map.get("deptId").toString()));
            post.setDeptIdStr(String.valueOf(map.get("deptName")));
            // 计算一个部门的岗检得分
            // 1 先查询问题
            BigDecimal postSouce = new BigDecimal("100");
            List<PostCheckedProblem> postCheckedProblems = postCheckedProblemMapper.selectList(Wrappers.<PostCheckedProblem>lambdaQuery()
                    .eq(PostCheckedProblem::getCheckedDeptId,post.getDeptId())
            );
            BigDecimal postTotal = postCheckedProblemMapper.getPostTotalByDeptId(post.getDeptId());
            if (postCheckedProblems.size() > 0){
                // 计算扣除分数
                BigDecimal postAfter = new BigDecimal("100");
                Set<PostAssessmentRules> collect = postAssessmentRules.stream().filter(d -> d.getType() == type).collect(Collectors.toSet());
                for (PostCheckedProblem postCheckedProblem : postCheckedProblems) {
                    Optional<PostAssessmentRules> first = postAssessmentRules.stream().filter(d ->d.getType() == type && d.getDutyType().equals(postCheckedProblem.getDutyType())).findFirst();
                    if (first.isPresent()){
                        if (postCheckedProblem.getProblemLevel().equals("1")){
                            postAfter = postAfter.subtract(new BigDecimal(String.valueOf(first.get().getProblemLevelOne()!=null?first.get().getProblemLevelOne():"0")));
                        }else{
                            postAfter = postAfter.subtract(new BigDecimal(String.valueOf(first.get().getProblemLevelTwo()!=null?first.get().getProblemLevelTwo():"0")));
                        }
                    }
                }
                BigDecimal divide = new BigDecimal("0");
                if (postTotal != null){
                    divide =  new BigDecimal(postCheckedProblems.size()).divide(postTotal.multiply(new BigDecimal(collect.size())),4, RoundingMode.HALF_UP);
                }
                // 计算系数 1-问题总数/需要查的问题数
                if (divide.compareTo(new BigDecimal("1")) < 0 && divide.compareTo(new BigDecimal("0")) > 0 ){
                    postSouce = postAfter.multiply(new BigDecimal("1").subtract(divide));
                }else{
                    postSouce = new BigDecimal("0");
                }
            }else {
                postSouce = new BigDecimal("0");
            }
            post.setPositionScore(postSouce);
            // 计算互评得分

            List<PostAssessmentRatingOtherInfo> postAssessmentRatingOtherInfos = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                    .eq(PostAssessmentRatingOtherInfo::getByDeptId,post.getDeptId())
                    .apply(" \"rating_other_id\" in (SELECT \"id\" FROM \"public\".\"post_assessment_rating_other\" WHERE \"type\"  = 1\n)")
                    .orderByAsc(PostAssessmentRatingOtherInfo::getByDeptScore)
            );
            BigDecimal peerEvaluationScore = new BigDecimal("100");
            if (postAssessmentRatingOtherInfos.size()>0){
                postAssessmentRatingOtherInfos.remove(postAssessmentRatingOtherInfos.size()-1);
                postAssessmentRatingOtherInfos.remove(0);
                BigDecimal sum = new BigDecimal("0");
                postAssessmentRatingOtherInfos.forEach(x -> {
                    sum.add(x.getByDeptScore()!=null?x.getByDeptScore():new BigDecimal("0"));
                });
                peerEvaluationScore = sum.divide(new BigDecimal(postAssessmentRatingOtherInfos.size()),4, RoundingMode.HALF_UP);
            }
            post.setPeerEvaluationScore(peerEvaluationScore);
            postAssessmentRatings.add(post);
            // 计算总得分
            post.setDepartmentScore(post.getPositionScore().add(post.getPeerEvaluationScore()).divide(new BigDecimal("2")));
        }
        List<PostAssessmentRating> collect = postAssessmentRatings.stream().sorted(Comparator.comparing(PostAssessmentRating::getDepartmentScore).reversed()).collect(Collectors.toList());
        // 计算  岗检得分
        return collect;
    }

    /**
     * 新增考核评比
     *
     * @param postAssessmentRating 考核评比
     * @return 结果
     */
    @Override
    public int insertPostAssessmentRating(PostAssessmentRating postAssessmentRating) {
        //TODO 自增主键修改为-MyBatis-Plus雪花算法(截取5位解决VUE精度丢失BUG)-系统登录日志
        if (postAssessmentRating.getId() == null)
            postAssessmentRating.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));

        postAssessmentRating.setCreateDefault();
        return postAssessmentRatingMapper.insertPostAssessmentRating(postAssessmentRating);
    }

    /**
     * 修改考核评比
     *
     * @param postAssessmentRating 考核评比
     * @return 结果
     */
    @Override
    public int updatePostAssessmentRating(PostAssessmentRating postAssessmentRating) {
        postAssessmentRating.setUpdateDefault();
        return postAssessmentRatingMapper.updatePostAssessmentRating(postAssessmentRating);
    }

    /**
     * 批量删除考核评比
     *
     * @param ids 需要删除的考核评比主键
     * @return 结果
     */
    @Override
    public int deletePostAssessmentRatingByIds(Long[] ids) {
        return postAssessmentRatingMapper.deletePostAssessmentRatingByIds(ids);
    }

    /**
     * 删除考核评比信息
     *
     * @param id 考核评比主键
     * @return 结果
     */
    @Override
    public int deletePostAssessmentRatingById(Long id) {
        return postAssessmentRatingMapper.deletePostAssessmentRatingById(id);
    }
}
