/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.estate.service.impl;

import cn.hutool.core.lang.Assert;
import org.springblade.estate.entity.Car;
import org.springblade.estate.entity.ParkingSpace;
import org.springblade.estate.service.ICarService;
import org.springblade.estate.vo.ParkingSpaceVO;
import org.springblade.estate.mapper.ParkingSpaceMapper;
import org.springblade.estate.service.IParkingSpaceService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * 车位信息 服务实现类
 *
 * @author BladeX
 * @since 2021-03-30
 */
@Service
public class ParkingSpaceServiceImpl extends BaseServiceImpl<ParkingSpaceMapper, ParkingSpace> implements IParkingSpaceService {

	@Resource
	private ICarService carService;

	@Override
	public IPage<ParkingSpaceVO> selectParkingSpacePage(IPage<ParkingSpaceVO> page, ParkingSpaceVO parkingSpace) {
		return page.setRecords(baseMapper.selectParkingSpacePage(page, parkingSpace));
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public Boolean bindCar(Long carId, Long parkingSpaceId) {
		ParkingSpace parkingSpace = this.getById(parkingSpaceId);
		Assert.notNull(parkingSpace, "找不到对应的车位信息");
		Car car = carService.getById(carId);
		Assert.notNull(parkingSpace, "找不到车辆信息");

		if (!Objects.isNull(parkingSpace.getCarId()) && !Objects.equals(parkingSpace.getCarId(), carId)) {
			//换绑车位
			this.changeInitialCar(parkingSpace.getCarId());
		}
		parkingSpace.setCarId(carId);
		parkingSpace.setIsUsed(1);
		parkingSpace.setCarNo(car.getNumber());


		car.setParkingLotId(parkingSpace.getParkingLotId());
		carService.updateById(car);
		return this.updateById(parkingSpace);
    }

	/**
	 * 将初始的车辆车场置空
	 * @param carId
	 */
	private void changeInitialCar(Long carId) {
		Car initialCar = carService.getById(carId);
		if (initialCar != null) {
			initialCar.setParkingLotId(null);
			carService.updateById(initialCar);
		}
	}

}
