package cn.newfeifan.mall.module.trade.service.messagelog;

import cn.newfeifan.mall.framework.common.pojo.PageResult;
import cn.newfeifan.mall.framework.common.util.object.BeanUtils;
import cn.newfeifan.mall.module.trade.controller.admin.messagelog.vo.MessageLogPageReqVO;
import cn.newfeifan.mall.module.trade.controller.admin.messagelog.vo.MessageLogSaveReqVO;
import cn.newfeifan.mall.module.trade.dal.dataobject.messagelog.MessageLogDO;
import cn.newfeifan.mall.module.trade.dal.mysql.messagelog.MessageLogMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

import static cn.newfeifan.mall.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.newfeifan.mall.module.trade.enums.ErrorCodeConstants.MESSAGE_LOG_NOT_EXISTS;

/**
 * 微信消息记录 Service 实现类
 *
 * @author 非繁人
 */
@Service
@Validated
public class MessageLogServiceImpl implements MessageLogService {

    @Resource
    private MessageLogMapper messageLogMapper;

    @Override
    public Long createMessageLog(MessageLogSaveReqVO createReqVO) {
        // 插入
        MessageLogDO messageLog = BeanUtils.toBean(createReqVO, MessageLogDO.class);
        messageLogMapper.insert(messageLog);
        // 返回
        return messageLog.getId();
    }

    @Override
    public void updateMessageLog(MessageLogSaveReqVO updateReqVO) {
        // 校验存在
        validateMessageLogExists(updateReqVO.getId());
        // 更新
        MessageLogDO updateObj = BeanUtils.toBean(updateReqVO, MessageLogDO.class);
        messageLogMapper.updateById(updateObj);
    }

    @Override
    public void deleteMessageLog(Long id) {
        // 校验存在
        validateMessageLogExists(id);
        // 删除
        messageLogMapper.deleteById(id);
    }

    private void validateMessageLogExists(Long id) {
        if (messageLogMapper.selectById(id) == null) {
            throw exception(MESSAGE_LOG_NOT_EXISTS);
        }
    }

    @Override
    public MessageLogDO getMessageLog(Long id) {
        return messageLogMapper.selectById(id);
    }

    @Override
    public PageResult<MessageLogDO> getMessageLogPage(MessageLogPageReqVO pageReqVO) {
        return messageLogMapper.selectPage(pageReqVO);
    }

}
