package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yh.saas.plugin.yiliangyiyun.entity.WarehousePositionInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.WarehousePositionStorageInfo;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.WarehousePositionInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IWarehousePositionInfoService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.service.IWarehousePositionStorageInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 记录仓库仓位信息 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-05-21
 */
@Service
public class WarehousePositionInfoServiceImpl extends ServiceImpl<WarehousePositionInfoMapper, WarehousePositionInfo> implements IWarehousePositionInfoService {

    @Autowired
    private IWarehousePositionStorageInfoService warehousePositionStorageInfoService;

    /**
     * 删除仓位
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWarehousePosition(String id) {
        WarehousePositionInfo warehousePositionInfo = this.selectById(id);
        if (warehousePositionInfo.getNowStorage() != null && warehousePositionInfo.getNowStorage() > 0) {
            throw new YException(YExceptionEnum.WAREHOSE_SYSTEM_ERROR);
        } else {
            this.deleteById(warehousePositionInfo.getId());
            List<WarehousePositionStorageInfo> warehousePositionStorageInfoList = warehousePositionStorageInfoService
                    .selectList(new EntityWrapper<WarehousePositionStorageInfo>()
                            .eq("position_id", id));
            if (!CollectionUtils.isEmpty(warehousePositionStorageInfoList)) {
                warehousePositionStorageInfoList.forEach(warehousePositionStorageInfo -> {
                    warehousePositionStorageInfoService.deleteById(warehousePositionStorageInfo.getId());
                });
            }
        }
    }

}
