郑永安
2023-06-19 2fcd97552d16718cc7997629fd637a73a5a4483f
src/main/java/com/gk/firework/Service/ServiceImpl/StockServiceImpl.java
对比新文件
@@ -0,0 +1,899 @@
package com.gk.firework.Service.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gk.firework.Domain.*;
import com.gk.firework.Domain.BO.DirectionProductBO;
import com.gk.firework.Domain.BO.ProductLocusInfoBO;
import com.gk.firework.Domain.BO.SaleOrderDetailInfoBO;
import com.gk.firework.Domain.DO.ProductDO;
import com.gk.firework.Domain.Exception.BusinessException;
import com.gk.firework.Domain.Extension.StockTotal;
import com.gk.firework.Domain.Utils.Msg;
import com.gk.firework.Domain.Utils.PageInfo;
import com.gk.firework.Domain.Utils.StringUtils;
import com.gk.firework.Domain.Vo.*;
import com.gk.firework.Mapper.ProductInfoMapper;
import com.gk.firework.Mapper.StockInfoMapper;
import com.gk.firework.Service.*;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import java.math.BigDecimal;
import java.util.*;
import static com.gk.firework.Domain.Enum.ErrorCode.*;
/**
 * @author : jingjy
 * @date : 2021/3/24 14:04
 */
