package cn.iocoder.yudao.module.asset.service.parking;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.asset.controller.admin.parking.vo.ParkingPageReqVO;
import cn.iocoder.yudao.module.asset.controller.admin.parking.vo.ParkingSaveReqVO;
import cn.iocoder.yudao.module.asset.dal.dataobject.parking.ParkingDO;
import cn.iocoder.yudao.module.asset.dal.mysql.parking.ParkingMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.util.List;

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

/**
 * 停车场 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ParkingServiceImpl implements ParkingService {

    @Resource
    private ParkingMapper parkingMapper;

    @Override
    public Long createParking(ParkingSaveReqVO createReqVO) {
        // 业务校验
        validateParkingBusiness(createReqVO);
        
        ParkingDO parking = BeanUtils.toBean(createReqVO, ParkingDO.class);
        parkingMapper.insert(parking);
        return parking.getId();
    }

    @Override
    public void updateParking(ParkingSaveReqVO updateReqVO) {
        validateParkingExists(updateReqVO.getId());
        
        // 业务校验
        validateParkingBusiness(updateReqVO);
        
        ParkingDO updateObj = BeanUtils.toBean(updateReqVO, ParkingDO.class);
        parkingMapper.updateById(updateObj);
    }

    @Override
    public void deleteParking(Long id) {
        validateParkingExists(id);
        parkingMapper.deleteById(id);
    }

    private void validateParkingExists(Long id) {
        if (parkingMapper.selectById(id) == null) {
            throw exception(PARKING_NOT_EXISTS);
        }
    }

    /**
     * 业务校验
     */
    private void validateParkingBusiness(ParkingSaveReqVO reqVO) {
        // 校验已停车辆数不能超过容量
        if (reqVO.getCapacity() != null && reqVO.getParkedAmount() != null) {
            if (reqVO.getParkedAmount() > reqVO.getCapacity()) {
                throw exception(PARKING_PARKED_AMOUNT_EXCEED_CAPACITY);
            }
        }
        
        // 校验租赁时间
        if (reqVO.getLeaseStartDate() != null && reqVO.getLeaseEndDate() != null) {
            if (reqVO.getLeaseEndDate().isBefore(reqVO.getLeaseStartDate())) {
                throw exception(PARKING_LEASE_END_DATE_BEFORE_START_DATE);
            }
        }
    }

    @Override
    public ParkingDO getParking(Long id) {
        return parkingMapper.selectById(id);
    }

    @Override
    public PageResult<ParkingDO> getParkingPage(ParkingPageReqVO pageReqVO) {
        return parkingMapper.selectPage(pageReqVO);
    }

    @Override
    public List<ParkingDO> getParkingSimpleList() {
        return parkingMapper.selectSimpleList();
    }

}
