package com.ytpm.middle.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ytpm.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.general.ResultTable;
import com.ytpm.middle.dao.MessageMapper;
import com.ytpm.middle.model.YtPlatformMessage;
import com.ytpm.middle.model.YtPlatformMessageRecord;
import com.ytpm.middle.param.MessageParam;
import com.ytpm.middle.service.MessageService;
import com.ytpm.middle.view.MessageVO;
import com.ytpm.util.IDUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author Marx
 * @date 2025/8/5 11:56
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Resource
    private MessageMapper messageMapper;

    /**
     * 发送消息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> sendMessage(MessageParam param) {
        YtPlatformMessage message = new YtPlatformMessage();
        BeanUtils.copyProperties(param, message);
        message.setMessageId(IDUtil.generateFlowID("message"));
        message.setSendTime(new Date());
        message.setMessageStatus(0);
        messageMapper.insertMessage(message);
        List<String> recipientList = param.getRecipientList();

        if(CollUtil.isNotEmpty(recipientList)){
            YtPlatformMessageRecord record = new YtPlatformMessageRecord();
            record.setMessageId(message.getMessageId());
            record.setRecipient(String.join(",", recipientList));
            record.setRecipientStatus(0);
            record.setDefaultParam(param.getCreateUserId());
            messageMapper.batchInsertMessageRecipient(record);
        }
        return Result.resultOk(RepMessage.SAVE_SUCCESS);
    }

    /**
     * 查询消息列表
     */
    @Override
    public ResultTable<MessageVO> queryList(MessageParam param) {
        PageHelper.startPage(param.getPage(), param.getLimit());
        return ResultTable.resultTableOk(new PageInfo<>(messageMapper.queryAll(param)));
    }
}
