package com.srs.routine.service.impl;
import java.util.List;
import java.util.stream.Collectors;
import java.util.ArrayList;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.WeChatUtil;
import com.srs.routine.domain.NotificationManagement;
import com.srs.comprehensive.domain.SrsGrade;
import com.srs.routine.domain.dto.SendNotificationDto;
import com.srs.routine.mapper.NotificationManagementMapper;
import com.srs.routine.service.INotificationManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 通知管理Service业务层处理
 *
 * @author srs
 * @date 2025-07-30
 */
@Service
public class NotificationManagementServiceImpl extends ServiceImpl<NotificationManagementMapper,NotificationManagement> implements INotificationManagementService {
    @Autowired
    private NotificationManagementMapper notificationManagementMapper;

    @Autowired
    public WeChatUtil weChatUtil;

    /**
     * 查询通知管理
     *
     * @param id 通知管理主键
     * @return 通知管理
     */
    @Override
    public NotificationManagement selectNotificationManagementById(Long id) {
        return notificationManagementMapper.selectNotificationManagementById(id);
    }

    /**
     * 查询通知管理列表
     *
     * @param notificationManagement 通知管理
     * @return 通知管理集合
     */
    @Override
    public List<NotificationManagement> selectNotificationManagementList(NotificationManagement notificationManagement) {
        return notificationManagementMapper.selectNotificationManagementList(notificationManagement);
    }

    /**
     * 新增通知管理
     *
     * @param notificationManagement 通知管理
     * @return 结果
     */
    @Override
    public int insertNotificationManagement(NotificationManagement notificationManagement) {
        notificationManagement.setCreateTime(DateUtils.getNowDate());
        notificationManagement.setCreateBy(SecurityUtils.getUsername());
        return notificationManagementMapper.insertNotificationManagement(notificationManagement);
    }

    /**
     * 修改通知管理
     *
     * @param notificationManagement 通知管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updateNotificationManagement(NotificationManagement notificationManagement) {
        // 获取修改前的通知信息
        NotificationManagement originalNotification = selectNotificationManagementById(notificationManagement.getId());

        // 更新srs_notification表
        notificationManagement.setUpdateTime(DateUtils.getNowDate());
        notificationManagement.setUpdateBy(SecurityUtils.getUsername());
        int result = notificationManagementMapper.updateNotificationManagement(notificationManagement);

        // 如果更新成功，同步更新cph_msg表数据
        if (result > 0 && originalNotification != null) {
            // 构建更新条件：根据原内容、发送人和创建时间匹配
            List<NotificationManagement> updateList = new ArrayList<>();
            updateList.add(originalNotification);

            // 构建新数据用于更新
            List<NotificationManagement> newList = new ArrayList<>();
            NotificationManagement newMsg = new NotificationManagement();
            newMsg.setContent(notificationManagement.getContent());
            newMsg.setSender(notificationManagement.getSender());
            newMsg.setCreateTime(originalNotification.getCreateTime()); // 保持原创建时间不变
            newList.add(newMsg);

            // 批量更新cph_msg表
            notificationManagementMapper.batchUpdateCphMsg(updateList, newList);
        }

        return result;
    }

    /**
     * 批量删除通知管理
     *
     * @param ids 需要删除的通知管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNotificationManagementByIds(Long[] ids) {
        // 先删除相关的cph_msg表数据
        List<NotificationManagement> notifications = new ArrayList<>();
        for (Long id : ids) {
            NotificationManagement notification = selectNotificationManagementById(id);
            if (notification != null) {
                notifications.add(notification);
            }
        }

        if (!notifications.isEmpty()) {
            notificationManagementMapper.batchDeleteCphMsg(notifications);
        }

        // 删除srs_notification表数据
        return notificationManagementMapper.deleteNotificationManagementByIds(ids);
    }

    /**
     * 删除通知管理信息
     *
     * @param id 通知管理主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNotificationManagementById(Long id) {
        // 先删除相关的cph_msg表数据
        NotificationManagement notification = selectNotificationManagementById(id);
        if (notification != null) {
            List<NotificationManagement> notifications = new ArrayList<>();
            notifications.add(notification);
            notificationManagementMapper.batchDeleteCphMsg(notifications);
        }

        // 删除srs_notification表数据
        return notificationManagementMapper.deleteNotificationManagementById(id);
    }

    /**
     * 获取年级列表
     *
     * @return 年级列表
     */
    @Override
    public List<SrsGrade> getGradeList() {
        return notificationManagementMapper.selectGradeList();
    }

