package com.wms.service.serviceImplements;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wms.entity.table.Stock;
import com.wms.entity.table.StockUpdateRecord;
import com.wms.mapper.StockUpdateRecordMapper;
import com.wms.service.IStockUpdateRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

import static com.wms.utils.WmsUtils.generateId;

/**
 * 库存接收记录服务实现类
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class StockUpdateRecordServiceImpl extends ServiceImpl<StockUpdateRecordMapper, StockUpdateRecord> implements IStockUpdateRecordService {
    private final StockUpdateRecordMapper stockUpdateRecordMapper;
    @Override
    public boolean addStockUpdateRecord(Stock stockBefore, Stock stockAfter, String reason, String opUser, BigDecimal quantityBefore) {
        if (stockBefore == null && stockAfter == null) {
            return false;
        }
        StockUpdateRecord stockUpdateRecord = new StockUpdateRecord();
        stockUpdateRecord.setRecordId(generateId("STOCK_UPDATE_"));
        // 解析数据
        if (stockBefore != null) {
            stockUpdateRecord.setStockId(stockBefore.getStockId());
            stockUpdateRecord.setGoodsId(stockBefore.getGoodsRelated().getGoodsId());
            stockUpdateRecord.setGoodsName(stockBefore.getGoodsRelated().getGoodsName());
            stockUpdateRecord.setVehicleId(stockBefore.getVehicleId());
            stockUpdateRecord.setLocationBefore(stockBefore.getLocationId());
            stockUpdateRecord.setQuantityBefore(quantityBefore);
        } else {
            stockUpdateRecord.setStockId(stockAfter.getStockId());
            stockUpdateRecord.setGoodsId(stockAfter.getGoodsRelated().getGoodsId());
            stockUpdateRecord.setGoodsName(stockAfter.getGoodsRelated().getGoodsName());
            stockUpdateRecord.setVehicleId(stockAfter.getVehicleId());
            stockUpdateRecord.setLocationBefore("");
            stockUpdateRecord.setQuantityBefore(BigDecimal.ZERO);
        }
        if (stockAfter != null) {
            stockUpdateRecord.setLocationAfter(stockAfter.getLocationId());
            stockUpdateRecord.setQuantityAfter(stockAfter.getGoodsRelated().getRemainNum());
        }
        stockUpdateRecord.setReason(reason);
        stockUpdateRecord.setUpdateTime(LocalDateTime.now());
        stockUpdateRecord.setUpdateUser(opUser);
        return stockUpdateRecordMapper.insert(stockUpdateRecord) > 0;
    }
}
