package com.bcxin.message.service.messagecenter;

import cn.hutool.core.collection.CollectionUtil;
import cn.wildfirechat.sdk.MessageAdmin;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bcxin.message.common.utils.DateUtil;
import com.bcxin.message.dao.mapper.messagecenter.MsgExpiredTimeMapper;
import com.bcxin.message.entity.messagecenter.MsgExpiredTimeEntity;
import com.bcxin.message.service.yehuo.TMessagesService;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description：消息中心-消息过期时间表 service
 * author：linchunpeng
 * date：2025/8/11
 */
@Slf4j
@Service
public class MsgExpiredTimeService extends ServiceImpl<MsgExpiredTimeMapper, MsgExpiredTimeEntity> {

    @Autowired
    private TMessagesService tMessagesService;

    /**
     * description：创建消息过期时间记录
     * author：linchunpeng
     * date：2025/8/14
     */
    @Transactional
    public void createMsgExpiredTimeRecord(Long id, Integer number, Date sendTime, String userIdAndOrgIdAndEffectiveTime) {
        log.info("创建消息过期时间记录");
        String[] split = userIdAndOrgIdAndEffectiveTime.split(";");
        MsgExpiredTimeEntity entity = new MsgExpiredTimeEntity();
        entity.setId(id);
        entity.setNumber(number);
        entity.setOrganizationId(split[1]);
        entity.setUserId(split[0]);
        entity.setSendTime(sendTime);
        entity.setExpiredTime(DateUtil.offsetDay(sendTime, Integer.parseInt(split[2])));
        entity.setCreateTime(new Date());
        this.save(entity);
        log.info("创建消息过期时间记录成功");
    }

//    /**
//     * description：删除过期消息
//     * author：linchunpeng
//     * date：2025/8/14
//     */
//    public void deleteExpiredMsg() {
//        Date now = new Date();
//        log.info("删除过期消息，当前时间：{}", DateUtil.formatDateTime(now));
//        LambdaQueryChainWrapper<MsgExpiredTimeEntity> lqw = this.lambdaQuery();
//        lqw.le(MsgExpiredTimeEntity::getExpiredTime, now);
//        List<MsgExpiredTimeEntity> list = lqw.list();
//        if (CollectionUtil.isNotEmpty(list)) {
//            log.info("过期消息总条数：{}", list.size());
//            Map<Integer, List<MsgExpiredTimeEntity>> numberListMap = list.stream().collect(Collectors.groupingBy(MsgExpiredTimeEntity::getNumber));
//            for (Map.Entry<Integer, List<MsgExpiredTimeEntity>> listEntry : numberListMap.entrySet()) {
//                Integer number = listEntry.getKey();
//                List<MsgExpiredTimeEntity> messageList = listEntry.getValue();
//                log.info("分表：{}，过期消息总条数：{}", number, messageList.size());
//                if (messageList.size() > 1000) {
//                    //分片删除
//                    List<List<MsgExpiredTimeEntity>> partitionList = ListUtil.partition(messageList, 1000);
//                    log.info("分片删除，总片数：{}", partitionList.size());
//                    for (List<MsgExpiredTimeEntity> l : partitionList) {
//                        List<Long> idList = l.stream().map(MsgExpiredTimeEntity::getId).collect(Collectors.toList());
//                        tMessagesService.deleteByNumberAndIds(number, idList);
//                        log.info("分片删除，已删除：{}", l.size());
//                    }
//                } else {
//                    log.info("消息不足1000， 不需要分片");
//                    List<Long> idList = messageList.stream().map(MsgExpiredTimeEntity::getId).collect(Collectors.toList());
//                    tMessagesService.deleteByNumberAndIds(number, idList);
//                    log.info("全部删除，已删除：{}", messageList.size());
//                }
//            }
//            log.info("过期消息删完成");
//            log.info("删除过期记录");
//            List<Long> idList = list.stream().map(MsgExpiredTimeEntity::getId).collect(Collectors.toList());
//            this.removeBatchByIds(idList, 1000);
//            log.info("删除过期记录完成");
//        }
//    }


    /**
     * description：删除过期消息
     * author：linchunpeng
     * date：2025/8/14
     */
    public void deleteExpiredMsg() {
        Date now = new Date();
        log.info("删除过期消息，当前时间：{}", DateUtil.formatDateTime(now));
        LambdaQueryChainWrapper<MsgExpiredTimeEntity> lqw = this.lambdaQuery();
        lqw.le(MsgExpiredTimeEntity::getExpiredTime, now);
        List<MsgExpiredTimeEntity> list = lqw.list();
        if (CollectionUtil.isNotEmpty(list)) {
            log.info("过期消息总条数：{}", list.size());
            int successCount = 0;
            int failCount = 0;
            List<Long> idList = list.stream().map(MsgExpiredTimeEntity::getId).collect(Collectors.toList());
            for (MsgExpiredTimeEntity entity : list) {
                try {
                    MessageAdmin.deleteMessage(entity.getId());
                    successCount++;
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("删除消息id：{}，报异常，{}", entity.getId(), e.getMessage(), e);
                    idList.remove(entity.getId());
                    failCount++;
                }
            }
            log.info("过期消息删完成，成功：{}，失败：{}", successCount, failCount);
            log.info("删除过期记录");
            this.removeBatchByIds(idList, 1000);
            log.info("删除过期记录完成");
        }
    }
}