    /**
     * 按年级发送通知
     *
     * @param sendNotificationDto 发送通知DTO
     * @return 结果
     */
    @Override
    @Transactional
    public int sendNotificationByGrades(SendNotificationDto sendNotificationDto) {
        // 1. 先插入srs_notification表
        NotificationManagement notification = new NotificationManagement();
        notification.setTitle(sendNotificationDto.getTitle());
        notification.setContent(sendNotificationDto.getContent());
        notification.setGradeIds(String.join(",", sendNotificationDto.getSelectedGrades()));
        notification.setSender(SecurityUtils.getUserId());
        notification.setCreateTime(DateUtils.getNowDate());
        notification.setCreateBy(SecurityUtils.getUsername());

        int result = notificationManagementMapper.insertNotificationManagement(notification);

        // 2. 如果插入成功，向cph_msg表插入学生通知记录
        if (result > 0) {
            // 根据年级获取学生用户ID列表
            List<Long> studentIds = notificationManagementMapper.selectStudentIdsByGrades(sendNotificationDto.getSelectedGrades());

            if (studentIds != null && !studentIds.isEmpty()) {
                // 使用srs_notification表的create_time，确保两个表的时间一致
                java.util.Date notificationCreateTime = notification.getCreateTime();

                // 批量构建cph_msg记录
                List<NotificationManagement> cphMsgList = studentIds.stream()
                        .map(studentId -> {
                            NotificationManagement msg = new NotificationManagement();
                            msg.setSender(SecurityUtils.getUserId());
                            msg.setReceiver(studentId);
                            msg.setContent(sendNotificationDto.getContent());
                            msg.setCreateTime(notificationCreateTime);
                            return msg;
                        })
                        .collect(Collectors.toList());

                // 批量插入cph_msg表
                int i= notificationManagementMapper.batchInsertNotification(cphMsgList);
                // 如果插入成功，发送企业微信消息
                if (i > 0) {
                    //根据年级获取学生学号列表
                    List<String> studentNos = getStudentNosByGrades(sendNotificationDto.getSelectedGrades());
                    if (studentNos != null && !studentNos.isEmpty()) {
                        // 批量发送企业微信消息
                        sendWeChatMessagesBatch(studentNos, sendNotificationDto.getContent());
                    }
                }
                return i;
            }
        }
        return result;
    }

    /**
     * 查询当前用户发送的通知列表
     *
     * @param notificationManagement 通知管理
     * @return 通知管理集合
     */
    @Override
    public List<NotificationManagement> selectNotificationManagementListBySender(NotificationManagement notificationManagement) {
        // 获取当前登录用户ID
        Long senderId = SecurityUtils.getUserId();
        return notificationManagementMapper.selectNotificationManagementListBySender(notificationManagement, senderId);
    }
    /**
     * 批量发送企业微信消息
     *
     * @param studentNos 学生学号列表
     * @param content 消息内容
     */
    private void sendWeChatMessagesBatch(List<String> studentNos, String content) {
        // 企业微信批量发送限制，每次最多发送1000个用户
        int batchSize = 1000;

        for (int i = 0; i < studentNos.size(); i += batchSize) {
            List<String> batch = studentNos.subList(i, Math.min(i + batchSize, studentNos.size()));
            // 拼接成"2023001|2023002|2023003"格式
            String toUser = String.join("|", batch);
            // 如果内容包含超链接标签，转换为 Markdown
            String md = convertHtmlLinkToMarkdown(content);
            
            try {
                if (md != null) {
                    weChatUtil.sendMarkdownMessage(toUser, md);
                } else {
                    // 如果没有标签但包含 http 链接，直接发送文本也可点击
                    weChatUtil.sendTextMessage(toUser, content);
                }
            } catch (Exception e) {
                // 记录错误但不抛出异常，避免影响其他批次或后续流程
                System.err.println("批量发送企业微信消息失败 (batch " + i + "): " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    /**
     * 将单个 a 标签的 HTML 转为 Markdown 格式；不匹配返回 null
     */
    private String convertHtmlLinkToMarkdown(String html) {
        if (html == null) return null;
        String lower = html.toLowerCase();
        if (!lower.contains("<a")) return null;
        try {
            // 简单提取 href 与锚文本
            int aStart = lower.indexOf("<a");
            int hrefStart = lower.indexOf("href", aStart);
            if (hrefStart < 0) return null;
            int quoteStart = lower.indexOf("\"", hrefStart);
            int quoteStartSingle = lower.indexOf("'", hrefStart);
            int qs = -1, qe = -1;
            if (quoteStart >= 0 && (quoteStartSingle < 0 || quoteStart < quoteStartSingle)) {
                qs = quoteStart;
                qe = lower.indexOf("\"", qs + 1);
            } else if (quoteStartSingle >= 0) {
                qs = quoteStartSingle;
                qe = lower.indexOf("'", qs + 1);
            }
            if (qs < 0 || qe < 0) return null;
            String url = html.substring(qs + 1, qe).trim();
            int textStart = lower.indexOf(">", qe) + 1;
            int textEnd = lower.indexOf("</a>", textStart);
            if (textStart <= 0 || textEnd <= textStart) return null;
            String text = html.substring(textStart, textEnd).trim();
            // 其余文本去掉标签
            String before = html.substring(0, aStart).replaceAll("<[^>]+>", "");
            String after = html.substring(textEnd + 4).replaceAll("<[^>]+>", "");
            String mdLink = "[" + (text.isEmpty() ? url : text) + "](" + url + ")";
            return before + mdLink + after;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据年级获取学生学号列表
     *
     * @param gradeIds 年级ID列表
     * @return 学生学号列表
     */
    @Override
    public List<String> getStudentNosByGrades(List<String> gradeIds) {
        return notificationManagementMapper.selectStudentNosByGrades(gradeIds);
    }

}
