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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zfire.mall.manager.bean.ExcelData;
import com.zfire.mall.manager.bean.PoySaleCountBean;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.bean.k3.K3CustomerBean;
import com.zfire.mall.manager.bean.k3.RequestApiBean;
import com.zfire.mall.manager.bean.k3.bill.*;
import com.zfire.mall.manager.bean.k3.bill.result.BillItem;
import com.zfire.mall.manager.bean.k3.bill.result.ResultBean;
import com.zfire.mall.manager.bean.k3.bill.result.ResultEntity;
import com.zfire.mall.manager.bean.k3.bill.result.SuccessEntitys;
import com.zfire.mall.manager.bean.sale.*;
import com.zfire.mall.manager.bean.stock.StockBean;
import com.zfire.mall.manager.bean.stock.StockBeanCustomerToDay;
import com.zfire.mall.manager.commonmapper.CommonCountMapper;
import com.zfire.mall.manager.commonmapper.InvoiceMapper;
import com.zfire.mall.manager.commonmapper.SaleOrderMapper;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.constant.KingDeeCons;
import com.zfire.mall.manager.enums.ExamineStatusEnum;
import com.zfire.mall.manager.enums.InvoiceCustomerEnum;
import com.zfire.mall.manager.enums.OrderTypeStatusEnum;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.logic.common.CommonLogic;
import com.zfire.mall.manager.logic.customer.CustomerProductTypeLogic;
import com.zfire.mall.manager.logic.invoice.InvoiceLogic;
import com.zfire.mall.manager.logic.k3.K3CustomerLogic;
import com.zfire.mall.manager.logic.k3.K3GeJiangLogic;
import com.zfire.mall.manager.logic.k3.K3Logic;
import com.zfire.mall.manager.logic.k3.K3MaterialLogic;
import com.zfire.mall.manager.logic.k3.bill.GeJiangInStockLogic;
import com.zfire.mall.manager.logic.k3.bill.SalesOrderLogic;
import com.zfire.mall.manager.logic.k3.bill.SalesOutStockLogic;
import com.zfire.mall.manager.logic.k3.bill.SalesReturnLogic;
import com.zfire.mall.manager.logic.retail.RetailOrderLogic;
import com.zfire.mall.manager.logic.stock.StockCommonLogic;
import com.zfire.mall.manager.logic.wallet.WalletLogic;
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.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 销售出库单
 *
 * @author Administrator
 */
@Slf4j
@Service
public class SaleOrderLogic {

    @Autowired
    SaleOrderMapper saleOrderMapper;

    @Autowired
    RetailOrderLogic retailOrderLogic;

    @Autowired
    SalesOrderService salesOrderService;

    @Autowired
    InvoiceApplicationOrderService invoiceApplicationOrderService;

    @Autowired
    InvoiceApplicationService invoiceApplicationService;

    @Autowired
    EnginOrderService enginOrderService;

    @Autowired
    EnginOrderItemService enginOrderItemService;

    @Autowired
    DisplaceOrderService displaceOrderService;

    @Autowired
    DisplaceOrderItemService displaceOrderItemService;

    @Autowired
    PickManagerShipService pickManagerService;


    @Autowired
    CommonLogic commonLogic;

    @Autowired
    K3MaterialLogic k3MaterialLogic;

    @Autowired
    StockCommonLogic stockCommonLogic;

    @Autowired
    SalesOrderLogic salesOrderLogic;

    @Autowired
    K3CustomerLogic k3CustomerLogic;

    @Autowired
    SalesOutStockLogic salesOutStockLogic;

    @Autowired
    StockCorrespondPositionService stockCorrespondPositionService;

    @Autowired
    KingDeeStockService kingDeeStockService;

    @Autowired
    KingDeeMaterialService kingDeeMaterialService;

    @Autowired
    InvoiceLogic invoiceLogic;

    @Autowired
    CommonCountMapper commonCountMapper;

    @Autowired
    SalesOrderItemService salesOrderItemService;

    @Autowired
    RetailOrderItemService retailOrderItemService;

    @Autowired
    RequisitionOrderItemService requisitionOrderItemService;

    @Autowired
    CustomerWalletService customerWalletService;

    @Autowired
    WalletLogic walletLogic;

    @Autowired
    EnginInfoOrderItemService enginInfoOrderItemService;

    @Autowired
    SalesOrderKingSyncService salesOrderKingSyncService;

    @Autowired
    StockService stockService;

    @Autowired
    SalesReturnLogic salesReturnLogic;

    @Autowired
    K3GeJiangLogic k3GeJiangLogic;

    @Autowired
    K3Logic k3Logic;

    @Autowired
    GeJiangInStockLogic geJiangInStockLogic;

    @Autowired
    InvoiceApplicationSyncGejiangService invoiceApplicationSyncGejiangService;

    @Autowired
    AdminUserStockService adminUserStockService;

    @Autowired
    InvoiceMapper invoiceMapper;

    @Autowired
    StockCorrespondService stockCorrespondService;

    @Autowired
    RetailOrderService retailOrderService;



    final static String orgId = "1";
    final static String orgNum = "100";

    @Autowired
    CustomerProductTypeLogic customerProductTypeLogic;

    @Autowired
    SalesOrderPictureService salesOrderPictureService;

    @Autowired
    KingDeeOtherStockOutService kingDeeOtherStockOutService;

    @Autowired
    KingDeeOtherStockOutItemService kingDeeOtherStockOutItemService;

    @Autowired
    KingDeeDepartmentService kingDeeDepartmentService;

    @Autowired
    RedisLockRegistry redisLockRegistry;