@Service("StockService")
public class StockServiceImpl extends ServiceImpl<StockInfoMapper, StockInfo> implements StockService {
    @Autowired
    private StockInfoMapper stockInfoMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;
    @Autowired
    private ProductLocusService productLocusService;
    @Autowired
    private ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private SoldNoStockService soldNoStockService;
    @Autowired
    private EntryService entryService;
    @Autowired
    private SaleOrderService saleOrderService;
    @Autowired
    private SaleOrderDetailService saleOrderDetailService;
    @Autowired
    private DeliveryOrderService deliveryOrderService;
    @Autowired
    private WarnContentService warnContentService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private StaticStockService staticStockService;
    /** 入库 **/
    @Override
    public boolean putInStorage(UserInfo userInfo, List<ProductVo> productVos, Date datetime, String type) {
        boolean flag = false;
        for (ProductVo productVo : productVos){
            StockInfo stockInfo = selectStockByDirection(productVo.getDirectionCode());
            ProductInfo productInfo = productInfoMapper.selectProductByDirectionCode(productVo.getItemCode());
            ProductLocusInfo productLocusInfo = new ProductLocusInfo();
            //如果为空则创建
            if (stockInfo == null){
                stockInfo = new StockInfo();
                stockInfo.setDirectioncode(productVo.getDirectionCode());
                stockInfo.setCreateddate(new Date());
                stockInfo.setCreatedby(userInfo.getUsername());
                stockInfo.setDirectionboxcode(String.format("%03d",productVo.getBoxNumber()));
                stockInfo.setModifieddate(datetime);
                stockInfo.setNum(1);
                stockInfo.setOperator(userInfo.getUsername());
                stockInfo.setIndate(datetime);
                stockInfo.setProductid(productInfo.getId());
                stockInfo.setOwner(userInfo.getCompanyid().toString());
                stockInfo.setFlag((byte)0);
                stockInfo.setType(Byte.parseByte(type));
                int i = insertStockInfo(stockInfo);
                if (i == 1){ flag = true; }
                productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),
                        datetime,userInfo.getCompany(),null,ProductLocusInfo.ENTRY_STATUS,
                        productVo.getBoxNumber().toString());
                productLocusService.insertProductLocus(productLocusInfo);
            }else {
                //一般入库
                if (EntryUtils.RK_ENTRY.equals(type)){
                    // 判断入库是否大于修改时间,小于修改时间不做修改
                    if (stockInfo.getModifieddate().compareTo(datetime) > 0 ){
                        continue;
                    }
                    //如果不为空,判断flag,如果flag=1,则不进行修改,只记录流向,否则修改owner
                    if (stockInfo.getFlag() == 0){
                        stockInfo.setModifieddate(datetime);
                        stockInfo.setModifiedby(userInfo.getUsername());
                        stockInfo.setIndate(datetime);
                        stockInfo.setOwner(userInfo.getCompanyid().toString());
                        stockInfo.setFlag((byte)0);
                        stockInfo.setStatus("");
                    }
                    productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),
                            datetime,userInfo.getCompany(),null,ProductLocusInfo.ENTRY_STATUS,
                            productVo.getBoxNumber().toString());
                }else if (EntryUtils.TH_ENTRY.equals(type)){
                    //退货入库
                    //未使用
                    stockInfo.setOwner(userInfo.getCompanyid().toString());
                    stockInfo.setModifieddate(datetime);
                    stockInfo.setModifiedby(userInfo.getUsername());
                    stockInfo.setStatus("");
                    productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),
                            datetime,userInfo.getCompany(),null,ProductLocusInfo.RETURN_ENTRY_STATUS,
                            productVo.getBoxNumber().toString());
                }
                productLocusService.insertProductLocus(productLocusInfo);
                int i = updateStockInfo(stockInfo);
                if (i == 1){ flag = true; }
            }
        }
        return flag;
    }
    @Override
    public void setProductEntryStatus(List<ProductVo> productVos, UserInfo userInfo) {
        if (productVos.size() != 0 && userInfo != null){
            for (ProductVo productVo : productVos) {
                if (isStockInfoExist(productVo.getDirectionCode(),userInfo.getCompanyid())){
                    productVo.setEntryFlag("历史入库");
                }else {
                    productVo.setEntryFlag("可以入库");
                }
            }
        }
    }
    @Override
    public void deliveryByDetail(Date datetime, List<DeliveryDetailInfo> deliveryDetailInfos, UserInfo userInfo) {
        List<ProductVo>productVos = new ArrayList<>();
        List<ProductLocusInfo>productLocusInfos = new ArrayList<>();
        for (DeliveryDetailInfo deliveryDetailInfo : deliveryDetailInfos){
            String dire = deliveryDetailInfo.getDirectioncode();
            DirectionDetail detail = FireworkDeal.dealDirectionCode(dire);
            ProductVo productVo = productInfoMapper.selectProductVoByDirectionCode(detail.getItemCode());
            if (FireworkDeal.is22Characters(dire)){
                FireworkDeal.getProductVos(dire,detail,detail,productVos,productVo);
                ProductLocusInfo productLocusInfo = new ProductLocusInfo(dire,new Date(),datetime,userInfo.getCompany()
                        ,null, ProductLocusInfo.DELIVERY_STATUS,detail.getBoxNo());
                productLocusInfos.add(productLocusInfo);
            }else if (FireworkDeal.is19Characters(dire)){
                productVos.add(productVo);
            }
        }
        for (ProductVo productVo : productVos){
            StockInfo stockInfo = selectStockByDirection(productVo.getDirectionCode());
            DirectionDetail detail = FireworkDeal.dealDirectionCode(productVo.getDirectionCode());
            ProductInfo productInfo = productService.selectByDirection(productVo.getDirectionCode());
            ProductLocusInfo productLocusInfo = new ProductLocusInfo(productVo.getDirectionCode(),new Date(),datetime,userInfo.getCompany()
                    ,null, ProductLocusInfo.DELIVERY_STATUS,detail.getBoxNo());
            productLocusInfos.add(productLocusInfo);
            if (stockInfo == null) {
                stockInfo = new StockInfo();
                stockInfo.setDirectioncode(productVo.getDirectionCode());
                stockInfo.setCreateddate(new Date());
                stockInfo.setDirectionboxcode(String.format("%03d", productVo.getBoxNumber()));
                stockInfo.setCreatedby(userInfo.getUsername());
                stockInfo.setNum(1);
                stockInfo.setOperator(userInfo.getUsername());
                stockInfo.setIndate(new Date());
                stockInfo.setProductid(productInfo.getId());
                stockInfo.setOwner("");
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setModifieddate(datetime);
                stockInfo.setOutdate(datetime);
                stockInfo.setFlag((byte) 0);
                stockInfo.setType((byte) 1);
                insertStockInfo(stockInfo);
            }else {
                //库存修改原则,时间最近的修改才生效
                // 判断出库是否大于修改时间,小于修改时间不做库存修改
                if (stockInfo.getModifieddate().compareTo(datetime) > 0){
                    continue;
                }
                //出库后Owner设空
                stockInfo.setOwner("");
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setModifieddate(datetime);
                stockInfo.setOutdate(datetime);
                updateStockInfo(stockInfo);
            }
        }
        productLocusService.insertBatch(productLocusInfos);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Msg changeStockBySale(CustomerInfo customerInfo, List<SaleOrderDetailInfoBO> detailInfoList, UserInfo userInfo, Date salesTime) {
        Msg msg = new Msg();
        if (customerInfo == null || userInfo == null
                || detailInfoList == null || detailInfoList.size() ==0){
            msg.setCode(ERROR_10002.getCode());
            msg.setMessage(ERROR_10002.getMsg()+":销售出库失败");
            return msg;
        }
        Date now = new Date();
        List<ProductLocusInfo> productLocuses = new ArrayList<>();
        List<SoldNoStockInfo> soldNoStockInfos = new ArrayList<>();
        List<WarnContentInfo> warnContentInfos = new ArrayList<>();
        for (SaleOrderDetailInfoBO detailInfo : detailInfoList){
            DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(detailInfo.getDirectioncode());
            if (directionDetail.getLength().equals(FireworkDeal.DIRECTION_INSIDE)){
                ProductDO productInfo = detailInfo.getProductDO();
                //流向码为19位时
                StockInfo stockInfo = selectStockByDirectionAndSlice(directionDetail.getOriginalCode(),productInfo.getSlice());
                if (stockInfo == null){
                    //库存为空则插入
                    stockInfo = new StockInfo();
                    stockInfo.setDirectioncode(directionDetail.getOriginalCode());
                    stockInfo.setOwner(userInfo.getCompanyid().toString());
                    stockInfo.setCreateddate(now);
                    stockInfo.setCreatedby(userInfo.getUsername());
                    stockInfo.setDirectionboxcode(directionDetail.getBoxNo());
                    stockInfo.setModifieddate(salesTime);
                    stockInfo.setNum(1);
                    stockInfo.setOperator(userInfo.getUsername());
                    stockInfo.setIndate(new Date());
                    stockInfo.setProductid(productInfo.getId());
                    stockInfo.setOwner(userInfo.getCompanyid().toString());
                    stockInfo.setFlag((byte)0);
                    stockInfo.setType((byte)1);
                    //插入一条已销未入库
                    SoldNoStockInfo soldNoStockInfo = new SoldNoStockInfo();
                    soldNoStockInfo.setDirectioncode(stockInfo.getDirectioncode());
                    soldNoStockInfo.setItemcode(productInfo.getDirectionCode());
                    soldNoStockInfo.setItemname(productInfo.getName());
                    soldNoStockInfo.setSalestime(salesTime);
                    soldNoStockInfo.setSalesperson(userInfo.getUsername());
                    soldNoStockInfo.setCompanynumber(userInfo.getCompanynumber());
                    soldNoStockInfo.setCreatedat(new Date());
                    soldNoStockInfo.setCreatedby("系统生成");
                    soldNoStockInfo.setContent(productInfo.getManufacturer());
//                    soldNoStockService.save(soldNoStockInfo);
                    soldNoStockInfos.add(soldNoStockInfo);
                }
                if (stockInfo.getStatus() != null && stockInfo.getStatus().equals(StockInfo.STOCK_SOLD)
                        && !stockInfo.getOwner().equals(customerInfo.getId().toString())){
                    WarnContentInfo warnContentInfo = new WarnContentInfo();
                    warnContentInfo.setWarntype("多次售出");
                    warnContentInfo.setWarnlevel("预警");
                    warnContentInfo.setEnterpriseid(userInfo.getCompanyid());
                    warnContentInfo.setWarncontent(stockInfo.getDirectioncode()+"多次售出");
                    warnContentInfo.setIsmend((byte) 0);
                    warnContentInfo.setIsneed((byte) 0);
                    warnContentInfo.setIssend((byte) 0);
                    warnContentInfo.setModifiedby("系统生成");
                    warnContentInfo.setModifieddate(new Date());
                    warnContentInfo.setCreateddate(new Date());
                    warnContentInfos.add(warnContentInfo);
//                    warnContentService.save(warnContentInfo);
                }
                if (StringUtils.isNotBlank(stockInfo.getOwner()) && Long.parseLong(stockInfo.getOwner()) != userInfo.getCompanyid()
                    || StringUtils.isBlank(stockInfo.getOwner())){
                    //已销未入库信息插入
                    SoldNoStockInfo soldNoStockInfo = new SoldNoStockInfo();
                    soldNoStockInfo.setDirectioncode(stockInfo.getDirectioncode());
                    soldNoStockInfo.setItemcode(productInfo.getDirectionCode());
                    soldNoStockInfo.setItemname(productInfo.getName());
                    soldNoStockInfo.setSalestime(salesTime);
                    soldNoStockInfo.setSalesperson(userInfo.getUsername());
                    soldNoStockInfo.setCompanynumber(userInfo.getCompanynumber());
                    soldNoStockInfo.setCreatedat(new Date());
                    soldNoStockInfo.setCreatedby("系统生成");
                    soldNoStockInfo.setContent(productInfo.getManufacturer());
//                    soldNoStockService.save(soldNoStockInfo);
                    soldNoStockInfos.add(soldNoStockInfo);
                }
                stockInfo.setOwner(customerInfo.getId().toString());
                stockInfo.setModifieddate(salesTime);
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setStatus(StockInfo.STOCK_SOLD);
                int flag;
                if (stockInfo.getId() == null){
                    flag = this.insertStockInfoBySlice(stockInfo,productInfo.getSlice());
                }else {
                    flag = this.updateStockInfoBySlice(stockInfo,productInfo.getSlice());
                }
                //插入流向轨迹
//                ProductLocusInfo productLocusInfo = new ProductLocusInfo(directionDetail.getOriginalCode(),new Date(),salesTime,
//                        userInfo.getCompany(),customerInfo.getId(),ProductLocusInfo.SALES_STATUS,null);
//                productLocusService.insertProductLocus(productLocusInfo);
                ProductLocusInfoBO productLocusInfoBO = new ProductLocusInfoBO();
                productLocusInfoBO.setSlice(productInfo.getSlice());
                productLocusInfoBO.setDirectioncode(directionDetail.getOriginalCode());
                productLocusInfoBO.setCreateddate(now);
                productLocusInfoBO.setModifieddate(salesTime);
                productLocusInfoBO.setContent(userInfo.getCompany());
                productLocusInfoBO.setCustomerid(customerInfo.getId());
                productLocusInfoBO.setType(ProductLocusInfo.SALES_STATUS);
                productLocusInfoBO.setBoxcode(null);
                productLocuses.add(productLocusInfoBO);
                // 判断是否更新库存成功
                if (flag == 0){
                    msg.setCode(ERROR_30001.getCode());
                    msg.setMessage(ERROR_30001.getMsg()+":流向码为:"+directionDetail.getOriginalCode()+" 库存更新失败,销售失败");
                    break;
                }else {
                    msg.setCode(SUCCESS.getCode());
                    msg.setMessage("出库成功!");
                }
            }
        }
        if (productLocuses.size() > 0) {
            productLocusService.saveBatchLocus(productLocuses);
        }
        if (warnContentInfos.size() > 0) {
            warnContentService.saveBatchInfo(warnContentInfos);
        }
        if (soldNoStockInfos.size() > 0) {
            soldNoStockService.saveBatchInfo(soldNoStockInfos);
        }
        if (!SUCCESS.getCode().equals(msg.getCode())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return msg;
    }
    private boolean isStockInfoExist(String directionCode, Long id) {
        boolean flag = false;
        StockInfo stockInfo = selectStockByDireAndUser(id,directionCode);
        if (stockInfo != null){
            flag = true;
        }
        return flag;
    }
    private int insertStockInfo(StockInfo stockInfo){
        int i = 0;
        if (stockInfo == null){
            return i;
        }
        String slice = productService.getSlice(stockInfo.getDirectioncode());
        i = stockInfoMapper.insertStockInfo(stockInfo, slice);
        return i;
    }
    private int updateStockInfo(StockInfo stockInfo){
        int i = 0;
        if (stockInfo == null){
            return i;
        }
        String slice = productService.getSlice(stockInfo.getDirectioncode());
        i = stockInfoMapper.updateStockInfo(stockInfo,slice);
        return i;
    }
    @Override
    public StockInfo selectStockByDirection(String directionCode){
        String slice = productService.getSlice(directionCode);
        if (StringUtils.isBlank(slice)){
            return null;
        }
        return stockInfoMapper.selectStockByDirection(directionCode,slice);
    }
    @Override
    public int doReturn(StockInfo stockInfo, UserInfo userInfo, CustomerInfo customerInfo, Date date) {
        int flag = 0;
        if (stockInfo.getModifieddate().compareTo(date)>0){
            WarnContentInfo warnContentInfo = warnContentService.selectByWarnTypeAndContent("多次售出",stockInfo.getDirectioncode()+"多次售出");
            if (warnContentInfo != null){
                warnContentService.removeById(warnContentInfo.getId());
            }
        }else {
            stockInfo.setOwner(userInfo.getCompanyid().toString());
            stockInfo.setModifieddate(new Date());
            stockInfo.setModifiedby(userInfo.getUsername());
            stockInfo.setStatus("");
            flag = updateStockInfo(stockInfo);
        }
        //插入流向轨迹
        ProductLocusInfo productLocusInfo = new ProductLocusInfo(stockInfo.getDirectioncode(), new Date(), new Date(),
                userInfo.getCompany(), customerInfo == null ? null : customerInfo.getId(), ProductLocusInfo.RETURN_ENTRY_STATUS, null);
        productLocusService.insertProductLocus(productLocusInfo);
        return flag;
    }
    @Override
    public StockInfo selectStockByDireAndUser(Long companyId, String directionCode) {
        String slice = productService.getSlice(directionCode);
        if (StringUtils.isBlank(slice)){
            return new StockInfo();
        }
        return stockInfoMapper.selectStockByDireAndUser(directionCode,companyId,slice);
    }
    @Override
    public void updateStocks(List<StockInfo> stockInfos, UserInfo user) {
        for (StockInfo stockInfo : stockInfos){
            updateStockInfo(stockInfo);
            //插入流向轨迹
            ProductLocusInfo productLocusInfo = new ProductLocusInfo(stockInfo.getDirectioncode(),new Date(),new Date(),
                    user.getCompany(),null,ProductLocusInfo.RETURN_DELIVERY_STATUS,null);
            productLocusService.insertProductLocus(productLocusInfo);
        }
    }
    @Override
    public void selectDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc(pageInfo.getOrder().equalsIgnoreCase("ascending"));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("createddate");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("createddate");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        List<StockVo> stockVos = stockInfoMapper.selectStockDataGrid(pageInfo.getCondition(),page,list);
        /*for (StockVo stockVo : stockVos){
            pageInfo.getCondition().put("companyNumber",stockVo.getEnterpriseNumber());
            pageInfo.getCondition().put("itemCode",stockVo.getDirectioncode());
            BigDecimal entryNum = entryService.getEntryNumByCondition(pageInfo.getCondition());
            BigDecimal returnNum = entryService.getReturnNumByCondition(pageInfo.getCondition());
            BigDecimal saleNum = saleOrderService.getSaleNumByCondition(pageInfo.getCondition());
            BigDecimal deliveryNum = deliveryOrderService.getDeliveryNum(pageInfo.getCondition());
            BigDecimal returnDeliveryNum = deliveryOrderService.getReturnDeliveryNum(pageInfo.getCondition());
            BigDecimal zero = new BigDecimal("0");
            stockVo.setEntryNum(entryNum == null ? zero:entryNum);
            stockVo.setReturnNum(returnNum == null ? zero : returnNum);
            stockVo.setSaleNum(saleNum == null ? zero: saleNum);
            stockVo.setDeliveryNum(deliveryNum == null ? zero: deliveryNum);
            stockVo.setReturnDeliveryNum(returnDeliveryNum == null ? zero : returnDeliveryNum);
        }*/
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount(page.getTotal());
    }
    @Override
    public void selectEnterpriseStockDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc("ascending".equalsIgnoreCase(pageInfo.getOrder()));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("owner");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("owner");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        List<StockVo> stockVos = stockInfoMapper.selectEnterpriseStockDataGrid(pageInfo.getCondition(),page,list);
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount(page.getTotal());
    }
    @Override
    public List<NoEntryVo> selectNoEntryCount(Date time, Integer warnPeriod) {
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        return stockInfoMapper.selectNoEntryCount(time,list,warnPeriod);
    }
    @Override
    public void selectNoEntryDetail(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc(pageInfo.getOrder().equalsIgnoreCase("ascending"));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("modifieddate");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        pageInfo.getCondition().put("list",list);
        List<StockVo> stockVoList = stockInfoMapper.selectNoEntryDetail(page,pageInfo.getCondition());
        pageInfo.setResult(stockVoList);
        pageInfo.setTotalCount(page.getTotal());
    }
    @Override
    public void doReturnBatch(UserInfo userInfo, List<EntryDetailInfo> entryDetailInfos, Date date) {
        for (EntryDetailInfo entryDetailInfo : entryDetailInfos){
            String directionCode = entryDetailInfo.getDirectioncode();
            SaleOrderDetailInfo detailInfo = saleOrderService.selectOrderByDirectionReturnflag(directionCode,(byte) 0, null);
            CustomerInfo customerInfo = customerService.getCustomerBySaleOrder(detailInfo.getOrdercode());
            byte flag = 1;
            detailInfo.setReturnflag(flag);
            saleOrderDetailService.updateById(detailInfo);
            StockInfo stockInfo = selectStockByDirection(directionCode);
            if (stockInfo.getModifieddate().compareTo(date)>0){
                WarnContentInfo warnContentInfo = warnContentService.selectByWarnTypeAndContent("多次售出",stockInfo.getDirectioncode()+"多次售出");
                if (warnContentInfo != null){
                    warnContentService.removeById(warnContentInfo.getId());
                }
            }else {
                stockInfo.setOwner(userInfo.getCompanyid().toString());
                stockInfo.setModifieddate(new Date());
                stockInfo.setModifiedby(userInfo.getUsername());
                stockInfo.setStatus("");
                updateStockInfo(stockInfo);
            }
            //插入流向轨迹
            ProductLocusInfo productLocusInfo = new ProductLocusInfo(stockInfo.getDirectioncode(), new Date(), new Date(),
                    userInfo.getCompany(), customerInfo == null ? null : customerInfo.getId(), ProductLocusInfo.RETURN_ENTRY_STATUS, null);
            productLocusService.insertProductLocus(productLocusInfo);
        }
    }
    @Override
    public List<StockInfo> selectStockByProductId(Long id) {
        String slice = productService.getSlice(id);
        List<StockInfo>stockInfos = new ArrayList<>();
        if (StringUtils.isBlank(slice)){
            return stockInfos;
        }
        return stockInfoMapper.selectStockByProductId(id,slice);
    }
    @Override
    public PageInfoExtension<Map> selectEnterpriseSaleDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc("ascending".equalsIgnoreCase(pageInfo.getOrder()));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("companynumber");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("companynumber");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        List<StockVo> stockVos = stockInfoMapper.selectEnterpriseSaleDataGrid(pageInfo.getCondition(),page,list);
        Map total = stockInfoMapper.selectEnterpriseSaleDataCount(pageInfo.getCondition(), list);
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount(page.getTotal());
        PageInfoExtension<Map> extension = new PageInfoExtension<>(pageInfo);
        extension.setExtension(total);
        return extension;
    }
    @Override
    public void selectStockDetailByItemCode(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc("ascending".equalsIgnoreCase(pageInfo.getOrder()));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("stock.id");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("stock.id");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        String itemCode = pageInfo.getCondition().get("itemCode").toString();
        ProductInfo productInfo = productService.selectByDirection(itemCode);
        if (productInfo != null){
            String slice = productService.getSlice(itemCode);
            pageInfo.getCondition().put("slice",slice);
            List<StockVo> stockVos = stockInfoMapper.selectStockVoByItemCode(pageInfo.getCondition(),page);
            pageInfo.setResult(stockVos);
            pageInfo.setTotalCount(page.getTotal());
        }
    }
    @Override
    public void selectSaleDetailDataGrid(PageInfo pageInfo) {
        Page<StockVo> page = new Page<>(pageInfo.getPageIndex(), pageInfo.getPageSize());
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        if (StringUtils.isNotBlank(pageInfo.getSort()) && StringUtils.isNotBlank(pageInfo.getOrder())) {
            orderItem.setAsc(pageInfo.getOrder().equalsIgnoreCase("ascending"));
            orderItem.setColumn(pageInfo.getSort());
        }else {
            orderItem.setAsc(false);
            orderItem.setColumn("companynumber");
        }
        orderItems.add(orderItem);
        page.setOrders(orderItems);
        if (StringUtils.isBlank(pageInfo.getSort())){
            pageInfo.setSort("companynumber");
        }
        if (StringUtils.isBlank(pageInfo.getOrder())){
            pageInfo.setOrder("desc");
        }
        List<StockVo>stockVoList = stockInfoMapper.selectSaleDetailDataGrid(pageInfo.getCondition(),page);
        pageInfo.setResult(stockVoList);
        pageInfo.setTotalCount(page.getTotal());
    }
    @Override
    public PageInfoExtension<StockTotal> selectDataGridExtensions(PageInfo pageInfo) {
        List<Integer> slices = new ArrayList<Integer>(){{
            for (int i = 1; i <= 20; i++) {
                add(i);
            }
        }};
        List<StockVo> stockVos = stockInfoMapper.selectStockDataGrid(pageInfo.getCondition(),null,slices);
        pageInfo.setResult(stockVos);
        pageInfo.setTotalCount((long) stockVos.size());
        StockTotal stockTotal = new StockTotal(BigDecimal.ZERO);
        if (stockVos.size() > 0) {
            stockVos.forEach(item->{
                BigDecimal toAdd = BigDecimal.ZERO;
                if (item.getCountNum() != null )
                    toAdd = item.getCountNum();
                stockTotal.setCountNum(stockTotal.getCountNum().add(toAdd));
            });
        }
        PageInfoExtension<StockTotal> extension = new PageInfoExtension<>(pageInfo);
        extension.setExtension(stockTotal);
        return extension;
    }
    @Override
    public PageInfoExtension<ProductVo> selectCurrentFireStatus(Integer pageIndex,Integer pageSize, Map filter, UserInfo user) {
        String directioncode = (String) filter.get("directioncode");
        if (StringUtils.isBlank(directioncode) || FireworkDeal.isNotDirectionCode(directioncode))
            throw new BusinessException("请输入合法的流向码");
        DirectionDetail directionDetail = FireworkDeal.dealDirectionCode(directioncode);
        ProductVo productVo = productService.selectVoByDirection(directioncode);
        if (productVo == null)  throw new BusinessException("产品不存在");
        //分表
        String slice = productService.getSlice(directioncode);
        List<ProductVo> productVos = new ArrayList<>();
        List<StockInfo> records;
        List<String> codes = null;
        PageInfoExtension<ProductVo> extension = new PageInfoExtension<>();
        //22位
        if (FireworkDeal.is22Characters(directioncode)) {
            FireworkDeal.getProductVos(directioncode,directionDetail,directionDetail,productVos,productVo);
            if (productVos.size() < 1) throw new BusinessException("产品流向码出现问题");
             codes = new ArrayList<String>() {{
                for (ProductVo product : productVos) {
                    add(product.getDirectionCode());
                }
            }};
        }
        //19位
        if (FireworkDeal.is19Characters(directioncode)) {
             codes = new ArrayList<String>(){{
                add(directioncode);
            }};
        }
        //条件准备
        Map<String, Object> params = new HashMap<>();
        String status = (String) filter.get("status");
        //1.已售出
        if ("已售出".equals(status))
            params.put("status", status);
        if ("未入库".equals(status)) {
            params.put("status", "");
            params.put("owner", "");
        }
        if ("已入库".equals(status)) {
            params.put("status", "");
            params.put("owner", "库存owner");
        }
        params.put("directioncode", directioncode);
        //查询结果集
        records = stockInfoMapper.selectCurrentFireStatus(codes,params,slice);
        extension.setExtension(productVo);
        extension.setResult(records);
        extension.setPageIndex(pageIndex);
        extension.setPageSize(pageSize);
        //总数
        assert codes != null;
        extension.setTotalCount((long) codes.size());
        return extension;
    }
    @Override
    public List<StockVo> selectEnterpriseStocks(Map<String, Object> condition) {
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        return stockInfoMapper.selectEnterpriseStocks(condition,list);
    }
    @Override
    public void saveOrUpdateCurrentStock(String updatedBy) {
        Map<String, Object> condition = new HashMap<>(16);
        List<StockVo>stockVos = selectEnterpriseStocks(condition);
        List<StaticStock>staticStocks = new ArrayList<>();
        for (StockVo stockVo : stockVos){
            Enterprise enterprise = enterpriseService.getById(stockVo.getOwner());
            StaticStock staticStock = new StaticStock(Long.parseLong(stockVo.getOwner()),stockVo.getEnterpriseName(),stockVo.getEnterpriseNumber(),
                    enterprise.getSafetysupervision(),stockVo.getProvince(),stockVo.getCity(),stockVo.getDistrict(),
                    stockVo.getStockNum(), stockVo.getFirecracker(),stockVo.getSpray(),stockVo.getRotation(),stockVo.getBead(),
                    stockVo.getToy(),stockVo.getCombined(),updatedBy,new Date(),(byte)0 );
            StaticStock staticStock1 = staticStockService.getByOwner(Long.parseLong(stockVo.getOwner()));
            if (staticStock1 != null){
                staticStock.setId(staticStock1.getId());
            }
            staticStocks.add(staticStock);
        }
        staticStockService.saveOrUpdateBatch(staticStocks);
    }
    @Override
    public boolean clearStock(Enterprise enterprise) {
        /*List<StockInfo>stocks = selectEnterpriseAllStock(enterprise);
        stocks.forEach(item->{
            item.setRemark();
            item.setOwner("");
            item.setModifieddate(date);
        });*/
        Date date = new Date();
        String remark = "系统管理员清空,清空前归属:"+enterprise.getId()+",清空时间:"+new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
        for (int i = 1; i<=20; i++){
            int flag = stockInfoMapper.clearStock(enterprise.getId(),remark,date,"_slice"+i);
        }
        /*for (StockInfo stockInfo : stocks){
            updateStockInfo(stockInfo);
        }*/
        StaticStock staticStock = staticStockService.getByOwner(enterprise.getId());
        staticStock.setStockNum(new BigDecimal("0"));
        staticStock.setFirecracker(new BigDecimal("0"));
        staticStock.setSpray(new BigDecimal("0"));
        staticStock.setRotation(new BigDecimal("0"));
        staticStock.setBead(new BigDecimal("0"));
        staticStock.setToy(new BigDecimal("0"));
        staticStock.setCombined(new BigDecimal("0"));
        staticStock.setUpdateat(date);
        staticStockService.updateById(staticStock);
        return true;
    }
    @Override
    public boolean clearStockByItems(Enterprise enterprise, List<String> list) {
        Date date = new Date();
        String remark = "系统管理员清空,清空前归属:"+enterprise.getId()+",清空时间:"+new DateTime(date).toString("yyyy-MM-dd HH:mm:ss");
        for (int i = 1; i<=20; i++){
            int flag = stockInfoMapper.clearStockByItem(enterprise.getId(),list,remark,date,"_slice"+i);
        }
        /*StaticStock staticStock = staticStockService.getByOwner(enterprise.getId());
        staticStock.setStockNum(new BigDecimal("0"));
        staticStock.setFirecracker(new BigDecimal("0"));
        staticStock.setSpray(new BigDecimal("0"));
        staticStock.setRotation(new BigDecimal("0"));
        staticStock.setBead(new BigDecimal("0"));
        staticStock.setToy(new BigDecimal("0"));
        staticStock.setCombined(new BigDecimal("0"));
        staticStock.setUpdateat(date);
        staticStockService.updateById(staticStock);*/
        return true;
    }
    @Override
    public StockInfo selectStockByDirectionAndSlice(String directionCodeStr, String slice) {
        if (slice == null || StringUtils.isBlank(directionCodeStr)) {
            throw new BusinessException("系统入参为空");
        }
        return stockInfoMapper.selectStockByDirection(directionCodeStr,slice);
    }
    @Override
    public int insertStockInfoBySlice(StockInfo stockInfo, String slice) {
        if (stockInfo == null || StringUtils.isBlank(slice)) {
            throw new BusinessException("系统入参为空");
        }
        return stockInfoMapper.insertStockInfo(stockInfo, slice);
    }
    @Override
    public int updateStockInfoBySlice(StockInfo stockInfo, String slice) {
        if (stockInfo == null || StringUtils.isBlank(slice)) {
            throw new BusinessException("系统入参为空");
        }
        return stockInfoMapper.updateStockInfo(stockInfo, slice);
    }
    private List<StockInfo> selectEnterpriseAllStock(Enterprise enterprise) {
        List<Integer>list = new ArrayList<>();
        for (int i = 1; i<=20; i++){
            list.add(i);
        }
        return stockInfoMapper.selectEnterpriseAllStock(enterprise.getId(),list);
    }
    @Override
    public List<StockInfo> selectEarlyWarn(Integer min, Integer max, String enterprisetype,List<Integer> slices) {
        return stockInfoMapper.selectEarlyWarn(min, max, enterprisetype,slices);
    }
    @Override
    public List<StockInfo> selectAlarm(Integer max, String enterprisetype, List<Integer> slices) {
        return stockInfoMapper.selectAlarm(max, enterprisetype, slices);
    }
}