package com.xindazhou.vehicle.service.sound;

import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.framework.common.pojo.PageResult;
import com.xindazhou.vehicle.controller.admin.vehicle.vo.VehicleSoundPageReqVO;
import com.xindazhou.vehicle.controller.admin.vehicle.vo.VehicleSoundRespVO;
import com.xindazhou.vehicle.controller.admin.vehicle.vo.VehicleSoundSaveReqVO;
import com.xindazhou.vehicle.convert.sound.VehicleSoundConvert;
import com.xindazhou.vehicle.dal.dataobject.sound.VehicleSoundDO;
import com.xindazhou.vehicle.dal.mysql.sound.VehicleSoundMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.xindazhou.vehicle.enums.ErrorCodeConstants.VEHICLE_SOUND_NOT_EXISTS;

/**
 * APP音效管理 Service 实现类
 *
 * @author xindazhou
 */
@Service
@Validated
public class VehicleSoundServiceImpl implements VehicleSoundService {

    @Resource
    private VehicleSoundMapper soundMapper;

    @Override
    public PageResult<VehicleSoundRespVO> getVehicleSoundPage(VehicleSoundPageReqVO pageReqVO) {
        PageResult<VehicleSoundDO> pageResult = soundMapper.selectPage(pageReqVO);
        return VehicleSoundConvert.INSTANCE.convertPage(pageResult);
    }

    @Override
    public VehicleSoundRespVO getVehicleSound(Long id) {
        VehicleSoundDO sound = soundMapper.selectById(id);
        if (sound == null) {
            throw ServiceExceptionUtil.exception(VEHICLE_SOUND_NOT_EXISTS);
        }
        return VehicleSoundConvert.INSTANCE.convert(sound);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createVehicleSound(VehicleSoundSaveReqVO createReqVO) {
        VehicleSoundDO sound = VehicleSoundConvert.INSTANCE.convert(createReqVO);
        soundMapper.insert(sound);
        return sound.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVehicleSound(VehicleSoundSaveReqVO updateReqVO) {
        validateVehicleSoundExists(updateReqVO.getId());
        VehicleSoundDO updateObj = VehicleSoundConvert.INSTANCE.convert(updateReqVO);
        soundMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteVehicleSound(Long id) {
        validateVehicleSoundExists(id);
        soundMapper.deleteById(id);
    }

    private void validateVehicleSoundExists(Long id) {
        if (soundMapper.selectById(id) == null) {
            throw ServiceExceptionUtil.exception(VEHICLE_SOUND_NOT_EXISTS);
        }
    }

}
