package com.hzya.frame.plugin.lets.plugin.transfer;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.base.PluginBaseEntity;
import com.hzya.frame.plugin.lets.constant.OverallConstant;
import com.hzya.frame.plugin.lets.constant.ProfilesActiveConstant;
import com.hzya.frame.plugin.lets.dao.IIaMonthledgerDao;
import com.hzya.frame.plugin.lets.entity.BdCorpEntity;
import com.hzya.frame.plugin.lets.entity.BdInvbasdocEntity;
import com.hzya.frame.plugin.lets.entity.BdInvmandocEntity;
import com.hzya.frame.plugin.lets.entity.IaMonthledgerEntity;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsStockinOrderRequestVO;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsStockoutOrderRequestVO;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsTransferOrderRequestVO;
import com.hzya.frame.plugin.lets.u8cdto.BillVO;
import com.hzya.frame.plugin.lets.u8cdto.GeneralBillVO_4IDto;
import com.hzya.frame.plugin.lets.u8cdto.ReusltStrDto;
import com.hzya.frame.plugin.lets.util.PushDataByU8cUtil;
import com.hzya.frame.plugin.lets.util.QueryU8CEntityUtil;
import com.hzya.frame.plugin.lets.util.SaveOrUpdateBusinessLogUtil;
import com.hzya.frame.plugin.lets.util.pushData.Attribute;
import com.hzya.frame.plugin.lets.util.pushData.PushU8CByApiCode;
import com.hzya.frame.plugin.lets.util.pushData.ZTResult;
import com.hzya.frame.stringutil.StringUtil;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.dao.IIntegrationTaskLivingDetailsDao;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.ttxofs.dto.InterfaceParamDto;
import com.hzya.frame.ttxofs.dto.ofsTransferOrderSearch.OFSTranseferOrderSearchResponse;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.DetailsDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDetailsDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.HeaderDto;
import com.hzya.frame.ttxofs.dto.ofssaleorderoutsearch.SaleOutReturnMessageDto;
import com.hzya.frame.ttxofs.dto.stock.StockinOrderSearchResponse;
import com.hzya.frame.ttxofs.dto.stock.StockoutOrderSearchResponse;
import com.hzya.frame.ttxofs.service.OfsUnifiedService;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）
 */
public class TransferOutPluginInitializer extends PluginBaseEntity {
    Logger logger = LoggerFactory.getLogger(TransferOutPluginInitializer.class);

    private static final ReentrantLock LOCK = new ReentrantLock(true);

    @Override
    public void initialize() {
        logger.info(getPluginLabel() + "執行初始化方法initialize()");
    }

    @Override
    public void destroy() {
        logger.info(getPluginLabel() + "執行銷毀方法destroy()");
    }

    @Override
    public String getPluginId() {
        return "transfer.TransferOutPluginInitializer";
    }

    @Override
    public String getPluginName() {
        return "丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）";
    }

    @Override
    public String getPluginLabel() {
        return "丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）";
    }

    @Override
    public String getPluginType() {
        return "1";
    }

    @Autowired
    private IIntegrationTaskLivingDetailsDao iIntegrationTaskLivingDetailsDao;
    @Autowired
    private PushDataByU8cUtil pushDataByU8cUtil;
    @Autowired
    private PushU8CByApiCode pushU8CByApiCode;
    @Autowired
    private SaveOrUpdateBusinessLogUtil saveOrUpdateBusinessLogUtil;

    @Autowired
    private OfsUnifiedService ofsUnifiedService;


    @Autowired
    private IIaMonthledgerDao iaMonthledgerDao;
    @Autowired
    private QueryU8CEntityUtil queryU8CEntityUtil;

