package com.wms_main.service.controller.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms_main.dao.ITAppStockService;
import com.wms_main.model.dto.query.StockQuery;
import com.wms_main.model.dto.response.wms.WmsApiResponse;
import com.wms_main.model.po.TAppStock;
import com.wms_main.model.vo.wms.PageVo;
import com.wms_main.model.vo.wms.StockVo;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.service.controller.IStockControllerService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 库存控制类 服务实现
 */
@Service
@RequiredArgsConstructor
public class StockControllerServiceImpl implements IStockControllerService {
    private final ITAppStockService appStockService;// 库存服务

    /**
     * 查询库存---分页实现
     *
     * @param stockQuery 查询参数
     * @return 查询结果
     */
    @Override
    public WmsApiResponse<PageVo<StockVo>> queryStocksByPage(StockQuery stockQuery) {
        if (stockQuery == null) {
            return WmsApiResponse.error("查询参数不能为NULL", null);
        }
        Page<TAppStock> page = stockQuery.toMpPage();
        LambdaQueryWrapper<TAppStock> lambdaQueryWrapper = new LambdaQueryWrapper<TAppStock>()
                .like(StringUtils.isNotEmpty(stockQuery.getVehicleId()), TAppStock::getVehicleId, stockQuery.getVehicleId())
                .like(StringUtils.isNotEmpty(stockQuery.getLocationId()), TAppStock::getLocationId, stockQuery.getLocationId())
                .eq(StringUtils.isNotEmpty(stockQuery.getStandId()), TAppStock::getBarCode, stockQuery.getStandId())
                .eq(StringUtils.isNotEmpty(stockQuery.getGoodsId()), TAppStock::getGoodsId, stockQuery.getGoodsId())
                .eq(stockQuery.getStockStatus() != null, TAppStock::getStockStatus, stockQuery.getStockStatus())
                .eq(stockQuery.getGoodsStatus() != null, TAppStock::getGoodsStatus, stockQuery.getGoodsStatus());
        if (stockQuery.getFromDate() != null) {
            lambdaQueryWrapper.ge(TAppStock::getFirstInTime, stockQuery.getFromDate().atStartOfDay());
        }
        if (stockQuery.getToDate() != null) {
            // toDate + 1天的凌晨。
            lambdaQueryWrapper.lt(TAppStock::getFirstInTime, stockQuery.getToDate().plusDays(1).atStartOfDay());
        }
        Page<TAppStock> stockPage = appStockService.page(page, lambdaQueryWrapper);

        PageVo<StockVo> pageVo = PageVo.of(stockPage, StockVo::ofPo);
        return WmsApiResponse.success("查询库存数据成功", pageVo);
    }
}
