package com.srs.staff.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.srs.common.exception.ServiceException;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.WeChatUtil;
import com.srs.staff.domain.SrsStaffOneStopCommunityActivities;
import com.srs.staff.domain.vo.SrsStaffOneStopRegistrationRecordExportVo;
import com.srs.staff.mapper.SrsStaffOneStopCommunityActivitiesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.staff.mapper.SrsStaffOneStopRegistrationRecordMapper;
import com.srs.staff.domain.SrsStaffOneStopRegistrationRecord;
import com.srs.staff.service.ISrsStaffOneStopRegistrationRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 一站式社区模块-社区活动-报名记录Service业务层处理
 *
 * @author chc
 * @date 2024-07-16
 */
@Service
public class SrsStaffOneStopRegistrationRecordServiceImpl extends ServiceImpl<SrsStaffOneStopRegistrationRecordMapper, SrsStaffOneStopRegistrationRecord> implements ISrsStaffOneStopRegistrationRecordService {
    private static final Logger log = LoggerFactory.getLogger(SrsStaffOneStopRegistrationRecordServiceImpl.class);

    @Autowired
    private SrsStaffOneStopRegistrationRecordMapper srsStaffOneStopRegistrationRecordMapper;

    @Autowired
    private SrsStaffOneStopCommunityActivitiesMapper srsStaffOneStopCommunityActivitiesMapper;

    @Autowired
    private WeChatUtil weChatUtil; // 添加WeChatUtil的注入  知无涯

    /**
     * 查询一站式社区模块-社区活动-报名记录
     *
     * @param recordId 一站式社区模块-社区活动-报名记录主键
     * @return 一站式社区模块-社区活动-报名记录
     */
    @Override
    public SrsStaffOneStopRegistrationRecord selectSrsStaffOneStopRegistrationRecordByRecordId(Long recordId) {
        SrsStaffOneStopRegistrationRecord record = srsStaffOneStopRegistrationRecordMapper.selectSrsStaffOneStopRegistrationRecordByRecordId(recordId);
        int num = 0; // 重置计数器
        // 根据每一个报名记录的活动id 查询出活动
        SrsStaffOneStopCommunityActivities srsStaffOneStopCommunityActivities = srsStaffOneStopCommunityActivitiesMapper.selectSrsStaffOneStopCommunityActivitiesByActivityId(record.getActivityId());
        // 根据活动里的报名记录统计报名人数，一条记录就是一个人数，审核不通过也就是getAuditStatus（）等于2 ,不计算在报名人数
        for (SrsStaffOneStopRegistrationRecord records : srsStaffOneStopCommunityActivities.getOneStopRegistrationRecords()) {
            if (records.getAuditStatus() == 1 || records.getAuditStatus() == 0) {
                num++;
            }
        }
        record.setNumberApplicants((long) num);
        return record;
    }

    @Override
    public SrsStaffOneStopRegistrationRecord selectRecordByActivityIdAndApplicant(Long activityId, String applicant) {
        return srsStaffOneStopRegistrationRecordMapper.selectRecordByActivityIdAndApplicant(activityId, applicant);
    }

    /**
     * 查询一站式社区模块-社区活动-报名记录列表
     *
     * @param srsStaffOneStopRegistrationRecord 一站式社区模块-社区活动-报名记录
     * @return 一站式社区模块-社区活动-报名记录
     */
    @Override
    public List<SrsStaffOneStopRegistrationRecord> selectSrsStaffOneStopRegistrationRecordList(SrsStaffOneStopRegistrationRecord srsStaffOneStopRegistrationRecord) {
        List<SrsStaffOneStopRegistrationRecord> srsStaffOneStopRegistrationRecords = srsStaffOneStopRegistrationRecordMapper.selectSrsStaffOneStopRegistrationRecordList(srsStaffOneStopRegistrationRecord);
        // 先循环报名记录
        for (SrsStaffOneStopRegistrationRecord records : srsStaffOneStopRegistrationRecords) {
            int num = 0; // 重置计数器
            // 根据每一个报名记录的活动id 查询出活动
            SrsStaffOneStopCommunityActivities srsStaffOneStopCommunityActivities = srsStaffOneStopCommunityActivitiesMapper.selectSrsStaffOneStopCommunityActivitiesByActivityId(records.getActivityId());
            // 根据活动里的报名记录统计报名人数，一条记录就是一个人数，审核不通过也就是getAuditStatus（）等于2 ,不计算在报名人数
            if (srsStaffOneStopCommunityActivities != null && srsStaffOneStopCommunityActivities.getOneStopRegistrationRecords() != null) {
                for (SrsStaffOneStopRegistrationRecord record : srsStaffOneStopCommunityActivities.getOneStopRegistrationRecords()) {
                    if (record != null && (record.getAuditStatus() == 1 || record.getAuditStatus() == 0)) {
                        num++;
                    }
                }
            }
            records.setNumberApplicants((long) num);
        }
        return srsStaffOneStopRegistrationRecords;
    }

