package com.zfire.mall.manager.logic.stock;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.stock.*;
import com.zfire.mall.manager.commonmapper.StockCostMapper;
import com.zfire.mall.manager.commonmapper.stock.StockCommonMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.enums.*;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.plus.entity.*;
import com.zfire.mall.manager.plus.service.*;
import com.zfire.mall.manager.zfire.bean.ZfireParamBean;
import com.zfire.mall.manager.zfire.util.FieldUtils;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Log4j
public class StockCostLogic {

    @Autowired
    CommonLogic commonLogic;

    @Autowired
    StockCostMapper stockCostMapper;

    @Autowired
    SysDictService sysDictService;

    @Autowired
    OrderFullCostService orderFullCostService;

    @Autowired
    RetailOrderService retailOrderService;

    @Autowired
    RetailOrderItemService retailOrderItemService;

    @Autowired
    EnginOrderService enginOrderService;

    @Autowired
    EnginOrderItemService enginOrderItemService;

    @Autowired
    AdminUserService adminUserService;

    @Autowired
    AdminUserStockService adminUserStockService;

    @Autowired
    StockCommonMapper stockCommonMapper;

    @Autowired
    KingDeeMaterialService kingDeeMaterialService;

    @Autowired
    StockCommonLogic stockCommonLogic;

    @Autowired
    StockCorrespondCategoryService stockCorrespondCategoryService;

    @Autowired
    OrderFullDateService orderFullDateService;


    @Autowired
    InvoiceApplicationOrderService invoiceApplicationOrderService;

    @Autowired
    SalesOrderItemService salesOrderItemService;


    @Autowired
    SalesOrderService salesOrderService;

    @Autowired
    StockService stockService;

    @Autowired
    StockAccService stockAccService;

    @Autowired
    KingDeeStockService kingDeeStockService;

    @Autowired
    StockXzService stockXzService;

    @Autowired
    StockCorrespondService stockCorrespondService;

    @Autowired
    StockForceLogic stockForceLogic;


    public IPage<OrderFullCostVO> list(String orderId, String startTime, String endTime, String materialOldNumber, String materialName, String materialNumber, String specification, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        return stockCostMapper.list(new Page<>(pageNum, pageSize), orderId, materialName, materialNumber, specification, startTime, endTime, materialOldNumber, customerId);
    }

    public IPage<OrderFullCostDayVO> listFullCost(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<OrderFullCostDayVO> orderFullCostDayVOIPage = stockCostMapper.listFullCost(new Page(zfireParamBean.getPageNum(),
                zfireParamBean.getPageSize()), zfireParamBean, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());
        return orderFullCostDayVOIPage;
    }

    public SysDict sysDict() {
        return sysDictService.lambdaQuery().eq(SysDict::getDictCode, "FULL_COST").last("limit 1").one();
    }

    public void update(String dictValue) {
        sysDictService.lambdaUpdate().eq(SysDict::getDictCode, "FULL_COST")
                .set(SysDict::getDictValue, dictValue)
                .update();
    }

