package com.hotwj.platform.securityManagement.training.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.flow.service.ISysFlowService;
import com.hotwj.platform.noticeManagerment.systemNotification.domain.bo.HotSystemNotificationGroupBo;
import com.hotwj.platform.noticeManagerment.systemNotification.service.IHotSystemNotificationService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.HotCompanySafetyManager;
import com.hotwj.platform.resourceManagement.companySafetyManager.mapper.HotCompanySafetyManagerMapper;
import com.hotwj.platform.securityManagement.training.domain.HotTraining;
import com.hotwj.platform.securityManagement.training.domain.bo.HotTrainingBo;
import com.hotwj.platform.securityManagement.training.domain.vo.HotTrainingVo;
import com.hotwj.platform.securityManagement.training.mapper.HotTrainingMapper;
import com.hotwj.platform.securityManagement.training.service.IHotTrainingService;
import com.hotwj.platform.securityManagement.trainingParticipant.domain.HotTrainingParticipant;
import com.hotwj.platform.securityManagement.trainingParticipant.mapper.HotTrainingParticipantMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 安全教育培训-培训主Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-17
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotTrainingServiceImpl implements IHotTrainingService {

    private static final String FLOW_CODE_TRAINING_STUDY = "TRAINING_STUDY";

    private final HotTrainingMapper baseMapper;
    private final HotCompanySafetyManagerMapper managerMapper;
    private final HotTrainingParticipantMapper participantMapper;
    private final ISysFlowService flowService;
    private final IHotSystemNotificationService notificationService;

    /**
     * 查询安全教育培训-培训主
     *
     * @param id 主键
     * @return 安全教育培训-培训主
     */
    @Override
    public HotTrainingVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询安全教育培训-培训主列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 安全教育培训-培训主分页列表
     */
    @Override
    public TableDataInfo<HotTrainingVo> queryPageList(HotTrainingBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotTraining> lqw = buildQueryWrapper(bo);
        Page<HotTrainingVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的安全教育培训-培训主列表
     *
     * @param bo 查询条件
     * @return 安全教育培训-培训主列表
     */
    @Override
    public List<HotTrainingVo> queryList(HotTrainingBo bo) {
        LambdaQueryWrapper<HotTraining> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotTraining> buildQueryWrapper(HotTrainingBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotTraining> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotTraining::getCreateTime);
        lqw.eq(bo.getCompanyId() != null, HotTraining::getCompanyId, bo.getCompanyId());
        lqw.like(StringUtils.isNotBlank(bo.getPlanName()), HotTraining::getPlanName, bo.getPlanName());
        lqw.eq(StringUtils.isNotBlank(bo.getPersonType()), HotTraining::getPersonType, bo.getPersonType());
        lqw.eq(bo.getStartTime() != null, HotTraining::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, HotTraining::getEndTime, bo.getEndTime());
        lqw.eq(bo.getClassHours() != null, HotTraining::getClassHours, bo.getClassHours());
        lqw.eq(StringUtils.isNotBlank(bo.getPaperIds()), HotTraining::getPaperIds, bo.getPaperIds());
        lqw.eq(StringUtils.isNotBlank(bo.getTrainingLocation()), HotTraining::getTrainingLocation, bo.getTrainingLocation());
        lqw.like(StringUtils.isNotBlank(bo.getTeacherName()), HotTraining::getTeacherName, bo.getTeacherName());
        lqw.eq(StringUtils.isNotBlank(bo.getPlanOwner()), HotTraining::getPlanOwner, bo.getPlanOwner());
        lqw.eq(bo.getTotalCount() != null, HotTraining::getTotalCount, bo.getTotalCount());
        lqw.eq(bo.getPassedCount() != null, HotTraining::getPassedCount, bo.getPassedCount());
        lqw.eq(bo.getIncompleteCount() != null, HotTraining::getIncompleteCount, bo.getIncompleteCount());
        lqw.eq(bo.getPendingReviewCount() != null, HotTraining::getPendingReviewCount, bo.getPendingReviewCount());
        lqw.eq(bo.getIsEnabled() != null, HotTraining::getIsEnabled, bo.getIsEnabled());
        lqw.eq(bo.getIsMakeUp() != null, HotTraining::getIsMakeUp, bo.getIsMakeUp());
        lqw.eq(bo.getIsIssued() != null, HotTraining::getIsIssued, bo.getIsIssued());
        lqw.eq(bo.getIssuedCompanyId() != null, HotTraining::getIssuedCompanyId, bo.getIssuedCompanyId());
        lqw.eq(StringUtils.isNotBlank(bo.getCourseIds()), HotTraining::getCourseIds, bo.getCourseIds());
        lqw.eq(StringUtils.isNotBlank(bo.getTrainingType()), HotTraining::getTrainingType, bo.getTrainingType());
        lqw.eq(StringUtils.isNotBlank(bo.getParticipantIds()), HotTraining::getParticipantIds, bo.getParticipantIds());
        lqw.eq(StringUtils.isNotBlank(bo.getAssessmentDetail()), HotTraining::getAssessmentDetail, bo.getAssessmentDetail());
        lqw.eq(StringUtils.isNotBlank(bo.getReviewFlow()), HotTraining::getReviewFlow, bo.getReviewFlow());
        lqw.eq(StringUtils.isNotBlank(bo.getMeetingType()), HotTraining::getMeetingType, bo.getMeetingType());
        lqw.eq(StringUtils.isNotBlank(bo.getMeetingCategory()), HotTraining::getMeetingCategory, bo.getMeetingCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getIndustryType()), HotTraining::getIndustryType, bo.getIndustryType());

        if (params != null) {
            Object startBeginDate = params.get("startBeginDate");
            Object startEndDate = params.get("startEndDate");
            Object endBeginDate = params.get("endBeginDate");
            Object endEndDate = params.get("endEndDate");
            if (startBeginDate instanceof java.util.Date) {
                lqw.ge(HotTraining::getStartTime, (java.util.Date) startBeginDate);
            }
            if (startEndDate instanceof java.util.Date) {
                lqw.le(HotTraining::getStartTime, (java.util.Date) startEndDate);
            }
            if (endBeginDate instanceof java.util.Date) {
                lqw.ge(HotTraining::getEndTime, (java.util.Date) endBeginDate);
            }
            if (endEndDate instanceof java.util.Date) {
                lqw.le(HotTraining::getEndTime, (java.util.Date) endEndDate);
            }
        }
        lqw.eq(bo.getIsDeleted() != null, HotTraining::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增安全教育培训-培训主
     *
     * @param bo 安全教育培训-培训主
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(HotTrainingBo bo) {
        HotTraining add = MapstructUtils.convert(bo, HotTraining.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改安全教育培训-培训主
     *
     * @param bo 安全教育培训-培训主
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(HotTrainingBo bo) {
        HotTraining update = MapstructUtils.convert(bo, HotTraining.class);
        validEntityBeforeSave(update);
        HotTraining before = baseMapper.selectById(update.getId());
        boolean ok = baseMapper.updateById(update) > 0;
        if (ok && before != null) {
            HotTraining after = baseMapper.selectById(update.getId());
            syncTrainingStudyVisibilityOnGain(before, after);
            Long oldHours = before.getClassHours();
            Long newHours = update.getClassHours();
            boolean hoursConfigured = newHours != null && !newHours.equals(oldHours);
            if (hoursConfigured && update.getCompanyId() != null) {
                java.util.List<HotCompanySafetyManager> managers = managerMapper.selectList(
                        com.baomidou.mybatisplus.core.toolkit.Wrappers.<HotCompanySafetyManager>lambdaQuery()
                                .eq(HotCompanySafetyManager::getCompanyId, update.getCompanyId())
                                .eq(HotCompanySafetyManager::getIsDeleted, 0L)
                                .eq(HotCompanySafetyManager::getIsResigned, 0L)
                                .eq(HotCompanySafetyManager::getStatus, 1L)
                );
                if (managers != null && !managers.isEmpty()) {
                    java.util.List<String> receiverIds = managers.stream().map(m -> String.valueOf(m.getId())).toList();
                    String planName = org.dromara.common.core.utils.StringUtils.blankToDefault(update.getPlanName(), "培训计划");
                    HotSystemNotificationGroupBo bos = new HotSystemNotificationGroupBo();
                    bos.setLevel("普通");
                    bos.setContent(planName + "培训计划课时已配置，当前计划已可启用下发。");
                    bos.setSourceType("培训计划");
                    bos.setSenderType("SYSTEM");
                    bos.setReceiverType("管理员");
                    bos.setReceiverIds(receiverIds);
                    bos.setIsDeleted(0L);
                    try {
                        notificationService.insertByBo(bos);
                    } catch (Exception e) {
                        log.warn("培训课时配置通知失败 companyId={} trainingId={}", update.getCompanyId(), update.getId(), e);
                    }
                }
            }
        }
        return ok;
    }

    private void syncTrainingStudyVisibilityOnGain(HotTraining before, HotTraining after) {
        if (before == null || after == null || after.getId() == null) {
            return;
        }
        Date now = new Date();
        if (isTrainingStudyAccessible(before, now) || !isTrainingStudyAccessible(after, now)) {
            return;
        }
        List<HotTrainingParticipant> participants = participantMapper.selectList(
                Wrappers.<HotTrainingParticipant>lambdaQuery()
                        .eq(HotTrainingParticipant::getTrainingId, after.getId())
                        .eq(HotTrainingParticipant::getIsDeleted, 0L)
        );
        if (participants == null || participants.isEmpty()) {
            return;
        }

        Long companyId = after.getCompanyId();
        String title = "安全教育培训：" + StringUtils.blankToDefault(after.getPlanName(), "培训");
        String businessId = String.valueOf(after.getId());
        List<String> driverIds = new ArrayList<>();
        List<String> managerIds = new ArrayList<>();

        for (HotTrainingParticipant participant : participants) {
            if (participant == null || StringUtils.isBlank(participant.getUserId())) {
                continue;
            }
            if (Long.valueOf(1L).equals(participant.getIsCompleted())) {
                continue;
            }
            if (flowService.hasPendingTask(FLOW_CODE_TRAINING_STUDY, businessId, participant.getUserId())) {
                collectNotificationReceiver(participant, driverIds, managerIds);
                continue;
            }
            try {
                flowService.pushDirectTodo(FLOW_CODE_TRAINING_STUDY, businessId, title, companyId, participant.getUserId());
                collectNotificationReceiver(participant, driverIds, managerIds);
            } catch (Exception e) {
                log.warn("培训恢复可见后补发待办失败 trainingId={} userId={} err={}", after.getId(), participant.getUserId(), e.getMessage());
            }
        }

        sendTrainingStudyNotifications(after, driverIds, "驾驶员");
        sendTrainingStudyNotifications(after, managerIds, "管理员");
    }

    private void collectNotificationReceiver(HotTrainingParticipant participant, List<String> driverIds, List<String> managerIds) {
        if (participant == null || StringUtils.isBlank(participant.getUserId())) {
            return;
        }
        if (Long.valueOf(2L).equals(participant.getPersonType())) {
            managerIds.add(participant.getUserId());
        } else {
            driverIds.add(participant.getUserId());
        }
    }

    private void sendTrainingStudyNotifications(HotTraining training, List<String> receiverIds, String receiverType) {
        if (training == null || receiverIds == null || receiverIds.isEmpty()) {
            return;
        }
        HotSystemNotificationGroupBo msg = new HotSystemNotificationGroupBo();
        msg.setLevel("普通");
        msg.setSourceType("安全教育培训");
        msg.setSenderType("SYSTEM");
        msg.setReceiverType(receiverType);
        msg.setReceiverIds(receiverIds);
        msg.setContent("您有一个" + StringUtils.blankToDefault(training.getPlanName(), "培训") + "培训需要进行学习");
        msg.setIsDeleted(0L);
        try {
            notificationService.insertByBo(msg);
        } catch (Exception e) {
            log.warn("培训恢复可见后发送系统消息失败 trainingId={} receiverType={} count={} err={}",
                    training.getId(), receiverType, receiverIds.size(), e.getMessage());
        }
    }

    private boolean isTrainingStudyAccessible(HotTraining training, Date now) {
        if (training == null || now == null) {
            return false;
        }
        if (!Long.valueOf(1L).equals(training.getIsEnabled())) {
            return false;
        }
        if (training.getStartTime() == null || training.getEndTime() == null) {
            return false;
        }
        if (training.getStartTime().after(now)) {
            return false;
        }
        if (!training.getEndTime().before(now)) {
            return true;
        }
        return Long.valueOf(1L).equals(training.getIsMakeUp());
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotTraining entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除安全教育培训-培训主信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
