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.IIcGeneralBDao;
import com.hzya.frame.plugin.lets.dao.IIcGeneralHDao;
import com.hzya.frame.plugin.lets.dao.IToBillDao;
import com.hzya.frame.plugin.lets.entity.IcGeneralBEntity;
import com.hzya.frame.plugin.lets.entity.IcGeneralHEntity;
import com.hzya.frame.plugin.lets.entity.ToBillEntity;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsStockinOrderRequestVO;
import com.hzya.frame.plugin.lets.ofsvo.QueryOfsTransferOrderRequestVO;
import com.hzya.frame.plugin.lets.u8cdto.BillVO;
import com.hzya.frame.plugin.lets.u8cdto.GeneralBillVO;
import com.hzya.frame.plugin.lets.u8cdto.ReusltStrDto;
import com.hzya.frame.plugin.lets.util.PushDataByU8cUtil;
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.sysnew.integtationTaskLivingDetails.dao.IIntegrationTaskLivingDetailsDao;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.ttxofs.basics.ReturnMessageBasics;
import com.hzya.frame.ttxofs.dto.InterfaceParamDto;
import com.hzya.frame.ttxofs.dto.ofsTransferOrderSearch.OFSTranseferOrderSearchResponse;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * 丽知：OFS调拨入库订单--->U8C调拨入库订单
 */
public class TransferInPluginInitializer extends PluginBaseEntity {
    Logger logger = LoggerFactory.getLogger(TransferInPluginInitializer.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.TransferInPluginInitializer";
    }

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