    public IPage<SaleOrderBean> list(String categoryId, String invoiceStartTime, String invoiceEndTime, String createBy, Integer syncStatus, String printStartTime, String printEndTime, String printTimeDesc, String approvalStartTime, String approvalEndTime,
                                     String mainOrderId, List<String> id, List<String> orderNo, String correspondName,
                                     String materialNumber, String customerName, List<String> correspondId, String specification,
                                     String materialName, String customerNumber, String examineStatus, String startTime, String endTime, Integer pageNum, Integer pageSize) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        List<String> collect = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).select(AdminUserStock::getCorrespondId).list()
                .stream().map(AdminUserStock::getCorrespondId).distinct().collect(Collectors.toList());


        Integer count = saleOrderMapper.listCount(categoryId, invoiceStartTime, invoiceEndTime, createBy, syncStatus, printStartTime, printEndTime, printTimeDesc, approvalStartTime, approvalEndTime, mainOrderId, id, correspondName, materialNumber, orderNo, customerName, correspondId, specification, materialName,
                customerNumber, examineStatus, startTime, endTime, customerId, adminUser.getServiceIds(), collect, adminUser.getK3CategoryIds());

        IPage<SaleOrderBean> list = saleOrderMapper.list(new Page<>(pageNum, pageSize, count, false), categoryId, invoiceStartTime, invoiceEndTime, createBy, syncStatus,
                printStartTime, printEndTime, printTimeDesc, approvalStartTime, approvalEndTime, mainOrderId, id, correspondName, materialNumber, orderNo, customerName, correspondId,
                specification, materialName,
                customerNumber, examineStatus, startTime, endTime, customerId, adminUser.getServiceIds(), collect, adminUser.getK3CategoryIds());

        Map<String, String> kingDeeMap = kingDeeDepartmentService.lambdaQuery()
                .select(KingDeeDepartment::getNumber, KingDeeDepartment::getName).list()
                .stream().collect(Collectors.toMap(KingDeeDepartment::getNumber, KingDeeDepartment::getName));
        List<SaleOrderBean> records = list.getRecords();
        for (SaleOrderBean record : records) {
           /* List<SalesOrderPicture> listPicture = salesOrderPictureService.lambdaQuery().eq(SalesOrderPicture::getSalesId, record.getId()).list();
            record.setSalesOrderPictures(listPicture);*/
            record.setK3OrgName(kingDeeMap.get(record.getK3OrgNumber()));
        }
        list.setRecords(records);
        return list;
    }

    public PoySaleCountBean listCount(String orderNo, String correspondName, String materialNumber, String customerName, String correspondId, String specification,
                                      String materialName, String customerNumber, String examineStatus, String startTime, String endTime) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        PoySaleCountBean list = commonCountMapper.saleOrderlistCount(correspondName, materialNumber, orderNo, customerName, correspondId, specification, materialName,
                customerNumber, examineStatus, startTime, endTime, customerId, adminUser.getServiceIds(), adminUser.getK3CategoryIds());
        return list;
    }

    public SaleOrderBody detail(String id) {
        SaleOrderBody detail = saleOrderMapper.detail(id);
        List<SalesOrderPicture> listPicture = salesOrderPictureService.lambdaQuery().eq(SalesOrderPicture::getSalesId, detail.getId()).list();
        detail.setSalesOrderPictures(listPicture);
        return detail;
    }

    @Transactional(rollbackFor = Exception.class)
    public void approval(SalesOrder salesOrder) throws Exception {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        SaleOrderBody detail = saleOrderMapper.detail(salesOrder.getId());

        if (detail.getExamineStatus().equals(ExamineStatusEnum.OK.toString()))
            throw new RemoteServiceException("此订单已审批通过，无法再次审批");

        //更新销售出库单状态
        salesOrder.setApprovalName(adminUser.getNickName());
        salesOrder.setApprovalTime(new Date());
        salesOrder.updateById();

        //通过的执行这个逻辑
        if (salesOrder.getExamineStatus().equals(ExamineStatusEnum.OK.toString())) {


            if (!detail.getInvoiceType().equals(3))
                checkApproval(detail.getSaleOrderData(), detail.getCorrespondId(), salesOrder.getExamineStatus());


            for (InvoiceApplicationOrder order : detail.getSaleOrderData()) {

                Lock obtain = redisLockRegistry.obtain(Constant.RedisPrefix.INVOICE_APPLICATION+order.getOrderId());
                try {
                    if (!obtain.tryLock(5, TimeUnit.SECONDS)) {
                        throw new RemoteServiceException("系统繁忙，请稍后再试");
                    }

                //记录台账记录
                String customerWalletId = null;
                if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY")) {
                    RetailOrderItem retailOrderItem = retailOrderItemService.getById(order.getOrderId());
                    retailOrderItem.setHasSendQty(retailOrderItem.getHasSendQty() + order.getRefundableQty());

                    if (retailOrderItem.getQty() < retailOrderItem.getHasSendQty())
                        throw new RemoteServiceException("出库数量大于了订单数量");

                    retailOrderItem.updateById();
                    customerWalletId = retailOrderItem.getCustomerWalletId();
                }

                if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME")) {
                    EnginOrderItem enginOrderItem = enginOrderItemService.getById(order.getOrderId());
                    enginOrderItem.setHasSendQty(enginOrderItem.getHasSendQty() + order.getRefundableQty());

                    if (enginOrderItem.getQty() < enginOrderItem.getHasSendQty())
                        throw new RemoteServiceException("出库数量大于了订单数量");


                    if (order.getOrderType().equals("TRADE")) {
                        EnginInfoOrderItem one = enginInfoOrderItemService.lambdaQuery().eq(EnginInfoOrderItem::getEnginInfoNo, enginOrderItem.getRefEnginRecordNo())
                                .eq(EnginInfoOrderItem::getSaleTypeId, enginOrderItem.getSaleTypeId())
                                .eq(EnginInfoOrderItem::getMaterialNumber, enginOrderItem.getMaterialNumber())
                                .one();

                        if (one != null) {
                            one.setHasDeliverQty(one.getHasDeliverQty() + order.getRefundableQty());
                            one.updateById();
                        }
                    }

                    enginOrderItem.updateById();
                    customerWalletId = enginOrderItem.getCustomerWalletId();
                }

                } finally {
                    obtain.unlock();
                }


                //计算扣除库存

                StockCorrespondPosition stockCorrespondPosition = stockCorrespondPositionService.lambdaQuery()
                        .eq(StockCorrespondPosition::getCorrespondId, detail.getCorrespondId())
                        .last("limit 1").one();

                Stock stock = stockService.lambdaQuery().eq(Stock::getMaterialId, order.getMaterialId()).eq(Stock::getStockId, stockCorrespondPosition.getStockId())
                        .last("limit 1").one();


                stock.setStockQty(stock.getStockQty().subtract(new BigDecimal(StrUtil.toString(order.getRefundableQty()))));
                if (stock.getStockQty().compareTo(BigDecimal.ZERO) == -1)
                    throw new RemoteServiceException(order.getMaterialName() + ":" + order.getSpecification() + "库存不足");

                stock.updateById();

            }

            SalesOrderKingSync salesOrderKingSync = new SalesOrderKingSync();
            salesOrderKingSync.setSalesId(salesOrder.getId());
            salesOrderKingSync.insert();

            //更新销售出库单状态
            salesOrder.setApprovalName(adminUser.getNickName());
            salesOrder.setApprovalTime(new Date());
            salesOrder.updateById();
        }

        invoiceMapper.updateStatus(salesOrder.getOrderNo());
        saleOrderMapper.updateInvoice(salesOrder.getId());
    }


    private void checkApproval(List<SaleOrderData> orders, String correspondId, String status) throws Exception {
        for (SaleOrderData order : orders) {
            //查询订单明细
            //invoiceLogic.syncInStock(order.getMaterialId());
            //查询该仓库库存
            Integer integer = stockCommonLogic.stockKingDeeNumber(correspondId, order.getMaterialId());

            if ((status.equals(ExamineStatusEnum.WAIT.toString()) || status.equals(ExamineStatusEnum.SAVE.toString())) && order.getRefundableQty() > integer)
                throw new RemoteServiceException(order.getMaterialName() + order.getSpecification() + "库存不足");

            if (status.equals(ExamineStatusEnum.OK.toString()) && order.getRefundableQty() > integer)
                throw new RemoteServiceException(order.getMaterialName() + order.getSpecification() + "库存不足");
        }
    }

    private void toK3(ResultEntity resultEntity, SaleOrderBody detail, List<InvoiceApplicationOrder> invoiceApplicationOrders) {
        SalesOutStockBean salesOutStockBean = new SalesOutStockBean();
        salesOutStockBean.setBillNo(detail.getId());
        salesOutStockBean.setId(resultEntity.getId());
        salesOutStockBean.setDate(DateUtil.formatDate(new Date()));
        salesOutStockBean.setRemarks(detail.getRemark());

        //所有物料单位
        List<KingDeeMaterial> kingDeeMaterials = k3MaterialLogic.allUnit();

        List<SalesOutStockItemBean> salesOutStockItemBeans = new ArrayList<>();
        for (BillItem item : resultEntity.getItems()) {
            for (InvoiceApplicationOrder invoiceApplicationOrder : invoiceApplicationOrders) {
                if (invoiceApplicationOrder.getOrderId().equals(item.getSupplyColVal())) {
                    if (invoiceApplicationOrder.getRefundableQty().equals(0))
                        continue;

                    CustomerProductTypeRela byCustomerWalletId = customerProductTypeLogic.getByCustomerWalletId(invoiceApplicationOrder.getCustomerWalletId());

                    SalesOutStockItemBean salesOutStockItem = new SalesOutStockItemBean();
                    salesOutStockItem.setEntryId(item.getEntryId());
                    salesOutStockItem.setUnit(k3MaterialLogic.queryUnitCode(kingDeeMaterials, invoiceApplicationOrder.getUnit()));
                    //仓库编码
                    StockCorrespondPosition one = stockCorrespondPositionService.lambdaQuery().eq(StockCorrespondPosition::getCorrespondId, detail.getCorrespondId()).one();
                    KingDeeStock kingDeeStock = kingDeeStockService.getById(one.getStockId());
                    salesOutStockItem.setStock(kingDeeStock.getNumber());

                    salesOutStockItem.setMustQty(new BigDecimal(Convert.toStr(invoiceApplicationOrder.getRefundableQty())));
                    salesOutStockItem.setRealQty(new BigDecimal(Convert.toStr(invoiceApplicationOrder.getRefundableQty())));
                    salesOutStockItem.setSupplyColVal(invoiceApplicationOrder.getId());
                    salesOutStockItem.setSalesTypeName(invoiceApplicationOrder.getSaleTypeName() + "|" + invoiceApplicationOrder.getSaleTypeCode());
                    salesOutStockItem.setSalesTypId(invoiceApplicationOrder.getSaleTypeId());

                    if (byCustomerWalletId != null && !StringUtils.isEmpty(byCustomerWalletId.getK3OrgNumber()))
                        salesOutStockItem.setKls(byCustomerWalletId.getK3OrgNumber());
                    salesOutStockItemBeans.add(salesOutStockItem);

                }
            }
        }

        salesOutStockBean.setEntry(salesOutStockItemBeans);
        ResultEntity resultEntitySales = salesOutStockLogic.syncPushBillData(salesOutStockBean);
    }


    /**
     * 销售出库单导出
     *
     * @param saleOrderBeanList
     * @return
     */
    public ExcelData export(List<SaleOrderBean> saleOrderBeanList) {
        String[] titles = new String[]{"状态", "打印时间", "发票号码", "出库单号", "发货单号", "订单号", "仓库",
                "经销商编码", "经销商名称", "销售类型", "物料编码", "厂产品代码", "产品名称", "规格型号", "存货类别", "单位", "数量", "单价", "订单金额", "表头备注", "表体备注", "业务员", "表头业务员", "审核时间","金蝶部门"};
        List<List<Object>> rows = new ArrayList<>();
        for (SaleOrderBean saleOrderBean : saleOrderBeanList) {
            List<Object> row = new ArrayList<>();
//            row.add(ExamineStatusEnum.valueOf(saleOrderBean.getExamineStatus()).getMsg());
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(saleOrderBean.getExamineStatus()));
            row.add(saleOrderBean.getPrintTime() != null ? DateUtil.format(saleOrderBean.getPrintTime(), "yyyy-MM-dd HH:mm:ss") : "");
            row.add(saleOrderBean.getBillReceipt());
            row.add(saleOrderBean.getId());
            row.add(saleOrderBean.getOrderNo());
            row.add(saleOrderBean.getOrderType().equals("TRADE") ? saleOrderBean.getEnginOrderNo() : saleOrderBean.getOrderType().equals("HOME") ? saleOrderBean.getEnginOrderNo() :
                    saleOrderBean.getOrderType().equals("REQUISITION_TRADE") ? saleOrderBean.getEnginOrderNo() : saleOrderBean.getOrderType().equals("REQUISITION_HOME") ? saleOrderBean.getEnginOrderNo() : saleOrderBean.getMainOrderId());

            row.add(saleOrderBean.getCorrespondName());
            //关联经销商
            row.add(saleOrderBean.getCustomerNumber());
            row.add(saleOrderBean.getCustomerName());
            row.add(saleOrderBean.getSaleTypeName());
            row.add(saleOrderBean.getMaterialCode());
            row.add(saleOrderBean.getMaterialOldNumber());
            row.add(saleOrderBean.getMaterialName());
            row.add(saleOrderBean.getSpecification());
            row.add(saleOrderBean.getK3CategoryName());
            row.add(saleOrderBean.getUnit());
            row.add(saleOrderBean.getRefundableQty());
            row.add(saleOrderBean.getSinglePayPrice());
            row.add(saleOrderBean.getPayAmount());
            row.add(saleOrderBean.getHeaderRemark());
            row.add(saleOrderBean.getInvoiceRemark());
            row.add(saleOrderBean.getServiceName());
            row.add(saleOrderBean.getK3ServiceName());
            row.add(saleOrderBean.getApprovalTime() != null ? DateUtil.format(saleOrderBean.getApprovalTime(), "yyyy-MM-dd HH:mm:ss") : "");
            row.add(saleOrderBean.getK3OrgName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public void approvalJudge(String id) {
        SalesOrder salesOrder = salesOrderService.getById(id);
        if (salesOrder.getType().equals(2))
            return;

        InvoiceApplication invoiceApplicationServiceById = invoiceApplicationService.getById(salesOrder.getOrderNo());
        if (invoiceApplicationServiceById.getType().equals(3))
            return;
        StockCorrespond stockCorrespondServiceById = stockCorrespondService.getById(invoiceApplicationServiceById.getCorrespondId());
        if (stockCorrespondServiceById.getType().equals(2))
            return;
        List<InvoiceApplicationOrder> list = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, salesOrder.getOrderNo()).list();
        for (InvoiceApplicationOrder invoiceApplicationOrder : list) {
            Integer count = pickManagerService.lambdaQuery().eq(PickManagerShip::getInvoiceOrderId, invoiceApplicationOrder.getId()).count();
            if (count < 1)
                throw new RemoteServiceException("未预约提货不可审批");

            if (pickManagerService.lambdaQuery().eq(PickManagerShip::getInvoiceOrderId, invoiceApplicationOrder.getId())
                    .eq(PickManagerShip::getStatus, 1).count() < 1)
                throw new RemoteServiceException("未打印订单不可审批");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void trialApproval(String id, String examineStatus, String approvalRemark) {
        SalesOrder salesOrder = salesOrderService.getById(id);
        if (!salesOrder.getSyncStatus().equals(1))
            throw new RemoteServiceException("订单尚未同步，无法反审");
        List<SalesOrderItem> list = salesOrderItemService.lambdaQuery().eq(SalesOrderItem::getSalesOrderNo, salesOrder.getId()).list();
        for (SalesOrderItem order : list) {
            //记录台账记录
            String customerWalletId = null;
            if (order.getOrderType().equals("RETAIL") || order.getOrderType().equals("RETAIL_POLICY")) {
                RetailOrderItem retailOrderItem = retailOrderItemService.getById(order.getOrderId());
                retailOrderItem.setHasSendQty(retailOrderItem.getHasSendQty() - order.getRefundableQty());

                retailOrderItem.updateById();
                customerWalletId = retailOrderItem.getCustomerWalletId();
            }

            if (order.getOrderType().equals("TRADE") || order.getOrderType().equals("HOME")) {
                EnginOrderItem enginOrderItem = enginOrderItemService.getById(order.getOrderId());
                enginOrderItem.setHasSendQty(enginOrderItem.getHasSendQty() - order.getRefundableQty());

                enginOrderItem.updateById();
                customerWalletId = enginOrderItem.getCustomerWalletId();


                if (order.getOrderType().equals("TRADE")) {
                    EnginInfoOrderItem one = enginInfoOrderItemService.lambdaQuery().eq(EnginInfoOrderItem::getEnginInfoNo, enginOrderItem.getRefEnginRecordNo())
                            .eq(EnginInfoOrderItem::getSaleTypeId, enginOrderItem.getSaleTypeId())
                            .eq(EnginInfoOrderItem::getMaterialNumber, enginOrderItem.getMaterialNumber())
                            .one();

                    if (one != null) {
                        one.setHasDeliverQty(one.getHasDeliverQty() - order.getRefundableQty());
                        one.updateById();
                    }
                }
            }

            StockCorrespondPosition stockCorrespondPosition = stockCorrespondPositionService.lambdaQuery()
                    .eq(StockCorrespondPosition::getCorrespondId, salesOrder.getCorrespondId())
                    .last("limit 1").one();

            Stock stock = stockService.lambdaQuery().eq(Stock::getMaterialId, order.getMaterialId()).eq(Stock::getStockId, stockCorrespondPosition.getStockId())
                    .last("limit 1").one();


            stock.setStockQty(stock.getStockQty().add(new BigDecimal(StrUtil.toString(order.getRefundableQty()))));
            stock.updateById();
        }


        String billNo = salesOrder.getId();

        if (billNo == null)
            throw new RemoteServiceException("销售出库单未同步金蝶，无法反审");
        boolean b = salesOutStockLogic.unAuditByBillNo(billNo);
        if (!b)
            throw new RemoteServiceException("反审失败");
        salesOrder.setExamineStatus(ExamineStatusEnum.WAIT.toString());
        salesOrder.setSyncStatus(0);
        salesOrder.updateById();
        salesOrderItemService.lambdaUpdate().eq(SalesOrderItem::getSalesOrderNo, salesOrder.getId()).set(SalesOrderItem::getKingBillNo, null).update();
        saleOrderMapper.updateInvoice(salesOrder.getId());
        invoiceMapper.updateStatus(salesOrder.getOrderNo());
    }

    public String listOrderNo(List<String> orderNo) {
        String remark = "";
        for (String s : orderNo) {
            SalesOrder byId = salesOrderService.lambdaQuery().eq(SalesOrder::getOrderNo, s).one();
            if (byId == null) {
                continue;
            }
            if (byId.getCounterclaim() == true) {
                if (StringUtils.isEmpty(remark)) {
                    remark = s;
                    continue;
                }
                remark = remark + "," + s;

            }

        }
        if (StringUtils.isEmpty(remark)) {
            return null;
        }
        return "当前发货单有做过反审再审核" + remark + "请注意审核销售出库单";
    }

    public ExcelData exportChuKu(List<SaleOrderBean> records) {
        String[] titles = new String[]{"状态", "打印时间", "订单类型", "出库单号", "发货单号", "订单号", "仓库",
                "经销商编码", "经销商名称", "物料编码", "厂产品代码", "产品名称", "规格型号", "存货类别", "单位", "审核人", "审核时间","数量","金蝶部门"};
        List<List<Object>> rows = new ArrayList<>();
        for (SaleOrderBean saleOrderBean : records) {
            List<Object> row = new ArrayList<>();
//            row.add(ExamineStatusEnum.valueOf(saleOrderBean.getExamineStatus()).getMsg());
            row.add(EnumUtil.getNameFieldMap(ExamineStatusEnum.class, "value").get(saleOrderBean.getExamineStatus()));
            row.add(saleOrderBean.getPrintTime() != null ? DateUtil.format(saleOrderBean.getPrintTime(), "yyyy-MM-dd HH:mm:ss") : "");
            row.add(OrderTypeStatusEnum.valueOf(saleOrderBean.getOrderType()).getMsg());
            row.add(saleOrderBean.getId());
            row.add(saleOrderBean.getOrderNo());
            row.add(saleOrderBean.getOrderType().equals("TRADE") ? saleOrderBean.getEnginOrderNo() : saleOrderBean.getOrderType().equals("HOME") ? saleOrderBean.getEnginOrderNo() :
                    saleOrderBean.getOrderType().equals("REQUISITION_TRADE") ? saleOrderBean.getEnginOrderNo() : saleOrderBean.getOrderType().equals("REQUISITION_HOME") ? saleOrderBean.getEnginOrderNo() : saleOrderBean.getMainOrderId());
            row.add(saleOrderBean.getCorrespondName());
            //关联经销商
            row.add(saleOrderBean.getCustomerNumber());
            row.add(saleOrderBean.getCustomerName());
            row.add(saleOrderBean.getMaterialCode());
            row.add(saleOrderBean.getMaterialOldNumber());
            row.add(saleOrderBean.getMaterialName());
            row.add(saleOrderBean.getSpecification());
            row.add(saleOrderBean.getK3CategoryName());
            row.add(saleOrderBean.getUnit());
            row.add(saleOrderBean.getApprovalName());
            row.add(saleOrderBean.getApprovalTime() != null ? DateUtil.format(saleOrderBean.getApprovalTime(), "yyyy-MM-dd HH:mm:ss") : "");
            row.add(saleOrderBean.getRefundableQty());
            row.add(saleOrderBean.getK3OrgName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public IPage<StorageFeeBean> listStorageFee(List<String> categoryNum,String approvalStartTime, String approvalEndTime, String saleExamineStatus, String saleStartTime, String saleEndTime, String invoiceStartTime, String invoiceEndTime, String mainOrderId, List<String> id, List<String> orderNo, String materialNumber, String customerName,
                                                List<String> correspondId, String specification, String materialName, String customerNumber, String startTime, String endTime, Integer pageNum,
                                                Integer pageSize) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerNumber() : customerNumber;

        Integer count = saleOrderMapper.listStorageFeeCount(categoryNum,approvalStartTime, approvalEndTime,
                saleExamineStatus, saleStartTime, saleEndTime, invoiceStartTime, invoiceEndTime, mainOrderId, id, materialNumber, orderNo,
                customerName, correspondId, specification, materialName, customerId, startTime, endTime, adminUser.getServiceIds(),
                adminUser.getAdminUserId(), adminUser.getK3CategoryIds());

        IPage<StorageFeeBean> list = saleOrderMapper.listStorageFee(new Page<>(pageNum, pageSize,false),categoryNum, approvalStartTime, approvalEndTime,
                saleExamineStatus, saleStartTime, saleEndTime, invoiceStartTime, invoiceEndTime, mainOrderId, id, materialNumber, orderNo,
                customerName, correspondId, specification, materialName, customerId, startTime, endTime, adminUser.getServiceIds(),
                adminUser.getAdminUserId(), adminUser.getK3CategoryIds());

        list.setTotal(count);

        if (CollectionUtils.isEmpty(list.getRecords()))
            return new Page<>();


        List<String> collect1 = list.getRecords().stream().map(StorageFeeBean::getOrderId).collect(Collectors.toList());
        List<String> mainOrderIds = list.getRecords().stream().map(StorageFeeBean::getMainOrderId).collect(Collectors.toList());

        List<InvoiceApplicationOrder> listInvoice = invoiceApplicationOrderService.lambdaQuery()
                .in(InvoiceApplicationOrder::getOrderId,collect1)
                .select(InvoiceApplicationOrder::getOrderId, InvoiceApplicationOrder::getRefundableQty).list();

        List<RetailOrder> retailOrderItems = retailOrderService.lambdaQuery()
                .select(RetailOrder::getId,RetailOrder::getExamineTime)
                .in(RetailOrder::getId, mainOrderIds).list();

        List<EnginOrder> enginOrderList = enginOrderService.lambdaQuery()
                .select(EnginOrder::getEnginOrderNo,EnginOrder::getConfirmTime,EnginOrder::getRefUseUnit)
                .in(EnginOrder::getEnginOrderNo, mainOrderIds).list();

        for (StorageFeeBean record : list.getRecords()) {
            List<InvoiceApplicationOrder> collect = listInvoice.stream()
                    .filter(item -> item.getOrderId().equals(record.getOrderId()))
                    .collect(Collectors.toList());

            List<RetailOrder> retailOrderList = retailOrderItems.stream()
                    .filter(item -> item.getId().equals(record.getMainOrderId()))
                    .collect(Collectors.toList());

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

            if (!CollectionUtils.isEmpty(retailOrderList)){
                RetailOrder retailOrder = retailOrderList.get(0);
                record.setExamineTime(DateUtil.format(retailOrder.getExamineTime(),"yyyy-MM-dd HH:mm:ss"));
            }else {
                EnginOrder enginOrder = enginOrders.get(0);
                record.setExamineTime(DateUtil.format(enginOrder.getConfirmTime(),"yyyy-MM-dd HH:mm:ss"));
                record.setRefUseUnit(enginOrder.getRefUseUnit());
            }



            record.setSendQty(record.getQty() - collect.stream().mapToInt(InvoiceApplicationOrder::getRefundableQty).sum());

            /*
             * 合计=现金+返利+格力折扣
             *发货金额=合计/数量*发货数量
             *起算日期：=预留日期与发货审核日期取小值（取早），然后+5天
             *结算日期：=出库审核时间
             *计算天数：=结算日期-起算日期+1天
             *仓租：=如果计算天数小于等于15天，发货金额*0.0003*计算天数，否则发货金额*0.0004*计算天数
             * */

            record.setShipmentAmount(record.getTotalAmount());
            if (record.getReservedCreateTime() != null && record.getApprovalTime() != null)
                record.setStartCalculationTime(record.getReservedCreateTime().before(record.getApprovalTime()) ? DateUtil.offset(record.getReservedCreateTime(), DateField.DAY_OF_MONTH, 5) : DateUtil.offset(record.getApprovalTime(), DateField.DAY_OF_MONTH, 5));
            else if (record.getReservedCreateTime() != null && record.getApprovalTime() == null)
                record.setStartCalculationTime(DateUtil.offset(record.getReservedCreateTime(), DateField.DAY_OF_MONTH, 5));
            else
                record.setStartCalculationTime(DateUtil.offset(record.getApprovalTime(), DateField.DAY_OF_MONTH, 5));

            record.setEndCalculationTime(record.getSalesApprovalTime());
            if (record.getEndCalculationTime() == null || StringUtils.isEmpty(record.getSalesExamineStatus()) || !record.getSalesExamineStatus().equals(ExamineStatusEnum.OK.toString()))
                continue;
            if ( DateUtil.parse(DateUtil.format(record.getStartCalculationTime(), "yyyy-MM-dd"))
                    .compareTo(DateUtil.parse(DateUtil.format(record.getEndCalculationTime(), "yyyy-MM-dd"),"yyyy-MM-dd")) > 0 )
                continue;
            record.setCalculationDays(Convert.toInt(DateUtil.between( DateUtil.parse(DateUtil.format(record.getStartCalculationTime(), "yyyy-MM-dd"),"yyyy-MM-dd")
                    , DateUtil.parse(DateUtil.format(record.getEndCalculationTime(), "yyyy-MM-dd"),"yyyy-MM-dd"), DateUnit.DAY)) + 1);
            if (record.getCalculationDays() > 0) {
                record.setWarehouseRent((record.getCalculationDays() < 15 ?
                        record.getShipmentAmount().multiply(Constant.STORAGE_FEE_ONE) : record.getShipmentAmount().multiply(Constant.STORAGE_FEE_TWO))
                        .multiply(new BigDecimal(record.getCalculationDays())));
            }

        }
        return list;
    }

    public ExcelData listStorageFeeExport(List<StorageFeeBean> records) {
        String[] titles = new String[]{"订单类型", "订单号", "订单日期", "订单审核时间", "预留单日期", "预留单号", "发货单号","使用单位",
                "发货单日期", "发货单审核时间", "出库状态", "出库审核时间", "出库审核人", "仓库", "客户编码", "客户名称",
                "存货编码", "规格型号", "订单数量", "价税合计", "返利金额","格力折扣额", "合计", "发货数量", "钱包", "钱包对应业务", "金蝶部门", "发货金额", "起算日期", "结算日期",
                "计算天数", "仓租金额","存货类别"};
        List<List<Object>> rows = new ArrayList<>();
        for (StorageFeeBean storageFeeBean : records) {
            List<Object> row = new ArrayList<>();
            row.add(OrderTypeStatusEnum.valueOf(storageFeeBean.getOrderType()).getMsg());
            row.add(storageFeeBean.getMainOrderId());
            row.add(storageFeeBean.getTheTime());
            row.add(storageFeeBean.getExamineTime());
             row.add(DateUtil.format(storageFeeBean.getReservedCreateTime(),"yyyy-MM-dd HH:mm:ss"));
            row.add(storageFeeBean.getReservedId());
            row.add(storageFeeBean.getInvoiceId());
            row.add(storageFeeBean.getRefUseUnit());
            row.add(DateUtil.format(storageFeeBean.getOrderTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(DateUtil.format(storageFeeBean.getApprovalTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(!StringUtils.isEmpty(storageFeeBean.getSalesExamineStatus()) && storageFeeBean.getSalesExamineStatus().equals("OK") ? "已审核" : "未审核");
            row.add(!StringUtils.isEmpty(storageFeeBean.getSalesExamineStatus()) && storageFeeBean.getSalesExamineStatus().equals("OK") ? DateUtil.format(storageFeeBean.getSalesApprovalTime(), "yyyy-MM-dd HH:mm:ss") : "");
            row.add(!StringUtils.isEmpty(storageFeeBean.getSalesExamineStatus()) && storageFeeBean.getSalesExamineStatus().equals("OK") ? storageFeeBean.getSalesApprovalName() : "");
            row.add(storageFeeBean.getCorrespondName());
            row.add(storageFeeBean.getCustomerNumber());
            row.add(storageFeeBean.getCustomerName());
            row.add(storageFeeBean.getMaterialCode());
            row.add(storageFeeBean.getSpecification());
            row.add(storageFeeBean.getQty());
            row.add(storageFeeBean.getPayAmount());
            row.add(storageFeeBean.getPayRebateAmount());
            row.add(storageFeeBean.getTotalDiscAmount());
            row.add(storageFeeBean.getTotalAmount());
            row.add(storageFeeBean.getRefundableQty());
            row.add(storageFeeBean.getCustomerWalletName());
            row.add(storageFeeBean.getServiceName());
            row.add(storageFeeBean.getK3OrgNumber());
            row.add(storageFeeBean.getShipmentAmount());
            row.add(DateUtil.format(storageFeeBean.getStartCalculationTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(DateUtil.format(storageFeeBean.getEndCalculationTime(), "yyyy-MM-dd HH:mm:ss"));
            row.add(storageFeeBean.getCalculationDays());
            row.add(storageFeeBean.getWarehouseRent());
            row.add(storageFeeBean.getK3CategoryName());
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        return excelData;
    }

    public void syncSalesOrder() throws Exception {
        List<SalesOrderKingSync> list = salesOrderKingSyncService.lambdaQuery().in(SalesOrderKingSync::getStatus, 0).last("limit 10").list();
        for (SalesOrderKingSync salesOrderKingSync : list) {
            SalesOrder salesOrder = salesOrderService.getById(salesOrderKingSync.getSalesId());

            //销售出库单
            if (salesOrder.getType().equals(1)) {
                salesOrderSync(salesOrder);
            }
            //销售退库单
            if (salesOrder.getType().equals(2)) {
                salesOutOrderSync(salesOrder);
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    void salesOutOrderSync(SalesOrder salesOrder) {
        try {

            // 同步到金蝶
            SaleOrderBody detail = saleOrderMapper.detail(salesOrder.getId());
            List<String> ids = new ArrayList<>();
            for (SaleOrderData saleOrderDatum : detail.getSaleOrderData()) {
                ids.add(saleOrderDatum.getKingDeeOrderId());
            }
            ResultEntity resultEntity = salesOutStockLogic.pushRet("", ids);
            // 回填金蝶信息
            for (BillItem item : resultEntity.getItems()) {
                for (InvoiceApplicationOrder invoiceApplicationOrder : detail.getSaleOrderData()) {
                    if (invoiceApplicationOrder.getOrderId().equals(item.getSupplyColVal())) {
                        invoiceApplicationOrder.setKingSaleId(resultEntity.getId());
                        invoiceApplicationOrder.setKingDeeOrderSeq(item.getSeq());
                        invoiceApplicationOrder.setKingDeeOrderId(item.getEntryId());
                        invoiceApplicationOrder.updateById();
                    }
                }
            }
            List<InvoiceApplicationOrder> invoiceApplicationOrders = BeanUtil.copyToList(detail.getSaleOrderData(), InvoiceApplicationOrder.class);
            //金蝶审核成功
            toKOut3(resultEntity, detail, invoiceApplicationOrders);

            salesOrderKingSyncService.lambdaUpdate().eq(SalesOrderKingSync::getSalesId, salesOrder.getId())
                    .set(SalesOrderKingSync::getStatus, 1)
                    .set(SalesOrderKingSync::getRemark, "退单成功推送")
                    .update();
            salesOrderService.lambdaUpdate().eq(SalesOrder::getId, salesOrder.getId())
                    .set(SalesOrder::getSyncStatus, 1)
                    .update();
        } catch (Exception exception) {
            salesOrderKingSyncService.lambdaUpdate().eq(SalesOrderKingSync::getSalesId, salesOrder.getId())
                    .set(SalesOrderKingSync::getStatus, -1)
                    .set(SalesOrderKingSync::getRemark, "推送失败：" + exception.getMessage())
                    .update();
            salesOrderService.lambdaUpdate().eq(SalesOrder::getId, salesOrder.getId())
                    .set(SalesOrder::getSyncStatus, -1)
                    .update();
            throw new RemoteServiceException("推送失败");
        }
    }


    private void toKOut3(ResultEntity resultEntity, SaleOrderBody detail, List<InvoiceApplicationOrder> invoiceApplicationOrders) {
        SalesReturnBean salesOutStockBean = new SalesReturnBean();
        salesOutStockBean.setBillNo(detail.getId());
        salesOutStockBean.setId(resultEntity.getId());
        salesOutStockBean.setDate(DateUtil.formatDate(detail.getCreateTime()));
        salesOutStockBean.setHeadNote(detail.getRemark());

        //所有物料单位
        List<KingDeeMaterial> kingDeeMaterials = k3MaterialLogic.allUnit();

        List<SalesReturnItemBean> salesOutStockItemBeans = new ArrayList<>();
        for (BillItem item : resultEntity.getItems()) {
            for (InvoiceApplicationOrder invoiceApplicationOrder : invoiceApplicationOrders) {
                if (invoiceApplicationOrder.getOrderId().equals(item.getSupplyColVal()) || invoiceApplicationOrder.getSalesOrderItemId().equals(item.getSupplyColVal())) {
                    SalesReturnItemBean salesOutStockItem = new SalesReturnItemBean();


                    CustomerProductTypeRela byCustomerWalletId = customerProductTypeLogic.getByCustomerWalletId(invoiceApplicationOrder.getCustomerWalletId());
                    if (byCustomerWalletId != null && !StringUtils.isEmpty(byCustomerWalletId.getK3OrgNumber()))
                        salesOutStockItem.setKls(byCustomerWalletId.getK3OrgNumber());


                    salesOutStockItem.setEntryId(item.getEntryId());
                    salesOutStockItem.setUnit(k3MaterialLogic.queryUnitCode(kingDeeMaterials, invoiceApplicationOrder.getUnit()));

                    //仓库编码
                    StockCorrespondPosition one = stockCorrespondPositionService.lambdaQuery().eq(StockCorrespondPosition::getCorrespondId, detail.getCorrespondId()).one();
                    KingDeeStock kingDeeStock = kingDeeStockService.getById(one.getStockId());
                    salesOutStockItem.setStock(kingDeeStock.getNumber());

                    salesOutStockItem.setMustQty(new BigDecimal(Convert.toStr(-1 * invoiceApplicationOrder.getRefundableQty())));
                    salesOutStockItem.setRealQty(new BigDecimal(Convert.toStr(-1 * invoiceApplicationOrder.getRefundableQty())));
                    salesOutStockItem.setSalesTypeName(invoiceApplicationOrder.getSaleTypeName() + "|" + invoiceApplicationOrder.getSaleTypeCode());
                    salesOutStockItem.setSalesTypId(invoiceApplicationOrder.getSaleTypeId());
                    salesOutStockItem.setSupplyColVal(invoiceApplicationOrder.getId());
                    salesOutStockItemBeans.add(salesOutStockItem);
                    invoiceApplicationOrder.setKingBillNo(salesOutStockBean.getBillNo());
                    invoiceApplicationOrder.updateById();
                }
            }
        }

        salesOutStockBean.setEntry(salesOutStockItemBeans);
        ResultEntity resultEntitySales = salesReturnLogic.syncPushBillData(salesOutStockBean);
    }

    @Transactional(rollbackFor = Exception.class)
    void salesOrderSync(SalesOrder salesOrder) {
        try {

            if (salesOrder.getSyncType().equals(1)) {

                SaleOrderBody detail = saleOrderMapper.detail(salesOrder.getId());

                List<String> ids = new ArrayList<>();
                Boolean requistion = false;
                for (InvoiceApplicationOrder order : detail.getSaleOrderData()) {
                    if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY")
                            || order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME")) {
                        requistion = true;
                    }
                    if (order.getRefundableQty() > 0)
                        ids.add(order.getKingDeeEntryId());
                }

                //下推到金蝶
                if (CollectionUtils.isEmpty(ids))
                    return;
                ResultEntity resultEntity;
                long start = System.currentTimeMillis();

                if (requistion) {
                    resultEntity = salesOrderLogic.pushTransferToOutStock("", ids);
                } else {
                    resultEntity = salesOrderLogic.pushOutStock("", ids);
                }
                long endSave = System.currentTimeMillis();
                log.info("金蝶下推" + "时间耗时" + (endSave - start) + "ms");
                // 回填金蝶信息
                for (BillItem item : resultEntity.getItems()) {
                    for (InvoiceApplicationOrder invoiceApplicationOrder : detail.getSaleOrderData()) {
                        if (invoiceApplicationOrder.getOrderId().equals(item.getSupplyColVal())) {
                            InvoiceApplicationOrder invoiceApplicationOrder1 = new InvoiceApplicationOrder();
                            invoiceApplicationOrder1.setId(invoiceApplicationOrder.getId());
                            invoiceApplicationOrder1.setKingSaleId(resultEntity.getId());
                            invoiceApplicationOrder1.setKingDeeOrderSeq(item.getSeq());
                            invoiceApplicationOrder1.setKingDeeOrderId(item.getEntryId());
                            invoiceApplicationOrder1.updateById();
                            SalesOrderItem salesOrderItem = new SalesOrderItem();
                            salesOrderItem.setId(invoiceApplicationOrder.getId());
                            salesOrderItem.setKingSaleId(resultEntity.getId());
                            salesOrderItem.setKingDeeOrderSeq(item.getSeq());
                            salesOrderItem.setKingDeeOrderId(item.getEntryId());
                            salesOrderItem.setKingBillNo(detail.getId());
                            salesOrderItem.updateById();
                        }
                    }
                }
                List<InvoiceApplicationOrder> invoiceApplicationOrders = BeanUtil.copyToList(detail.getSaleOrderData(), InvoiceApplicationOrder.class);
                //金蝶审核成功
                long startres = System.currentTimeMillis();

                toK3(resultEntity, detail, invoiceApplicationOrders);

                long endSaveres = System.currentTimeMillis();
                log.info("金蝶审核" + "时间耗时" + (endSaveres - startres) + "ms");
                salesOrderKingSyncService.lambdaUpdate().eq(SalesOrderKingSync::getSalesId, salesOrder.getId())
                        .set(SalesOrderKingSync::getStatus, 1)
                        .set(SalesOrderKingSync::getRemark, "旧单成功推送")
                        .update();
                salesOrderService.lambdaUpdate().eq(SalesOrder::getId, salesOrder.getId())
                        .set(SalesOrder::getSyncStatus, 1)
                        .update();
            }
            if (salesOrder.getSyncType().equals(2)) {
                //todo 同步销售单到金蝶

                SaleOrderBody detailOrder = saleOrderMapper.detail(salesOrder.getId());
                ResultEntity resultEntityOrder = this.toK3(salesOrder, detailOrder.getSaleOrderData());
                if (resultEntityOrder == null) {
                    throw new RemoteServiceException("同步金蝶单据失败");
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(resultEntityOrder.getId())) {
                    Map<String, BillItem> map = resultEntityOrder.getItems().stream()
                            .collect(Collectors.toMap(billItem -> billItem.getSupplyColVal() + billItem.getMaterialId(), Function.identity()));
                    for (SaleOrderData item : detailOrder.getSaleOrderData()) {
                        if (item.getRefundableQty() > 0) {
                            BillItem billItem = map.get(item.getId() + item.getMaterialId());
                            SalesOrderItem salesOrderItem = new SalesOrderItem();
                            salesOrderItem.setId(item.getId());
                            salesOrderItem.setKingDeeSeq(billItem.getSeq());
                            salesOrderItem.setKingDeeEntryId(billItem.getEntryId());
                            salesOrderItem.updateById();
                        }
                    }
                }

                salesOrderKingSyncService.lambdaUpdate().eq(SalesOrderKingSync::getSalesId, salesOrder.getId())
                        .set(SalesOrderKingSync::getRemark, "新单成功推送")
                        .update();
                salesOrderService.lambdaUpdate().eq(SalesOrder::getId, salesOrder.getId())
                        .set(SalesOrder::getSyncStatus, 1)
                        .update();


                //推销售出库单

                SaleOrderBody detail = saleOrderMapper.detail(salesOrder.getId());

                List<String> ids = new ArrayList<>();
                Boolean requistion = false;
                for (InvoiceApplicationOrder order : detail.getSaleOrderData()) {
                    if (order.getOrderType().equals("REQUISITION_RETAIL") || order.getOrderType().equals("REQUISITION_RETAIL_POLICY")
                            || order.getOrderType().equals("REQUISITION_TRADE") || order.getOrderType().equals("REQUISITION_HOME")) {
                        requistion = true;
                    }
                    if (order.getRefundableQty() > 0)
                        ids.add(order.getKingDeeEntryId());
                }

                //下推到金蝶
                if (CollectionUtils.isEmpty(ids))
                    return;
                ResultEntity resultEntity;
                long start = System.currentTimeMillis();

                if (requistion) {
                    resultEntity = salesOrderLogic.pushTransferToOutStock("", ids);
                } else {
                    resultEntity = salesOrderLogic.pushOutStock("", ids);
                }
                long endSave = System.currentTimeMillis();
                log.info("金蝶下推" + "时间耗时" + (endSave - start) + "ms");
                // 回填金蝶信息
                for (BillItem item : resultEntity.getItems()) {
                    for (InvoiceApplicationOrder invoiceApplicationOrder : detail.getSaleOrderData()) {
                        if (invoiceApplicationOrder.getId().equals(item.getSupplyColVal())) {
                            InvoiceApplicationOrder invoiceApplicationOrder1 = new InvoiceApplicationOrder();
                            invoiceApplicationOrder1.setId(invoiceApplicationOrder.getId());
                            invoiceApplicationOrder1.setKingSaleId(resultEntity.getId());
                            invoiceApplicationOrder1.setKingDeeOrderSeq(item.getSeq());
                            invoiceApplicationOrder1.setKingDeeOrderId(item.getEntryId());
                            invoiceApplicationOrder1.updateById();
                            SalesOrderItem salesOrderItem = new SalesOrderItem();
                            salesOrderItem.setId(invoiceApplicationOrder.getId());
                            salesOrderItem.setKingSaleId(resultEntity.getId());
                            salesOrderItem.setKingDeeOrderSeq(item.getSeq());
                            salesOrderItem.setKingDeeOrderId(item.getEntryId());
                            salesOrderItem.setKingBillNo(detail.getId());
                            salesOrderItem.updateById();
                        }
                    }
                }
                List<InvoiceApplicationOrder> invoiceApplicationOrders = BeanUtil.copyToList(detail.getSaleOrderData(), InvoiceApplicationOrder.class);
                //金蝶审核成功
                long startres = System.currentTimeMillis();

                toK3New(resultEntity, detail, invoiceApplicationOrders);

                long endSaveres = System.currentTimeMillis();
                log.info("金蝶审核" + "时间耗时" + (endSaveres - startres) + "ms");
                salesOrderKingSyncService.lambdaUpdate().eq(SalesOrderKingSync::getSalesId, salesOrder.getId())
                        .set(SalesOrderKingSync::getStatus, 1)
                        .set(SalesOrderKingSync::getRemark, "新单成功推送")
                        .update();
                salesOrderService.lambdaUpdate().eq(SalesOrder::getId, salesOrder.getId())
                        .set(SalesOrder::getSyncStatus, 1)
                        .update();

            }

        } catch (Exception exception) {
            salesOrderKingSyncService.lambdaUpdate().eq(SalesOrderKingSync::getSalesId, salesOrder.getId())
                    .set(SalesOrderKingSync::getStatus, -1)
                    .set(SalesOrderKingSync::getRemark, "推送失败：" + exception.getMessage())
                    .update();
            salesOrderService.lambdaUpdate().eq(SalesOrder::getId, salesOrder.getId())
                    .set(SalesOrder::getSyncStatus, -1)
                    .update();
            throw new RemoteServiceException("推送失败");
        }
    }

    private void toK3New(ResultEntity resultEntity, SaleOrderBody detail, List<InvoiceApplicationOrder> invoiceApplicationOrders) {
        SalesOutStockBean salesOutStockBean = new SalesOutStockBean();
        salesOutStockBean.setBillNo(detail.getId());
        salesOutStockBean.setId(resultEntity.getId());
        salesOutStockBean.setDate(DateUtil.formatDate(new Date()));
        salesOutStockBean.setRemarks(detail.getRemark());

        //所有物料单位
        List<KingDeeMaterial> kingDeeMaterials = k3MaterialLogic.allUnit();

        List<SalesOutStockItemBean> salesOutStockItemBeans = new ArrayList<>();
        for (BillItem item : resultEntity.getItems()) {
            for (InvoiceApplicationOrder invoiceApplicationOrder : invoiceApplicationOrders) {
                if (invoiceApplicationOrder.getId().equals(item.getSupplyColVal())) {
                    if (invoiceApplicationOrder.getRefundableQty().equals(0))
                        continue;

                    CustomerProductTypeRela byCustomerWalletId = customerProductTypeLogic.getByCustomerWalletId(invoiceApplicationOrder.getCustomerWalletId());

                    SalesOutStockItemBean salesOutStockItem = new SalesOutStockItemBean();
                    salesOutStockItem.setEntryId(item.getEntryId());
                    salesOutStockItem.setUnit(k3MaterialLogic.queryUnitCode(kingDeeMaterials, invoiceApplicationOrder.getUnit()));
                    //仓库编码
                    StockCorrespondPosition one = stockCorrespondPositionService.lambdaQuery().eq(StockCorrespondPosition::getCorrespondId, detail.getCorrespondId()).one();
                    KingDeeStock kingDeeStock = kingDeeStockService.getById(one.getStockId());
                    salesOutStockItem.setStock(kingDeeStock.getNumber());

                    salesOutStockItem.setMustQty(new BigDecimal(Convert.toStr(invoiceApplicationOrder.getRefundableQty())));
                    salesOutStockItem.setRealQty(new BigDecimal(Convert.toStr(invoiceApplicationOrder.getRefundableQty())));
                    salesOutStockItem.setSupplyColVal(invoiceApplicationOrder.getId());
                    salesOutStockItem.setSalesTypeName(invoiceApplicationOrder.getSaleTypeName() + "|" + invoiceApplicationOrder.getSaleTypeCode());
                    salesOutStockItem.setSalesTypId(invoiceApplicationOrder.getSaleTypeId());

                    if (byCustomerWalletId != null && !StringUtils.isEmpty(byCustomerWalletId.getK3OrgNumber()))
                        salesOutStockItem.setKls(byCustomerWalletId.getK3OrgNumber());
                    salesOutStockItemBeans.add(salesOutStockItem);

                }
            }
        }

        salesOutStockBean.setEntry(salesOutStockItemBeans);
        ResultEntity resultEntitySales = salesOutStockLogic.syncPushBillData(salesOutStockBean);
    }

    /**
     * 同步到金蝶
     */
    public ResultEntity toK3(SalesOrder salesOrder, List<SaleOrderData> items) {

        K3CustomerBean customer = k3CustomerLogic.detail(salesOrder.getCustomerId());
        SalesOrderBean salesOrderBean = new SalesOrderBean();
        salesOrderBean.setBillNo(salesOrder.getId());
        salesOrderBean.setCustomerNumber(customer.getNumber());
        salesOrderBean.setOrgNumber(customer.getUseOrgNumber());
        salesOrderBean.setDate(DateUtil.formatDate(salesOrder.getCreateTime()));

        List<SalesOrderItemBean> k3Items = new ArrayList<>();
        for (SaleOrderData item : items) {
            if (item.getRefundableQty() > 0) {
                String customerWalletId = item.getCustomerWalletId();
                CustomerProductTypeRela customerProductTypeRela = customerProductTypeLogic.getByCustomerWalletId(customerWalletId);
                KingDeeMaterial byId = kingDeeMaterialService.getById(item.getMaterialId());
                SalesOrderItemBean k3Item = new SalesOrderItemBean();
                k3Item.setSupplyColVal(item.getId());
                k3Item.setUnit(byId.getBaseUnitCode());
                k3Item.setMaterialNumber(byId.getNumber());
                k3Item.setQty(BigDecimal.valueOf(item.getRefundableQty()));
                k3Item.setTaxPrice(item.getPrice());
                k3Item.setDiscount(item.getTotalDiscAmount().add(item.getPayRebateAmount()));
                k3Item.setEntryNote(item.getRemark());
                k3Item.setWalletNumber(item.getCustomerWalletNumber());
                k3Item.setfOrderEntryPlan(salesOrderBean.getDate());

                if (customerProductTypeRela != null && org.apache.commons.lang3.StringUtils.isNotEmpty(customerProductTypeRela.getK3OrgNumber())) {
                    k3Item.setK3OrgNumber(customerProductTypeRela.getK3OrgNumber());
                }
                k3Items.add(k3Item);
            }
        }
        if (CollectionUtils.isEmpty(k3Items))
            throw new RemoteServiceException("订单数量为空");

        salesOrderBean.setOrderItems(k3Items);

        return salesOrderLogic.syncBillData(salesOrderBean);
    }


    @Transactional(rollbackFor = Exception.class)
    public void stockInSyncInvoiceOrder() throws Exception {


        List<InvoiceApplicationSyncGejiang> list = invoiceApplicationSyncGejiangService.lambdaQuery().in(InvoiceApplicationSyncGejiang::getStatus, 0, -1).list();

        if (CollectionUtils.isEmpty(list))
            return;


        for (InvoiceApplicationSyncGejiang invoiceApplicationSyncGejiang : list) {
            try {
                if (invoiceApplicationSyncGejiang.getType().equals(1)) {
                    List<InvoiceApplicationOrder> invoiceApplicationOrders = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplicationSyncGejiang.getInvoiceId()).list();
                    InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceApplicationSyncGejiang.getInvoiceId());

                    PurchaseInStockBean purchaseInStockBean = new PurchaseInStockBean();
                    purchaseInStockBean.setBillNo(invoiceApplication.getId());

                    //是否是广州格匠
                    if (invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())) {

                        purchaseInStockBean.setSupplier(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_SUPPLIER.getCode());

                        //厂直调 龙山 给格匠龙山
                        if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK.getCode())
                                || invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LONGSHAN.getCode()) ||
                                invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_CHANGZHIDIAO.getCode())) {

                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());

                            //芦苞仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAO_STOCK.getCode())
                                || invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAOWANGPI_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());

                            //孜学仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_ZIXUE_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_ZIXUE_NUMBER.getCode());

                            //芦苞佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAOFOSHAN_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                            //三水佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHAN_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //三水珠海仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHANZHUHAI_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //三水珠海佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SHANSHUIZHUHAIFOSHAN_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //万豪
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_WANHAO_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_WANHAO_NUMBER.getCode());
                            //万豪样机
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_WANHAOYANGJI_STOCK.getCode())) {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_WANHAO_NUMBER.getCode());
                            //三水
                        } else {
                            purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                        }

                        //其他都是万豪仓
                    } else {
                        purchaseInStockBean.setSupplier(InvoiceCustomerEnum.GEJIANG_FOSHAN_SUPPLIER.getCode());

                        //芦苞佛山
                     if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAOFOSHAN_STOCK.getCode())) {
                        purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                        //三水佛山
                    } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHAN_STOCK.getCode())) {
                        purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                        //三水珠海佛山
                    } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SHANSHUIZHUHAIFOSHAN_STOCK.getCode())) {
                        purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                         //三水珠海仓
                     } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHANZHUHAI_STOCK.getCode())) {
                         purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                        //芦苞仓
                     } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAO_STOCK.getCode())) {
                         purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());

                     } else if (invoiceApplication.getCorrespondName().equals("三水仓")) {
                         purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                     } else if (invoiceApplication.getCorrespondName().equals("虚拟仓")) {
                         purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                     }else {

                        purchaseInStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                    }

                    }
                    purchaseInStockBean.setDate(DateUtil.formatDate(invoiceApplication.getCreateTime()));

                    List<PurchaseInStockItemBean> k3Items = new ArrayList<>();
                    String number = "";
                    for (InvoiceApplicationOrder item : invoiceApplicationOrders) {
                        if (item.getRefundableQty() > 0) {
                            PurchaseInStockItemBean k3Item = new PurchaseInStockItemBean();


                            // 调用物料接口
                            RequestApiBean request = k3Logic.getInstance(orgId, orgNum, KingDeeCons.MATERIAL_INFO, "2010-10-08 15:13:04", "2062-10-08 15:13:04");
                            String filterStr = "FDocumentStatus = 'C' AND F_abcd_Text = '" + item.getMaterialOldNumber() + "' AND FUseOrgId.FNUMBER = %s ";
                            request.setFieldKeys("FMATERIALID,FNumber,FName,FUseOrgId.FName,FBaseUnitId.FNumber,FBaseUnitId.FName");

                            request.setFilterString(String.format(filterStr, orgNum));
                            request.setOrderString("FMATERIALID ASC");

                            String[] fields = new String[]{"id", "number", "name", "useOrgName", "baseUnitCode", "baseUnitId"};
                            List<KingDeeMaterial> objects = k3GeJiangLogic.allSync(request, fields, KingDeeMaterial.class);
                            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(objects)) {
                                if (StringUtils.isEmpty(number)) {
                                    number = "查不到物料,套机码：" + item.getMaterialOldNumber();
                                } else {
                                    number = number + "," + item.getMaterialOldNumber();
                                }

                                continue;
                            }

                            k3Item.setMaterial(objects.get(0).getNumber());
                            k3Item.setUnit(objects.get(0).getBaseUnitCode());
                            k3Item.setPriceUnit(objects.get(0).getBaseUnitCode());
                            k3Item.setRemainInStockUnit(objects.get(0).getBaseUnitCode());
                            k3Item.setStock(purchaseInStockBean.getStock());
                            k3Item.setRealQty(new BigDecimal(item.getRefundableQty()));
                            k3Item.setPrice(item.getSinglePayPrice().divide(new BigDecimal("1.13"), 6, BigDecimal.ROUND_HALF_UP).setScale(6, BigDecimal.ROUND_UP));
                            k3Item.setFTaxPrice(item.getSinglePayPrice());
                            k3Item.setFAllAmount(item.getPayAmount());
                            k3Item.setAmount(item.getPayAmount().divide(new BigDecimal("1.13"), 6, BigDecimal.ROUND_HALF_UP).setScale(6, BigDecimal.ROUND_UP));
                            k3Item.setFTaxRate(new BigDecimal("13"));
                            k3Item.setDiscount(item.getPayRebateAmount());
                            k3Item.setFGiveAway(false);
                            if (item.getPayAmount().compareTo(BigDecimal.ZERO) == 0 && item.getPayRebateAmount().compareTo(BigDecimal.ZERO) == 0)
                                k3Item.setFGiveAway(true);

                            k3Items.add(k3Item);
                        }
                    }
                    if (!StringUtils.isEmpty(number))
                        throw new RemoteServiceException(number);

                    if (CollectionUtils.isEmpty(k3Items))
                        throw new RemoteServiceException("订单数量为空");

                    purchaseInStockBean.setOrderItems(k3Items);
                    ResultEntity resultEntity = geJiangInStockLogic.syncBillData(purchaseInStockBean);

                    invoiceApplicationSyncGejiang.setStatus(1);
                    invoiceApplicationSyncGejiang.setRemark(null);
                    invoiceApplicationSyncGejiang.updateById();

                    invoiceApplication.setGejiangSync(1);
                    invoiceApplication.setGejiangSyncRemark(null);
                    invoiceApplication.updateById();
                } else{

                    List<InvoiceApplicationOrder> invoiceApplicationOrders = invoiceApplicationOrderService.lambdaQuery().eq(InvoiceApplicationOrder::getInvoiceId, invoiceApplicationSyncGejiang.getInvoiceId()).list();
                    InvoiceApplication invoiceApplication = invoiceApplicationService.getById(invoiceApplicationSyncGejiang.getInvoiceId());
                    SalesOrder salesOrder = salesOrderService.getById(invoiceApplication.getSalesId());

                    String correspondName = salesOrder.getCorrespondName();

                    SalesOrder salesOrderOne = salesOrderService.getById(salesOrder.getSalesOrderNo());

                    if (salesOrderOne != null){
                         correspondName = salesOrderOne.getCorrespondName();
                    }

                    PurchaseOutStockBean purchaseOutStockBean = new PurchaseOutStockBean();
                    purchaseOutStockBean.setBillNo(invoiceApplication.getId());

                    //是否是广州格匠
                    if (invoiceApplication.getCustomerNumber().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU.getCode())) {

                        purchaseOutStockBean.setSupplier(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_SUPPLIER.getCode());

                        //厂直调 龙山 给格匠龙山
                        if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK.getCode())
                                || invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LONGSHAN.getCode()) ||
                                invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_CHANGZHIDIAO.getCode())) {

                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());

                            //芦苞仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAO_STOCK.getCode())
                                || invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAOWANGPI_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());

                            //孜学仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_ZIXUE_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_ZIXUE_NUMBER.getCode());

                            //芦苞佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAOFOSHAN_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                            //三水佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHAN_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //三水珠海仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHANZHUHAI_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //三水珠海佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SHANSHUIZHUHAIFOSHAN_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //万豪
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_WANHAO_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_WANHAO_NUMBER.getCode());
                            //万豪样机
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_WANHAOYANGJI_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_WANHAO_NUMBER.getCode());
                            //三水
                        } else {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                        }

                        //其他都是万豪仓
                    } else {
                        purchaseOutStockBean.setSupplier(InvoiceCustomerEnum.GEJIANG_FOSHAN_SUPPLIER.getCode());

                        //芦苞佛山
                        if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAOFOSHAN_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                            //三水佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHAN_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //三水珠海佛山
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SHANSHUIZHUHAIFOSHAN_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //三水珠海仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_SANSHUIFOSHANZHUHAI_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                            //芦苞仓
                        } else if (invoiceApplication.getCorrespondName().equals(InvoiceCustomerEnum.GEJIANG_LUBAO_STOCK.getCode())) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());

                        } else if (invoiceApplication.getCorrespondName().equals("三水仓")) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_SANSHUI_NUMBER.getCode());
                        } else if (invoiceApplication.getCorrespondName().equals("虚拟仓")) {
                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                        }else {

                            purchaseOutStockBean.setStock(InvoiceCustomerEnum.GEJIANG_GUANGZHOU_STOCK_LUBAO_NUMBER.getCode());
                        }
                    }
                    purchaseOutStockBean.setDate(DateUtil.formatDate(invoiceApplication.getCreateTime()));

                    List<PurchaseOutStockItemBean> k3Items = new ArrayList<>();
                    String number = "";
                    for (InvoiceApplicationOrder item : invoiceApplicationOrders) {
                        if (item.getRefundableQty() < 0) {
                            PurchaseOutStockItemBean k3Item = new PurchaseOutStockItemBean();


                            // 调用物料接口
                            RequestApiBean request = k3Logic.getInstance(orgId, orgNum, KingDeeCons.MATERIAL_INFO, "2010-10-08 15:13:04", "2062-10-08 15:13:04");
                            String filterStr = "FDocumentStatus = 'C' AND F_abcd_Text = '" + item.getMaterialOldNumber() + "' AND FUseOrgId.FNUMBER = %s ";
                            request.setFieldKeys("FMATERIALID,FNumber,FName,FUseOrgId.FName,FBaseUnitId.FNumber,FBaseUnitId.FName");

                            request.setFilterString(String.format(filterStr, orgNum));
                            request.setOrderString("FMATERIALID ASC");

                            String[] fields = new String[]{"id", "number", "name", "useOrgName", "baseUnitCode", "baseUnitId"};
                            List<KingDeeMaterial> objects = k3GeJiangLogic.allSync(request, fields, KingDeeMaterial.class);
                            if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(objects)) {
                                if (StringUtils.isEmpty(number)) {
                                    number = "查不到物料,套机码：" + item.getMaterialOldNumber();
                                } else {
                                    number = number + "," + item.getMaterialOldNumber();
                                }

                                continue;
                            }

                            k3Item.setMaterial(objects.get(0).getNumber());
                            k3Item.setUnit(objects.get(0).getBaseUnitCode());
                            k3Item.setPriceUnit(objects.get(0).getBaseUnitCode());
                            k3Item.setRemainInStockUnit(objects.get(0).getBaseUnitCode());
                            k3Item.setStock(purchaseOutStockBean.getStock());
                            k3Item.setFRmrealqty(new BigDecimal(item.getRefundableQty()*-1));
                            k3Item.setPrice(item.getSinglePayPrice().divide(new BigDecimal("1.13"), 6, BigDecimal.ROUND_HALF_UP).setScale(6, BigDecimal.ROUND_UP));
                            k3Item.setFTaxPrice(item.getSinglePayPrice());
                            k3Item.setFAllAmount(item.getPayAmount());
                            k3Item.setAmount(item.getPayAmount().divide(new BigDecimal("1.13"), 6, BigDecimal.ROUND_HALF_UP).setScale(6, BigDecimal.ROUND_UP));
                            k3Item.setFEntryTaxRate(new BigDecimal("13"));
                            k3Item.setDiscount(item.getPayRebateAmount());
                            k3Item.setFGiveAway(false);
                            if (item.getPayAmount().compareTo(BigDecimal.ZERO) == 0 && item.getPayRebateAmount().compareTo(BigDecimal.ZERO) == 0)
                                k3Item.setFGiveAway(true);

                            k3Items.add(k3Item);
                        }
                    }
                    if (!StringUtils.isEmpty(number))
                        throw new RemoteServiceException(number);

                    if (CollectionUtils.isEmpty(k3Items))
                        throw new RemoteServiceException("订单数量为空");

                    purchaseOutStockBean.setOrderItems(k3Items);
                    ResultEntity resultEntity = geJiangInStockLogic.syncBillTuiLiaoData(purchaseOutStockBean);

                    invoiceApplicationSyncGejiang.setStatus(1);
                    invoiceApplicationSyncGejiang.setRemark(null);
                    invoiceApplicationSyncGejiang.updateById();

                    invoiceApplication.setGejiangSync(1);
                    invoiceApplication.setGejiangSyncRemark(null);
                    invoiceApplication.updateById();
                }
            } catch (Exception exception) {
                invoiceApplicationSyncGejiang.setStatus(-1);
                invoiceApplicationSyncGejiang.setRemark(exception.getMessage());
                invoiceApplicationSyncGejiang.updateById();

                InvoiceApplication byId = invoiceApplicationService.getById(invoiceApplicationSyncGejiang.getInvoiceId());
                if (byId != null) {
                    byId.setGejiangSync(-1);
                    if (!StringUtils.isEmpty(exception.getMessage())) {
                        byId.setGejiangSyncRemark(exception.getMessage().substring(0, exception.getMessage().length() > 1000 ? 1000 : exception.getMessage().length()));
                    }
                    byId.updateById();
                }
            }
        }


    }


    @Transactional(rollbackFor = Exception.class)
    public void stockInSyncOtherOrder1() throws Exception {
        //全量更新
        // 调用退料单接口
        List<KingDeeOtherStockOut> kingDeeOtherStockOuts = kingDeeOtherStockOutService.lambdaQuery().eq(KingDeeOtherStockOut::getFdDocumentStatus, "C")
                .between(KingDeeOtherStockOut::getApproveDate, DateUtil.offset(new Date(), DateField.MONTH, -2), new Date())
                .select(KingDeeOtherStockOut::getId).list();
        if (CollectionUtil.isEmpty(kingDeeOtherStockOuts))
            return;
        //获得所有通过的单
        String orderId = "";
        for (KingDeeOtherStockOut kingDeePurchaseStockOut : kingDeeOtherStockOuts) {
            if (org.apache.commons.lang3.StringUtils.isEmpty(orderId)) {
                orderId = kingDeePurchaseStockOut.getId();
                continue;
            }
            orderId = orderId + "," + kingDeePurchaseStockOut.getId();
        }
        RequestApiBean request = k3Logic.getInstance(orgId, orgNum, KingDeeCons.OTHER_OUT_STOCK, "2002-09-19 16:55:01", "2062-09-19 16:55:01");

        //查找被弃审的单
        String filterStr = "FDocumentStatus != 'C'" + " AND FID IN (" + orderId + ")";
        request.setFieldKeys("FID,FBillNo,FDate,FStockOrgId,FApproverId.FName,FApproveDate,FCancelDate," +
                "FNote,FDocumentStatus,FStockDirect");
        request.setFilterString(String.format(filterStr, orgNum));
        request.setOrderString("FID ASC");

        String[] fields = new String[]{"id", "billNo", "fDate", "stockOrgId", "approverId", "approveDate", "cancelDate",
                "note", "fdDocumentStatus,stockDirect"};
        request.setNotTime(true);
        List<KingDeeOtherStockOut> objects = k3Logic.allSync(request, fields, KingDeeOtherStockOut.class);
        /**
         *  全量查询表中不为已审核状态的单，退回数量，再删除数据，等下次审核
         * */
        if (CollectionUtil.isEmpty(objects))
            return;
        for (KingDeeOtherStockOut object : objects) {
            //被弃审的返回数量
            List<KingDeeOtherStockOutItem> list = kingDeeOtherStockOutItemService.lambdaQuery().eq(KingDeeOtherStockOutItem::getFId, object.getId()).list();
            for (KingDeeOtherStockOutItem kingDeeOtherStockOutItem : list) {
                //查出被反审的内容
                Stock stock = stockService.lambdaQuery().eq(Stock::getStockId, kingDeeOtherStockOutItem.getStockId())
                        .eq(Stock::getMaterialId, kingDeeOtherStockOutItem.getMaterialId()).last("limit 1").one();
                if (object.getStockDirect().equals(Constant.OTHER_STOCK_IN)) {
                    //库存减记录
                    stockAccLog("全量反审的其他出库单仓库加", stock, kingDeeOtherStockOutItem.getQty(), kingDeeOtherStockOutItem.getFId(), true, "其他出库单");
                    stock.setStockQty(stock.getStockQty().add(kingDeeOtherStockOutItem.getQty()));
                    stock.updateById();
                    kingDeeOtherStockOutItemService.removeById(kingDeeOtherStockOutItem.getId());
                }
                if (object.getStockDirect().equals(Constant.OTHER_STOCK_OUT)) {
                    //库存减记录
                    stockAccLog("全量反审的其他出库单退货仓库加", stock, kingDeeOtherStockOutItem.getQty(), kingDeeOtherStockOutItem.getFId(), false, "其他出库单");
                    stock.setStockQty(stock.getStockQty().subtract(kingDeeOtherStockOutItem.getQty()));
                    stock.updateById();
                    kingDeeOtherStockOutItemService.removeById(kingDeeOtherStockOutItem.getId());
                }
            }
            kingDeeOtherStockOutService.removeById(object.getId());
        }

    }


    @Transactional(rollbackFor = Exception.class)
    public void stockInSyncOtherOrder() throws Exception {
        //1采购退料单入库库存
        List<KingDeeOtherStockOutItem> kingDeePurchaseStockOuts = allOtherOutSync(orgId, orgNum, null, null);

        if (CollectionUtil.isNotEmpty(kingDeePurchaseStockOuts)) {
            for (KingDeeOtherStockOutItem kingDeePurchaseStockOutItem : kingDeePurchaseStockOuts) {
                KingDeeOtherStockOutItem byId = kingDeeOtherStockOutItemService.getById(kingDeePurchaseStockOutItem.getId());
                KingDeeOtherStockOut kingDeeOtherStockOut = kingDeeOtherStockOutService.getById(kingDeePurchaseStockOutItem.getFId());
                // 入库表表中能找到，相减加库存
                if (byId != null) {

                    Stock stock = stockService.lambdaQuery().eq(Stock::getStockId, byId.getStockId())
                            .eq(Stock::getMaterialId, byId.getMaterialId()).last("limit 1").one();

                    //仓库相同  相减加减库存
                    if (byId.getStockId().equals(kingDeePurchaseStockOutItem.getStockId())) {

                        //加库存数量
                        BigDecimal subtract = byId.getQty().subtract(kingDeePurchaseStockOutItem.getQty());

                        //仓库库存记录有记录
                        if (stock != null) {
                            if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_IN)) {
                                //库存加减记录
                                stockAccLog("反审的其他出库单相同仓库加减", stock, subtract.compareTo(BigDecimal.ZERO) < 0 ? (subtract.multiply(new BigDecimal("-1"))) : subtract, kingDeePurchaseStockOutItem.getFId(), subtract.compareTo(BigDecimal.ZERO) < 0 ? false : true, "其他出库单");
                                //理解     退料反审   前一个为2  反审再审 3（相当于比反审前多退一个）   库存反审前是5    5+（2-3）
                                stock.setStockQty(stock.getStockQty().add(subtract));
                                stock.updateById();
                            }
                            if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_OUT)) {
                                //库存加减记录
                                stockAccLog("反审的其他出库单退货相同仓库加减", stock, subtract.compareTo(BigDecimal.ZERO) < 0 ? (subtract.multiply(new BigDecimal("-1"))) : subtract, kingDeePurchaseStockOutItem.getFId(), subtract.compareTo(BigDecimal.ZERO) < 0 ? true : false, "其他出库单");
                                //理解     退料反审   前一个为2  反审再审 3（相当于比反审前多退一个）   库存反审前是5    5+（2-3）
                                stock.setStockQty(stock.getStockQty().subtract(subtract));
                                stock.updateById();
                            }
                        }
                        //仓库库存记录无记录  不会发生
                        if (stock == null) {

                        }
                    }

                    //仓库不同 先扣回之前仓库，再加现库存
                    if (!byId.getStockId().equals(kingDeePurchaseStockOutItem.getStockId())) {

                        //减除之前仓库 退料加回数量
                        if (stock != null) {
                            if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_IN)) {
                                //库存加减记录
                                stockAccLog("反审的其他出库单不同仓库加", stock, byId.getQty(), kingDeePurchaseStockOutItem.getFId(), true, "其他出库单");
                                //减少回之前的库存
                                stock.setStockQty(stock.getStockQty().add(byId.getQty()));
                                stock.updateById();
                            }
                            if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_OUT)) {
                                //库存加减记录
                                stockAccLog("反审的其他出库单退货不同仓库减少", stock, byId.getQty(), kingDeePurchaseStockOutItem.getFId(), false, "其他出库单");
                                //减少回之前的库存
                                stock.setStockQty(stock.getStockQty().subtract(byId.getQty()));
                                stock.updateById();
                            }

                        }

                        //新仓库加减
                        Stock stockNew = stockService.lambdaQuery().eq(Stock::getStockId, kingDeePurchaseStockOutItem.getStockId())
                                .eq(Stock::getMaterialId, kingDeePurchaseStockOutItem.getMaterialId()).last("limit 1").one();
                        //仓库有记录
                        if (stockNew != null) {
                            if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_IN)) {
                                //库存加减记录
                                stockAccLog("反审的其他出库单不同仓库减少", stockNew, kingDeePurchaseStockOutItem.getQty(), kingDeePurchaseStockOutItem.getFId(), false, "其他出库单");
                                //减少库存
                                stockNew.setStockQty(stockNew.getStockQty().subtract(kingDeePurchaseStockOutItem.getQty()));
                                stockNew.updateById();
                            }
                            if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_OUT)) {
                                //库存加减记录
                                stockAccLog("反审的其他出库单退货不同仓库加", stockNew, kingDeePurchaseStockOutItem.getQty(), kingDeePurchaseStockOutItem.getFId(), true, "其他出库单");
                                //减少库存
                                stockNew.setStockQty(stockNew.getStockQty().add(kingDeePurchaseStockOutItem.getQty()));
                                stockNew.updateById();
                            }

                        }
                        //仓库库存记录无记录 不存在这种情况
                        if (stockNew == null) {

                        }
                    }

                }


                // 入库表不能找到，查看库存表有无记录 ，无库存记录找库存，有库存记录相加
                if (byId == null) {
                    //新仓库加减
                    Stock stockNew = stockService.lambdaQuery().eq(Stock::getStockId, kingDeePurchaseStockOutItem.getStockId())
                            .eq(Stock::getMaterialId, kingDeePurchaseStockOutItem.getMaterialId()).last("limit 1").one();
                    //仓库有记录
                    if (stockNew != null) {
                        if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_IN)) {
                            //库存加减记录
                            stockAccLog("其他出库单仓库减", stockNew, kingDeePurchaseStockOutItem.getQty(), kingDeePurchaseStockOutItem.getFId(), false, "其他出库单");
                            //加库存
                            stockNew.setStockQty(stockNew.getStockQty().subtract(kingDeePurchaseStockOutItem.getQty()));
                            stockNew.updateById();
                        }
                        if (kingDeeOtherStockOut.getStockDirect().equals(Constant.OTHER_STOCK_OUT)) {
                            //库存加减记录
                            stockAccLog("其他出库单仓库加", stockNew, kingDeePurchaseStockOutItem.getQty(), kingDeePurchaseStockOutItem.getFId(), true, "其他出库单");
                            //加库存
                            stockNew.setStockQty(stockNew.getStockQty().add(kingDeePurchaseStockOutItem.getQty()));
                            stockNew.updateById();
                        }

                    }
                    //仓库库存记录无记录 不存在这种可能
                    if (stockNew == null) {

                    }
                }
            }

            kingDeeOtherStockOutItemService.saveOrUpdateBatch(kingDeePurchaseStockOuts);
        }

    }


    public List<KingDeeOtherStockOutItem> allOtherOutSync(String orgId, String orgNumber, String startTime, String endTime) throws Exception {
        // 调用入库单接口
        RequestApiBean request = k3Logic.getInstance(orgId, orgNumber, KingDeeCons.OTHER_OUT_STOCK, startTime, endTime);
        String filterStr = "FDocumentStatus = 'C' " + k3Logic.supplySql("FApproveDate", request.getStartTime(), request.getEndTime());
        request.setFieldKeys("FID,FBillNo,FDate,FStockOrgId,FApproverId.FName,FApproveDate,FCancelDate," +
                "FNote,FDocumentStatus,FStockDirect");
        request.setFilterString(String.format(filterStr, orgNum));
        request.setOrderString("FID ASC");

        String[] fields = new String[]{"id", "billNo", "fDate", "stockOrgId", "approverId", "approveDate", "cancelDate",
                "note", "fdDocumentStatus", "stockDirect"};
        request.setNotTime(true);
        List<KingDeeOtherStockOut> objects = k3Logic.allSync(request, fields, KingDeeOtherStockOut.class);
        if (!org.springframework.util.CollectionUtils.isEmpty(objects)) {
            kingDeeOtherStockOutService.saveOrUpdateBatch(objects);
        }

        return allSyncOtherOutOrder(orgId, orgNumber, startTime, endTime);
    }


    public List<KingDeeOtherStockOutItem> allSyncOtherOutOrder(String orgId, String orgNumber, String startTime, String endTime) throws Exception {
        // 调用入库单接口
        RequestApiBean request = k3Logic.getInstance(orgId, orgNumber, KingDeeCons.OTHER_OUT_STOCK, startTime, endTime);
        String filterStr = "FDocumentStatus = 'C' " + k3Logic.supplySql("FApproveDate", request.getStartTime(), request.getEndTime());
        request.setFieldKeys("FEntity_FEntryID,FID,FBillNo,FMaterialId,FMaterialId.FNumber,FMaterialId.FName," +
                "FStockId,FEntryNote,FQty");
        request.setFilterString(String.format(filterStr, orgNumber));
        request.setOrderString("FID ASC");

        String[] fields = new String[]{"id", "fId", "billNo", "materialId", "materialNumber", "materialName", "stockId", "entryNote", "qty"};
        List<KingDeeOtherStockOutItem> objects = k3Logic.allSync(request, fields, KingDeeOtherStockOutItem.class);
/*        if (CollectionUtil.isNotEmpty(objects)) {
            kingDeePurchaseStockInItemService.saveOrUpdateBatch(objects);
        }*/
        return objects;
    }

    @Transactional(rollbackFor = Exception.class)
    public void stockAccLog(String remark, Stock stock, BigDecimal number, String FID, Boolean type, String refType) {
        StockAcc stockAcc = new StockAcc();
        stockAcc.setStockId(stock.getStockId());
        stockAcc.setMaterialId(stock.getMaterialId());
        stockAcc.setChangeTime(new Date());
        int i = number.compareTo(BigDecimal.ZERO);
        stockAcc.setDirectFlag(type);
        stockAcc.setStockChangeQty(number);
        stockAcc.setStockCurQty(stock.getStockQty());
        stockAcc.setStockCloseQty(type == true ? stock.getStockQty().add(number) : stock.getStockQty().subtract(number));
        stockAcc.setRef(FID);
        stockAcc.setRefType(org.apache.commons.lang3.StringUtils.isNotEmpty(refType) ? refType : "采购入库单");
        stockAcc.setUpdateTime(new Date());
        stockAcc.setNotes(remark);
        stockAcc.insert();
    }

    public IPage<StorageFeeBeanVO> listStorageFeeV2(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);
        IPage<StorageFeeBeanVO> stockBeanToDayIPage = saleOrderMapper.listStorageFeeV2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize()), zfireParamBean,
                adminUser.getServiceIds(), adminUser.getAdminUserId(), adminUser.getK3CategoryIds());

        return stockBeanToDayIPage;

    }

    public IPage<SaleOrderVO> listV2(ZfireParamBean zfireParamBean) {

        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        List<String> collect = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).select(AdminUserStock::getCorrespondId).list()
                .stream().map(AdminUserStock::getCorrespondId).distinct().collect(Collectors.toList());



        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);


        Integer count = saleOrderMapper.listCountV2(zfireParamBean, customerId, adminUser.getServiceIds(), collect, adminUser.getK3CategoryIds());


        IPage<SaleOrderVO> stockBeanToDayIPage = saleOrderMapper.listV2(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize(),count,false), zfireParamBean
                , customerId, adminUser.getServiceIds(), collect, adminUser.getK3CategoryIds());

        return stockBeanToDayIPage;
    }

    public IPage<SaleOrderVOV> listV3(ZfireParamBean zfireParamBean) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        String customerId = adminUser.getIsCustomer() ? adminUser.getCustomerId() : "";

        List<String> collect = adminUserStockService.lambdaQuery().eq(AdminUserStock::getAdminUserId, adminUser.getAdminUserId()).select(AdminUserStock::getCorrespondId).list()
                .stream().map(AdminUserStock::getCorrespondId).distinct().collect(Collectors.toList());



        zfireParamBean = FieldUtils.supplyParam(zfireParamBean);


        Integer count = saleOrderMapper.listCountV2(zfireParamBean, customerId, adminUser.getServiceIds(), collect, adminUser.getK3CategoryIds());


        IPage<SaleOrderVOV> stockBeanToDayIPage = saleOrderMapper.listV3(new Page(zfireParamBean.getPageNum(), zfireParamBean.getPageSize(),count,false), zfireParamBean
                , customerId, adminUser.getServiceIds(), collect, adminUser.getK3CategoryIds());

        return stockBeanToDayIPage;
    }
}
