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.DeptConstants;
import com.ruoyi.common.constant.PostPlanEnum;
import com.ruoyi.common.constant.PostProgrammeEnum;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.postCheck.domain.PostAssessmentRating;
import com.ruoyi.postCheck.domain.PostPlan;
import com.ruoyi.postCheck.domain.PostPlanCheckUser;
import com.ruoyi.postCheck.domain.PostPlanInfo;
import com.ruoyi.postCheck.mapper.PostAssessmentRatingMapper;
import com.ruoyi.postCheck.mapper.PostPlanInfoMapper;
import com.ruoyi.postCheck.mapper.PostPlanMapper;
import com.ruoyi.postCheck.service.IPostPlanCheckUserService;
import com.ruoyi.postCheck.service.IPostPlanInfoService;
import com.ruoyi.postCheck.service.IPostPlanService;
import org.apache.commons.lang3.StringUtils;
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.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 岗检计划Service业务层处理
 *
 * @author csg
 * @date 2023-12-19
 */
@Service
public class PostPlanServiceImpl extends ServiceImpl<PostPlanMapper, PostPlan> implements IPostPlanService {
    @Autowired
    private PostPlanMapper postPlanMapper;

    @Autowired
    private IPostPlanInfoService postPlanInfoService;

    @Autowired
    private PostAssessmentRatingMapper postAssessmentRatingMapper;


    @Autowired
    private PostPlanInfoMapper postPlanInfoMapper;
    @Autowired
    private IPostPlanCheckUserService postPlanCheckUserService;

    /**
     * 查询岗检计划
     *
     * @param id 岗检计划主键
     * @return 岗检计划
     */
    @Override
    public PostPlan selectPostPlanById(Long id) {
        PostPlan data = postPlanMapper.selectPostPlanById(id);
        if (data != null) {
            Long dataId = data.getId();
            PostPlanInfo info = new PostPlanInfo();
            info.setPostPlanId(dataId);
            List<PostPlanInfo> infoList = postPlanInfoService.selectPostPlanInfoList(info);
            data.setChildren(infoList);
        }
        return data;
    }

    /**
     * 查询岗检计划列表
     *
     * @param postPlan 岗检计划
     * @return 岗检计划
     */
    @Override
    public List<PostPlan> selectPostPlanList(PostPlan postPlan) {
        return postPlanMapper.selectPostPlanList(postPlan);
    }

    /**
     * 新增岗检计划
     *
     * @param postPlan 岗检计划
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertPostPlan(PostPlan postPlan) {
        //TODO 自增主键修改为-MyBatis-Plus雪花算法(截取5位解决VUE精度丢失BUG)-系统登录日志
//        if (postPlan.getId() == null)
        postPlan.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
        postPlan.setCreateDefault();
        postPlan.setCreateUserId(SecurityUtils.getUserId());
        postPlan.setStatus(PostPlanEnum.STATUS_WAIT.getValue());//待审核
        int rows = postPlanMapper.insertPostPlan(postPlan);
        if (rows > 0) {
            //添加检查人员
            List<PostPlanCheckUser> checkUserChildren = postPlan.getCheckUserChildren();
            if (CollectionUtils.isEmpty(checkUserChildren)) {
                int index = 0;
                for (PostPlanCheckUser checkUserChild : checkUserChildren) {
                    checkUserChild.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
                    checkUserChild.setPostPlanId(postPlan.getId());
                    checkUserChild.setCreateDefault();
                    //检查人员ID：1-组长；2-组员；
                    if (index++ == 0) {
                        checkUserChild.setType(1);
                    } else {
                        checkUserChild.setType(2);
                    }
                }
                postPlanCheckUserService.saveBatch(checkUserChildren);
            }


            List<PostPlanInfo> children = postPlan.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                for (PostPlanInfo child : children) {
                    child.setPostPlanId(postPlan.getId());
                    postPlanInfoService.insertPostPlanInfo(child);
                }
            }
        }

        return rows;
    }

    /**
     * 修改岗检计划
     *
     * @param postPlan 岗检计划
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updatePostPlan(PostPlan postPlan) {
        postPlan.setUpdateDefault();
        int rows = postPlanMapper.updatePostPlan(postPlan);

        if (rows > 0) {
            //删除检查人员
            LambdaUpdateWrapper<PostPlanCheckUser> updateWrapperCheckUser = new LambdaUpdateWrapper<>();
            updateWrapperCheckUser.eq(PostPlanCheckUser::getPostPlanId,postPlan.getId());
            postPlanCheckUserService.remove(updateWrapperCheckUser);

            //新增检查人员
            List<PostPlanCheckUser> checkUserChildren = postPlan.getCheckUserChildren();
            if (CollectionUtils.isEmpty(checkUserChildren)) {
                int index = 0;
                for (PostPlanCheckUser checkUserChild : checkUserChildren) {
                    checkUserChild.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
                    checkUserChild.setPostPlanId(postPlan.getId());
                    checkUserChild.setCreateDefault();
                    //检查人员ID：1-组长；2-组员；
                    if (index++ == 0) {
                        checkUserChild.setType(1);
                    } else {
                        checkUserChild.setType(2);
                    }
                }
                postPlanCheckUserService.saveBatch(checkUserChildren);
            }

            //删除明细
            LambdaUpdateWrapper<PostPlanInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(PostPlanInfo::getPostPlanId, postPlan.getId());
            postPlanInfoMapper.delete(updateWrapper);

            //新增明细
            List<PostPlanInfo> children = postPlan.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                for (PostPlanInfo child : children) {
                    child.setPostPlanId(postPlan.getId());
                    postPlanInfoService.insertPostPlanInfo(child);
                }
            }
        }

        return rows;
    }

    /**
     * 批量删除岗检计划
     *
     * @param ids 需要删除的岗检计划主键
     * @return 结果
     */
    @Override
    public int deletePostPlanByIds(Long[] ids) {
        return postPlanMapper.deletePostPlanByIds(ids);
    }

