package com.ruoyi.postCheck.service.impl;

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.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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
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;

    /**
     * 查询打分表(职能互评生产日常)
     *
     * @param id 打分表(职能互评生产日常)主键
     * @return 打分表(职能互评生产日常)
     */
    @Override
    public PostAssessmentRatingOther selectPostAssessmentRatingOtherById(Long id) {
        PostAssessmentRatingOther data = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherById(id);
        List<PostAssessmentRatingOther> postAssessmentRatingOthers = postAssessmentRatingOtherMapper.selectList(Wrappers.<PostAssessmentRatingOther>lambdaQuery()
                .eq(PostAssessmentRatingOther::getBatchId,data.getBatchId())
        );
        if (postAssessmentRatingOthers.isEmpty()){
            return new PostAssessmentRatingOther();
        }
//        String[] deptArr = new String[]{"健康安全环保中心", "生产指挥中心", "设备管理中心", "技术中心", "仓储组", "党建工作部", "内控法务部", "人力资源部", "商务部", "办公室", "规划计划部", "信息中心", "财务资金部"};
        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) {
            PostAssessmentRatingOtherInfo child1 = new PostAssessmentRatingOtherInfo();
// "评分分类/项目/专业：职责类别：1-业务职责；2-党建及党风廉政；3-安全环保职责；4-合规与保密职责；5-任职资格与能力素质要求；6-岗位责任制文件完整性与适宜性；
// 10-工作态度；11-部门协作；12-廉洁从业；13-主要工作完成情况；
// 20-HSE；21-生产；22-设备；")
            child1.setDutyType(postAssessmentRule.getDutyType());
            child1.setScoreWeight(new BigDecimal(postAssessmentRule.getFullScore()));
            List<PostAssessmentRatingOtherInfoDept> children1 = new ArrayList<>();
            for (PostAssessmentRatingOther postAssessmentRatingOther : postAssessmentRatingOthers) {
                List<PostAssessmentRatingOtherInfo> postAssessmentRatingOtherInfos = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                        .eq(PostAssessmentRatingOtherInfo::getRatingOtherId,postAssessmentRatingOther.getId())
                        .eq(PostAssessmentRatingOtherInfo::getDutyType,postAssessmentRule.getDutyType())
                );
                BigDecimal distance = new BigDecimal("0");
                if (postAssessmentRatingOtherInfos.isEmpty()){
                    continue;
                }
                distance = postAssessmentRatingOtherInfos.get(0).getByDeptScore();
                children1.add(new PostAssessmentRatingOtherInfoDept(postAssessmentRatingOtherInfos.get(0).getId(),postAssessmentRatingOther.getDeptId(), postAssessmentRatingMapper.getSysDeptName(postAssessmentRatingOther.getDeptId()), distance));
            }
            child1.setChildren(children1);
            children.add(child1);
        }
        data.setChildren(children);
        return data;
    }

    /**
     * 查询打分表(职能互评生产日常)列表
     *
     * @param postAssessmentRatingOther 打分表(职能互评生产日常)
     * @return 打分表(职能互评生产日常)
     */
    @Override
    public List<PostAssessmentRatingOther> selectPostAssessmentRatingOtherList(PostAssessmentRatingOther postAssessmentRatingOther) {
        List<PostAssessmentRatingOther> list = postAssessmentRatingOtherMapper.selectPostAssessmentRatingOtherListGroup(postAssessmentRatingOther);
        if (list.isEmpty()){
            return new ArrayList<>();
        }
        List<Long> collect = list.stream().map(PostAssessmentRatingOther::getId).collect(Collectors.toList());
        List<PostAssessmentRatingOtherInfo> children = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                .in(PostAssessmentRatingOtherInfo::getRatingOtherId,collect)
        );
        for (PostAssessmentRatingOther assessmentRatingOther : list) {
            List<PostAssessmentRatingOtherInfo> collect1 = children.stream().filter(d -> d.getRatingOtherId().equals(assessmentRatingOther.getId())).collect(Collectors.toList());
            assessmentRatingOther.setChildren(collect1);
        }
        return list;
    }

    /**
     * 新增打分表(职能互评生产日常)
     *
     * @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);
    }

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

        Integer type = postAssessmentRatingOther.getType();//类型：1-职能互评；2-生产日常；
        Date startTime = postAssessmentRatingOther.getStartTime();//评分开始时间（管理员创建的）
        if (type == null || startTime == null) {
            return 0;
        }

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

        List<PostAssessmentRules> postAssessmentRules = new ArrayList<>();
        //初始化13个职能部门评分 类型：1-职能互评；
        if (type == PostAssessmentRatingOtherEnum.TYPE_ZN_HP.getValue()) {
            postAssessmentRules = postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
                    .eq(PostAssessmentRules::getType,2)
            );
        }

        //初始化13个生产部门评分 类型：2-生产日常；
        if (type == PostAssessmentRatingOtherEnum.TYPE_SC_RC.getValue()) {
            postAssessmentRules =postAssessmentRulesMapper.selectList(Wrappers.<PostAssessmentRules>lambdaQuery()
                    .eq(PostAssessmentRules::getType,3)
            );

        }
        List<Long> deptIdList = postAssessmentRatingOtherMapper.getDeptIdList(postAssessmentRatingOther.getDeptId());
        String string = UUID.randomUUID().toString();
        for (Long deptId : deptIdList) {
            PostAssessmentRatingOther postAssessmentRatingOtherOther =new PostAssessmentRatingOther();
            postAssessmentRatingOtherOther.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
            postAssessmentRatingOtherOther.setType(type);
            postAssessmentRatingOtherOther.setBatchId(string);
            postAssessmentRatingOtherOther.setStartTime(new Date());
            postAssessmentRatingOtherOther.setStatus(1);
            postAssessmentRatingOtherOther.setDeptId(deptId);
            postAssessmentRatingOtherOther.setCreateDefault();
            postAssessmentRatingOtherOther.setCreateUserId(SecurityUtils.getLoginUser().getUserId());
            postAssessmentRatingOtherMapper.insert(postAssessmentRatingOtherOther);
            if(!postAssessmentRules.isEmpty()){
                for (PostAssessmentRules postAssessmentRule : postAssessmentRules) {
                    PostAssessmentRatingOtherInfo info = new PostAssessmentRatingOtherInfo();
                    info.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
                    info.setRatingOtherId(postAssessmentRatingOtherOther.getId());
                    info.setDutyType(postAssessmentRule.getDutyType());
                    info.setScoreWeight(new BigDecimal(postAssessmentRule.getFullScore()));
                    info.setByDeptId(deptId);
                    info.setCreateDefault();
                    postAssessmentRatingOtherInfoMapper.insert(info);
                }

            }
        }
        return 1;
    }

    @Override
    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());
        List<PostAssessmentRatingOtherInfo> info = postAssessmentRatingOtherInfoMapper.selectList(Wrappers.<PostAssessmentRatingOtherInfo>lambdaQuery()
                .in(PostAssessmentRatingOtherInfo::getRatingOtherId,collect)
        );
        List<PostAssessmentRatingOtherInfo> children = postAssessmentRatingOther.getChildren();
        children.forEach(x->{
            List<PostAssessmentRatingOtherInfoDept> dept = x.getChildren();
            dept.forEach(y->{
                List<PostAssessmentRatingOtherInfo> collect1 = info.stream().filter(d -> d.getByDeptId().equals(y.getByDeptId()) && d.getDutyType().equals(x.getDutyType())).collect(Collectors.toList());
                for (PostAssessmentRatingOtherInfo postAssessmentRatingOtherInfo : collect1) {
                    postAssessmentRatingOtherInfo.setUpdateDefault();
                    postAssessmentRatingOtherInfo.setByDeptScore(y.getByDeptScore());
                    postAssessmentRatingOtherInfoMapper.updateById(postAssessmentRatingOtherInfo);
                }
            });
        });
        return 1;
    }

    @Override
    public int productionDepartmentSub(List<PostAssessmentRatingOther> postAssessmentRatingOther) {
        for (PostAssessmentRatingOther assessmentRatingOther : postAssessmentRatingOther) {
            List<PostAssessmentRatingOtherInfo> children = assessmentRatingOther.getChildren();
            children.forEach(x->{
                PostAssessmentRatingOtherInfo info = new PostAssessmentRatingOtherInfo();
                info.setId(x.getId());
                info.setByDeptScore(x.getByDeptScore());
                info.setUpdateDefault();
                postAssessmentRatingOtherInfoMapper.updateById(info);
            });
        }
        return 1;
    }

}
