package cn.iocoder.yudao.module.energy.service.config;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.energy.controller.admin.config.vo.EnergyStationConfigPageReqVO;
import cn.iocoder.yudao.module.energy.controller.admin.config.vo.EnergyStationConfigSaveReqVO;
import cn.iocoder.yudao.module.energy.convert.config.EnergyStationConfigConvert;
import cn.iocoder.yudao.module.energy.dal.dataobject.config.EnergyStationConfigDO;
import cn.iocoder.yudao.module.energy.dal.mysql.config.EnergyStationConfigMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.energy.enums.ErrorCodeConstants.*;

@Service
@Validated
public class EnergyStationConfigServiceImpl implements EnergyStationConfigService {

    @Resource
    private EnergyStationConfigMapper stationConfigMapper;

    @Override
    public Long createConfig(EnergyStationConfigSaveReqVO createReqVO) {
        // 校验站点唯一
        EnergyStationConfigDO existing = stationConfigMapper.selectByStationId(createReqVO.getStationId());
        if (existing != null) {
            throw exception(STATION_CONFIG_DUPLICATE);
        }
        EnergyStationConfigDO config = EnergyStationConfigConvert.INSTANCE.convert(createReqVO);
        stationConfigMapper.insert(config);
        return config.getId();
    }

    @Override
    public void updateConfig(EnergyStationConfigSaveReqVO updateReqVO) {
        validateConfigExists(updateReqVO.getId());
        EnergyStationConfigDO updateObj = EnergyStationConfigConvert.INSTANCE.convert(updateReqVO);
        stationConfigMapper.updateById(updateObj);
    }

    @Override
    public EnergyStationConfigDO getConfig(Long id) {
        return stationConfigMapper.selectById(id);
    }

    @Override
    public PageResult<EnergyStationConfigDO> getConfigPage(EnergyStationConfigPageReqVO pageReqVO) {
        return stationConfigMapper.selectPage(pageReqVO);
    }

    @Override
    public EnergyStationConfigDO getByStationId(Long stationId) {
        return stationConfigMapper.selectByStationId(stationId);
    }

    private void validateConfigExists(Long id) {
        if (stationConfigMapper.selectById(id) == null) {
            throw exception(STATION_CONFIG_NOT_EXISTS);
        }
    }
}
