package org.dromara.member.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.dromara.member.domain.AppMessage;
import org.dromara.member.domain.bo.AppMessageBo;
import org.dromara.member.domain.vo.AppMessageVo;
import org.dromara.member.mapper.AppMessageMapper;
import org.dromara.member.service.AppMessageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;

/**
 * App端消息Service业务层处理
 *
 * @author pengles
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class AppMessageServiceImpl extends ServiceImpl<AppMessageMapper, AppMessage> implements AppMessageService {

    private final AppMessageMapper baseMapper;

    /**
     * 查询App端消息
     */
    @Override
    public AppMessageVo queryById(Long messageId) {
        return baseMapper.selectVoById(messageId);
    }

    /**
     * 查询App端消息列表
     */
    @Override
    public TableDataInfo<AppMessageVo> queryPageList(AppMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AppMessage> lqw = buildQueryWrapper(bo);
        Page<AppMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询App端消息列表
     */
    @Override
    public List<AppMessageVo> queryList(AppMessageBo bo) {
        LambdaQueryWrapper<AppMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<AppMessage> buildQueryWrapper(AppMessageBo bo) {
        LambdaQueryWrapper<AppMessage> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTitle()), AppMessage::getTitle, bo.getTitle());
        lqw.like(StringUtils.isNotBlank(bo.getContent()), AppMessage::getContent, bo.getContent());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageType()), AppMessage::getMessageType, bo.getMessageType());
        lqw.eq(StringUtils.isNotBlank(bo.getTargetType()), AppMessage::getTargetType, bo.getTargetType());
        lqw.like(StringUtils.isNotBlank(bo.getTargetIds()), AppMessage::getTargetIds, bo.getTargetIds());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AppMessage::getStatus, bo.getStatus());

        // 如果指定了接收者ID，查询该用户相关的消息
        if (ObjectUtil.isNotNull(bo.getReceiverId())) {
            lqw.and(wrapper -> wrapper.eq(AppMessage::getTargetType, "all")
                    .or()
                    .and(subWrapper -> subWrapper.eq(AppMessage::getTargetType, "user")
                            .like(AppMessage::getTargetIds, bo.getReceiverId().toString())));
        }

        lqw.orderByDesc(AppMessage::getCreateTime);
        return lqw;
    }

    /**
     * 新增App端消息
     */
    @Override
    public Boolean insertByBo(AppMessageBo bo) {
        AppMessage add = BeanUtil.toBean(bo, AppMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setMessageId(add.getMessageId());
        }
        return flag;
    }

    /**
     * 修改App端消息
     */
    @Override
    public Boolean updateByBo(AppMessageBo bo) {
        AppMessage update = BeanUtil.toBean(bo, AppMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

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

    /**
     * 批量删除App端消息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 获取用户未读消息数量
     */
    @Override
    public Long getUnreadCount(Long userId) {
        LambdaQueryWrapper<AppMessage> lqw = Wrappers.lambdaQuery();
        lqw.and(wrapper -> wrapper.eq(AppMessage::getTargetType, "user")
                .like(AppMessage::getTargetIds, userId.toString())
                .or()
                .eq(AppMessage::getTargetType, "all"));
        lqw.eq(AppMessage::getStatus, "1"); // 已发送
        return baseMapper.selectCount(lqw);
    }

    /**
     * 标记消息为已读
     */
    @Override
    public Boolean markAsRead(Long messageId, Long userId) {
        // 由于当前表结构不支持已读状态，这里只是示例实现
        // 实际项目中可能需要单独的消息阅读记录表
        log.info("用户 {} 标记消息 {} 为已读", userId, messageId);
        return true;
    }

    /**
     * 批量标记消息为已读
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean markAsReadBatch(List<Long> messageIds, Long userId) {
        // 由于当前表结构不支持已读状态，这里只是示例实现
        log.info("用户 {} 批量标记消息为已读，消息数量: {}", userId, messageIds.size());
        return true;
    }

    /**
     * 标记所有消息为已读
     */
    @Override
    public Boolean markAllAsRead(Long userId) {
        // 由于当前表结构不支持已读状态，这里只是示例实现
        log.info("用户 {} 标记所有消息为已读", userId);
        return true;
    }

    /**
     * 发送系统消息
     */
    @Override
    public Boolean sendSystemMessage(AppMessageBo bo) {
        bo.setMessageType("system"); // 系统消息
        bo.setTargetType("all"); // 全部用户
        bo.setStatus("0"); // 待发送
        bo.setSendTime(LocalDateTime.now());
        return insertByBo(bo);
    }

    /**
     * 发送个人消息
     */
    @Override
    public Boolean sendPersonalMessage(AppMessageBo bo) {
        bo.setMessageType("notice"); // 通知消息
        bo.setTargetType("user"); // 指定用户
        bo.setStatus("0"); // 待发送
        bo.setSendTime(LocalDateTime.now());
        return insertByBo(bo);
    }

    /**
     * 推送消息到指定用户
     */
    @Override
    public Boolean pushMessage(AppMessageBo bo) {
        bo.setTargetType("user");
        bo.setStatus("0"); // 待发送
        bo.setSendTime(LocalDateTime.now());

        // 先保存消息
        Boolean result = insertByBo(bo);
        if (result) {
            // 发送推送通知
            String[] userIds = bo.getTargetIds().split(",");
            for (String userId : userIds) {
                sendPushNotification(Long.valueOf(userId), bo.getTitle(), bo.getContent());
            }

            // 更新发送状态
            AppMessage update = new AppMessage();
            update.setMessageId(bo.getMessageId());
            update.setStatus("1"); // 已发送
            baseMapper.updateById(update);
        }
        return result;
    }

    /**
     * 群发消息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean broadcastMessage(AppMessageBo bo) {
        bo.setMessageType("activity"); // 活动消息
        bo.setTargetType("all"); // 全部用户
        bo.setStatus("0"); // 待发送
        bo.setSendTime(LocalDateTime.now());

        Boolean result = insertByBo(bo);
        if (result) {
            // 发送批量推送通知
            sendBatchPushNotification(null, bo.getTitle(), bo.getContent());

            // 更新发送状态
            AppMessage update = new AppMessage();
            update.setMessageId(bo.getMessageId());
            update.setStatus("1"); // 已发送
            baseMapper.updateById(update);
        }

        return result;
    }

    /**
     * 发送推送通知
     */
    @Override
    public Boolean sendPushNotification(Long userId, String title, String content) {
        try {
            // TODO: 集成第三方推送服务（极光推送、友盟推送等）
            // 这里只是示例代码，实际需要根据具体的推送服务进行实现
            log.info("发送推送通知 - 用户ID: {}, 标题: {}, 内容: {}", userId, title, content);

            // 模拟推送成功
            return true;
        } catch (Exception e) {
            log.error("发送推送通知失败", e);
            return false;
        }
    }

    /**
     * 批量发送推送通知
     */
    @Override
    public Boolean sendBatchPushNotification(List<Long> userIds, String title, String content) {
        try {
            // TODO: 集成第三方推送服务的批量推送接口
            if (userIds != null) {
                log.info("批量发送推送通知 - 用户数量: {}, 标题: {}, 内容: {}", userIds.size(), title, content);
            } else {
                log.info("全员推送通知 - 标题: {}, 内容: {}", title, content);
            }

            // 模拟推送成功
            return true;
        } catch (Exception e) {
            log.error("批量发送推送通知失败", e);
            return false;
        }
    }

    /**
     * 清理过期消息
     */
    @Override
    public Integer cleanExpiredMessages() {
        // 清理30天前的已发送消息
        LambdaQueryWrapper<AppMessage> lqw = Wrappers.lambdaQuery();
        lqw.lt(AppMessage::getCreateTime, LocalDateTime.now().minusDays(30));
        lqw.eq(AppMessage::getStatus, "1"); // 已发送

        List<AppMessage> expiredMessages = baseMapper.selectList(lqw);
        if (!expiredMessages.isEmpty()) {
            List<Long> ids = expiredMessages.stream().map(AppMessage::getMessageId).toList();
            baseMapper.deleteBatchIds(ids);
            log.info("清理过期消息 {} 条", ids.size());
            return ids.size();
        }

        return 0;
    }
}