package com.qnfhq.modules.c2c.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qnfhq.common.redis.RedisUtils;
import com.qnfhq.common.utils.Result;
import com.qnfhq.constant.CacheConstants;
import com.qnfhq.modules.c2c.dao.C2cMsgContentDao;
import com.qnfhq.modules.c2c.dto.C2cMsgContentDTO;
import com.qnfhq.modules.c2c.entity.C2cMsgContentEntity;
import com.qnfhq.modules.c2c.enums.MsgStatusEnum;
import com.qnfhq.modules.c2c.service.C2cMsgContactService;
import com.qnfhq.modules.c2c.service.C2cMsgContentService;
import com.qnfhq.modules.c2c.service.C2cMsgRelationService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;

/**
 * 聊天消息表
 *
 * @author yelz 30262728@qq.com
 * @since 1.0.0 2025-11-25
 */
@Service
public class C2cMsgContentServiceImpl extends ServiceImpl<C2cMsgContentDao, C2cMsgContentEntity> implements C2cMsgContentService {

    @Resource
    private C2cMsgRelationService c2cMsgRelationService;
    @Resource
    private C2cMsgContactService c2cMsgContactService;
    @Resource
    private RedisUtils redisUtils;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveMsg(C2cMsgContentDTO dto) throws Exception{
        C2cMsgContentEntity msgEntity = new C2cMsgContentEntity();
        msgEntity.setSenderId(StpUtil.getLoginIdAsLong());
        msgEntity.setRecipientId(dto.getRecipientId());
        msgEntity.setContent(dto.getContent());
        msgEntity.setMsgType(dto.getMsgType().toLowerCase());
        msgEntity.setStatus(MsgStatusEnum.SEND.getCode());
        msgEntity.setSendTime(new Date());
        if(save(msgEntity)) {
            // 保存消息关系
            c2cMsgRelationService.saveMsgRelation(msgEntity);

            // 保存最近联系人
            c2cMsgContactService.saveByMsgContact(msgEntity);

            //总未读数更新 2001534_UNREAD_T
            redisUtils.increment(CacheConstants.getTotalUnreadKey(msgEntity.getRecipientId()), 1L,-1L);
            //聊天用户未读数更新
            redisUtils.increment(CacheConstants.getChatUnreadKey(msgEntity.getRecipientId()), msgEntity.getSenderId().toString(), 1L, -1L);
        }
        return new Result().ok(msgEntity);
    }

}