    @Override
    public List<SrsStaffOneStopRegistrationRecordExportVo> selectSrsStaffOneStopRegistrationRecordListexport(SrsStaffOneStopRegistrationRecord srsStaffOneStopRegistrationRecord) {
        return srsStaffOneStopRegistrationRecordMapper.selectSrsStaffOneStopRegistrationRecordListexport(srsStaffOneStopRegistrationRecord);
    }

    /**
     * 新增一站式社区模块-社区活动-报名记录
     *
     * @param srsStaffOneStopRegistrationRecord 一站式社区模块-社区活动-报名记录
     * @return 结果
     */
    @Override
    public int insertSrsStaffOneStopRegistrationRecord(SrsStaffOneStopRegistrationRecord srsStaffOneStopRegistrationRecord) {
        srsStaffOneStopRegistrationRecord.setJobNumber(SecurityUtils.getUsername());   //获取的是当前登陆人信息
        String applicantJobNumber = srsStaffOneStopRegistrationRecord.getJobNumber(); // 获取申请人工号   知无涯
        if (applicantJobNumber == null) {
            throw new ServiceException("申请人工号不能为空", 500);
        }

        srsStaffOneStopRegistrationRecord.setJobNumber(applicantJobNumber);
        if (srsStaffOneStopRegistrationRecord.getApplicant() == null) {
            srsStaffOneStopRegistrationRecord.setApplicant(SecurityUtils.getLoginUser().getUser().getNickName());
        }
        SrsStaffOneStopRegistrationRecord srsStaffOneStopRegistrationRecord1 = srsStaffOneStopRegistrationRecordMapper.selectRecordByActivityIdAndApplicant(srsStaffOneStopRegistrationRecord.getActivityId(), srsStaffOneStopRegistrationRecord.getJobNumber());
        if (srsStaffOneStopRegistrationRecord1 != null) {
            throw new ServiceException("已报名，请勿重复报名", 500);
        }

        //报名人数不能超过活动容纳人数
        List<SrsStaffOneStopRegistrationRecord> srsStaffOneStopRegistrationRecords = srsStaffOneStopRegistrationRecordMapper.selectSrsStaffOneStopRegistrationRecordByActivityId(srsStaffOneStopRegistrationRecord.getActivityId());
        if (!srsStaffOneStopRegistrationRecords.isEmpty()) {
            // 筛选报名记录除去审核为2的，也就是审核不通过，不算做一条报名记录
            List<SrsStaffOneStopRegistrationRecord> filteredRecords =
                    srsStaffOneStopRegistrationRecords.stream() // 将列表转换为Stream
                            .filter(record -> record.getAuditStatus() != 2) // 应用筛选条件
                            .collect(Collectors.toList()); // 将结果收集回列表
            // 报名人数大于或等于活动容纳人数，则提示
            if (filteredRecords.size() >= srsStaffOneStopRegistrationRecords.get(0).getCommunityActivitiesList().get(0).getGalleryful()) {
                throw new ServiceException("报名人数已满", 500);
            }
        }
        // 活动结束后，不允许报名
        SrsStaffOneStopCommunityActivities srsStaffOneStopCommunityActivities = srsStaffOneStopCommunityActivitiesMapper.selectSrsStaffOneStopCommunityActivitiesByActivityId(srsStaffOneStopRegistrationRecord.getActivityId());
        if (srsStaffOneStopCommunityActivities.getActivityStatus() == 2) {
            throw new ServiceException("活动已结束", 500);
        }
        if (srsStaffOneStopCommunityActivities.getActivityStatus() == 0) {
            throw new ServiceException("活动进行中，已无法报名", 500);
        }
        return srsStaffOneStopRegistrationRecordMapper.insertSrsStaffOneStopRegistrationRecord(srsStaffOneStopRegistrationRecord);
    }

    /**
     * 修改一站式社区模块-社区活动-报名记录
     *
     * @param srsStaffOneStopRegistrationRecord 一站式社区模块-社区活动-报名记录
     * @return 结果
     */

