package com.zd.laboratory.service.impl;

import cn.hutool.core.collection.ListUtil;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.core.utils.DateUtils;
import com.zd.common.core.utils.SecurityUtils;
import com.zd.common.security.utils.SaveUtil;
import com.zd.laboratory.domain.LabGradeManage;
import com.zd.laboratory.domain.LabGradeManageRuleUser;
import com.zd.laboratory.domain.LabSubjectAccessRecord;
import com.zd.laboratory.domain.vo.LabSecurityApplyVO;
import com.zd.laboratory.mapper.*;
import com.zd.laboratory.service.ILabGradeManageRecordService;
import com.zd.laboratory.service.ILabGradeManageWorkService;
import com.zd.laboratory.service.ILabMessageUserService;
import com.zd.laboratory.service.ILabSecurityApplyService;
import com.zd.system.api.laboratory.domain.LabGradeManageRecord;
import com.zd.system.api.laboratory.domain.LabGradeManageRecordDetail;
import com.zd.system.api.laboratory.domain.LabMessageUser;
import com.zd.system.api.laboratory.domain.vo.LabGradeManageWorkDetailVO;
import com.zd.system.api.laboratory.domain.vo.LabGradeManageWorkVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 分级管控管理Service业务层处理
 *
 * @author liubo
 * @date 2022-02-10
 */
@Service
public class LabGradeManageWorkServiceImpl implements ILabGradeManageWorkService {
    @Autowired
    private LabSubjectMapper labSubjectMapper;
    @Autowired
    private LabGradeManageMapper labGradeManageMapper;
    @Autowired
    private LabGradeManageRuleMapper labGradeManageRuleMapper;
    @Autowired
    private LabGradeManageRuleUserMapper labGradeManageRuleUserMapper;
    @Autowired
    private ILabGradeManageRecordService labGradeManageRecordService;
    @Autowired
    private LabSubjectAccessRecordMapper labSubjectAccessRecordMapper;
    @Autowired
    private LabGradeManageRecordMapper labGradeManageRecordMapper;
    @Autowired
    private LabGradeManageRecordDetailMapper labGradeManageRecordDetailMapper;
    @Autowired
    private ILabSecurityApplyService labSecurityApplyService;
    @Autowired
    private ILabMessageUserService messageUserService;

    @Override
    public List<LabGradeManageWorkVO> selectMyGradeManageWorkListV2(LabGradeManageWorkVO labGradeManageWork) {
        // 条件检索： 实验室名称，学院，分类，分级，执行周期
        List<LabGradeManageWorkVO> manageWorkVOList = labGradeManageMapper.selectLabGradeManageListByWorkList(labGradeManageWork);

        manageWorkVOList.forEach(w -> {
            List<Long> manageIds = w.getManageIds().stream().map(LabGradeManageWorkVO.ManageId::getManageId).collect(Collectors.toList());
            // 选择人员的数据
            w.setDetailList(labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType(3, manageIds, SecurityUtils.getUserId(), w.getSubId()));
        });

        LabSecurityApplyVO applyvo = new LabSecurityApplyVO();
        applyvo.setUserId(SecurityUtils.getUserId());
        List<LabSecurityApplyVO> applist = labSecurityApplyService.selectApplyListEffective(applyvo);
        // 实验室准入人员
        manageWorkVOList.forEach(w -> {
            applist.forEach(a -> {
                if (w.getSubId().equals(a.getSubjectId())) {
                    List<Long> manageIds = w.getManageIds().stream().map(LabGradeManageWorkVO.ManageId::getManageId).collect(Collectors.toList());
                    w.getDetailList().addAll(labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType(4, manageIds, SecurityUtils.getUserId(), w.getSubId()));
                }
            });
        });


        // 如果是实验室负责人，则组装负责人数据
        List<Long> ids = labSubjectMapper.selectSubIdByAdminId(SecurityUtils.getUserId());
        if (ids.size() > 0) {
            for (Long subId : ids) {
                manageWorkVOList.forEach(w -> {
                    if (w.getSubId().equals(subId)) {
                        List<Long> manageIds = w.getManageIds().stream().map(LabGradeManageWorkVO.ManageId::getManageId).collect(Collectors.toList());
                        w.getDetailList().addAll(
                                labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType(1, manageIds, SecurityUtils.getUserId(), w.getSubId())
                        );
                    }
                });
            }
        }

        List<LabSubjectAccessRecord> joinSubIds = labSubjectAccessRecordMapper.selectSubIdByUserId(SecurityUtils.getUserId());
        if (joinSubIds.size() > 0) {
            for (LabSubjectAccessRecord record : joinSubIds) {
                // 如果当天进入过实验室，则组装数据
                manageWorkVOList.forEach(w -> {
                    if (w.getSubId().equals(record.getSubjectId())) {
                        List<Long> manageIds = w.getManageIds().stream().map(LabGradeManageWorkVO.ManageId::getManageId).collect(Collectors.toList());
                        w.getDetailList().addAll(
                                labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType(2, manageIds, SecurityUtils.getUserId(), w.getSubId()));
                    }
                });
            }
        }

        // 去除没有工作的数据
        for (int i = 0; i < manageWorkVOList.size(); i++) {
            if (manageWorkVOList.get(i).getDetailList().size() == 0) {
                manageWorkVOList.remove(i);
                i--;
                continue;
            }
        }

        // 排序规则
        for (LabGradeManageWorkVO labGradeManageWorkVO : manageWorkVOList) {
            labGradeManageWorkVO.setDetailList(labGradeManageWorkVO.getDetailList().stream().sorted(
                    Comparator.comparing(LabGradeManageWorkDetailVO::getEndDate, Comparator.naturalOrder())).collect(Collectors.toList()));
            labGradeManageWorkVO.setEndDate(labGradeManageWorkVO.getDetailList().get(0).getEndDate());
        }
        manageWorkVOList = manageWorkVOList.stream().sorted(
                Comparator.comparing(LabGradeManageWorkVO::getEndDate, Comparator.naturalOrder())).collect(Collectors.toList());

        return manageWorkVOList;
    }