    @Override
    public String getPluginLabel() {
        return "丽知：OFS调拨入库订单--->U8C调拨入库订单（保存签字，关联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 IToBillDao toBillDao;

    @Autowired
    private IIcGeneralHDao icGeneralHDao;
    @Autowired
    private IIcGeneralBDao icGeneralBDao;


    @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");

            QueryOfsStockinOrderRequestVO queryOfsStockinOrderRequestVO = new QueryOfsStockinOrderRequestVO();
            queryOfsStockinOrderRequestVO.setClosedAt_start(startTimeStr);
            queryOfsStockinOrderRequestVO.setClosedAt_end(endTimeStr);
            //状态 500待同步 510已同步 700收货中 900入库完成 911作废 100订单池 200暂挂 400待合单 410待出库单出库
            queryOfsStockinOrderRequestVO.setStatus("900");
            List<StockinOrderSearchResponse.StockinOrder> transferInOrder = queryOfsStockinOrder(queryOfsStockinOrderRequestVO);

            if (transferInOrder == null || transferInOrder.size() == 0) {
                return;
            }
            //过滤日志
            List<StockinOrderSearchResponse.StockinOrder> filterTransferInOrders = filterData(transferInOrder);
            if (filterTransferInOrders.size() == 0) {
                return;
            }
            implement(filterTransferInOrders);


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

    /**
     * 按单号
     */
    public void start(String stockinNo) {
        try {

            QueryOfsStockinOrderRequestVO queryOfsStockinOrderRequestVO = new QueryOfsStockinOrderRequestVO();
            queryOfsStockinOrderRequestVO.setCode(stockinNo);
            //状态 500待同步 510已同步 700收货中 900入库完成 911作废 100订单池 200暂挂 400待合单 410待出库单出库
            queryOfsStockinOrderRequestVO.setStatus("900");
            List<StockinOrderSearchResponse.StockinOrder> transferInOrder = queryOfsStockinOrder(queryOfsStockinOrderRequestVO);

            if (transferInOrder == null || transferInOrder.size() == 0) {
                Assert.state(false, "丽知：OFS调拨入库--->U8C调拨入库根据单据号[入库完成]：{}，未查询到调拨入库单", stockinNo);
            }
            //过滤日志
            List<StockinOrderSearchResponse.StockinOrder> filterTransferInOrders = filterData(transferInOrder);
            if (filterTransferInOrders.size() == 0) {
                Assert.state(false, "丽知：OFS调拨入库--->U8C调拨入库根据单据号[入库完成]：{}，该调拨入库单已被推送成功，请勿重新推送", stockinNo);
            }
            implement(filterTransferInOrders);


        } catch (Exception e) {
            logger.error("丽知：OFS调拨入库订单--->U8C调拨入库订单（保存签字，关联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";

            QueryOfsStockinOrderRequestVO queryOfsStockinOrderRequestVO = new QueryOfsStockinOrderRequestVO();
            queryOfsStockinOrderRequestVO.setClosedAt_start(start);
            queryOfsStockinOrderRequestVO.setClosedAt_end(end);
            //状态 500待同步 510已同步 700收货中 900入库完成 911作废 100订单池 200暂挂 400待合单 410待出库单出库
            queryOfsStockinOrderRequestVO.setStatus("900");
            List<StockinOrderSearchResponse.StockinOrder> transferInOrder = queryOfsStockinOrder(queryOfsStockinOrderRequestVO);

            if (transferInOrder == null || transferInOrder.size() == 0) {
                Assert.state(false, "丽知：OFS调拨入库订单--->U8C调拨入库订单根据日期期间[开始时间]-[结束时间]：{}-{}，未查询到调拨入库单[入库完成]", startTime, endTime);
            }
            //过滤日志
            List<StockinOrderSearchResponse.StockinOrder> filterTransferInOrders = filterData(transferInOrder);
            if (filterTransferInOrders.size() == 0) {
                Assert.state(false, "丽知：OFS调拨入库订单--->U8C调拨入库订单根据日期期间[开始时间]-[结束时间]：{}-{}，该调期调拨入库单[入库完成]已被推送成功，请勿重新推送", startTime, endTime);
            }
            implement(filterTransferInOrders);


        } catch (Exception e) {
            logger.error("丽知：OFS调拨入库订单--->U8C调拨入库订单（保存签字，关联U8C调拨出库单）,start(String startTime, String endTime)方法报错：", e);
        }
    }

    /**
     * 过滤成功日志
     *
     * @return
     */
    public List<StockinOrderSearchResponse.StockinOrder> filterData(List<StockinOrderSearchResponse.StockinOrder> stockinOrders) {
        List<StockinOrderSearchResponse.StockinOrder> filterStockinOrders = new ArrayList<>();
        for (StockinOrderSearchResponse.StockinOrder stockinOrder : stockinOrders) {
            StockinOrderSearchResponse.StockinOrder.StockinH header = stockinOrder.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) {
                filterStockinOrders.add(stockinOrder);
            }
        }
        return filterStockinOrders;
    }

    /**
     * ofs调拨入库推送u8c调拨入库，关联调拨订单。
     * <p>
     * 根据ofs调拨订单，可以查询到u8c调拨订单
     * u8c调拨出库单子表的来源单据号vsourcebillcode（调拨订单号）
     *
     * @param filterTransferInOrders
     */
    public void implement(List<StockinOrderSearchResponse.StockinOrder> filterTransferInOrders) {
        for (StockinOrderSearchResponse.StockinOrder transferInOrders : filterTransferInOrders) {
            System.out.println(transferInOrders);
            String mapStr = "";
            String format = "";
            String response = "";
            String ofsCode = "";
            try {
                StockinOrderSearchResponse.StockinOrder.StockinH ofsTransferHeader = transferInOrders.getHeader();

                //ofs调拨订单号
                String ofsSourceOrderCode = ofsTransferHeader.getSourceOrderCode();
                //ofs调拨入库单单号
                ofsCode = ofsTransferHeader.getCode();
                //ofs最后修改时间，调入时间
                format = ofsTransferHeader.getLastUpdated();

                GeneralBillVO generalBillVO = new GeneralBillVO();
                //主表
                GeneralBillVO.Parentvo parentvo = new GeneralBillVO.Parentvo();
                //coperatorid 制单人
                parentvo.setCoperatorid("tbadmin");
                //cwarehouseid 仓库
                parentvo.setCwarehouseid(ofsTransferHeader.getFacilityCode());
                //pk_calbody 库存组织
                parentvo.setPk_calbody(ofsTransferHeader.getCompanyCode());
                //pk_corp 公司
                parentvo.setPk_corp(ofsTransferHeader.getCompanyCode());
                //pk_defdoc19 自定义项19（ofs调拨订单号）
                parentvo.setVuserdef19(ofsSourceOrderCode);

                //U8C调拨订单信息
//                List<ToBillEntity> toBillEntityList = queryToBillByPkVdefdoc19(ofsSourceOrderCode);
                //U8C调拨出库单主表信息
                List<IcGeneralHEntity> icGeneralHEntityList = queryIcGeneralHByVdef19(ofsSourceOrderCode);
                if (icGeneralHEntityList == null) {
                    Assert.state(false, "在U8C内根据OFS调拨订单号（vdefdoc19）:{},没有查询到调拨出库单，请检查。", ofsSourceOrderCode);
                }
                if (icGeneralHEntityList.size() > 1) {
                    Assert.state(false, "在U8C内根据OFS调拨订单号（vdefdoc19）:{},查询到调拨出库单不唯一，请检查。", ofsSourceOrderCode);
                }
                IcGeneralHEntity icGeneralHEntity = icGeneralHEntityList.get(0);

                //U8C调拨出库单子表信息
                List<IcGeneralBEntity> icGeneralBEntityList = queryIcGeneralBByCgeneralhid(icGeneralHEntity.getCgeneralhid());
                if (icGeneralBEntityList == null) {
                    Assert.state(false, "在U8C内根据U8C调拨出库单主表主键：{}，调拨出库单单号：{}，未查询到调拨出库单子表信息，请检查。", icGeneralHEntity.getCgeneralhid(), icGeneralHEntity.getVbillcode());
                }

                List<GeneralBillVO.Childrenvo> ChildrenList = new ArrayList<>();
                int i = 1;
                for (StockinOrderSearchResponse.StockinOrder.StockinB ofsTransferDetail : transferInOrders.getDetails()) {
                    GeneralBillVO.Childrenvo childrenvo = new GeneralBillVO.Childrenvo();

                    //cinventoryid 存货
                    childrenvo.setCinventoryid(ofsTransferDetail.getSkuCode());
                    //ninnum 实收数量
                    childrenvo.setNinnum(ofsTransferDetail.getReceivedQty());
                    //csourcetype 来源单据类型编码
                    childrenvo.setCsourcetype("4Y");
                    //vsourcebillcode 来源单据号
                    childrenvo.setVsourcebillcode(icGeneralHEntity.getVbillcode());


                    for (IcGeneralBEntity icGeneralBEntity : icGeneralBEntityList) {
                        System.out.println(icGeneralBEntity);
                        //根据存货+行号匹配
                        if (ofsTransferDetail.getRefOrderDetailId().equals(icGeneralBEntity.getVuserdef20().trim()) && ofsTransferDetail.getSkuCode().equals(icGeneralBEntity.getCinvbascode())) {
                            //crowno 行号
                            childrenvo.setCrowno(i++ + "0");
                            //ofs来源单据行行号
                            childrenvo.setVuserdef20(ofsTransferDetail.getRefOrderDetailId());
                            //vsourcerowno 来源单据行号
                            childrenvo.setVsourcerowno(icGeneralBEntity.getCrowno());
                            break;
                        }
                    }
                    ChildrenList.add(childrenvo);
                }
                generalBillVO.setParentvo(parentvo);
                generalBillVO.setChildrenvo(ChildrenList);

                mapStr = "{\"GeneralBillVO\":[" + JSONUtil.toJsonStr(generalBillVO) + "]}";
                ZTResult ztResult = pushU8CByApiCode.pushByCode(OverallConstant.getOverAllValue("approveInqzCode"), mapStr);
                System.out.println(ztResult);
                //两层判断,一层中台转发,一层u8c返回
                if ("false".equals(ztResult.getFlag())) {
                    //转发失败
                    response = JSONUtil.toJsonStr(ztResult.getAttribute());
                    Assert.state(false, "丽知：OFS调拨入库订单--->U8C调拨入库订单.中台转发失败,失败原因:{}", response);
                }
                Attribute attribute = ztResult.getAttribute();
                System.out.println(attribute);
                boolean isSuccess = false;
                String vbillcode = "";
                if ("success".equals(attribute.getStatus())) {
                    isSuccess = true;
                    String data = attribute.getData();
                    GeneralBillVO generalBill = resultDataHandle(data);
                    System.out.println(generalBill);
                    vbillcode = generalBill.getParentvo().getVbillcode();
                }
                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.setDef1(vbillcode);
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);

            } catch (Exception e) {
                e.printStackTrace();
                logger.error("推送U8C，丽知：OFS调拨入库订单--->U8C调拨入库订单（保存签字，关联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);
                integrationTaskLivingDetailsEntity.setPluginId(getPluginId());
                saveOrUpdateBusinessLogUtil.saveOrUpdate(integrationTaskLivingDetailsEntity);
            }
        }

    }

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


    /**
     * 查询ofs调拨入库单
     *
     * @param queryOfsStockinOrderRequestVO
     * @return
     * @throws Exception
     */
    public List<StockinOrderSearchResponse.StockinOrder> queryOfsStockinOrder(QueryOfsStockinOrderRequestVO queryOfsStockinOrderRequestVO) throws Exception {
        Long pageNo = 1L;

        List<StockinOrderSearchResponse.StockinOrder> all = new ArrayList<>();

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

        int count = stockinOrderSearchResponse.getData().size();
        while (count >= 500) {//>=500,可能还有下一页。
            //还有下一页
            pageNo++;
            queryOfsStockinOrderRequestVO.setPageNo(pageNo);
            interfaceParamDto.setData(JSON.toJSONString(queryOfsStockinOrderRequestVO));
            StockinOrderSearchResponse stockinOrderSearchResponse1 = (StockinOrderSearchResponse) ofsUnifiedService.unified(interfaceParamDto);

            all.addAll(stockinOrderSearchResponse1.getData());

            count = stockinOrderSearchResponse1.getData().size();
        }

        return all;
    }

    /**
     * 根据单号查询调拨单  to_bill  单据主表  单据
     *
     * @param vcode
     */
    public List<ToBillEntity> queryToBillByVCode(String vcode) {
        ToBillEntity toBillEntity = new ToBillEntity();
        toBillEntity.setVcode(vcode);
        toBillEntity.setCbilltype("5X");
        List<ToBillEntity> toBillEntityList = toBillDao.queryToBillEntity(toBillEntity);
        return toBillEntityList;
    }

    /**
     * 根据自定义项19（ofs调拨订单单号），查询u8c调拨订单
     *
     * @param pkDefdoc19
     * @return
     */
    public List<ToBillEntity> queryToBillByPkVdefdoc19(String pkDefdoc19) {
        ToBillEntity toBillEntity = new ToBillEntity();
        toBillEntity.setPkDefdoc19(pkDefdoc19);
        toBillEntity.setCbilltype("5X");
        toBillEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<ToBillEntity> toBillEntityList = toBillDao.query(toBillEntity);
        return toBillEntityList;
    }

    /**
     * 根据调拨出库单主表自定义项19（ofs调拨订单号）查询调拨出库单主表
     */
    public List<IcGeneralHEntity> queryIcGeneralHByVdef19(String pkDefdoc19) {
        IcGeneralHEntity icGeneralHEntity = new IcGeneralHEntity();
        icGeneralHEntity.setDr(0);
        icGeneralHEntity.setVuserdef19(pkDefdoc19);
        icGeneralHEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<IcGeneralHEntity> icGeneralHEntityList = icGeneralHDao.query(icGeneralHEntity);
        if (icGeneralHEntityList == null || icGeneralHEntityList.size() == 0) {
            return null;
        }
        return icGeneralHEntityList;
    }

    /**
     * 根据调拨出库单主表主键，查询调拨出库单子表
     */
    public List<IcGeneralBEntity> queryIcGeneralBByCgeneralhid(String cgeneralhid) {
//        IcGeneralBEntity icGeneralBEntity = new IcGeneralBEntity();
//        icGeneralBEntity.setDr(0);
//        icGeneralBEntity.setCgeneralhid(cgeneralhid);
//        icGeneralBEntity.setDataSourceCode(ProfilesActiveConstant.LETS_DATE_SOURCE);
        List<IcGeneralBEntity> icGeneralBEntityList = icGeneralBDao.queryAndCinvbasCode(cgeneralhid);
        if (icGeneralBEntityList == null || icGeneralBEntityList.size() == 0) {
            return null;
        }
        return icGeneralBEntityList;
    }

}
