package com.xindazhou.business.service.message;

import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.business.controller.admin.message.vo.ServiceMessagePageReqVO;
import com.xindazhou.business.controller.admin.message.vo.ServiceMessageSaveReqVO;
import com.xindazhou.business.convert.message.ServiceMessageConvert;
import com.xindazhou.business.dal.dataobject.message.ServiceMessageDO;
import com.xindazhou.business.dal.mysql.message.ServiceMessageMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static com.xindazhou.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.xindazhou.business.enums.ErrorCodeConstants.*;

/**
 * 服务消息 Service 实现类
 *
 * @author xindazhou
 */
@Service
@Slf4j
@Validated
public class ServiceMessageServiceImpl implements ServiceMessageService {

    @Resource
    private ServiceMessageMapper serviceMessageMapper;

    @Override
    public Long createMessage(ServiceMessageSaveReqVO createReqVO) {
        // 插入消息
        ServiceMessageDO message = ServiceMessageConvert.INSTANCE.convert(createReqVO);
        serviceMessageMapper.insert(message);
        return message.getId();
    }

    @Override
    public void updateMessage(ServiceMessageSaveReqVO updateReqVO) {
        // 校验消息存在
        validateMessageExists(updateReqVO.getId());

        // 更新消息
        ServiceMessageDO updateObj = ServiceMessageConvert.INSTANCE.convert(updateReqVO);
        serviceMessageMapper.updateById(updateObj);
    }

    @Override
    public void deleteMessage(Long id) {
        // 校验消息存在
        validateMessageExists(id);
        // 删除
        serviceMessageMapper.deleteById(id);
    }

    @Override
    public ServiceMessageDO getMessage(Long id) {
        return serviceMessageMapper.selectById(id);
    }

    @Override
    public PageResult<ServiceMessageDO> getMessagePage(ServiceMessagePageReqVO pageReqVO) {
        return serviceMessageMapper.selectPage(pageReqVO);
    }

    private ServiceMessageDO validateMessageExists(Long id) {
        ServiceMessageDO message = serviceMessageMapper.selectById(id);
        if (message == null) {
            throw exception(SERVICE_MESSAGE_NOT_EXISTS);
        }
        return message;
    }

}

