package com.bcxin.message.service.yehuo;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcxin.message.common.utils.DateUtil;
import com.bcxin.message.dao.mapper.yehuo.TMessagesMapper;
import com.bcxin.message.dtos.yehuo.TMessagesResponse;
import com.bcxin.message.entity.yehuo.TMessagesEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * description：野火-消息表
 * author：linchunpeng
 * date：2024/12/31
 */
@Slf4j
@Service
public class TMessagesService extends ServiceImpl<TMessagesMapper, TMessagesEntity> {

    @Autowired
    private TGroupService tGroupService;

    /**
     * description：查询野火发送消息记录，查所有36个表
     * author：linchunpeng
     * date：2025/8/11
     */
    public List<TMessagesResponse> getMessageListByParam(Date startTime, Date endTime) {
        List<TMessagesResponse> resultList = new ArrayList<>();
        log.info("查询野火发送消息记录，时间范围：{} ~ {}", DateUtil.formatDateTime(startTime), DateUtil.formatDateTime(endTime));
        for (int i = 0; i < 36; i++) {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("number", i);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            log.info("参数：{}", JSONObject.toJSONString(paramMap));
            List<TMessagesResponse> list = this.baseMapper.selectByNumber(paramMap);
            log.info("消息数量：{}", CollectionUtil.isNotEmpty(list) ? list.size() : 0);
            if (CollectionUtil.isNotEmpty(list)) {
                for (TMessagesResponse messages : list) {
                    if (messages.getType() == 1) {
                        //群组消息，需要找到所有者
                        messages.setOwnerUserId(tGroupService.getOwnerByGid(messages.getTarget()));
                    }
                }
                resultList.addAll(list);
            }
        }
        log.info("消息总数量：{}", CollectionUtil.isNotEmpty(resultList) ? resultList.size() : 0);
        return resultList;
    }

    /**
     * description：根据id列表删除消息
     * author：linchunpeng
     * date：2025/8/14
     */
    @Transactional
    public void deleteByNumberAndIds(Integer number,  List<Long> idList) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("number", number);
        paramMap.put("idList", idList);
        this.baseMapper.deleteByIds(paramMap);
    }

}