    @Override
    public LabGradeManageWorkVO queryByMessage(LabGradeManageRecord labGradeManageRecord) {

        if(labGradeManageRecord.getSubId() != null){
            LabGradeManageWorkVO labGradeManageWork = new LabGradeManageWorkVO();
            labGradeManageWork.setSubId(labGradeManageRecord.getSubId());
            List<LabGradeManageWorkVO> list = labGradeManageMapper.selectLabGradeManageListByWorkList(labGradeManageWork);
            if(list.size() > 0){
                LabGradeManageWorkVO data = list.get(0);

                data.setDetailList(labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByMessage(labGradeManageRecord.getRuleUserId()));
                return data;
            }
        }

        throw new ServiceException("管控工作已失效或未查询到数据！");
    }

    /**
     * 查询分级管控工作列表
     */
    @Override
    public List<LabGradeManageWorkVO> selectMyGradeManageWorkList(LabGradeManage labGradeManage) {

        // 查询登录用户管控工作的所有实验室 - 选择人员
        String subIds = labGradeManageMapper.selectSubIdsByUserId(SecurityUtils.getUserId());

        List<String> subs;
        if (StringUtils.isBlank(subIds)) {
            subs = ListUtil.empty();
        } else {
            subs = Arrays.asList(subIds.split(","));
        }


        // 根据实验室为单位查询工作列表
        List<LabGradeManageWorkVO> list = new ArrayList<>();
        LabGradeManageWorkVO labGradeManageWorkVO;
        for (String subId : subs) {
            if (StringUtils.isBlank(subId)) {
                continue;
            }

            labGradeManageWorkVO = labSubjectMapper.selectSubInfoByMyGradeManageWork(Long.parseLong(subId));
            if (labGradeManageWorkVO == null) {
                continue;
            }

            // 这里只是选择人员的数据
            labGradeManageWorkVO.setDetailList(labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType3(Long.parseLong(subId), SecurityUtils.getUserId()));

            list.add(labGradeManageWorkVO);
        }

        // 如果是实验室负责人，则组装负责人数据
        List<Long> ids = labSubjectMapper.selectSubIdByAdminId(SecurityUtils.getUserId());
        if (ids.size() > 0) {
            for (Long subId : ids) {
                List<Long> ruleUserIds = labGradeManageRuleUserMapper.selectType1ByAdminSubId(subId);
                if (ruleUserIds.size() > 0) {
                    if (subs.contains(subId + "")) {
                        for (LabGradeManageWorkVO gradeManageWorkVO : list) {

                            if (gradeManageWorkVO.getSubId().equals(subId)) {
                                gradeManageWorkVO.getDetailList().addAll(
                                        labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType1(ruleUserIds, SecurityUtils.getUserId(), subId)
                                );
                            }
                        }
                    } else {
                        labGradeManageWorkVO = labSubjectMapper.selectSubInfoByMyGradeManageWork(subId);
                        if (labGradeManageWorkVO == null) {
                            continue;
                        }

                        labGradeManageWorkVO.setDetailList(labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType1(ruleUserIds, SecurityUtils.getUserId(), subId));

                        list.add(labGradeManageWorkVO);
                    }
                }
            }
        }

        List<LabSubjectAccessRecord> joinSubIds = labSubjectAccessRecordMapper.selectSubIdByUserId(SecurityUtils.getUserId());

        if (joinSubIds.size() > 0) {
            for (LabSubjectAccessRecord record : joinSubIds) {
                // 如果当天进入过实验室，则组装数据
                List<LabGradeManageRuleUser> manageRuleUserList = labGradeManageRuleUserMapper.selectType2ByAdminSubId(record.getSubjectId());

                for (LabGradeManageRuleUser labGradeManageRuleUser : manageRuleUserList) {
                    labGradeManageRuleUser.setUserId(SecurityUtils.getUserId());
                    labGradeManageRuleUser.setSubId(record.getSubjectId());

                    if (subs.contains(record.getSubjectId() + "")) {
                        for (LabGradeManageWorkVO gradeManageWorkVO : list) {
                            if (gradeManageWorkVO.getSubId().equals(record.getSubjectId())) {

                                gradeManageWorkVO.getDetailList().addAll(
                                        labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType2(labGradeManageRuleUser)
                                );
                            }
                        }
                    } else {
                        labGradeManageWorkVO = labSubjectMapper.selectSubInfoByMyGradeManageWork(record.getSubjectId());
                        labGradeManageWorkVO.setDetailList(new ArrayList<>());
                        labGradeManageWorkVO.getDetailList().addAll(labGradeManageRuleMapper.selectMyLabGradeManageWorkDetailByType2(labGradeManageRuleUser));

                        list.add(labGradeManageWorkVO);
                    }
                }
            }
        }

        //如果有过期未执行的管控工作-也要查出来，并且可以完成（万马奔腾）
        List<LabGradeManageWorkDetailVO> expiredList = labGradeManageRecordMapper.selectExpiredByUserId(SecurityUtils.getUserId(), 1);
        if (expiredList.size() > 0) {
            Map<Long, List<LabGradeManageWorkDetailVO>> map = expiredList.stream().collect(Collectors.groupingBy(LabGradeManageWorkDetailVO::getSubId));

            List<LabGradeManageWorkVO> list1 = new ArrayList<>();

            for (Long k : map.keySet()) {
                List<LabGradeManageWorkDetailVO> v = map.get(k);

                for (LabGradeManageWorkVO gradeManageWorkVO : list) {
                    // 如果包含 则去除
                    v.removeAll(v.stream().filter(
                                    s -> gradeManageWorkVO.getDetailList().stream().filter(
                                                    f -> (f.getRecordId() != null && f.getRecordId().equals(s.getRecordId())))
                                            .findAny().isPresent())
                            .collect(Collectors.toList()));

                    if (gradeManageWorkVO.getSubId().equals(k)) {
                        gradeManageWorkVO.getDetailList().addAll(v);
                    } else {

                        if (v.size() == 0) {
                            continue;
                        }

                        LabGradeManageWorkVO expiredLabGradeManageWorkVO = labSubjectMapper.selectSubInfoByMyGradeManageWork(k);
                        if (expiredLabGradeManageWorkVO == null) {
                            continue;
                        }

                        expiredLabGradeManageWorkVO.setDetailList(v);

                        list1.add(expiredLabGradeManageWorkVO);
                    }
                }
            }

            if (list1.size() > 0) {
                list1 = list1.stream().filter(l -> l.getDetailList() != null && l.getDetailList().size() > 0).collect(Collectors.toList());
                list.addAll(list1);
            }
        }

        return list;
    }