    /**
     * 更新单个报名记录并发送微信通知  知无涯
     * @param srsStaffOneStopRegistrationRecord 报名记录对象
     * @return 更新结果影响行数
     */
    @Override
    public int updateSrsStaffOneStopRegistrationRecord(SrsStaffOneStopRegistrationRecord srsStaffOneStopRegistrationRecord) {
        // 1. 先更新数据库中的报名记录
        int result = srsStaffOneStopRegistrationRecordMapper.updateSrsStaffOneStopRegistrationRecord(srsStaffOneStopRegistrationRecord);

        // 2. 如果更新成功且审核状态为通过(1)或拒绝(2)，则发送微信通知
        if (result > 0 && (srsStaffOneStopRegistrationRecord.getAuditStatus() == 1 || srsStaffOneStopRegistrationRecord.getAuditStatus() == 2)) {
            sendWeChatNotice(srsStaffOneStopRegistrationRecord);
        }
        return result;
    }


    /**
     * 批量更新报名记录并发送微信通知  知无涯
     * @param registrationRecordList 报名记录列表
     * @return 更新结果影响行数
     */
    @Override
    public int batchUpdateSysRegistrationRecord(List<SrsStaffOneStopRegistrationRecord> registrationRecordList) {
        // 1. 批量更新数据库记录
        int result = srsStaffOneStopRegistrationRecordMapper.batchUpdateSysRegistrationRecord(registrationRecordList);

        // 2. 如果更新成功，遍历处理每条记录
        if (result > 0) {
            for (SrsStaffOneStopRegistrationRecord record : registrationRecordList) {
                // 只对审核通过或拒绝的记录发送通知
                if (record.getAuditStatus() == 1 || record.getAuditStatus() == 2) {
                    sendWeChatNotice(record);
                }
            }
        }
        return result;
    }


    /**
     * 发送企业微信通知
     * @param record 报名记录对象
     */
    private void sendWeChatNotice(SrsStaffOneStopRegistrationRecord record) {
        try {
            // 1. 获取关联的活动详情
            SrsStaffOneStopCommunityActivities activity = srsStaffOneStopCommunityActivitiesMapper
                    .selectSrsStaffOneStopCommunityActivitiesByActivityId(record.getActivityId());

            // 2. 构建通知消息内容
            String content = buildNoticeContent(record, activity);

            // 3. 通过企业微信工具类发送消息
            // 参数1: 接收人工号(对应企业微信账号)
            // 参数2: 消息内容
            weChatUtil.sendTextMessage(record.getJobNumber(), content);
        } catch (Exception e) {
            // 记录发送失败日志，但不影响主流程
            log.error("发送企业微信消息失败", e);
        }
    }

    /**
     * 构建通知消息内容
     * @param record 报名记录
     * @param activity 关联的活动
     * @return 格式化后的消息内容
     */
    private String buildNoticeContent(SrsStaffOneStopRegistrationRecord record,
                                      SrsStaffOneStopCommunityActivities activity) {
        // 根据审核状态显示不同文本
        String status = record.getAuditStatus() == 1 ? "审核通过" : "审核未通过";

        // 格式化消息模板
        return String.format(
                "【活动报名通知】\n" +
                        "您报名的活动【%s】%s",
                activity.getActivityTheme(), // 活动主题
                status                      // 审核状态
        );
    }


    /**
     * 批量删除一站式社区模块-社区活动-报名记录
     *
     * @param recordIds 需要删除的一站式社区模块-社区活动-报名记录主键
     * @return 结果
     */
    @Override
    public int deleteSrsStaffOneStopRegistrationRecordByRecordIds(Long[] recordIds) {
        return srsStaffOneStopRegistrationRecordMapper.deleteSrsStaffOneStopRegistrationRecordByRecordIds(recordIds);
    }

    /**
     * 删除一站式社区模块-社区活动-报名记录信息
     *
     * @param recordId 一站式社区模块-社区活动-报名记录主键
     * @return 结果
     */
    @Override
    public int deleteSrsStaffOneStopRegistrationRecordByRecordId(Long recordId) {
        return srsStaffOneStopRegistrationRecordMapper.deleteSrsStaffOneStopRegistrationRecordByRecordId(recordId);
    }

    // 统计各部门预约功能房数量
    public List<Map<String, Object>> getDepartmentReservationCount(String startTime,String endTime,String role,String borrower,Integer auditStatus,List<String> rtDepar) {
        return srsStaffOneStopRegistrationRecordMapper.getDepartmentUsage(startTime,endTime,role,borrower,auditStatus,rtDepar);
    }