    public List<SysDict> getSysDictList(String dictCode) {
        return sysDictService.lambdaQuery().eq(SysDict::getDictCode, dictCode).list();
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateCost(List<SysDict> sysDict) {

        sysDictService.lambdaUpdate().eq(SysDict::getDictType, sysDict.get(0).getDictType()).remove();
        sysDictService.saveBatch(sysDict);
    }

    public IPage<OrderFullCostMonthVO> listMonthFullCost(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<OrderFullCostMonthVO> orderFullCostMonthVOIPage = stockCostMapper.listMonthFullCost(new Page(zfireParamBean.getPageNum(),
                zfireParamBean.getPageSize()), zfireParamBean, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());

        List<OrderFullCostMonthVO> records = orderFullCostMonthVOIPage.getRecords();

        if (CollectionUtils.isEmpty(records))
            return orderFullCostMonthVOIPage;

        List<String> customerIds = records.stream().map(OrderFullCostMonthVO::getCustomerId).collect(Collectors.toList());
        List<String> yearTime = records.stream().map(OrderFullCostMonthVO::getYearTime).collect(Collectors.toList());
        List<String> monthTime = records.stream().map(OrderFullCostMonthVO::getMonthTime).collect(Collectors.toList());

        List<OrderFullCost> orderFullCosts = orderFullCostService.lambdaQuery()
                .in(OrderFullCost::getCustomerId, customerIds)
                .in(OrderFullCost::getYearTime, yearTime)
                .in(OrderFullCost::getMonthTime, monthTime)
                .eq(OrderFullCost::getStatus, OrderFullStatusEnum.ENABLE.getKey())
                .list();

        for (OrderFullCostMonthVO record : orderFullCostMonthVOIPage.getRecords()) {
            List<OrderFullCost> collect = orderFullCosts.stream().filter(item -> item.getCustomerId().equals(record.getCustomerId()) &&
                    item.getYearTime().equals(record.getYearTime()) && item.getMonthTime().equals(record.getMonthTime())).collect(Collectors.toList());

            BigDecimal reduce = collect.stream().map(OrderFullCost::getFullCost).reduce(BigDecimal.ZERO, BigDecimal::add);

            record.setFullDayNum(collect.size());
            record.setFullCost(reduce);
        }

        return orderFullCostMonthVOIPage;
    }

    @Async
    public void syncFullCost() throws Exception {

        try {


            SysDict sysDict = sysDictService.lambdaQuery().eq(SysDict::getDictType, "FULL_COST").last("limit 1").one();


            List<RetailOrderItem> retailOrderItems = retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.NO.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, false)
                    .last("and has_send_qty < qty")
                    .list();

            //添加直调结束得订单
            retailOrderItems.addAll(retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.NO.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, true)
                    .eq(RetailOrderItem::getDirectTransferStatus, true)
                    .last("and has_send_qty < qty")
                    .list());


            //存储之前经销商得仓库
            Map<String, List<String>> stockMap = new HashMap<>();


            for (RetailOrderItem retailOrderItem : retailOrderItems) {

                RetailOrder retailOrder = retailOrderService.getById(retailOrderItem.getRetailOrderId());

                RetailOrderItem retailOrderItemUp = new RetailOrderItem();
                retailOrderItemUp.setId(retailOrderItem.getId());

                if (retailOrder == null)
                    continue;

                if (!retailOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()))
                    continue;

                List<String> strings = stockMap.get(retailOrder.getCustomerId());

                //获得不了经销商得仓库就查找
                if (CollectionUtils.isEmpty(strings)) {
                    AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, retailOrder.getCustomerId()).eq(AdminUser::getIsMaster, true).last("limit 1").one();
                    List<AdminUserStock> list = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).list();
                    stockMap.put(adminUser.getCustomerId(), list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList()));

                    strings = list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList());
                }

                Integer stockNum = 0;

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(retailOrderItem.getMaterialId());

                for (String string : strings) {
                    stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, string, retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery()
                        .notIn(StockCorrespondCategory::getCorrespondId, strings)
                        .eq(StockCorrespondCategory::getCategoryId, kingDeeMaterial.getCategoryId()).list();

                if (!CollectionUtils.isEmpty(stockCorrespondCategories)) {
                    for (StockCorrespondCategory stockCorrespondCategory : stockCorrespondCategories) {

                        stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, stockCorrespondCategory.getCorrespondId(), retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                    }
                }


                List<SalesOrderItem> list = salesOrderItemService.lambdaQuery()
                        .eq(SalesOrderItem::getOrderId, retailOrderItem.getId())
                        .list();


                Integer qty = 0;


                if (!CollectionUtils.isEmpty(list)) {
                    for (SalesOrderItem salesOrderItem : list) {
                        SalesOrder salesOrder = salesOrderService.getById(salesOrderItem.getSalesOrderNo());

                        if (salesOrder != null && !salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()) && !salesOrder.getInvoiceType().equals(3)) {
                            qty = qty + salesOrderItem.getRefundableQty();
                        }
                    }

                }
                retailOrderItem.setRefundableQty(retailOrderItem.getRefundableQty() + qty);

                if (retailOrderItem.getRefundableQty() < 1)
                    continue;


                /*
                 *   库存得高于起始库存才能计算库存
                 *
                 *
                 * */
                if (stockNum >= Convert.toInt(sysDict.getDictValue()) || qty > 0) {
                    if (retailOrderItem.getRefundableQty() <= stockNum || qty > 0) {

                        if (retailOrderItem.getRefundableQty() > stockNum)
                            retailOrderItem.setRefundableQty(qty);

                        if (retailOrderItem.getFullStatus().equals(PickIsEnum.NO.getKey())) {
                            retailOrderItem.setFullNum(1);
                            retailOrderItem.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), 0)));
                            retailOrderItem.setFullStatus(PickIsEnum.YES.getKey());
                            generateDate(retailOrder, retailOrderItem, Convert.toLong(1), null);

                            retailOrderItemUp.setFullNum(1);
                            retailOrderItemUp.setFullTime(DateUtil.beginOfDay(new Date()));
                            retailOrderItemUp.setFullStatus(PickIsEnum.YES.getKey());

                            retailOrderItemUp.updateById();
                        } else {
                            DateTime dateStart = DateUtil.beginOfDay(new Date());
                            long betweenDay = retailOrderItem.getFullNum() + 1;

                            retailOrderItem.setFullNum(Convert.toInt(betweenDay));

                            retailOrderItemUp.setFullNum(Convert.toInt(betweenDay));

                            String id = null;

                            if (retailOrderItem.getFullNum() > 5) {
                                id = generate(retailOrder, retailOrderItem, betweenDay);
                            }
                            if (betweenDay > 0)
                                generateDate(retailOrder, retailOrderItem, Convert.toLong(betweenDay), id);
                        }
                        retailOrderItemUp.updateById();
                    } else {
                        //仓库不足不需要置灰
     /*               retailOrderItemUp.setFullNum(0);
                    retailOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                    retailOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());*/
                    }

                } else {
                    //仓库不足不需要置灰
   /*             retailOrderItemUp.setFullNum(0);
                retailOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                retailOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());
                retailOrderItemUp.updateById();*/
                }


            }

            List<EnginOrderItem> enginOrderItems = enginOrderItemService.lambdaQuery()
                    .eq(EnginOrderItem::getIsCost, PickIsEnum.NO.getKey())
                    .eq(EnginOrderItem::getIsDirectTransfer, false)
                    .last("and has_send_qty < qty")
                    .list();

            //添加直调结束得订单
            enginOrderItems.addAll(enginOrderItemService.lambdaQuery()
                    .eq(EnginOrderItem::getIsCost, PickIsEnum.NO.getKey())
                    .eq(EnginOrderItem::getIsDirectTransfer, true)
                    .eq(EnginOrderItem::getDirectTransferStatus, true)
                    .last("and has_send_qty < qty")
                    .list());


            for (EnginOrderItem enginOrderItem : enginOrderItems) {

                EnginOrder enginOrder = enginOrderService.getById(enginOrderItem.getParentId());

                EnginOrderItem enginOrderItemUp = new EnginOrderItem();
                enginOrderItemUp.setId(enginOrderItem.getId());

                if (enginOrder == null)
                    continue;

                if (!enginOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()))
                    continue;

                List<String> strings = stockMap.get(enginOrder.getCustomerId());

                if (CollectionUtils.isEmpty(strings)) {
                    AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, enginOrder.getCustomerId()).eq(AdminUser::getIsMaster, true).last("limit 1").one();
                    List<AdminUserStock> list = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).list();
                    stockMap.put(adminUser.getCustomerId(), list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList()));

                    strings = list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList());
                }

                Integer stockNum = 0;

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(enginOrderItem.getMaterialId());

                for (String string : strings) {
                    stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, string, enginOrderItem.getMaterialId(), enginOrder.getCustomerId());
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery().notIn(StockCorrespondCategory::getCorrespondId, strings)
                        .eq(StockCorrespondCategory::getCategoryId, kingDeeMaterial.getCategoryId()).list();

                if (!CollectionUtils.isEmpty(stockCorrespondCategories)) {
                    for (StockCorrespondCategory stockCorrespondCategory : stockCorrespondCategories) {

                        stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, stockCorrespondCategory.getCorrespondId(), enginOrderItem.getMaterialId(), enginOrder.getCustomerId());
                    }
                }

                List<SalesOrderItem> list = salesOrderItemService.lambdaQuery()
                        .eq(SalesOrderItem::getOrderId, enginOrderItem.getId())
                        .list();


                Integer qty = 0;


                if (!CollectionUtils.isEmpty(list)) {
                    for (SalesOrderItem salesOrderItem : list) {
                        SalesOrder salesOrder = salesOrderService.getById(salesOrderItem.getSalesOrderNo());
                        if (salesOrder != null && !salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()) && !salesOrder.getInvoiceType().equals(3)) {
                            qty = qty + salesOrderItem.getRefundableQty();
                        }
                    }

                }

                enginOrderItem.setRefundableQty(enginOrderItem.getRefundableQty() + qty);

                if (enginOrderItem.getRefundableQty() < 1)
                    continue;


                if (stockNum >= Convert.toInt(sysDict.getDictValue()) || qty > 0) {
                    if (enginOrderItem.getRefundableQty() <= stockNum || qty > 0) {

                        if (enginOrderItem.getRefundableQty() > stockNum)
                            enginOrderItem.setRefundableQty(qty);

                        if (enginOrderItem.getFullStatus().equals(PickIsEnum.NO.getKey())) {

                            enginOrderItem.setFullNum(1);
                            enginOrderItem.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), 0)));
                            enginOrderItem.setFullStatus(PickIsEnum.YES.getKey());

                            enginOrderItemUp.setFullNum(1);
                            enginOrderItemUp.setFullTime(DateUtil.beginOfDay(new Date()));
                            enginOrderItemUp.setFullStatus(PickIsEnum.YES.getKey());


                            generateDate(enginOrder, enginOrderItem, Convert.toLong(1), null);
                            enginOrderItemUp.updateById();
                        } else {
                            DateTime dateStart = DateUtil.beginOfDay(new Date());
                            long betweenDay = enginOrderItem.getFullNum() + 1;

                            enginOrderItem.setFullNum(Convert.toInt(betweenDay));

                            enginOrderItemUp.setFullNum(Convert.toInt(betweenDay));


                            String id = null;

                            if (enginOrderItem.getFullNum() > 5) {
                                id = generate(enginOrder, enginOrderItem, betweenDay);
                            }
                            if (betweenDay > 0)
                                generateDate(enginOrder, enginOrderItem, Convert.toLong(betweenDay), id);

                            enginOrderItemUp.updateById();

                        }
                    } else {
            /*        enginOrderItemUp.setFullNum(0);
                    enginOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                    enginOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());*/
                    }

                } else {
        /*        enginOrderItemUp.setFullNum(0);
                enginOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                enginOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());
                enginOrderItemUp.updateById();*/
                }
            }


            //给免租得单生成仓租费用
            List<RetailOrderItem> retailOrderItemsMian = retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.YES.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, false)
                    .lt(RetailOrderItem::getFullCostTime, new Date())
                    .last("and has_send_qty < qty")
                    .list();

            //添加直调结束得订单
            retailOrderItemsMian.addAll(retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.YES.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, true)
                    .lt(RetailOrderItem::getFullCostTime, new Date())
                    .eq(RetailOrderItem::getDirectTransferStatus, true)
                    .last("and has_send_qty < qty")
                    .list());


            for (RetailOrderItem retailOrderItem : retailOrderItemsMian) {

                RetailOrder retailOrder = retailOrderService.getById(retailOrderItem.getRetailOrderId());

                RetailOrderItem retailOrderItemUp = new RetailOrderItem();
                retailOrderItemUp.setId(retailOrderItem.getId());

                if (retailOrder == null)
                    continue;

                if (!retailOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()))
                    continue;

                List<String> strings = stockMap.get(retailOrder.getCustomerId());

                //获得不了经销商得仓库就查找
                if (CollectionUtils.isEmpty(strings)) {
                    AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, retailOrder.getCustomerId()).eq(AdminUser::getIsMaster, true).last("limit 1").one();
                    List<AdminUserStock> list = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).list();
                    stockMap.put(adminUser.getCustomerId(), list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList()));

                    strings = list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList());
                }

                Integer stockNum = 0;

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(retailOrderItem.getMaterialId());

                for (String string : strings) {
                    stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, string, retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery()
                        .notIn(StockCorrespondCategory::getCorrespondId, strings)
                        .eq(StockCorrespondCategory::getCategoryId, kingDeeMaterial.getCategoryId()).list();

                if (!CollectionUtils.isEmpty(stockCorrespondCategories)) {
                    for (StockCorrespondCategory stockCorrespondCategory : stockCorrespondCategories) {

                        stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, stockCorrespondCategory.getCorrespondId(), retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                    }
                }


                List<SalesOrderItem> list = salesOrderItemService.lambdaQuery()
                        .eq(SalesOrderItem::getOrderId, retailOrderItem.getId())
                        .list();


                Integer qty = 0;


                if (!CollectionUtils.isEmpty(list)) {
                    for (SalesOrderItem salesOrderItem : list) {
                        SalesOrder salesOrder = salesOrderService.getById(salesOrderItem.getSalesOrderNo());

                        if (salesOrder != null && !salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()) && !salesOrder.getInvoiceType().equals(3)) {
                            qty = qty + salesOrderItem.getRefundableQty();
                        }
                    }

                }
                retailOrderItem.setRefundableQty(retailOrderItem.getRefundableQty() + qty);

                if (retailOrderItem.getRefundableQty() < 1)
                    continue;


                /*
                 *   库存得高于起始库存才能计算库存
                 *
                 *
                 * */
                if (stockNum >= Convert.toInt(sysDict.getDictValue()) || qty > 0) {
                    if (retailOrderItem.getRefundableQty() <= stockNum || qty > 0) {

                        if (retailOrderItem.getRefundableQty() > stockNum)
                            retailOrderItem.setRefundableQty(qty);

                        if (retailOrderItem.getFullStatus().equals(PickIsEnum.NO.getKey())) {
                            retailOrderItem.setFullNum(1);
                            retailOrderItem.setFullTime(DateUtil.beginOfDay(new Date()));
                            retailOrderItem.setFullStatus(PickIsEnum.YES.getKey());

                            retailOrderItemUp.setFullNum(1);
                            retailOrderItemUp.setFullTime(DateUtil.beginOfDay(new Date()));
                            retailOrderItemUp.setFullStatus(PickIsEnum.YES.getKey());

                            String id = generateMianFive(retailOrder, retailOrderItem, Convert.toLong(1), DateUtil.beginOfDay(new Date()));
                            this.generateDate(retailOrder, retailOrderItem, Convert.toLong(1), null);
                            retailOrderItemUp.updateById();
                        } else {
                            DateTime dateStart = DateUtil.beginOfDay(new Date());
                            long betweenDay = retailOrderItem.getFullNum() + 1;

                            retailOrderItem.setFullNum(Convert.toInt(betweenDay));

                            retailOrderItemUp.setFullNum(Convert.toInt(betweenDay));

                            String id = null;
                            id = generateMianFive(retailOrder, retailOrderItem, betweenDay, dateStart);
                            this.generateDate(retailOrder, retailOrderItem, Convert.toLong(betweenDay), id);
                            retailOrderItemUp.updateById();
                        }

                    } else {
               /*     retailOrderItemUp.setFullNum(0);
                    retailOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                    retailOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());*/
                    }

                } else {
 /*               retailOrderItemUp.setFullNum(0);
                retailOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                retailOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());
                retailOrderItemUp.updateById();*/
                }


            }


            List<EnginOrderItem> enginOrderItemsMian = enginOrderItemService.lambdaQuery()
                    .eq(EnginOrderItem::getIsCost, PickIsEnum.YES.getKey())
                    .eq(EnginOrderItem::getIsDirectTransfer, false)
                    .lt(EnginOrderItem::getFullCostTime, new Date())
                    .last("and has_send_qty < qty")
                    .list();

            //添加直调结束得订单
            enginOrderItemsMian.addAll(enginOrderItemService.lambdaQuery()
                    .eq(EnginOrderItem::getIsCost, PickIsEnum.YES.getKey())
                    .eq(EnginOrderItem::getIsDirectTransfer, true)
                    .lt(EnginOrderItem::getFullCostTime, new Date())
                    .eq(EnginOrderItem::getDirectTransferStatus, true)
                    .last("and has_send_qty < qty")
                    .list());


            for (EnginOrderItem enginOrderItem : enginOrderItemsMian) {

                EnginOrder enginOrder = enginOrderService.getById(enginOrderItem.getParentId());

                EnginOrderItem enginOrderItemUp = new EnginOrderItem();
                enginOrderItemUp.setId(enginOrderItem.getId());

                if (enginOrder == null)
                    continue;

                if (!enginOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()))
                    continue;

                List<String> strings = stockMap.get(enginOrder.getCustomerId());

                if (CollectionUtils.isEmpty(strings)) {
                    AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, enginOrder.getCustomerId()).eq(AdminUser::getIsMaster, true).last("limit 1").one();
                    List<AdminUserStock> list = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).list();
                    stockMap.put(adminUser.getCustomerId(), list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList()));

                    strings = list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList());
                }

                Integer stockNum = 0;

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(enginOrderItem.getMaterialId());

                for (String string : strings) {
                    stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, string, enginOrderItem.getMaterialId(), enginOrder.getCustomerId());
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery().notIn(StockCorrespondCategory::getCorrespondId, strings)
                        .eq(StockCorrespondCategory::getCategoryId, kingDeeMaterial.getCategoryId()).list();

                if (!CollectionUtils.isEmpty(stockCorrespondCategories)) {
                    for (StockCorrespondCategory stockCorrespondCategory : stockCorrespondCategories) {

                        stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, stockCorrespondCategory.getCorrespondId(), enginOrderItem.getMaterialId(), enginOrder.getCustomerId());
                    }
                }

                List<SalesOrderItem> list = salesOrderItemService.lambdaQuery()
                        .eq(SalesOrderItem::getOrderId, enginOrderItem.getId())
                        .list();


                Integer qty = 0;


                if (!CollectionUtils.isEmpty(list)) {
                    for (SalesOrderItem salesOrderItem : list) {
                        SalesOrder salesOrder = salesOrderService.getById(salesOrderItem.getSalesOrderNo());
                        if (salesOrder != null && !salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()) && !salesOrder.getInvoiceType().equals(3)) {
                            qty = qty + salesOrderItem.getRefundableQty();
                        }
                    }

                }

                enginOrderItem.setRefundableQty(enginOrderItem.getRefundableQty() + qty);

                if (enginOrderItem.getRefundableQty() < 1)
                    continue;


                if (stockNum >= Convert.toInt(sysDict.getDictValue()) || qty > 0) {
                    if (enginOrderItem.getRefundableQty() <= stockNum || qty > 0) {

                        if (enginOrderItem.getRefundableQty() > stockNum)
                            enginOrderItem.setRefundableQty(qty);

                        if (enginOrderItem.getFullStatus().equals(PickIsEnum.NO.getKey())) {

                            enginOrderItem.setFullNum(2);
                            enginOrderItem.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                            enginOrderItem.setFullStatus(PickIsEnum.YES.getKey());

                            enginOrderItemUp.setFullNum(2);
                            enginOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                            enginOrderItemUp.setFullStatus(PickIsEnum.YES.getKey());

                            String id = generateMianFive(enginOrder, enginOrderItem, Convert.toLong(1), DateUtil.beginOfDay(new Date()));
                            this.generateDate(enginOrder, enginOrderItem, Convert.toLong(1), null);
                            enginOrderItemUp.updateById();
                        } else {
                            DateTime dateStart = DateUtil.beginOfDay(new Date());
                            long betweenDay = enginOrderItem.getFullNum() + 1;

                            enginOrderItem.setFullNum(Convert.toInt(betweenDay));

                            enginOrderItemUp.setFullNum(Convert.toInt(betweenDay));

                            String id = null;
                            id = generateMianFive(enginOrder, enginOrderItem, betweenDay, dateStart);
                            this.generateDate(enginOrder, enginOrderItem, Convert.toLong(betweenDay), id);
                            enginOrderItemUp.updateById();
                        }
                    } else {
             /*       enginOrderItemUp.setFullNum(0);
                    enginOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                    enginOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());*/
                    }

                } else {
/*                enginOrderItemUp.setFullNum(0);
                enginOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(new Date(), -1)));
                enginOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());
                enginOrderItemUp.updateById();*/
                }
            }
        }catch (Exception e){
            SyncLog syncLog = new SyncLog();
            syncLog.setTime(new Date());
            syncLog.setE(e.getMessage());
            syncLog.insert();
        }


    }

    private String generateMian(RetailOrder retailOrder, RetailOrderItem retailOrderItem, Long betweenDay) {

        DateTime dateTime = new DateTime(new Date());

        if (orderFullCostService.lambdaQuery()
                .eq(OrderFullCost::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullCost::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullCost::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullCost::getOrderNo, retailOrder.getId())
                .eq(OrderFullCost::getMaterialId, retailOrderItem.getMaterialId())
                .eq(OrderFullCost::getFullStartTime, retailOrderItem.getFullTime()).count() > 0) {
            return null;
        }


        OrderFullCost orderFullCost = new OrderFullCost();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
        orderFullCost.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
        orderFullCost.setOrderNo(retailOrder.getId());
        orderFullCost.setOrderTime(retailOrder.getTheTime());
        orderFullCost.setExamineTime(retailOrder.getExamineTime());
        orderFullCost.setCustomerId(retailOrder.getCustomerId());
        orderFullCost.setCustomerName(retailOrder.getCustomerName());
        orderFullCost.setCustomerNumber(retailOrder.getCustomerNumber());
        orderFullCost.setMaterialId(retailOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(retailOrderItem.getMaterialCode());
        orderFullCost.setMaterialName(retailOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(retailOrderItem.getSpecification());
        orderFullCost.setOrderNum(retailOrderItem.getRefundableQty());
        orderFullCost.setOrderItemId(retailOrderItem.getId());

        BigDecimal price = new BigDecimal(0);

        if (retailOrderItem.getRefundableQty().equals(retailOrderItem.getQty())) {
            price = retailOrderItem.getTotalAmount();
        } else {
            price = retailOrderItem.getTotalAmount().divide(Convert.toBigDecimal(retailOrderItem.getQty())).multiply(Convert.toBigDecimal(retailOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);

        orderFullCost.setOverdueNum(Convert.toInt(betweenDay));

        orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(retailOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(retailOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(retailOrderItem.getFullTime());

        orderFullCost.setFullEndTime(DateUtil.beginOfDay(new Date()));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));


        orderFullCost.setNote("免仓申请订单，申请免仓到期逾期 " + orderFullCost.getOverdueNum() + "天，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，" + "收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                (betweenDay < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (betweenDay < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");


        orderFullCost.insert();
        return orderFullCost.getOrderFullCostId();
    }

    private void generateDate(RetailOrder retailOrder, RetailOrderItem retailOrderItem, Long betweenDay, String id) {

        DateTime dateTime = new DateTime(new Date());


        if (orderFullDateService.lambdaQuery()
                .eq(OrderFullDate::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullDate::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullDate::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullDate::getOrderNo, retailOrder.getId())
                .eq(OrderFullDate::getMaterialId, retailOrderItem.getMaterialId())
                .eq(OrderFullDate::getFullStartTime, retailOrderItem.getFullTime()).count() > 0) {
            return;
        }


        OrderFullDate orderFullCost = new OrderFullDate();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
        orderFullCost.setOrderNo(retailOrder.getId());
        orderFullCost.setOrderTime(retailOrder.getTheTime());
        orderFullCost.setExamineTime(retailOrder.getExamineTime());
        orderFullCost.setCustomerId(retailOrder.getCustomerId());
        orderFullCost.setCustomerName(retailOrder.getCustomerName());
        orderFullCost.setCustomerNumber(retailOrder.getCustomerNumber());
        orderFullCost.setMaterialId(retailOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(retailOrderItem.getMaterialCode());
        orderFullCost.setMaterialName(retailOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(retailOrderItem.getSpecification());
        orderFullCost.setOrderNum(retailOrderItem.getRefundableQty());
        orderFullCost.setOrderItemId(retailOrderItem.getId());

        BigDecimal price = new BigDecimal(0);

        if (retailOrderItem.getRefundableQty().equals(retailOrderItem.getQty())) {
            price = retailOrderItem.getTotalAmount();
        } else {
            price = retailOrderItem.getTotalAmount().divide(Convert.toBigDecimal(retailOrderItem.getQty())).multiply(Convert.toBigDecimal(retailOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);


        orderFullCost.setFullCost(betweenDay < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(retailOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(retailOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(retailOrderItem.getFullTime());


        orderFullCost.setFullEndTime(DateUtil.beginOfDay(new Date()));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));
        orderFullCost.setCostId(id);


        orderFullCost.insert();
    }


    private void generateDate(EnginOrder enginOrder, EnginOrderItem enginOrderItem, long betweenDay, String id) {

        DateTime dateTime = new DateTime(new Date());

        if (orderFullDateService.lambdaQuery()
                .eq(OrderFullDate::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullDate::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullDate::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullDate::getOrderNo, enginOrder.getEnginOrderNo())
                .eq(OrderFullDate::getMaterialId, enginOrderItem.getMaterialId())
                .eq(OrderFullDate::getFullStartTime, enginOrderItem.getFullTime()).count() > 0) {
            return;
        }
        List<SalesOrderItem> list = salesOrderItemService.lambdaQuery()
                .eq(SalesOrderItem::getOrderId, enginOrderItem.getId())
                .list();


        OrderFullDate orderFullCost = new OrderFullDate();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setOrderType(enginOrder.getEnginOrderType().equals(OrderTypeEnum.HOME.getKey()) ? OrderTypeEnum.HOME.getKey() : OrderTypeEnum.TRADE.getKey());
        orderFullCost.setOrderNo(enginOrder.getEnginOrderNo());
        orderFullCost.setOrderTime(enginOrder.getOrderDate());
        orderFullCost.setExamineTime(enginOrder.getConfirmTime());
        orderFullCost.setCustomerId(enginOrder.getCustomerId());
        orderFullCost.setCustomerName(enginOrder.getCustomerName());
        orderFullCost.setCustomerNumber(enginOrder.getCustomerNumber());
        orderFullCost.setMaterialId(enginOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(enginOrderItem.getMaterialNumber());
        orderFullCost.setMaterialName(enginOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(enginOrderItem.getSpecification());
        orderFullCost.setOrderNum(enginOrderItem.getRefundableQty());
        orderFullCost.setRefUseUnit(enginOrder.getRefUseUnit());
        orderFullCost.setOrderItemId(enginOrderItem.getId());


        BigDecimal price = new BigDecimal(0);

        if (enginOrderItem.getRefundableQty().equals(enginOrderItem.getQty())) {
            price = enginOrderItem.getTotalAmount();
        } else {
            price = enginOrderItem.getTotalAmount().divide(Convert.toBigDecimal(enginOrderItem.getQty())).multiply(Convert.toBigDecimal(enginOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);


        orderFullCost.setFullCost(betweenDay > 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(enginOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(enginOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(enginOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(enginOrderItem.getFullTime());

        orderFullCost.setFullEndTime(DateUtil.beginOfDay(new Date()));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));
        orderFullCost.setCostId(id);

        orderFullCost.insert();
    }

    private String generate(RetailOrder retailOrder, RetailOrderItem retailOrderItem, long betweenDay) {

        DateTime dateTime = new DateTime(new Date());

        if (orderFullCostService.lambdaQuery()
                .eq(OrderFullCost::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullCost::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullCost::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullCost::getOrderNo, retailOrder.getId())
                .eq(OrderFullCost::getMaterialId, retailOrderItem.getMaterialId())
                .eq(OrderFullCost::getFullStartTime, retailOrderItem.getFullTime()).count() > 0) {
            return null;
        }


        OrderFullCost orderFullCost = new OrderFullCost();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
        orderFullCost.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
        orderFullCost.setOrderNo(retailOrder.getId());
        orderFullCost.setOrderTime(retailOrder.getTheTime());
        orderFullCost.setExamineTime(retailOrder.getExamineTime());
        orderFullCost.setCustomerId(retailOrder.getCustomerId());
        orderFullCost.setCustomerName(retailOrder.getCustomerName());
        orderFullCost.setCustomerNumber(retailOrder.getCustomerNumber());
        orderFullCost.setMaterialId(retailOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(retailOrderItem.getMaterialCode());
        orderFullCost.setMaterialName(retailOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(retailOrderItem.getSpecification());
        orderFullCost.setOrderNum(retailOrderItem.getRefundableQty());
        orderFullCost.setOrderItemId(retailOrderItem.getId());

        BigDecimal price = new BigDecimal(0);

        if (retailOrderItem.getRefundableQty().equals(retailOrderItem.getQty())) {
            price = retailOrderItem.getTotalAmount();
        } else {
            price = retailOrderItem.getTotalAmount().divide(Convert.toBigDecimal(retailOrderItem.getQty())).multiply(Convert.toBigDecimal(retailOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);

        orderFullCost.setOverdueNum(Convert.toInt(betweenDay - 5));

        orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(retailOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(retailOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(retailOrderItem.getFullTime());

        orderFullCost.setFullEndTime(DateUtil.beginOfDay(new Date()));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));


        orderFullCost.setNote("自货满日五天内免费，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，该单机型货满已" + betweenDay + "天，收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");


        orderFullCost.insert();
        return orderFullCost.getOrderFullCostId();
    }

    private String generate(EnginOrder enginOrder, EnginOrderItem enginOrderItem, long betweenDay) {

        DateTime dateTime = new DateTime(new Date());

        if (orderFullCostService.lambdaQuery()
                .eq(OrderFullCost::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullCost::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullCost::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullCost::getOrderNo, enginOrder.getEnginOrderNo())
                .eq(OrderFullCost::getMaterialId, enginOrderItem.getMaterialId())
                .eq(OrderFullCost::getFullStartTime, enginOrderItem.getFullTime()).count() > 0) {
            return null;
        }


        OrderFullCost orderFullCost = new OrderFullCost();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
        orderFullCost.setOrderType(enginOrder.getEnginOrderType().equals(OrderTypeEnum.HOME.getKey()) ? OrderTypeEnum.HOME.getKey() : OrderTypeEnum.TRADE.getKey());
        orderFullCost.setOrderNo(enginOrder.getEnginOrderNo());
        orderFullCost.setOrderTime(enginOrder.getOrderDate());
        orderFullCost.setExamineTime(enginOrder.getConfirmTime());
        orderFullCost.setCustomerId(enginOrder.getCustomerId());
        orderFullCost.setCustomerName(enginOrder.getCustomerName());
        orderFullCost.setCustomerNumber(enginOrder.getCustomerNumber());
        orderFullCost.setMaterialId(enginOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(enginOrderItem.getMaterialNumber());
        orderFullCost.setMaterialName(enginOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(enginOrderItem.getSpecification());
        orderFullCost.setOrderNum(enginOrderItem.getRefundableQty());
        orderFullCost.setOrderItemId(enginOrderItem.getId());

        orderFullCost.setRefUseUnit(enginOrder.getRefUseUnit());

        BigDecimal price = new BigDecimal(0);

        if (enginOrderItem.getRefundableQty().equals(enginOrderItem.getQty())) {
            price = enginOrderItem.getTotalAmount();
        } else {
            price = enginOrderItem.getTotalAmount().divide(Convert.toBigDecimal(enginOrderItem.getQty())).multiply(Convert.toBigDecimal(enginOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);


        orderFullCost.setOverdueNum(Convert.toInt(betweenDay - 5));

        orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(enginOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(enginOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(enginOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(enginOrderItem.getFullTime());

        orderFullCost.setFullEndTime(DateUtil.beginOfDay(new Date()));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));
        orderFullCost.setNote("自货满日五天内免费，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，该单机型货满已" + betweenDay + "天，收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");


        orderFullCost.insert();
        return orderFullCost.getOrderFullCostId();
    }


    public void updateOrderFull(List<String> id) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        if (adminUser.getIsCustomer())
            throw new RemoteServiceException("经销商不可剔除");

        orderFullCostService.lambdaUpdate().in(OrderFullCost::getOrderFullCostId, id)
                .set(OrderFullCost::getStatus, OrderFullStatusEnum.DEL.getKey())
                .update();
    }


    public IPage<OrderFullDateVO> listFullDate(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<OrderFullDateVO> orderFullCostDayVOIPage = stockCostMapper.listFullData(new Page(zfireParamBean.getPageNum(),
                zfireParamBean.getPageSize()), zfireParamBean, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());
        return orderFullCostDayVOIPage;
    }


    @Transactional(rollbackFor = Exception.class)
    public void updateOrderCost(List<String> orderId, Date time) {

        DateTime dateTime = DateUtil.offsetSecond(DateUtil.endOfDay(time), -1);


        retailOrderItemService
                .lambdaUpdate()
                .in(RetailOrderItem::getId, orderId)
                .set(RetailOrderItem::getIsCost, PickIsEnum.YES.getKey())
                .set(RetailOrderItem::getFullCostTime, dateTime)
                .update();


        enginOrderItemService
                .lambdaUpdate()
                .in(EnginOrderItem::getId, orderId)
                .set(EnginOrderItem::getIsCost, PickIsEnum.YES.getKey())
                .set(EnginOrderItem::getFullCostTime, dateTime)
                .update();

        orderFullCostService.lambdaUpdate()
                .in(OrderFullCost::getOrderItemId, orderId)
                .remove();


        orderFullDateService.lambdaUpdate()
                .in(OrderFullDate::getOrderItemId, orderId)
                .remove();
    }

    public void syncFullCostFive() {

        for (int i = 8; i < 30; i++) {

            SysDict sysDict = sysDictService.lambdaQuery().eq(SysDict::getDictType, "FULL_COST").last("limit 1").one();

            DateTime dateTime = DateUtil.offsetDay(new Date(), i);

            //存储之前经销商得仓库
            Map<String, List<String>> stockMap = new HashMap<>();

            //给免租得单生成仓租费用

            List<RetailOrderItem> retailOrderItemsMian = retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.YES.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, false)
                    .lt(RetailOrderItem::getFullCostTime, dateTime)
                    .last("and has_send_qty < qty")
                    .list();

            //添加直调结束得订单
            retailOrderItemsMian.addAll(retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.YES.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, true)
                    .lt(RetailOrderItem::getFullCostTime, dateTime)
                    .eq(RetailOrderItem::getDirectTransferStatus, true)
                    .last("and has_send_qty < qty")
                    .list());


            for (RetailOrderItem retailOrderItem : retailOrderItemsMian) {

                RetailOrder retailOrder = retailOrderService.getById(retailOrderItem.getRetailOrderId());

                RetailOrderItem retailOrderItemUp = new RetailOrderItem();
                retailOrderItemUp.setId(retailOrderItem.getId());

                if (retailOrder == null)
                    continue;

                if (!retailOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()))
                    continue;

                List<String> strings = stockMap.get(retailOrder.getCustomerId());

                //获得不了经销商得仓库就查找
                if (CollectionUtils.isEmpty(strings)) {
                    AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, retailOrder.getCustomerId()).eq(AdminUser::getIsMaster, true).last("limit 1").one();
                    List<AdminUserStock> list = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).list();
                    stockMap.put(adminUser.getCustomerId(), list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList()));

                    strings = list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList());
                }

                Integer stockNum = 0;

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(retailOrderItem.getMaterialId());

                for (String string : strings) {
                    stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, string, retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery()
                        .notIn(StockCorrespondCategory::getCorrespondId, strings)
                        .eq(StockCorrespondCategory::getCategoryId, kingDeeMaterial.getCategoryId()).list();

                if (!CollectionUtils.isEmpty(stockCorrespondCategories)) {
                    for (StockCorrespondCategory stockCorrespondCategory : stockCorrespondCategories) {

                        stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, stockCorrespondCategory.getCorrespondId(), retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                    }
                }


                List<SalesOrderItem> list = salesOrderItemService.lambdaQuery()
                        .eq(SalesOrderItem::getOrderId, retailOrderItem.getId())
                        .list();


                Integer qty = 0;


                if (!CollectionUtils.isEmpty(list)) {
                    for (SalesOrderItem salesOrderItem : list) {
                        SalesOrder salesOrder = salesOrderService.getById(salesOrderItem.getSalesOrderNo());

                        if (salesOrder != null && !salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()) && !salesOrder.getInvoiceType().equals(3)) {
                            qty = qty + salesOrderItem.getRefundableQty();
                        }
                    }

                }
                retailOrderItem.setRefundableQty(retailOrderItem.getRefundableQty() + qty);


                /*
                 *   库存得高于起始库存才能计算库存
                 *
                 *
                 * */
                if (stockNum >= Convert.toInt(sysDict.getDictValue())) {
                    if (retailOrderItem.getRefundableQty() <= stockNum) {
                        if (retailOrderItem.getFullStatus().equals(PickIsEnum.NO.getKey())) {
                            retailOrderItem.setFullNum(1);
                            retailOrderItem.setFullTime(DateUtil.beginOfDay(dateTime));
                            retailOrderItem.setFullStatus(PickIsEnum.YES.getKey());

                            retailOrderItemUp.setFullNum(1);
                            retailOrderItemUp.setFullTime(DateUtil.beginOfDay(dateTime));
                            retailOrderItemUp.setFullStatus(PickIsEnum.YES.getKey());

                            String id = generateMianFive(retailOrder, retailOrderItem, Convert.toLong(1), dateTime);
                            this.generateDateFive(retailOrder, retailOrderItem, Convert.toLong(1), null, dateTime);
                        } else {
                            DateTime dateStart = DateUtil.beginOfDay(dateTime);
                            long betweenDay = DateUtil.between(retailOrderItem.getFullTime(), dateStart, DateUnit.DAY) + 1;

                            retailOrderItem.setFullNum(Convert.toInt(betweenDay));

                            retailOrderItemUp.setFullNum(Convert.toInt(betweenDay));

                            String id = generateMianFive(retailOrder, retailOrderItem, Convert.toLong(betweenDay), dateTime);
                            this.generateDateFive(retailOrder, retailOrderItem, Convert.toLong(betweenDay), null, dateTime);
                        }

                    } else {
                        retailOrderItemUp.setFullNum(0);
                        retailOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(dateTime, -1)));
                        retailOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());
                    }
                    retailOrderItemUp.updateById();
                }


            }


/*
            SysDict sysDict = sysDictService.lambdaQuery().eq(SysDict::getDictType, "FULL_COST").last("limit 1").one();


            List<RetailOrderItem> retailOrderItems = retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.NO.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, false)
                    .last("and has_send_qty < qty")
                    .list();

            //添加直调结束得订单
            retailOrderItems.addAll(retailOrderItemService.lambdaQuery()
                    .eq(RetailOrderItem::getIsCost, PickIsEnum.NO.getKey())
                    .eq(RetailOrderItem::getIsDirectTransfer, true)
                    .eq(RetailOrderItem::getDirectTransferStatus, true)
                    .last("and has_send_qty < qty")
                    .list());


            //存储之前经销商得仓库
            Map<String, List<String>> stockMap = new HashMap<>();


            for (RetailOrderItem retailOrderItem : retailOrderItems) {

                RetailOrder retailOrder = retailOrderService.getById(retailOrderItem.getRetailOrderId());

                RetailOrderItem retailOrderItemUp = new RetailOrderItem();
                retailOrderItemUp.setId(retailOrderItem.getId());

                if (retailOrder == null)
                    continue;

                if (!retailOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey()))
                    continue;

                List<String> strings = stockMap.get(retailOrder.getCustomerId());

                //获得不了经销商得仓库就查找
                if (CollectionUtils.isEmpty(strings)) {
                    AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getCustomerId, retailOrder.getCustomerId()).eq(AdminUser::getIsMaster, true).last("limit 1").one();
                    List<AdminUserStock> list = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).list();
                    stockMap.put(adminUser.getCustomerId(), list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList()));

                    strings = list.stream().map(AdminUserStock::getCorrespondId).collect(Collectors.toList());
                }

                Integer stockNum = 0;

                KingDeeMaterial kingDeeMaterial = kingDeeMaterialService.getById(retailOrderItem.getMaterialId());

                for (String string : strings) {
                    stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, string, retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                }

                //仓库无配置分类 无拥有仓库有分类
                List<StockCorrespondCategory> stockCorrespondCategories = stockCorrespondCategoryService.lambdaQuery()
                        .notIn(StockCorrespondCategory::getCorrespondId, strings)
                        .eq(StockCorrespondCategory::getCategoryId, kingDeeMaterial.getCategoryId()).list();

                if (!CollectionUtils.isEmpty(stockCorrespondCategories)) {
                    for (StockCorrespondCategory stockCorrespondCategory : stockCorrespondCategories) {

                        stockNum = stockNum + stockCommonLogic.stockCorrespondStatusNO(null, stockCorrespondCategory.getCorrespondId(), retailOrderItem.getMaterialId(), retailOrder.getCustomerId());
                    }
                }


                List<SalesOrderItem> list = salesOrderItemService.lambdaQuery()
                        .eq(SalesOrderItem::getOrderId, retailOrderItem.getId())
                        .list();


                Integer qty = 0;


                if (!CollectionUtils.isEmpty(list)) {
                    for (SalesOrderItem salesOrderItem : list) {
                        SalesOrder salesOrder = salesOrderService.getById(salesOrderItem.getSalesOrderNo());
                        if (salesOrder != null && !salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.getKey())) {
                            qty = qty + salesOrderItem.getRefundableQty();
                        }
                    }

                }
                retailOrderItem.setRefundableQty(retailOrderItem.getRefundableQty() + qty);


                *//*
             *   库存得高于起始库存才能计算库存
             *
             *
             * *//*
                if (stockNum >= Convert.toInt(sysDict.getDictValue())) {
                    if (retailOrderItem.getRefundableQty() <= stockNum) {
                        if (retailOrderItem.getFullStatus().equals(PickIsEnum.NO.getKey())) {
                            retailOrderItem.setFullNum(2);
                            retailOrderItem.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(dateTime, -1)));
                            retailOrderItem.setFullStatus(PickIsEnum.YES.getKey());

                            retailOrderItemUp.setFullNum(2);
                            retailOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(dateTime, -1)));
                            retailOrderItemUp.setFullStatus(PickIsEnum.YES.getKey());
                            generateDateFive(retailOrder, retailOrderItem, Convert.toLong(1), null,dateTime);
                            generateDateFive(retailOrder, retailOrderItem, Convert.toLong(2), null,dateTime);
                        } else {
                            DateTime dateStart = DateUtil.beginOfDay(dateTime);
                            long betweenDay = DateUtil.between(retailOrderItem.getFullTime(), dateStart, DateUnit.DAY) + 1;

                            retailOrderItem.setFullNum(Convert.toInt(betweenDay));

                            retailOrderItemUp.setFullNum(Convert.toInt(betweenDay));

                            String id = null;

                            if (retailOrderItem.getFullNum() > 5) {
                                id = generateFive(retailOrder, retailOrderItem, betweenDay,dateTime);
                            }
                            if (betweenDay > 0)
                                generateDateFive(retailOrder, retailOrderItem, Convert.toLong(betweenDay), id,dateTime);
                        }

                    } else {
                        retailOrderItemUp.setFullNum(0);
                        retailOrderItemUp.setFullTime(DateUtil.beginOfDay(DateUtil.offsetDay(dateTime, -1)));
                        retailOrderItemUp.setFullStatus(PickIsEnum.NO.getKey());
                    }
                    retailOrderItemUp.updateById();
                }


            }*/
        }
    }


    private String generateMianFive(EnginOrder enginOrder, EnginOrderItem enginOrderItem, Long betweenDay, DateTime dateTime) {


        if (orderFullCostService.lambdaQuery()
                .eq(OrderFullCost::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullCost::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullCost::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullCost::getOrderNo, enginOrder.getEnginOrderNo())
                .eq(OrderFullCost::getMaterialId, enginOrderItem.getMaterialId())
                .eq(OrderFullCost::getFullStartTime, enginOrderItem.getFullTime()).count() > 0) {
            return null;
        }


        OrderFullCost orderFullCost = new OrderFullCost();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
        orderFullCost.setOrderType(enginOrder.getEnginOrderType().equals(OrderTypeEnum.HOME.getKey()) ? OrderTypeEnum.HOME.getKey() : OrderTypeEnum.TRADE.getKey());

        orderFullCost.setOrderNo(enginOrder.getEnginOrderNo());
        orderFullCost.setOrderTime(enginOrder.getOrderDate());
        orderFullCost.setExamineTime(enginOrder.getConfirmTime());
        orderFullCost.setCustomerId(enginOrder.getCustomerId());
        orderFullCost.setCustomerName(enginOrder.getCustomerName());
        orderFullCost.setCustomerNumber(enginOrder.getCustomerNumber());
        orderFullCost.setMaterialId(enginOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(enginOrderItem.getMaterialNumber());
        orderFullCost.setMaterialName(enginOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(enginOrderItem.getSpecification());
        orderFullCost.setOrderNum(enginOrderItem.getRefundableQty());
        orderFullCost.setOrderItemId(enginOrderItem.getId());

        BigDecimal price = new BigDecimal(0);

        if (enginOrderItem.getRefundableQty().equals(enginOrderItem.getQty())) {
            price = enginOrderItem.getTotalAmount();
        } else {
            price = enginOrderItem.getTotalAmount().divide(Convert.toBigDecimal(enginOrderItem.getQty())).multiply(Convert.toBigDecimal(enginOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);

        orderFullCost.setOverdueNum(Convert.toInt(betweenDay));

        orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(enginOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(enginOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(enginOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(enginOrderItem.getFullTime());

        orderFullCost.setFullEndTime(DateUtil.beginOfDay(dateTime));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));


        orderFullCost.setNote("免仓申请订单，申请免仓到期逾期 " + orderFullCost.getOverdueNum() + "天，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，" + "收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");


        orderFullCost.insert();
        return orderFullCost.getOrderFullCostId();
    }


    private String generateMianFive(RetailOrder retailOrder, RetailOrderItem retailOrderItem, Long betweenDay, DateTime dateTime) {


        if (orderFullCostService.lambdaQuery()
                .eq(OrderFullCost::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullCost::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullCost::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullCost::getOrderNo, retailOrder.getId())
                .eq(OrderFullCost::getMaterialId, retailOrderItem.getMaterialId())
                .eq(OrderFullCost::getFullStartTime, retailOrderItem.getFullTime()).count() > 0) {
            return null;
        }


        OrderFullCost orderFullCost = new OrderFullCost();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
        orderFullCost.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
        orderFullCost.setOrderNo(retailOrder.getId());
        orderFullCost.setOrderTime(retailOrder.getTheTime());
        orderFullCost.setExamineTime(retailOrder.getExamineTime());
        orderFullCost.setCustomerId(retailOrder.getCustomerId());
        orderFullCost.setCustomerName(retailOrder.getCustomerName());
        orderFullCost.setCustomerNumber(retailOrder.getCustomerNumber());
        orderFullCost.setMaterialId(retailOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(retailOrderItem.getMaterialCode());
        orderFullCost.setMaterialName(retailOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(retailOrderItem.getSpecification());
        orderFullCost.setOrderNum(retailOrderItem.getRefundableQty());

        BigDecimal price = new BigDecimal(0);

        if (retailOrderItem.getRefundableQty().equals(retailOrderItem.getQty())) {
            price = retailOrderItem.getTotalAmount();
        } else {
            price = retailOrderItem.getTotalAmount().divide(Convert.toBigDecimal(retailOrderItem.getQty())).multiply(Convert.toBigDecimal(retailOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);

        orderFullCost.setOverdueNum(Convert.toInt(betweenDay));

        orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(retailOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(retailOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(retailOrderItem.getFullTime());

        orderFullCost.setFullEndTime(DateUtil.beginOfDay(dateTime));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));


        orderFullCost.setNote("免仓申请订单，申请免仓到期逾期 " + orderFullCost.getOverdueNum() + "天，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，" + "收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");


        orderFullCost.insert();
        return orderFullCost.getOrderFullCostId();
    }


    private void generateDateFive(RetailOrder retailOrder, RetailOrderItem retailOrderItem, Long betweenDay, String id, Date date) {

        DateTime dateTime = DateUtil.offsetDay(date, 0);


        if (orderFullDateService.lambdaQuery()
                .eq(OrderFullDate::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullDate::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullDate::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullDate::getOrderNo, retailOrder.getId())
                .eq(OrderFullDate::getMaterialId, retailOrderItem.getMaterialId())
                .eq(OrderFullDate::getFullStartTime, retailOrderItem.getFullTime()).count() > 0) {
            return;
        }


        OrderFullDate orderFullCost = new OrderFullDate();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
        orderFullCost.setOrderNo(retailOrder.getId());
        orderFullCost.setOrderTime(retailOrder.getTheTime());
        orderFullCost.setExamineTime(retailOrder.getExamineTime());
        orderFullCost.setCustomerId(retailOrder.getCustomerId());
        orderFullCost.setCustomerName(retailOrder.getCustomerName());
        orderFullCost.setCustomerNumber(retailOrder.getCustomerNumber());
        orderFullCost.setMaterialId(retailOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(retailOrderItem.getMaterialCode());
        orderFullCost.setMaterialName(retailOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(retailOrderItem.getSpecification());
        orderFullCost.setOrderNum(retailOrderItem.getRefundableQty());

        BigDecimal price = new BigDecimal(0);

        if (retailOrderItem.getRefundableQty().equals(retailOrderItem.getQty())) {
            price = retailOrderItem.getTotalAmount();
        } else {
            price = retailOrderItem.getTotalAmount().divide(Convert.toBigDecimal(retailOrderItem.getQty())).multiply(Convert.toBigDecimal(retailOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);


        orderFullCost.setFullCost(betweenDay < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(retailOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(retailOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(retailOrderItem.getFullTime());


        orderFullCost.setFullEndTime(DateUtil.beginOfDay(dateTime));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));
        orderFullCost.setCostId(id);


        orderFullCost.insert();
    }


    private String generateFive(RetailOrder retailOrder, RetailOrderItem retailOrderItem, long betweenDay, Date date) {

        DateTime dateTime = DateUtil.offsetDay(date, 0);

        if (orderFullCostService.lambdaQuery()
                .eq(OrderFullCost::getYearTime, Convert.toStr(dateTime.year()))
                .eq(OrderFullCost::getMonthTime, Convert.toStr(dateTime.month() + 1))
                .eq(OrderFullCost::getFullNum, Convert.toInt(betweenDay))
                .eq(OrderFullCost::getOrderNo, retailOrder.getId())
                .eq(OrderFullCost::getMaterialId, retailOrderItem.getMaterialId())
                .eq(OrderFullCost::getFullStartTime, retailOrderItem.getFullTime()).count() > 0) {
            return null;
        }


        OrderFullCost orderFullCost = new OrderFullCost();
        orderFullCost.setYearTime(Convert.toStr(dateTime.year()));
        orderFullCost.setMonthTime(Convert.toStr(dateTime.month() + 1));
        orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
        orderFullCost.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
        orderFullCost.setOrderNo(retailOrder.getId());
        orderFullCost.setOrderTime(retailOrder.getTheTime());
        orderFullCost.setExamineTime(retailOrder.getExamineTime());
        orderFullCost.setCustomerId(retailOrder.getCustomerId());
        orderFullCost.setCustomerName(retailOrder.getCustomerName());
        orderFullCost.setCustomerNumber(retailOrder.getCustomerNumber());
        orderFullCost.setMaterialId(retailOrderItem.getMaterialId());
        orderFullCost.setMaterialCode(retailOrderItem.getMaterialCode());
        orderFullCost.setMaterialName(retailOrderItem.getMaterialName());
        orderFullCost.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
        orderFullCost.setSpecification(retailOrderItem.getSpecification());
        orderFullCost.setOrderNum(retailOrderItem.getRefundableQty());

        BigDecimal price = new BigDecimal(0);

        if (retailOrderItem.getRefundableQty().equals(retailOrderItem.getQty())) {
            price = retailOrderItem.getTotalAmount();
        } else {
            price = retailOrderItem.getTotalAmount().divide(Convert.toBigDecimal(retailOrderItem.getQty())).multiply(Convert.toBigDecimal(retailOrderItem.getRefundableQty()));
        }

        orderFullCost.setPayAmount(price);

        orderFullCost.setOverdueNum(Convert.toInt(betweenDay - 5));

        orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

        orderFullCost.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
        orderFullCost.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
        orderFullCost.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
        orderFullCost.setK3CategoryId(retailOrderItem.getK3CategoryId());
        orderFullCost.setK3CategoryName(retailOrderItem.getK3CategoryName());
        orderFullCost.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
        orderFullCost.setFullStartTime(retailOrderItem.getFullTime());

        orderFullCost.setFullEndTime(DateUtil.beginOfDay(dateTime));

        orderFullCost.setFullNum(Convert.toInt(betweenDay));


        orderFullCost.setNote("自货满日五天内免费，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，该单机型货满已" + betweenDay + "天，收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                (betweenDay < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (betweenDay < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");


        orderFullCost.insert();
        return orderFullCost.getOrderFullCostId();
    }


    public void syncStockNum() {

        List<Stock> list = stockService.lambdaQuery().list();

        List<StockAcc> stockAccList = stockAccService.lambdaQuery()
                .gt(StockAcc::getChangeTime, "2024-03-21 00:00:00")
                .list();

        List<SalesOrder> salesOrderList = salesOrderService.lambdaQuery().eq(SalesOrder::getExamineStatus, "OK")
                .gt(SalesOrder::getApprovalTime, "2024-03-21 00:00:00")
                .select(SalesOrder::getId, SalesOrder::getApprovalTime, SalesOrder::getCorrespondName, SalesOrder::getOrderNo)
                .list();

        List<String> salesIds = salesOrderList.stream().map(SalesOrder::getId).collect(Collectors.toList());

        List<SalesOrderItem> salesOrderItemList = salesOrderItemService.lambdaQuery()
                .in(SalesOrderItem::getSalesOrderNo, salesIds)
                .select(SalesOrderItem::getMaterialId, SalesOrderItem::getRefundableQty, SalesOrderItem::getSalesOrderNo, SalesOrderItem::getOrderId)
                .list();

        List<KingDeeStock> kingDeeStocks = kingDeeStockService.lambdaQuery().list();

        List<StockXz> stockChangeBeans = new ArrayList<>();

        for (int i = 0; i < 130; i++) {
            String dateStr = "2024-03-21 00:00:00";

            DateTime dateTime = DateUtil.parse(dateStr);

            DateTime parse = DateUtil.offsetDay(dateTime, i);

            if (parse.after(new DateTime()))
                break;

            for (Stock stock : list) {

                List<KingDeeStock> stockIds = kingDeeStocks.stream().filter(item -> item.getId().equals(stock.getStockId())).collect(Collectors.toList());


                List<String> stocksNames = stockIds.stream().map(KingDeeStock::getName).collect(Collectors.toList());

                List<StockAcc> stockAccsZJ = stockAccList.stream().filter(item -> item.getChangeTime().after(parse)
                        && item.getMaterialId().equals(stock.getMaterialId())
                        && item.getStockId().equals(stock.getStockId())).collect(Collectors.toList());

                Date endTime = new Date();

                if (!CollectionUtils.isEmpty(stockAccsZJ)) {
                    stock.setStockQty(stockAccsZJ.get(0).getStockCurQty());

                }


                List<StockAcc> stockAccsBetween = stockAccList.stream().filter(item -> item.getChangeTime().after(parse)
                        && item.getMaterialId().equals(stock.getMaterialId()) &&
                        item.getChangeTime().before(!CollectionUtils.isEmpty(stockAccsZJ) ? stockAccsZJ.get(0).getChangeTime() : endTime)
                        && item.getStockId().equals(stock.getStockId()))
                        .collect(Collectors.toList());


                List<String> salesIdList = salesOrderList.stream()
                        .filter(item -> stocksNames.contains(item.getCorrespondName()) && item.getApprovalTime().after(parse)
                                && item.getApprovalTime().before(!CollectionUtils.isEmpty(stockAccsZJ) ? stockAccsZJ.get(0).getChangeTime() : endTime))
                        .map(SalesOrder::getId)
                        .collect(Collectors.toList());

                Integer integer = salesOrderItemList.stream().filter(item -> item.getMaterialId().equals(stock.getMaterialId())
                        && salesIdList.contains(item.getSalesOrderNo())
                ).map(SalesOrderItem::getRefundableQty).reduce(Integer::sum).orElse(0);

                BigDecimal bigDecimal = stockAccsBetween.stream().filter(item -> item.getChangeTime().after(parse)
                        && item.getMaterialId().equals(stock.getMaterialId())
                        && item.getDirectFlag() && item.getStockId().equals(stock.getStockId())
                ).map(StockAcc::getStockChangeQty).reduce(BigDecimal::add).orElse(Convert.toBigDecimal("0"));


                BigDecimal fudecimal = stockAccsBetween.stream().filter(item -> item.getChangeTime().after(parse)
                        && item.getMaterialId().equals(stock.getMaterialId())
                        && !item.getDirectFlag() && item.getStockId().equals(stock.getStockId())
                ).map(StockAcc::getStockChangeQty).reduce(BigDecimal::add).orElse(Convert.toBigDecimal("0"));


                BigDecimal subtract = stock.getStockQty().subtract(bigDecimal).add(fudecimal).add(Convert.toBigDecimal(integer));

                StockXz stockChangeBean = new StockXz();
                stockChangeBean.setMId(stock.getMaterialId());
                stockChangeBean.setQty(Convert.toInt(subtract));
                stockChangeBean.setStockName(stockIds.get(0).getName());
                stockChangeBean.setXzTime(DateUtil.offsetHour(DateUtil.beginOfDay(parse), 1));

                if (subtract.doubleValue() > 0)
                    stockChangeBeans.add(stockChangeBean);

            }

        }

        stockXzService.saveBatch(stockChangeBeans);


    }

    public void syncStockPrice() {


        List<OrderFullDate> orderFullDates = orderFullDateService.lambdaQuery()
                .eq(OrderFullDate::getOrderFullDataId, "1770465377607139329")
                .between(OrderFullDate::getFullEndTime, "2024-03-19 23:59:59", "2024-03-20 23:59:00")
                .list();

        List<String> id = orderFullDates.stream().map(OrderFullDate::getOrderItemId).distinct().collect(Collectors.toList());

        List<StockXz> stockXzList = stockXzService.lambdaQuery().list();


        List<SalesOrderItem> salesOrderItemList = salesOrderItemService.lambdaQuery()
                .in(SalesOrderItem::getOrderId, id)
                .select(SalesOrderItem::getMaterialId, SalesOrderItem::getRefundableQty, SalesOrderItem::getSalesOrderNo, SalesOrderItem::getOrderId)
                .list();


        List<String> salesOrder = salesOrderItemList.stream().map(SalesOrderItem::getSalesOrderNo).collect(Collectors.toList());


        List<SalesOrder> salesOrderList = salesOrderService.lambdaQuery().in(SalesOrder::getId, salesOrder)
                .select(SalesOrder::getId, SalesOrder::getApprovalTime, SalesOrder::getCreateTime, SalesOrder::getCorrespondName, SalesOrder::getOrderNo)
                .list();

        List<StockCorrespond> stockCorrespondList = stockCorrespondService.lambdaQuery().list();


        List<RetailOrderItem> retailOrderItemList = retailOrderItemService.lambdaQuery().in(RetailOrderItem::getId, id).list();

        List<String> retailIds = retailOrderItemList.stream().map(RetailOrderItem::getRetailOrderId).collect(Collectors.toList());

        List<RetailOrder> retailOrders = retailOrderService.lambdaQuery().in(RetailOrder::getId, retailIds).list();

        List<EnginOrderItem> enginOrderItems = enginOrderItemService.lambdaQuery().in(EnginOrderItem::getId, id).list();


        //存储之前经销商得仓库
        Map<String, List<String>> stockMap = new HashMap<>();


        //获得不了经销商得仓库就查找

        List<AdminUser> adminUserList = adminUserService.lambdaQuery()
                .eq(AdminUser::getIsMaster, true).groupBy(AdminUser::getCustomerId).select(AdminUser::getAdminUserId, AdminUser::getCustomerId).list();

        List<String> adminUserIds = adminUserList.stream().map(AdminUser::getAdminUserId).collect(Collectors.toList());


        List<AdminUserStock> list = adminUserStockService.lambdaQuery()
                .in(AdminUserStock::getAdminUserId, adminUserIds).list();

        for (AdminUser adminUser : adminUserList) {

            List<String> cIds = list.stream().filter(item -> item.getAdminUserId().equals(adminUser.getAdminUserId()))
                    .map(AdminUserStock::getCorrespondId).collect(Collectors.toList());

            List<String> coNames = stockCorrespondList.stream().filter(item -> cIds.contains(item.getId()))
                    .map(StockCorrespond::getName).collect(Collectors.toList());

            stockMap.put(adminUser.getCustomerId(), coNames);
        }


        for (RetailOrderItem retailOrderItem : retailOrderItemList) {

            for (int i = 0; i < 130; i++) {
                String dateStr = "2024-03-21 00:00:00";

                DateTime dateTime = DateUtil.parse(dateStr);

                DateTime parse = DateUtil.offsetDay(dateTime, i);

                if (parse.after(DateUtil.offsetDay(new DateTime(), -1)))
                    break;

                //审批之后
                List<String> salesIds = salesOrderList.stream()
                        .filter(item -> item.getApprovalTime() != null && item.getApprovalTime().after(parse))
                        .map(SalesOrder::getId).collect(Collectors.toList());

                //没有审批
                salesIds.addAll(salesOrderList.stream()
                        .filter(item -> item.getApprovalTime() == null)
                        .map(SalesOrder::getId).collect(Collectors.toList()));

                Integer integer = salesOrderItemList.stream().filter(item -> item.getMaterialId().equals(retailOrderItem.getMaterialId())
                        && salesIds.contains(item.getSalesOrderNo()) && item.getOrderId().equals(retailOrderItem.getId())
                ).map(SalesOrderItem::getRefundableQty).reduce(Integer::sum).orElse(0);

                Integer refundQty = retailOrderItem.getRefundableQty() + integer;


                RetailOrder retailOrder = retailOrderService.getById(retailOrderItem.getRetailOrderId());

                RetailOrderItem retailOrderItemServiceById = retailOrderItemService.getById(retailOrderItem.getId());


                List<String> strings = stockMap.get(retailOrder.getCustomerId());


                Integer stockQty = stockXzList.stream().filter(item -> strings.contains(item.getStockName()) &&
                        item.getMId().equals(retailOrderItem.getMaterialId()) && item.getXzTime().after(DateUtil.beginOfDay(parse))
                        && item.getXzTime().before(DateUtil.endOfDay(parse))
                ).map(StockXz::getQty).reduce(Integer::sum).orElse(0);

                if (stockQty < 1)
                    continue;

                if (refundQty < 1)
                    continue;


                Integer betweenDay = retailOrderItemServiceById.getFullNum() + 1;


                if (stockQty < refundQty)
                    refundQty = stockQty;


                String costId = "";

                if (betweenDay > 5) {
                    OrderFullCost orderFullCost = new OrderFullCost();
                    orderFullCost.setYearTime(Convert.toStr(parse.year()));
                    orderFullCost.setMonthTime(Convert.toStr(parse.month() + 1));
                    orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
                    orderFullCost.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
                    orderFullCost.setOrderNo(retailOrder.getId());
                    orderFullCost.setOrderTime(retailOrder.getTheTime());
                    orderFullCost.setExamineTime(retailOrder.getExamineTime());
                    orderFullCost.setCustomerId(retailOrder.getCustomerId());
                    orderFullCost.setCustomerName(retailOrder.getCustomerName());
                    orderFullCost.setCustomerNumber(retailOrder.getCustomerNumber());
                    orderFullCost.setMaterialId(retailOrderItem.getMaterialId());
                    orderFullCost.setMaterialCode(retailOrderItem.getMaterialCode());
                    orderFullCost.setMaterialName(retailOrderItem.getMaterialName());
                    orderFullCost.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
                    orderFullCost.setSpecification(retailOrderItem.getSpecification());
                    orderFullCost.setOrderNum(refundQty);

                    BigDecimal price = new BigDecimal(0);

                    if (refundQty.equals(retailOrderItem.getQty())) {
                        price = retailOrderItem.getTotalAmount();
                    } else {
                        price = retailOrderItem.getTotalAmount()
                                .divide(Convert.toBigDecimal(retailOrderItem.getQty())).multiply(Convert.toBigDecimal(refundQty));
                    }

                    orderFullCost.setPayAmount(price);

                    orderFullCost.setOverdueNum(Convert.toInt(betweenDay - 5));

                    orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                            : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

                    orderFullCost.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
                    orderFullCost.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
                    orderFullCost.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
                    orderFullCost.setK3CategoryId(retailOrderItem.getK3CategoryId());
                    orderFullCost.setK3CategoryName(retailOrderItem.getK3CategoryName());
                    orderFullCost.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
                    orderFullCost.setFullStartTime(retailOrderItem.getFullTime());

                    orderFullCost.setFullEndTime(DateUtil.beginOfDay(parse));

                    orderFullCost.setFullNum(Convert.toInt(betweenDay));


                    orderFullCost.setNote("自货满日五天内免费，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，该单机型货满已" + betweenDay + "天，收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                            (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");

                    orderFullCost.insert();

                    costId = orderFullCost.getOrderFullCostId();
                }

                OrderFullDate orderFullDate = new OrderFullDate();
                orderFullDate.setYearTime(Convert.toStr(parse.year()));
                orderFullDate.setMonthTime(Convert.toStr(parse.month() + 1));
                orderFullDate.setOrderType(retailOrder.getType().equals(1) ? OrderTypeEnum.RETAIL.getKey() : OrderTypeEnum.RETAIL_POLICY.getKey());
                orderFullDate.setOrderNo(retailOrder.getId());
                orderFullDate.setOrderTime(retailOrder.getTheTime());
                orderFullDate.setExamineTime(retailOrder.getExamineTime());
                orderFullDate.setCustomerId(retailOrder.getCustomerId());
                orderFullDate.setCustomerName(retailOrder.getCustomerName());
                orderFullDate.setCustomerNumber(retailOrder.getCustomerNumber());
                orderFullDate.setMaterialId(retailOrderItem.getMaterialId());
                orderFullDate.setMaterialCode(retailOrderItem.getMaterialCode());
                orderFullDate.setMaterialName(retailOrderItem.getMaterialName());
                orderFullDate.setMaterialOldNumber(retailOrderItem.getMaterialOldNumber());
                orderFullDate.setSpecification(retailOrderItem.getSpecification());
                orderFullDate.setOrderNum(refundQty);
                orderFullDate.setOrderItemId(retailOrderItem.getId());

                BigDecimal price = new BigDecimal(0);

                if (refundQty.equals(retailOrderItem.getQty())) {
                    price = retailOrderItem.getTotalAmount();
                } else {
                    price = retailOrderItem.getTotalAmount()
                            .divide(Convert.toBigDecimal(retailOrderItem.getQty()))
                            .multiply(Convert.toBigDecimal(refundQty));
                }

                orderFullDate.setPayAmount(price);


                orderFullDate.setFullCost(betweenDay < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                        : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

                orderFullDate.setCustomerWalletId(retailOrderItem.getCustomerWalletId());
                orderFullDate.setCustomerWalletName(retailOrderItem.getCustomerWalletName());
                orderFullDate.setCustomerWalletNumber(retailOrderItem.getCustomerWalletNumber());
                orderFullDate.setK3CategoryId(retailOrderItem.getK3CategoryId());
                orderFullDate.setK3CategoryName(retailOrderItem.getK3CategoryName());
                orderFullDate.setK3CategoryNumber(retailOrderItem.getK3CategoryNumber());
                orderFullDate.setFullStartTime(retailOrderItem.getFullTime());


                orderFullDate.setFullEndTime(DateUtil.beginOfDay(parse));

                orderFullDate.setFullNum(Convert.toInt(betweenDay));
                orderFullDate.setCostId(costId);

                orderFullDate.insert();


                RetailOrderItem retailOrderItem1 = new RetailOrderItem();
                retailOrderItem1.setId(retailOrderItem.getId());
                retailOrderItem1.setFullNum(betweenDay);
                retailOrderItem1.updateById();


            }
        }

    }


    public void syncStockPriceEngin() {


        List<OrderFullDate> orderFullDates = orderFullDateService.lambdaQuery()
                .between(OrderFullDate::getFullEndTime, "2024-03-20 00:00:00", "2024-03-20 23:59:00")
                .list();

        List<String> id = orderFullDates.stream().map(OrderFullDate::getOrderItemId).distinct().collect(Collectors.toList());

        List<StockXz> stockXzList = stockXzService.lambdaQuery().list();


        List<SalesOrderItem> salesOrderItemList = salesOrderItemService.lambdaQuery()
                .in(SalesOrderItem::getOrderId, id)
                .select(SalesOrderItem::getMaterialId, SalesOrderItem::getRefundableQty, SalesOrderItem::getSalesOrderNo, SalesOrderItem::getOrderId)
                .list();


        List<String> salesOrder = salesOrderItemList.stream().map(SalesOrderItem::getSalesOrderNo).collect(Collectors.toList());


        List<SalesOrder> salesOrderList = salesOrderService.lambdaQuery().in(SalesOrder::getId, salesOrder)
                .select(SalesOrder::getId, SalesOrder::getApprovalTime, SalesOrder::getCreateTime, SalesOrder::getCorrespondName, SalesOrder::getOrderNo)
                .list();

        List<StockCorrespond> stockCorrespondList = stockCorrespondService.lambdaQuery().list();


        List<EnginOrderItem> enginOrderItemList = enginOrderItemService.lambdaQuery().in(EnginOrderItem::getId, id).list();

        List<String> enginId = enginOrderItemList.stream().map(EnginOrderItem::getEnginOrderNo).collect(Collectors.toList());

        List<EnginOrder> enginOrders = enginOrderService.lambdaQuery().in(EnginOrder::getEnginOrderNo, enginId).list();


        //存储之前经销商得仓库
        Map<String, List<String>> stockMap = new HashMap<>();


        //获得不了经销商得仓库就查找

        List<AdminUser> adminUserList = adminUserService.lambdaQuery()
                .eq(AdminUser::getIsMaster, true).groupBy(AdminUser::getCustomerId).select(AdminUser::getAdminUserId, AdminUser::getCustomerId).list();

        List<String> adminUserIds = adminUserList.stream().map(AdminUser::getAdminUserId).collect(Collectors.toList());


        List<AdminUserStock> list = adminUserStockService.lambdaQuery()
                .in(AdminUserStock::getAdminUserId, adminUserIds).list();

        for (AdminUser adminUser : adminUserList) {

            List<String> cIds = list.stream().filter(item -> item.getAdminUserId().equals(adminUser.getAdminUserId()))
                    .map(AdminUserStock::getCorrespondId).collect(Collectors.toList());

            List<String> coNames = stockCorrespondList.stream().filter(item -> cIds.contains(item.getId()))
                    .map(StockCorrespond::getName).collect(Collectors.toList());

            stockMap.put(adminUser.getCustomerId(), coNames);
        }


        for (EnginOrderItem enginOrderItem : enginOrderItemList) {

            for (int i = 0; i < 130; i++) {
                String dateStr = "2024-03-21 00:00:00";

                DateTime dateTime = DateUtil.parse(dateStr);

                DateTime parse = DateUtil.offsetDay(dateTime, i);

                if (parse.after(DateUtil.offsetDay(new DateTime(), -1)))
                    break;

                //审批之后
                List<String> salesIds = salesOrderList.stream()
                        .filter(item -> item.getApprovalTime() != null && item.getApprovalTime().after(parse))
                        .map(SalesOrder::getId).collect(Collectors.toList());

                //没有审批
                salesIds.addAll(salesOrderList.stream()
                        .filter(item -> item.getApprovalTime() == null)
                        .map(SalesOrder::getId).collect(Collectors.toList()));

                Integer integer = salesOrderItemList.stream().filter(item -> item.getMaterialId().equals(enginOrderItem.getMaterialId())
                        && salesIds.contains(item.getSalesOrderNo()) && item.getOrderId().equals(enginOrderItem.getId())
                ).map(SalesOrderItem::getRefundableQty).reduce(Integer::sum).orElse(0);

                Integer refundQty = enginOrderItem.getRefundableQty() + integer;


                List<EnginOrder> enginOrderList = enginOrders.stream()
                        .filter(item -> item.getEnginOrderNo().equals(enginOrderItem.getEnginOrderNo())).collect(Collectors.toList());

                EnginOrder enginOrder = enginOrderList.get(0);

                EnginOrderItem enginOrderItemServiceById = enginOrderItemService.getById(enginOrderItem.getId());


                List<String> strings = stockMap.get(enginOrder.getCustomerId());


                Integer stockQty = stockXzList.stream().filter(item -> strings.contains(item.getStockName()) &&
                        item.getMId().equals(enginOrderItem.getMaterialId()) && item.getXzTime().after(DateUtil.beginOfDay(parse))
                        && item.getXzTime().before(DateUtil.endOfDay(parse))
                ).map(StockXz::getQty).reduce(Integer::sum).orElse(0);

                if (stockQty < 1)
                    continue;

                if (refundQty < 1)
                    continue;


                Integer betweenDay = enginOrderItemServiceById.getFullNum() + i + 1;


                if (stockQty < refundQty)
                    refundQty = stockQty;


                String costId = "";

                if (betweenDay > 5) {
                    OrderFullCost orderFullCost = new OrderFullCost();
                    orderFullCost.setYearTime(Convert.toStr(parse.year()));
                    orderFullCost.setMonthTime(Convert.toStr(parse.month() + 1));

                    orderFullCost.setStatus(OrderFullStatusEnum.ENABLE.getKey());
                    orderFullCost.setOrderType(enginOrder.getEnginOrderType().equals(OrderTypeEnum.HOME.getKey()) ? OrderTypeEnum.HOME.getKey() : OrderTypeEnum.TRADE.getKey());
                    orderFullCost.setOrderNo(enginOrder.getEnginOrderNo());
                    orderFullCost.setOrderTime(enginOrder.getOrderDate());
                    orderFullCost.setExamineTime(enginOrder.getConfirmTime());
                    orderFullCost.setCustomerId(enginOrder.getCustomerId());
                    orderFullCost.setCustomerName(enginOrder.getCustomerName());
                    orderFullCost.setCustomerNumber(enginOrder.getCustomerNumber());
                    orderFullCost.setMaterialId(enginOrderItem.getMaterialId());
                    orderFullCost.setMaterialCode(enginOrderItem.getMaterialNumber());
                    orderFullCost.setMaterialName(enginOrderItem.getMaterialName());
                    orderFullCost.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
                    orderFullCost.setSpecification(enginOrderItem.getSpecification());
                    orderFullCost.setOrderNum(enginOrderItem.getRefundableQty());
                    orderFullCost.setOrderItemId(enginOrderItem.getId());
                    orderFullCost.setOrderNum(refundQty);

                    BigDecimal price = new BigDecimal(0);

                    if (refundQty.equals(enginOrderItem.getQty())) {
                        price = enginOrderItem.getTotalAmount();
                    } else {
                        price = enginOrderItem.getTotalAmount()
                                .divide(Convert.toBigDecimal(enginOrderItem.getQty())).multiply(Convert.toBigDecimal(refundQty));
                    }

                    orderFullCost.setPayAmount(price);

                    orderFullCost.setOverdueNum(Convert.toInt(betweenDay - 5));

                    orderFullCost.setFullCost(orderFullCost.getOverdueNum() < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                            : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

                    orderFullCost.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
                    orderFullCost.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
                    orderFullCost.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
                    orderFullCost.setK3CategoryId(enginOrderItem.getK3CategoryId());
                    orderFullCost.setK3CategoryName(enginOrderItem.getK3CategoryName());
                    orderFullCost.setK3CategoryNumber(enginOrderItem.getK3CategoryNumber());
                    orderFullCost.setFullStartTime(enginOrderItem.getFullTime());

                    orderFullCost.setFullEndTime(DateUtil.beginOfDay(parse));

                    orderFullCost.setFullNum(Convert.toInt(betweenDay));


                    orderFullCost.setNote("自货满日五天内免费，逾期15天内收取订单机型金额万分之3，逾15天以上收取订单机型金额万分之四，该单机型货满已" + betweenDay + "天，收取逾期第" + orderFullCost.getOverdueNum() + "天订单机型金额*" +
                            (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + "（" + price + "*" + (orderFullCost.getOverdueNum() < 15 ? "万分之3" : "万分之4") + " = " + orderFullCost.getFullCost() + "）");

                    orderFullCost.insert();

                    costId = orderFullCost.getOrderFullCostId();
                }

                OrderFullDate orderFullDate = new OrderFullDate();
                orderFullDate.setYearTime(Convert.toStr(parse.year()));
                orderFullDate.setMonthTime(Convert.toStr(parse.month() + 1));
                orderFullDate.setOrderType(enginOrder.getEnginOrderType().equals(OrderTypeEnum.HOME.getKey()) ? OrderTypeEnum.HOME.getKey() : OrderTypeEnum.TRADE.getKey());
                orderFullDate.setOrderNo(enginOrder.getEnginOrderNo());
                orderFullDate.setOrderTime(enginOrder.getOrderDate());
                orderFullDate.setExamineTime(enginOrder.getConfirmTime());
                orderFullDate.setCustomerId(enginOrder.getCustomerId());
                orderFullDate.setCustomerName(enginOrder.getCustomerName());
                orderFullDate.setCustomerNumber(enginOrder.getCustomerNumber());
                orderFullDate.setMaterialId(enginOrderItem.getMaterialId());
                orderFullDate.setMaterialCode(enginOrderItem.getMaterialNumber());
                orderFullDate.setMaterialName(enginOrderItem.getMaterialName());
                orderFullDate.setMaterialOldNumber(enginOrderItem.getMaterialOldNumber());
                orderFullDate.setSpecification(enginOrderItem.getSpecification());
                orderFullDate.setOrderNum(enginOrderItem.getRefundableQty());
                orderFullDate.setOrderItemId(enginOrderItem.getId());
                orderFullDate.setOrderNum(refundQty);

                BigDecimal price = new BigDecimal(0);

                if (refundQty.equals(enginOrderItem.getQty())) {
                    price = enginOrderItem.getTotalAmount();
                } else {
                    price = enginOrderItem.getTotalAmount()
                            .divide(Convert.toBigDecimal(enginOrderItem.getQty()))
                            .multiply(Convert.toBigDecimal(refundQty));
                }

                orderFullDate.setPayAmount(price);


                orderFullDate.setFullCost(betweenDay < 15 ? price.multiply(Constant.STORAGE_FEE_ONE).setScale(2, BigDecimal.ROUND_HALF_UP)
                        : price.multiply(Constant.STORAGE_FEE_TWO).setScale(2, BigDecimal.ROUND_HALF_UP));

                orderFullDate.setCustomerWalletId(enginOrderItem.getCustomerWalletId());
                orderFullDate.setCustomerWalletName(enginOrderItem.getCustomerWalletName());
                orderFullDate.setCustomerWalletNumber(enginOrderItem.getCustomerWalletNumber());
                orderFullDate.setK3CategoryId(enginOrderItem.getK3CategoryId());
                orderFullDate.setK3CategoryName(enginOrderItem.getK3CategoryName());
                orderFullDate.setK3CategoryNumber(enginOrderItem.getK3CategoryNumber());
                orderFullDate.setFullStartTime(enginOrderItem.getFullTime());


                orderFullDate.setFullEndTime(DateUtil.beginOfDay(parse));

                orderFullDate.setFullNum(Convert.toInt(betweenDay));
                orderFullDate.setCostId(costId);

                orderFullDate.insert();


                EnginOrderItem enginOrderItem1 = new EnginOrderItem();
                enginOrderItem1.setId(enginOrderItem.getId());
                enginOrderItem1.setFullNum(betweenDay);
                enginOrderItem1.updateById();


            }
        }

    }

    public void syncStockThree() {


        List<RetailOrder> retailOrderList = retailOrderService.lambdaQuery()
                .ne(RetailOrder::getId, "2240321000196")
                .gt(RetailOrder::getExamineTime, "2024-03-20 23:59:00").list();

        List<String> retailIds = retailOrderList.stream().map(RetailOrder::getId).collect(Collectors.toList());

        List<RetailOrderItem> retailOrderItemList = retailOrderItemService.lambdaQuery()
                .in(RetailOrderItem::getRetailOrderId, retailIds)
                .isNull(RetailOrderItem::getFullNum)
                .list();

        List<String> retailOrderItemZi = retailOrderItemList.stream().map(RetailOrderItem::getId).collect(Collectors.toList());

        List<StockXz> stockXzList = stockXzService.lambdaQuery().list();


        List<SalesOrderItem> salesOrderItemList = salesOrderItemService.lambdaQuery()
                .in(SalesOrderItem::getOrderId, retailOrderItemZi)
                .select(SalesOrderItem::getMaterialId, SalesOrderItem::getRefundableQty, SalesOrderItem::getSalesOrderNo, SalesOrderItem::getOrderId)
                .list();


        List<String> salesOrder = salesOrderItemList.stream().map(SalesOrderItem::getSalesOrderNo).collect(Collectors.toList());


        List<SalesOrder> salesOrderList = salesOrderService.lambdaQuery().in(SalesOrder::getId, salesOrder)
                .select(SalesOrder::getId, SalesOrder::getApprovalTime, SalesOrder::getCreateTime, SalesOrder::getCorrespondName, SalesOrder::getOrderNo)
                .list();

        List<StockCorrespond> stockCorrespondList = stockCorrespondService.lambdaQuery().list();


        //存储之前经销商得仓库
        Map<String, List<String>> stockMap = new HashMap<>();


        //获得不了经销商得仓库就查找

        List<AdminUser> adminUserList = adminUserService.lambdaQuery()
                .eq(AdminUser::getIsMaster, true).groupBy(AdminUser::getCustomerId).select(AdminUser::getAdminUserId, AdminUser::getCustomerId).list();

        List<String> adminUserIds = adminUserList.stream().map(AdminUser::getAdminUserId).collect(Collectors.toList());


        List<AdminUserStock> list = adminUserStockService.lambdaQuery()
                .in(AdminUserStock::getAdminUserId, adminUserIds).list();

        for (AdminUser adminUser : adminUserList) {

            List<String> cIds = list.stream().filter(item -> item.getAdminUserId().equals(adminUser.getAdminUserId()))
                    .map(AdminUserStock::getCorrespondId).collect(Collectors.toList());

            List<String> coNames = stockCorrespondList.stream().filter(item -> cIds.contains(item.getId()))
                    .map(StockCorrespond::getName).collect(Collectors.toList());

            stockMap.put(adminUser.getCustomerId(), coNames);
        }


        for (RetailOrderItem retailOrderItem : retailOrderItemList) {

            stockForceLogic.syncStockThreeSync(retailOrderItem,stockXzList,salesOrderList,salesOrderItemList,stockMap);

        }

    }


}


