package com.wms_main.service.business.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wms_main.app.AppCommon;
import com.wms_main.constant.enums.wms.AppConfigKeyEnums;
import com.wms_main.dao.ITAppStockService;
import com.wms_main.dao.ITAppStockUpdateService;
import com.wms_main.dao.ITAppVehicleService;
import com.wms_main.model.bo.wms.StockConfirmEntity;
import com.wms_main.model.po.TAppStock;
import com.wms_main.model.po.TAppStockUpdate;
import com.wms_main.model.po.TAppVehicle;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.repository.utils.UUIDUtils;
import com.wms_main.service.business.IStockDataService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 库存数据服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class StockDataServiceImpl implements IStockDataService {
    private final ITAppStockService appStockService;// 库存服务
    private final ITAppVehicleService appVehicleService;// 载具服务
    private final AppCommon appCommon;// app通用数据
    private final ITAppStockUpdateService appStockUpdateService;// 库存更新服务

    /**
     * 更新库存信息 实现
     * @param stockConfirm 库存确认信息
     */
    @Override
    public void updateStockInfo(StockConfirmEntity stockConfirm, String standId, String userName, String reason) {
        if (stockConfirm == null || StringUtils.isEmpty(stockConfirm.getVehicleId()) || StringUtils.isEmpty(stockConfirm.getGoodsId())
                || stockConfirm.getRealRemainQty() == null) {
            return;
        }
        // 查询对应的库存信息
        List<TAppStock> stockList = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                .eq(TAppStock::getVehicleId, stockConfirm.getVehicleId())
                .eq(TAppStock::getGoodsId, stockConfirm.getGoodsId())
                .orderByDesc(TAppStock::getFirstInTime)
        );
        // 更新列表
        List<TAppStock> removeStocks = new ArrayList<>();
        List<TAppStock> updateStocks = new ArrayList<>();
        // 库存更新记录列表
        List<TAppStockUpdate> stockUpdateList = new ArrayList<>();
        // 剩余数量
        int remainQty = stockConfirm.getPlanRemainQty();
        for (TAppStock stock : stockList) {
            if (remainQty <= 0) {
                removeStocks.add(stock);
                continue;
            }
            if (stock.getRealNum() <= remainQty) {
                remainQty -= stock.getRealNum();
            } else {
                TAppStockUpdate stockUpdate = new TAppStockUpdate(
                        UUIDUtils.getNewUUID(),
                        stock.getVehicleId(),
                        stock.getGoodsId(),
                        stock.getFirstInTime(),
                        stock.getRealNum(),
                        remainQty,
                        standId + "：" + reason,
                        stock.getLastUpdateTime(),
                        userName
                        );
                stockUpdateList.add(stockUpdate);
                stock.setRealNum(remainQty);
                remainQty = 0;
            }
            updateStocks.add(stock);
        }
        // 删除库存
        if (!removeStocks.isEmpty()) {
            appStockService.removeBatchByIds(removeStocks.stream().map(TAppStock::getStockId).toList());
        }
        // 更新库存数量
        if (!updateStocks.isEmpty()) {
            appStockService.updateBatchById(updateStocks);
        }
        // 增加库存更新记录
        if (!stockUpdateList.isEmpty()) {
            appStockUpdateService.saveBatch(stockUpdateList);
        }
    }

    /**
     * 获得库存预警值---实现
     * @return 库存预警值
     */
    @Override
    public int getWarningQty() {
        int warningQty = 5;
        try {
            // 获取配置数据
            warningQty = Integer.parseInt(appCommon.getConfigByKey(AppConfigKeyEnums.STOCK_WARNING_QTY.getKey()));
        } catch (Exception e) {
            log.warn("获取库存预警值失败，使用默认值5。");
        }
        return warningQty;
    }

    /**
     * 判断当前载具是否是空载具
     * @param vehicleId 载具号
     * @return true：空载具；false：非空载具
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean isEmptyVehicle(String vehicleId) {
        // 查询这个载具的所有库存数据
        List<TAppStock> thisVehicleStocks = appStockService.list(new LambdaQueryWrapper<TAppStock>()
                .eq(TAppStock::getVehicleId, vehicleId)
                .gt(TAppStock::getRealNum, 0)
        );
        boolean isEmpty = thisVehicleStocks == null || thisVehicleStocks.isEmpty();
        if (isEmpty) {
            // 更新载具数据
            appVehicleService.update(new LambdaUpdateWrapper<TAppVehicle>()
                    .set(TAppVehicle::getIsEmpty, 1)
                    .eq(TAppVehicle::getVehicleId, vehicleId)
                    .ne(TAppVehicle::getIsEmpty, 1));
        }
        return isEmpty;
    }
}