    /**
     * 获取分级管控工作详细信息 - 已完成的
     */
    @Override
    public LabGradeManageRecord selectLabGradeManageWorkById(Long id) {
        return labGradeManageRecordService.selectLabGradeManageRecordById(id);
    }

    /**
     * 完成分级管控工作
     *
     * @return
     */
    @Override
    public LabGradeManageRecord finishMyLabGradeManageWorkById(LabGradeManageRecord labGradeManageRecord) {

        if (labGradeManageRecord.getId() != null) {
            // 2.7 修改之后，理论上不会走到这
            int count = labGradeManageRecordMapper.updateStatusById(labGradeManageRecord.getId());
            if (count == 0) {
                throw new ServiceException("参数异常, 或工作重复完成！");
            }
            LabGradeManageRecordDetail labGradeManageRecordDetail = labGradeManageRecord.getDetail();
            SaveUtil.setCommonAttr(labGradeManageRecordDetail);
            labGradeManageRecordDetail.setManageRecordId(labGradeManageRecord.getId());

            labGradeManageRecordDetailMapper.insertLabGradeManageRecordDetail(labGradeManageRecordDetail);
            return labGradeManageRecord;
        } else {

            // 此处需要校验 是否是多人执行，单人执行，只需要完成一次即可

            LabGradeManageRuleUser ruleUser = labGradeManageRuleUserMapper.selectLabGradeManageRuleUserById(labGradeManageRecord.getRuleUserId());
            if (ruleUser == null) {
                throw new ServiceException("参数异常！");
            }
            if (!ruleUser.getGradeManageRuleId().equals(labGradeManageRecord.getRuleId())) {
                throw new ServiceException("参数不匹配！");
            }
            if (ruleUser.getIsUpload() == 1 && StringUtils.isBlank(labGradeManageRecord.getDetail().getImgUrl())) {
                throw new ServiceException("上传材料不能为空！");
            }
            if(ruleUser.getIsAll() == 0){
                LabGradeManageRecord record = new LabGradeManageRecord();
                record.setRuleId(labGradeManageRecord.getRuleId());
                record.setRuleUserId(labGradeManageRecord.getRuleUserId());
                record.setCycleCount(ruleUser.getCycleCount());
                record.setStatus(2);
                List<LabGradeManageRecord> list = labGradeManageRecordMapper.selectLabGradeManageRecordList(record);
                if(list.size() > 0){
                    throw new ServiceException("该管控工作已经完成，无需重复执行！");
                }
            }

            labGradeManageRecord.setCycleCount(ruleUser.getCycleCount());
            labGradeManageRecord.setStatus(2);
            labGradeManageRecord.setCarryTime(DateUtils.getNowDate());

            /**
             * 管控执行完成，处理已产生的消息通知
             */
            if(labGradeManageRecord.getMessageUserId() != null){
                LabMessageUser labMessageUser = new LabMessageUser();
                labMessageUser.setId(labGradeManageRecord.getMessageUserId());
                messageUserService.readByLoginUser(labMessageUser);
            }

            return labGradeManageRecordService.insertLabGradeManageRecord(labGradeManageRecord);
        }

    }


    @Override
    public List<LabGradeManageWorkVO> finishList(LabGradeManageRecord labGradeManageRecord) {
        List<LabGradeManageWorkVO> list1 = new ArrayList<>();

        List<LabGradeManageWorkDetailVO> expiredList = labGradeManageRecordMapper.selectExpiredByUserId(SecurityUtils.getUserId(), 2);
        expiredList.addAll(labGradeManageRecordMapper.selectExpiredByUserId(SecurityUtils.getUserId(), 0));
        if (expiredList.size() > 0) {
            Map<Long, List<LabGradeManageWorkDetailVO>> map = expiredList.stream().collect(Collectors.groupingBy(LabGradeManageWorkDetailVO::getSubId));

            for (Long k : map.keySet()) {
                List<LabGradeManageWorkDetailVO> v = map.get(k);

                LabGradeManageWorkVO labGradeManageWorkVO = labSubjectMapper.selectSubInfoByMyGradeManageWork(k);

                if (labGradeManageWorkVO == null) {
                    continue;
                }

                labGradeManageWorkVO.setDetailList(v);

                list1.add(labGradeManageWorkVO);
            }
        }

        return list1;
    }

}
