package com.wms.service.serviceImplements;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wms.entity.app.dto.StockOfGoodsDto;
import com.wms.entity.app.dto.extend.StockDetailInfo;
import com.wms.entity.table.Goods;
import com.wms.entity.table.Stock;
import com.wms.entity.table.WorkFlow;
import com.wms.mapper.StockMapper;
import com.wms.service.GoodsService;
import com.wms.service.StockService;
import com.wms.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import static com.wms.constants.WmsConstants.MYSQL_JSON_CI;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class StockServiceImplements extends ServiceImpl<StockMapper, Stock> implements StockService {
    /**
     * 库存mapper
     */
    private final StockMapper stockMapper;
    /**
     * 物料服务
     */
    private final GoodsService goodsService;

    /**
     * 查询物流总库存数
     * @param goodsId 查询条件
     * @return 结果
     */
    @Override
    public List<StockOfGoodsDto> selectSumOfGoods(String goodsId) {
        if (StringUtils.isNotEmpty(goodsId)) {
            List<String> godsIds = new ArrayList<>();
            godsIds.add(goodsId);
            return selectSumOfGoods(godsIds);
        } else {
            return selectSumOfGoods(new ArrayList<>());
        }
    }

    /**
     * 查询物流总库存数
     * @param goodsIdList 查询条件
     * @return 结果
     */
    @Override
    public List<StockOfGoodsDto> selectSumOfGoods(List<String> goodsIdList) {
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();
        if (goodsIdList != null && !goodsIdList.isEmpty()) {
            StringBuilder goodsSqlString = new StringBuilder();
            for (String goodsId : goodsIdList) {
                if (goodsSqlString.toString().equals("")) {
                    goodsSqlString.append("(goods_related ->> '$.goodsId' in (\"").append(goodsId).append("\"");
                } else {
                    goodsSqlString.append(",\"").append(goodsId).append("\"");
                }
            }
            goodsSqlString.append("))");
            queryWrapper.apply(goodsSqlString + MYSQL_JSON_CI);
        }
        // 先查询库存
        List<Stock> stocks = stockMapper.selectList(queryWrapper);
        if (stocks == null || stocks.isEmpty()) {
            // 查不到对应物料的库存
            return Collections.emptyList();
        }
        // 对库存做处理
        Map<String, BigDecimal> stockOfGoodsMap = new HashMap<>();
        for (Stock stock : stocks) {
            StockDetailInfo goodsDetail = stock.getGoodsRelated();
            if (stockOfGoodsMap.containsKey(goodsDetail.getGoodsId())) {
                // 直接增加数量
                stockOfGoodsMap.replace(goodsDetail.getGoodsId(), stockOfGoodsMap.get(goodsDetail.getGoodsId()).add(goodsDetail.getRemainNum()));
            } else {
                // 添加map的键值对
                stockOfGoodsMap.put(goodsDetail.getGoodsId(), goodsDetail.getRemainNum());
            }
        }
        // 根据上述结果集查询物料信息
        List<Goods> goodsList = goodsService.list(new LambdaQueryWrapper<Goods>()
                .in(Goods::getGoodsId, stockOfGoodsMap.keySet()));
        // 循环Map生成结果集
        List<StockOfGoodsDto> resultList = new ArrayList<>();
        for (String goodsId : stockOfGoodsMap.keySet()) {
            StockOfGoodsDto tempResult = new StockOfGoodsDto();// 临时结果集
            tempResult.setGoodsId(goodsId);
            tempResult.setRemainNumSum(stockOfGoodsMap.get(goodsId));
            // 获取当前物料信息
            List<Goods> currentGoodsList = goodsList.stream().filter(goods1 -> goods1.getGoodsId().equals(goodsId)).toList();
            if (!currentGoodsList.isEmpty()) {
                // 设定物料相关信息
                tempResult.setGoodsName(currentGoodsList.get(0).getGoodsName());
                tempResult.setFeedType(currentGoodsList.get(0).getFeedingType());
                tempResult.setFeedPoint(currentGoodsList.get(0).getFeedingValue());
                tempResult.setBoxType(currentGoodsList.get(0).getVehicleTypeDescription());
                tempResult.setNumOfKanban(currentGoodsList.get(0).getKanbanNum());
                tempResult.setNumOfPerKanban(currentGoodsList.get(0).getQuantityPerKanban());
                tempResult.setKanbanList(currentGoodsList.get(0).getKanbanList());
                tempResult.setHeat(currentGoodsList.get(0).getHeat());// 热度
                tempResult.setReleasePoint(currentGoodsList.get(0).getReleasePoint());// 卸货点
            }
            resultList.add(tempResult);
        }

        // 返回结果集
        return resultList;
    }
}