package com.wms_main.service.controller.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.wms_main.constant.enums.wms.OrderStatusEnum;
import com.wms_main.dao.ITAppOrderInService;
import com.wms_main.dao.ITAppOrderOutService;
import com.wms_main.dao.ITAppStockService;
import com.wms_main.model.dto.request.ycwms.*;
import com.wms_main.model.dto.response.ycwms.YcwmsResponse;
import com.wms_main.model.po.TAppOrderIn;
import com.wms_main.model.po.TAppOrderOut;
import com.wms_main.model.po.TAppStock;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.repository.utils.UUIDUtils;
import com.wms_main.service.controller.IYcwmsControllerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class YcwmsControllerServiceImpl implements IYcwmsControllerService {

    private final ITAppOrderInService appOrderInService;
    private final ITAppOrderOutService appOrderOutService;
    private final ITAppStockService appStockService;

    @Override
    public YcwmsResponse<Object> orderIn(OrderInReq request) {
        log.info("入库单请求参数{}", JSON.toJSON(request));
        if(request == null) return YcwmsResponse.error("参数错误", null);
        if(StringUtils.isEmpty(request.getOrderId())
                || StringUtils.isEmpty(request.getVehicleNo()) || StringUtils.isEmpty(request.getVehicleSize())
                || StringUtils.isEmpty(request.getInStand()) || request.getGoodsDetail() == null || request.getGoodsDetail().isEmpty()) {
            return YcwmsResponse.error("参数错误", null);
        }
        // 校验是否存在相同的入库单
        List<TAppOrderIn> withOrderId = appOrderInService.getWithOrderId(request.getOrderId());
        if(withOrderId == null) {
            return YcwmsResponse.error("数据服务异常，请稍后重试", null);
        }
        if(!withOrderId.isEmpty()) {
            return YcwmsResponse.error("入库单已存在，请勿重复推送", null);
        }
        List<TAppOrderIn> orderInList = new ArrayList<>();
        for (var goodsDetail : request.getGoodsDetail()) {
            if(goodsDetail == null || StringUtils.isEmpty(goodsDetail.getGoodsId()) || goodsDetail.getQuantity() == null) {
                return YcwmsResponse.error("参数错误", null);
            }
            TAppOrderIn orderIn = new TAppOrderIn();
            orderIn.setRecordId(UUIDUtils.getNewUUID());
            orderIn.setOrderId(request.getOrderId());
            orderIn.setVehicleNo(request.getVehicleNo());
            orderIn.setVehicleSize(request.getVehicleSize());
            orderIn.setInStand(request.getInStand());
            orderIn.setClientId(request.getClientId());
            orderIn.setGoodsId(goodsDetail.getGoodsId());
            orderIn.setGoodsName(goodsDetail.getGoodsName());
            orderIn.setBatch(goodsDetail.getBatch());
            orderIn.setGoodsType(goodsDetail.getGoodsType());
            orderIn.setSpecification(goodsDetail.getSpecification());
            orderIn.setQuantity(goodsDetail.getQuantity());
            orderIn.setGoodsDesc(goodsDetail.getGoodsDesc());
            orderIn.setOrderStatus(OrderStatusEnum.CREATE.getCode());
            orderIn.setCreateTime(LocalDateTime.now());
            orderIn.setUpdateTime(LocalDateTime.now());
            orderInList.add(orderIn);
        }
        if(!appOrderInService.saveBatch(orderInList)) {
            return YcwmsResponse.error("入库单保存失败，请稍后再试", null);
        }
        return YcwmsResponse.success();
    }

    @Override
    public YcwmsResponse<Object> orderOut(OrderOutReq request) {
        log.info("亚驰出库单请求参数{}", JSON.toJSON(request));
        if(request == null) return YcwmsResponse.error("参数错误", null);
        if(StringUtils.isEmpty(request.getOrderId()) || request.getQuantity() == null
                || (StringUtils.isEmpty(request.getGoodsId()) && request.getBatch() == null && request.getSpecification() == null)) {
            return YcwmsResponse.error("参数错误", null);
        }
        List<TAppOrderOut> orderOutCheckList = appOrderOutService.getWithOrderId(request.getOrderId());
        if(orderOutCheckList == null) {
            return YcwmsResponse.error("数据服务异常，请稍后重试", null);
        }
        if(!orderOutCheckList.isEmpty()) {
            return YcwmsResponse.error("出库单已存在，请勿重复推送", null);
        }
        TAppOrderOut orderOut = new TAppOrderOut();
        orderOut.setRecordId(UUIDUtils.getNewUUID());
        orderOut.setOrderId(request.getOrderId());
        orderOut.setGoodsId(request.getGoodsId());
        orderOut.setBatch(request.getBatch());
        orderOut.setSpecification(request.getSpecification());
        orderOut.setQuantity(request.getQuantity());
        orderOut.setOrderStatus(OrderStatusEnum.CREATE.getCode());
        orderOut.setCreateTime(LocalDateTime.now());
        orderOut.setUpdateTime(LocalDateTime.now());
        if(!appOrderOutService.save(orderOut)) {
            return YcwmsResponse.error("出库单保存失败，请稍后再试", null);
        }
        return YcwmsResponse.success();
    }

    @Override
    public YcwmsResponse<List<StockResp>> stock(StockReq request) {
        log.info("亚驰库存请求参数{}", JSON.toJSON(request));
        if(request == null) return YcwmsResponse.error("参数错误", null);
        // stocks: 请求库存的当前库存
        List<TAppStock> stocks = null;
        if(request.empty()) {
            stocks = appStockService.list();
        } else {
            TAppStock queryEntity = new TAppStock();
            queryEntity.setGoodsId(request.getGoodsId());
            queryEntity.setLocationId(request.getLocation());
            queryEntity.setSled(request.getSpecification());
            queryEntity.setVehicleId(request.getVehicleNo());
            stocks = appStockService.getWithEntity(queryEntity);
        }
        if(stocks == null) {
            return YcwmsResponse.error("数据服务异常，请稍后重试", null);
        }
        List<StockResp> respList = new ArrayList<>();
        // locations: 当前库存的对应库位
        List<String> locations = stocks.stream().map(TAppStock::getLocationId).distinct().toList();
        // 检查每个库存的库位location
        for (var location : locations) {
            // 库存反馈
            StockResp stockResp = new StockResp();
            // 查询location库位上当前有多少库存locationStocks
            List<TAppStock> locationStocks = stocks.stream().filter(stock -> stock.getLocationId().equals(location)).toList();
            if(locationStocks.isEmpty()) {
                continue;
            }
            stockResp.setVehicleNo(locationStocks.getFirst().getVehicleId());
            stockResp.setLocation(location);
            List<StockRespGoodsDetail> goodsDetails = new ArrayList<>();
            for (var stock : locationStocks) {
                StockRespGoodsDetail goodsDetail = new StockRespGoodsDetail();
                goodsDetail.setGoodsId(stock.getGoodsId());
                goodsDetail.setGoodsName(stock.getGoodsDesc());
                goodsDetail.setSpecification(stock.getSled());
                goodsDetail.setQuantity(stock.getTotalNum());
                goodsDetail.setGoodsDesc(stock.getGoodsDesc());
                goodsDetail.setStoreTime(stock.getFirstInTime());
                goodsDetail.setBatch(stock.getBatch());
                goodsDetail.setGoodsType(stock.getGoodsType());
                goodsDetails.add(goodsDetail);
            }
            stockResp.setGoodsDetail(goodsDetails);
            respList.add(stockResp);
        }
        return YcwmsResponse.success(respList);
    }


}