    @Override
    public JsonResultEntity executeBusiness(JSONObject requestJson) throws Exception {
        try {
            logger.info("调用：" + getPluginName() + "-插件");
            String prod = "prod";
            String param = String.valueOf(requestJson.get("param"));
            if (requestJson != null && ProfilesActiveConstant.TYPE_DATE.equals(requestJson.get("type"))) {
                //按日期
                if (param != null && !"".equals(param)) {
                    String[] split = param.split("/");
                    if (!(split.length == 2)) {
                        Assert.state(false, "时间格式传递不正确");
                    }
                    Assert.notNull(split[0], "开始时间不能为空");
                    Assert.notNull(split[1], "结束时间不能为空");
                    start(split[0], split[1]);
                }
            } else if (requestJson != null && ProfilesActiveConstant.TYPE_VBILLCODE.equals(requestJson.get("type"))) {
                //按单号
                if (param != null && !"".equals(param)) {
                    start(param);
                }
            } else if (ProfilesActiveConstant.TYPE_DETAIL_ERROR.equals(requestJson.get("type"))) {
                String integrationTaskLivingDetails = (String) requestJson.get("integration_task_living_details_id");
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = saveOrUpdateBusinessLogUtil.queryIntegrationTaskLivingDetailsEntity(integrationTaskLivingDetails);
                start(integrationTaskLivingDetailsEntity.getRootAppPk());
            } else if (ProfilesActiveConstant.LETS_PROFILES_ACTIVE.equals(prod)) {
                //默认
                start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("executeBusiness方法抛出异常", e);
        }
        return null;
    }


    /**
     * 默认推送
     */
    public void start() {
        try {
            //获取当前时间
            Date currentDate = new Date();
            Date startTime = DateUtil.offset(currentDate, DateField.MINUTE, -10);
            Date endTime = DateUtil.offset(currentDate, DateField.MINUTE, -2);
            String startTimeStr = DateUtil.format(startTime, "yyyy-MM-dd HH:mm:ss");
            String endTimeStr = DateUtil.format(endTime, "yyyy-MM-dd HH:mm:ss");

            QueryOfsStockoutOrderRequestVO queryOfsStockoutOrderRequestVO = new QueryOfsStockoutOrderRequestVO();
            queryOfsStockoutOrderRequestVO.setClosedAt_start(startTimeStr);
            queryOfsStockoutOrderRequestVO.setClosedAt_end(endTimeStr);
            queryOfsStockoutOrderRequestVO.setStatus("900");//状态 500待同步 510已同步 700收货中 900入库完成 911作废 100订单池 200暂挂 400待合单 410待出库单出库
            List<StockoutOrderSearchResponse.StockoutOrder> transferOutOrder = queryOfsStockoutOrder(queryOfsStockoutOrderRequestVO);
            if (transferOutOrder.size() == 0) {
                return;
            }
            //过滤成功日志
            List<StockoutOrderSearchResponse.StockoutOrder> filterTransferOutOrders = filterData(transferOutOrder);
            if (filterTransferOutOrders.size() == 0) {
                return;
            }
            //推送U8C
            implement(filterTransferOutOrders);
        } catch (Exception e) {
            logger.error("丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）,start()方法报错：", e);
        }
    }

    /**
     * 按单号
     */
    public void start(String stockoutNo) {
        try {
            QueryOfsStockoutOrderRequestVO queryOfsStockoutOrderRequestVO = new QueryOfsStockoutOrderRequestVO();
            queryOfsStockoutOrderRequestVO.setCode(stockoutNo);
            queryOfsStockoutOrderRequestVO.setStatus("900");//状态 500待同步 510已同步 700收货中 900入库完成 911作废 100订单池 200暂挂 400待合单 410待出库单出库
            List<StockoutOrderSearchResponse.StockoutOrder> transferOutOrder = queryOfsStockoutOrder(queryOfsStockoutOrderRequestVO);
            if (transferOutOrder.size() == 0) {
                Assert.state(false, "丽知：OFS调拨出库订单[出库完成]--->U8C调拨订单，自动生成调拨出库单（保存签字），未查询到调拨出库单：{}", stockoutNo);
            }
            //过滤成功日志
//            List<StockoutOrderSearchResponse.StockoutOrder> filterTransferOutOrders = filterData(transferOutOrder);
//            if (filterTransferOutOrders.size() == 0) {
//                Assert.state(false, "丽知：OFS调拨出库订单[出库完成]--->U8C调拨订单，自动生成调拨出库单（保存签字），该调拨出库单：{}，已被推送成功，请勿重新推送", stockoutNo);
//            }
            //推送U8C
//            implement(filterTransferOutOrders);
            implement(transferOutOrder);

        } catch (Exception e) {
            logger.error("丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）,start(String goodsName)方法报错：", e);
        }
    }

    /**
     * 按时间区间
     */
    public void start(String startTime, String endTime) {
        try {
            Date business_start = DateUtil.parse(startTime);
            Date business_end = DateUtil.parse(endTime);
            String start = DateUtil.format(business_start, "yyyy-MM-dd") + " 00:00:00";
            String end = DateUtil.format(business_end, "yyyy-MM-dd") + " 23:59:59";

            QueryOfsStockoutOrderRequestVO queryOfsStockoutOrderRequestVO = new QueryOfsStockoutOrderRequestVO();
            queryOfsStockoutOrderRequestVO.setClosedAt_start(start);
            queryOfsStockoutOrderRequestVO.setClosedAt_end(end);
            queryOfsStockoutOrderRequestVO.setStatus("900");//状态 500待同步 510已同步 700收货中 900入库完成 911作废 100订单池 200暂挂 400待合单 410待出库单出库
            List<StockoutOrderSearchResponse.StockoutOrder> transferOutOrder = queryOfsStockoutOrder(queryOfsStockoutOrderRequestVO);

            if (transferOutOrder.size() == 0) {
                Assert.state(false, "丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）根据日期期间[开始时间]-[结束时间]：{}-{}，未查询到调拨出库单[出库完成]", startTime, endTime);
            }
            //过滤成功日志
            List<StockoutOrderSearchResponse.StockoutOrder> filterTransferOutOrders = filterData(transferOutOrder);
            if (filterTransferOutOrders.size() == 0) {
                Assert.state(false, "丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）根据日期期间[开始时间]-[结束时间]：{}-{}，该调期调拨出库单[出库完成]已被推送成功，请勿重新推送", startTime, endTime);
            }
            //推送U8C
//            implement(transferOutOrder);
            implement(filterTransferOutOrders);
        } catch (Exception e) {
            logger.error("丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）,start(String startTime, String endTime)方法报错：", e);
        }
    }

    /**
     * 过滤成功日志
     */
    public List<StockoutOrderSearchResponse.StockoutOrder> filterData(List<StockoutOrderSearchResponse.StockoutOrder> transferOutOrder) {
        List<StockoutOrderSearchResponse.StockoutOrder> filterTransferOutOrders = new ArrayList<>();
        for (StockoutOrderSearchResponse.StockoutOrder stockoutOrder : transferOutOrder) {
            StockoutOrderSearchResponse.StockoutOrder.StockoutH header = stockoutOrder.getHeader();
            String rootAppPk = header.getCode();
            boolean isExis = true;
            IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
            integrationTaskLivingDetailsEntity.setRootAppPk(rootAppPk);
            integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
            integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
            List<IntegrationTaskLivingDetailsEntity> integrationTaskLivingDetailsEntities = iIntegrationTaskLivingDetailsDao.query(integrationTaskLivingDetailsEntity);
            if (integrationTaskLivingDetailsEntities == null || integrationTaskLivingDetailsEntities.size() == 0) {
                isExis = false;
            }
            if (!isExis) {
                filterTransferOutOrders.add(stockoutOrder);
            }
        }
        return filterTransferOutOrders;
    }

    /**
     * ofs调拨出库单推送U8C调拨订单，自动生成调拨出库单（保存签字）
     *
     * @param filterTransferOutOrders
     */
    public void implement(List<StockoutOrderSearchResponse.StockoutOrder> filterTransferOutOrders) {
        for (StockoutOrderSearchResponse.StockoutOrder transferOutOrder : filterTransferOutOrders) {
            System.out.println(transferOutOrder);
            BillVO billVO = new BillVO();

            String mapStr = "";
            String format = "";
            String response = "";
            String ofsCode = "";
            try {
                //主表
                StockoutOrderSearchResponse.StockoutOrder.StockoutH stockoutH = transferOutOrder.getHeader();
                BillVO.Parentvo parentvo = new BillVO.Parentvo();
                ofsCode = stockoutH.getCode();

                ////////////////////////////////////////////////////////////////////////////////ofs调拨订单
                List<OFSTranseferOrderSearchResponse.OFSTranseferOrder> ofsTranseferOrders = queryOfsTransderOrder(stockoutH.getSourceOrderCode());
                if (ofsTranseferOrders == null || ofsTranseferOrders.size() == 0 || ofsTranseferOrders.size() > 1) {
                    Assert.state(false, "根据调拨出库单：{}，的来源单据号：{}，查询OFS调拨订单为空或不唯一。请检查。", ofsCode, stockoutH.getSourceOrderCode());
                }
                OFSTranseferOrderSearchResponse.OFSTranseferOrder ofsTranseferOrder = ofsTranseferOrders.get(0);
                System.out.println(ofsTranseferOrder);
                ////////////////////////////////////////////////////////////////////////////////ofs调拨订单

                //创建日期，调拨出库创建时间
                String created = stockoutH.getCreated();
                format = created;
                //dbilldate 单据日期
                parentvo.setDbilldate(format.substring(0,10));
                //dauditdate 审批日期
                parentvo.setDauditdate(format);
                //coperatorid 制单人
                parentvo.setCoperatorid("tbadmin");
                //cbiztypeid 业务流程编码
                parentvo.setCbiztypeid("to01");
                //coutcbid 调出组织编码 对应OFS->原库存地点公司
                parentvo.setCoutcbid(ofsTranseferOrder.getHeader().getCompanyCode());

                //coutcorpid 调出公司编码 对应OFS->原库存地点公司
                parentvo.setCoutcorpid(ofsTranseferOrder.getHeader().getCompanyCode());

                //coutwhid 调出仓库编码 对应OFS->原库存地点
                parentvo.setCoutwhid(ofsTranseferOrder.getHeader().getFacilityCode());

                //cincbid 调入组织编码 对应OFS->目标库存地点公司
                parentvo.setCincbid(ofsTranseferOrder.getHeader().getToCompanyCode());

                //cincorpid 调入公司编码 对应OFS->目标库存地点公司
                parentvo.setCincorpid(ofsTranseferOrder.getHeader().getToCompanyCode());

                //cinwhid 调入仓库编码 对应OFS->目标库存地点
                parentvo.setCinwhid(ofsTranseferOrder.getHeader().getToFacilityCode());

                //vnote 备注
                parentvo.setVnote(ofsTranseferOrder.getHeader().getNotes());

//              //pk_defdoc1 ofs调出店铺
                parentvo.setPk_defdoc1(ofsTranseferOrder.getHeader().getStoreCode());
//              //pk_defdoc4 ofs调入店铺
                parentvo.setPk_defdoc4(ofsTranseferOrder.getHeader().getToStoreCode());
                //vuserdef17 来源系统
                parentvo.setVdef17(ProfilesActiveConstant.sourceSystem1);

                //vuserdef19 OFS调拨订单号
                parentvo.setVdef19(ofsTranseferOrder.getHeader().getCode());
                //vuserdef20 OFS调拨订单 id
                parentvo.setVdef20(ofsTranseferOrder.getHeader().getId());

                //子表
                List<OFSTranseferOrderSearchResponse.OFSTranseferOrder.OFSTranseferB> ofsDetails = ofsTranseferOrder.getDetails();
                List<BillVO.Childrenvo> childrenvo = new ArrayList<>();
                for (OFSTranseferOrderSearchResponse.OFSTranseferOrder.OFSTranseferB ofsDetail : ofsDetails) {
                    System.out.println(ofsDetail);
                    BillVO.Childrenvo children = new BillVO.Childrenvo();
                    //表体
                    //cinvbasid 存货基本档案
                    children.setCinvbasid(ofsDetail.getSkuCode());
                    //nnum 数量
                    children.setNnum(BigDecimal.valueOf(Long.parseLong(ofsDetail.getShipQty())));
                    childrenvo.add(children);
                    //ofs行id
//                    children.setPk_defdoc20(ofsDetail.getId());
                    children.setVbdef20(ofsDetail.getId());

                    //nprice 单价(含税单价)，取上一次结账的单价  nmny金额 nnotaxmny无税金额 nnotaxprice	无税单价
                    IaMonthledgerEntity iaMonthledgerEntity = queryIaMonthledger(ofsDetail, ofsTranseferOrder.getHeader().getCompanyCode());
                    System.out.println(iaMonthledgerEntity);
                    if(iaMonthledgerEntity==null){
                        children.setNprice("0");
                    }else {
                        children.setNprice(iaMonthledgerEntity.getNabprice());
                    }
                    //ntaxrate 税率
                    children.setNtaxrate("13");
                }
                billVO.setParentvo(parentvo);
                billVO.setChildrenvo(childrenvo);
                String jsonStr = JSONUtil.toJsonStr(billVO);
                mapStr = "{\"billvo\":" + jsonStr + "}";
                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("approveqzCode"), mapStr);
                System.out.println(ztResult);
                //两层判断,一层中台转发,一层u8c返回
                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    response = JSONUtil.toJsonStr(ztResult.getAttribute());
                    Assert.state(false, "丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）.中台转发失败,失败原因:{}", ztResult.getAttribute());
                }
                Attribute attribute = ztResult.getAttribute();
                System.out.println(attribute);
                boolean isSuccess = false;
                String vbillcode = "";
                String cbillid = "";
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
                    String data = attribute.getData();
                    BillVO resBillVO = resultDataHandle(data);
                    System.out.println(resBillVO);
                    vbillcode = resBillVO.getParentvo().getVcode();
                    cbillid = resBillVO.getParentvo().getCbillid();
                }
                if (!isSuccess) {
                    Assert.state(false, "推送U8C--> 丽知：OFS调整出库--->U8C其它出库 失败 接口返回结果：{} 接口入参:{}", response, mapStr);
                }

                //成功
                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_Y);
                integrationTaskLivingDetailsEntity.setRootAppNewData(mapStr);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(response);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(format);
                integrationTaskLivingDetailsEntity.setRootAppPk(ofsCode);
                integrationTaskLivingDetailsEntity.setRootAppBill(ofsCode);
                integrationTaskLivingDetailsEntity.setNewSystemNumber(vbillcode);//u8c调拨订单号
                integrationTaskLivingDetailsEntity.setNewSystemPrimary(cbillid);//u8c调拨订单号
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("推送U8C，丽知：OFS调拨出库订单--->U8C调拨订单，自动生成调拨出库单（保存签字）失败，失败原因：" + e);