    // 统计各个功能房的预约数量
    public List<Map<String, Object>> getRoomReservationCount(String startTime,String endTime,String role,String borrower,Integer auditStatus,List<String> rtDepar) {
        return srsStaffOneStopRegistrationRecordMapper.getRoomReservationCount(startTime,endTime,role,borrower,auditStatus,rtDepar);
    }

    // 统计各部门功能房使用情况
    public List<Map<String, Object>> getDepartmentUsageStatistics(String startTime,String endTime,String role,String borrower,Integer auditStatus,List<String> rtDepar) {
        return srsStaffOneStopRegistrationRecordMapper.getDepartmentUsageStatistics(startTime,endTime,role,borrower,auditStatus,rtDepar);
    }

    // 统计各个功能房使用情况
    public List<Map<String, Object>> getRoomUsageStatistics(String startTime,String endTime,String role,String borrower,Integer auditStatus,List<String> rtDepar) {
        return srsStaffOneStopRegistrationRecordMapper.getRoomUsageStatistics(startTime,endTime,role,borrower,auditStatus,rtDepar);
    }

    @Override
    public int resetAuditStatus(Integer id) {
        return srsStaffOneStopRegistrationRecordMapper.updateAuditStatusToPending(id);
    }

    /**
     * 取消报名 - 学生取消自己的社区活动报名
     *
     * @param recordId 报名记录ID
     * @return 结果
     */
    @Override
    public com.srs.common.core.domain.AjaxResult cancelRegistration(Long recordId) {
        log.info("开始执行取消报名方法，recordId: {}", recordId);
        try {
            // 1. 查询报名记录
            SrsStaffOneStopRegistrationRecord record = srsStaffOneStopRegistrationRecordMapper.selectSrsStaffOneStopRegistrationRecordByRecordId(recordId);
            if (record == null) {
                return com.srs.common.core.domain.AjaxResult.error("报名记录不存在");
            }

            // 2. 查询关联的活动信息
            if (record.getActivityId() == null) {
                return com.srs.common.core.domain.AjaxResult.error("报名记录中活动ID为空");
            }
            SrsStaffOneStopCommunityActivities activity = srsStaffOneStopCommunityActivitiesMapper.selectSrsStaffOneStopCommunityActivitiesByActivityId(record.getActivityId());
            if (activity == null) {
                return com.srs.common.core.domain.AjaxResult.error("活动不存在");
            }

            // 3. 检查是否在报名截止时间前
            java.util.Date now = new java.util.Date();
            if (activity.getSignUpEndTime() != null && now.after(activity.getSignUpEndTime())) {
                return com.srs.common.core.domain.AjaxResult.error("报名已截止，无法取消报名");
            }

            // 5. 检查报名状态（只有待审核或已通过的可以取消）
            if (record.getAuditStatus() != null && record.getAuditStatus() == 2) {
                return com.srs.common.core.domain.AjaxResult.error("报名已被拒绝，无需取消");
            }

            // 6. 删除报名记录
            int result = srsStaffOneStopRegistrationRecordMapper.deleteSrsStaffOneStopRegistrationRecordByRecordId(recordId);

            if (result > 0) {
                // 7. 发送取消报名通知
                sendCancelNotice(record, activity);
                return com.srs.common.core.domain.AjaxResult.success("取消报名成功");
            } else {
                return com.srs.common.core.domain.AjaxResult.error("取消报名失败");
            }
        } catch (Exception e) {
            log.error("取消报名失败", e);
            return com.srs.common.core.domain.AjaxResult.error("取消报名失败：" + e.getMessage());
        }
    }

    /**
     * 发送取消报名通知
     * @param record 报名记录对象
     * @param activity 活动对象
     */
    private void sendCancelNotice(SrsStaffOneStopRegistrationRecord record, SrsStaffOneStopCommunityActivities activity) {
        try {
            // 检查必要参数是否为空
            if (record == null || activity == null || record.getJobNumber() == null || activity.getActivityTheme() == null) {
                log.warn("发送取消报名通知失败：参数为空");
                return;
            }

            // 构建取消报名通知消息内容
            String content = String.format(
                    "【活动报名通知】\n" +
                            "您已成功取消报名活动【%s】\n" +
                            "如需重新报名，请在报名截止时间前重新提交申请。",
                    activity.getActivityTheme()
            );

            // 通过企业微信工具类发送消息
            weChatUtil.sendTextMessage(record.getJobNumber(), content);
        } catch (Exception e) {
            // 记录发送失败日志，但不影响主流程
            log.error("发送取消报名企业微信消息失败", e);
        }
    }
}