    /**
     * 删除岗检计划信息
     *
     * @param id 岗检计划主键
     * @return 结果
     */
    @Override
    public int deletePostPlanById(Long id) {
        return postPlanMapper.deletePostPlanById(id);
    }

    /**
     * 审核1：岗检方案审核-Icfa
     *
     * @param id         主键ID
     * @param statusIcfa 2-内控法务部审批-状态：1-待审核；3-通过；4-驳回；
     * @param reasonIcfa 2-内控法务部审批-未通过理由
     * @return
     */
    @Override
    public int approveIcfa(Long id, Integer statusIcfa, String reasonIcfa) {

        if (id == null || statusIcfa == null) {
            return 0;
        }

        //状态错误
        if (statusIcfa != PostPlanEnum.STATUS_ICFA_PASS.getValue() && statusIcfa != PostPlanEnum.STATUS_ICFA_BACK.getValue()) {
            return 0;
        }

        //未写理由
        if (statusIcfa == PostPlanEnum.STATUS_ICFA_BACK.getValue() && StringUtils.isBlank(reasonIcfa)) {
            return 0;
        }

        PostPlan data = new PostPlan();
        data.setId(id);
        data.setStatusIcfa(statusIcfa);
        data.setReasonIcfa(reasonIcfa);

        if (statusIcfa == PostPlanEnum.STATUS_ICFA_PASS.getValue()) {
            data.setStep(PostPlanEnum.STEP_ICFA.getValue());
            data.setStatus(PostPlanEnum.STATUS_ING.getValue());//审核中
        } else {
            data.setStatus(PostPlanEnum.STATUS_BACK.getValue());//驳回
        }
        return postPlanMapper.updatePostPlan(data);
    }

    /**
     * 审核2：岗检方案审核-HR
     *
     * @param id       主键ID
     * @param statusHr 1-人力资源审批-状态：1-待审核；3-通过；4-驳回；
     * @param reasonHr 1-人力资源审批-未通过理由
     * @return
     */
    @Override
    public int approveHr(Long id, Integer statusHr, String reasonHr) {
        if (id == null || statusHr == null) {
            return 0;
        }

        //状态错误
        if (statusHr != PostPlanEnum.STATUS_HR_PASS.getValue() && statusHr != PostPlanEnum.STATUS_HR_BACK.getValue()) {
            return 0;
        }

        //未写理由
        if (statusHr == PostPlanEnum.STATUS_HR_BACK.getValue() && StringUtils.isBlank(reasonHr)) {
            return 0;
        }

        PostPlan data = new PostPlan();
        data.setId(id);
        data.setStatusHr(statusHr);
        data.setReasonHr(reasonHr);

        data.setStatus(statusHr);//最终审核结果

        if(statusHr==PostPlanEnum.STATUS_ICFA_PASS.getValue()){
            data.setStep(PostPlanEnum.STEP_HR.getValue());
            // 如果审核通过开始初始化岗检排名表
            initializationPostAssessmentRating(id);

        }
        return postPlanMapper.updatePostPlan(data);
    }

    public void initializationPostAssessmentRating(Long id) {
        PostPlan postPlan = postPlanMapper.selectById(id);
        // 查询被检查部门

        List<PostPlanInfo> postPlanInfos = postPlanInfoMapper.selectList(Wrappers.<PostPlanInfo>lambdaQuery().eq(PostPlanInfo::getPostPlanId, id));
        if (postPlan!=null && !postPlanInfos.isEmpty()){
            Map<Long, List<PostPlanInfo>> postMap = postPlanInfos.stream().collect(Collectors.groupingBy(PostPlanInfo::getCheckedDeptId));
            for (Map.Entry<Long, List<PostPlanInfo>> longListEntry : postMap.entrySet()) {
                Long key = longListEntry.getKey();
                PostAssessmentRating rating = new PostAssessmentRating();
                rating.setId(Long.parseLong(IdWorker.getIdStr().substring(4)));
                String sysDeptName = postAssessmentRatingMapper.getSysDeptName(key);
                if (DeptConstants.FunctionalDepartment.contains(sysDeptName)){
                    // 在这是职能部门
                    rating.setType(1);
                }else{
                    // 生产部门
                    rating.setType(2);
                }
                rating.setDeptId(key);
                rating.setPlanId(postPlan.getId());
                rating.setPlanStartTime(postPlan.getStartTime());
                rating.setPlanEndTime(postPlan.getEndTime());
                rating.setPeerEvaluationScore(new BigDecimal("100"));
                rating.setPositionScore(new BigDecimal("100"));
                rating.setDepartmentScore(new BigDecimal("100"));
                rating.setCreateDefault();
                postAssessmentRatingMapper.insert(rating);
            }
        }
    }



}