                //失败
                ReusltStrDto reusltStrDto = JSON.parseObject(response, ReusltStrDto.class);
                String ErrMessage = null;
                if (reusltStrDto != null) {
                    ErrMessage = "推送U8C，丽知：OFS调整出库--->U8C其它出库失败，失败原因：" + reusltStrDto.getErrormsg();
                } else {
                    ErrMessage = e.getMessage();
                }

                IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
                integrationTaskLivingDetailsEntity.setNewState(ProfilesActiveConstant.LOG_STATUS_N);
                integrationTaskLivingDetailsEntity.setRootAppNewData(mapStr);
                integrationTaskLivingDetailsEntity.setNewTransmitInfo(ErrMessage);
                integrationTaskLivingDetailsEntity.setNewPushDate(new Date());
                integrationTaskLivingDetailsEntity.setBusinessDate(format);
                integrationTaskLivingDetailsEntity.setRootAppPk(ofsCode);
                integrationTaskLivingDetailsEntity.setRootAppBill(ofsCode);//u8c其他出库单号
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            }
        }

    }


    /**
     * ofs调拨出库单查询
     *
     * @param queryOfsStockoutOrderRequestVO
     * @return
     * @throws Exception
     */
    public List<StockoutOrderSearchResponse.StockoutOrder> queryOfsStockoutOrder(QueryOfsStockoutOrderRequestVO queryOfsStockoutOrderRequestVO) throws Exception {
        Long pageNo = 1L;

        List<StockoutOrderSearchResponse.StockoutOrder> all = new ArrayList<>();

        InterfaceParamDto interfaceParamDto = new InterfaceParamDto();
        interfaceParamDto.setApi("ofs.shipment.search");
        queryOfsStockoutOrderRequestVO.setInternalInstructionType("TRANSFER");//入库单类型 SALES销售 EXCHANGE换货 REISSUE补发RETURN销退 PURCHASE采购 PURCHASE_RETURN采退 TRANSFER调拨 WORK_ORDER加工 OTHER其他 ADJUST调整 EXCHANGE换货
        queryOfsStockoutOrderRequestVO.setClientCode("LETS");
        queryOfsStockoutOrderRequestVO.setPageNo(pageNo);
        queryOfsStockoutOrderRequestVO.setPageSize(500L);
        interfaceParamDto.setData(JSON.toJSONString(queryOfsStockoutOrderRequestVO));
        SaleOutReturnMessageDto saleOutReturnMessageDto = (SaleOutReturnMessageDto) ofsUnifiedService.unified(interfaceParamDto);
        StockoutOrderSearchResponse stockoutOrderSearchResponse = SaleOutReturnMessageDto2StockoutOrderSearchResponse(saleOutReturnMessageDto);
        if (stockoutOrderSearchResponse.getData() == null || stockoutOrderSearchResponse.getData().size() == 0) {
            return null;
        }
        all.addAll(stockoutOrderSearchResponse.getData());

        int count = stockoutOrderSearchResponse.getData().size();
        while (count >= 500) {//>=500,可能还有下一页。
            //还有下一页
            pageNo++;
            queryOfsStockoutOrderRequestVO.setPageNo(pageNo);
            interfaceParamDto.setData(JSON.toJSONString(queryOfsStockoutOrderRequestVO));
            SaleOutReturnMessageDto saleOutReturnMessageDto1 = (SaleOutReturnMessageDto) ofsUnifiedService.unified(interfaceParamDto);
            StockoutOrderSearchResponse stockoutOrderSearchResponse1 = SaleOutReturnMessageDto2StockoutOrderSearchResponse(saleOutReturnMessageDto1);

            all.addAll(stockoutOrderSearchResponse1.getData());
            count = stockoutOrderSearchResponse1.getData().size();
        }

        return all;
    }

    /**
     * 根据调拨订单号查询ofs调拨订单
     *
     * @param transferNo
     * @throws Exception
     */
    public List<OFSTranseferOrderSearchResponse.OFSTranseferOrder> queryOfsTransderOrder(String transferNo) throws Exception {
        QueryOfsTransferOrderRequestVO queryOfsTransferOrderRequestVO = new QueryOfsTransferOrderRequestVO();
//            queryOfsTransferOrderRequestVO.setStatus("100");//状态 100订单池 200待出库 300已出库 400待入库 900已入库 250出库中 450入库中
        queryOfsTransferOrderRequestVO.setCode(transferNo);
        queryOfsTransferOrderRequestVO.setPageNo(1L);
        queryOfsTransferOrderRequestVO.setPageSize(500L);

        InterfaceParamDto interfaceParamDto = new InterfaceParamDto();
        interfaceParamDto.setApi("ofs.transferOrder.search");
        queryOfsTransferOrderRequestVO.setClientCode("LETS");
        interfaceParamDto.setData(JSON.toJSONString(queryOfsTransferOrderRequestVO));
        OFSTranseferOrderSearchResponse ofsTranseferOrderSearchResponse = (OFSTranseferOrderSearchResponse) ofsUnifiedService.unified(interfaceParamDto);
        System.out.println(ofsTranseferOrderSearchResponse);
        if (ofsTranseferOrderSearchResponse.getData().size() == 0) {
            return null;
        } else {
            List<OFSTranseferOrderSearchResponse.OFSTranseferOrder> data = ofsTranseferOrderSearchResponse.getData();
            return data;
        }
    }

    /**
     * 只是命名不一样，为了方便区分，顾转换为stockout
     *
     * @param saleOutReturnMessageDto
     * @return
     */
    public StockoutOrderSearchResponse SaleOutReturnMessageDto2StockoutOrderSearchResponse(SaleOutReturnMessageDto saleOutReturnMessageDto) {
        StockoutOrderSearchResponse stockoutOrderSearchResponse = new StockoutOrderSearchResponse();
        List<StockoutOrderSearchResponse.StockoutOrder> data = new ArrayList<>();
        BeanUtils.copyProperties(saleOutReturnMessageDto, stockoutOrderSearchResponse);
        for (HeaderDetailsDto saleOutData : saleOutReturnMessageDto.getData()) {
            HeaderDto saleOutHeader = saleOutData.getHeader();
            StockoutOrderSearchResponse.StockoutOrder stockoutOrder = new StockoutOrderSearchResponse.StockoutOrder();
            StockoutOrderSearchResponse.StockoutOrder.StockoutH stockoutH = new StockoutOrderSearchResponse.StockoutOrder.StockoutH();
            List<StockoutOrderSearchResponse.StockoutOrder.StockoutB> stockoutBList = new ArrayList<>();
            for (DetailsDto saleOutDetail : saleOutData.getDetails()) {
                StockoutOrderSearchResponse.StockoutOrder.StockoutB stockoutB = new StockoutOrderSearchResponse.StockoutOrder.StockoutB();
                BeanUtils.copyProperties(saleOutDetail, stockoutB);
                stockoutBList.add(stockoutB);
            }
            //创建时间，修改时间，创建人，修改人，赋给表头
            StockoutOrderSearchResponse.StockoutOrder.StockoutB stockoutB = stockoutBList.get(0);
            stockoutH.setCreated(stockoutB.getCreated());
            stockoutH.setCreatedBy(stockoutB.getCreatedBy());
            stockoutH.setLastUpdated(stockoutB.getLastUpdated());
            stockoutH.setLastUpdatedBy(stockoutB.getLastUpdatedBy());

            BeanUtils.copyProperties(saleOutHeader, stockoutH);
            stockoutOrder.setHeader(stockoutH);
            stockoutOrder.setDetails(stockoutBList);
            data.add(stockoutOrder);
        }
        stockoutOrderSearchResponse.setData(data);
        System.out.println(stockoutOrderSearchResponse);
        return stockoutOrderSearchResponse;
    }

    private BillVO resultDataHandle(String resultData) {
        try {
            if (resultData != null && !"".equals(resultData)) {
                if (resultData.contains("[")) {
                    resultData = resultData.substring(1, resultData.length() - 1);
                }
                return JSON.parseObject(resultData, BillVO.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("解析返回参数失败的错误", e);
            //如果解析失败，记录原因，但是不能影响结果的记录
        }
        return null;
    }


    /**
     * 根据存货管理档案档案，查询最后一次结算的单价,已根据ts 倒排，get(0)为最近一次核算价格
     */
    public IaMonthledgerEntity queryIaMonthledger(OFSTranseferOrderSearchResponse.OFSTranseferOrder.OFSTranseferB sku,String companyCode){

        //查询公司
        BdCorpEntity bdCorpEntity = queryU8CEntityUtil.queryBdCorpByUnitCode(companyCode);
        if(bdCorpEntity==null){
            Assert.state(false,"根据OFS公司编码：{}，查询U8C公司不存在。请检查U8C档案",companyCode);
        }

        //查询存货基本档案主键
        BdInvbasdocEntity bdInvbasdocEntity = queryU8CEntityUtil.queryBdInvbasdocByCode(sku.getSkuCode());
        if(bdInvbasdocEntity==null){
            Assert.state(false,"根据OFS SKU CODE：{}，查询U8C存货基本档案不存在。请检查U8C档案",sku.getSkuCode());
        }

        //查询存货管理档案
        BdInvmandocEntity bdInvmandocEntity = queryU8CEntityUtil.queryBdInvmandocByPkInvbasdocAndPkCorp(bdInvbasdocEntity.getPkInvbasdoc(), bdCorpEntity.getPkCorp());
        if(bdInvmandocEntity==null){
            Assert.state(false,"根据U8C存货基本档案主键：{},U8C公司主键：{}，查询U8C存货管理档案不存在。请检查U8C档案",bdInvbasdocEntity.getPkInvbasdoc(),bdCorpEntity.getPkCorp());
        }

        IaMonthledgerEntity iaMonthledgerEntity = new IaMonthledgerEntity();
        iaMonthledgerEntity.setPkCorp(bdCorpEntity.getPkCorp());
        iaMonthledgerEntity.setCinventoryid(bdInvmandocEntity.getPkInvmandoc());
        iaMonthledgerEntity.setFrecordtypeflag("3");
        iaMonthledgerEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<IaMonthledgerEntity> iaMonthledgerEntityList = iaMonthledgerDao.query(iaMonthledgerEntity);
        if (iaMonthledgerEntityList.size() == 0) {//没有也没事
            return null;
//            Assert.state(false, "该存货名称：{}，编码:{}，U8C基本档案主键：{}，没有进行过结算，请检查",sku.getSkuName(),sku.getSkuCode(),bdInvbasdocEntity.getPkInvbasdoc());
        }
        return iaMonthledgerEntityList.get(0);

    }
}
