package com.steering.pss.sale.order;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.pss.plan.order.model.SlmOrderLineCopy;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.sale.order.model.CoreOrderStatus;
import com.steering.pss.sale.order.model.ReportOrderLineDelivery;
import com.steering.pss.sale.order.orderchange.CrmOrderProduceService;

import net.sf.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CoreOrderReport extends DBCommon {

    /**
     * 合同提报
     * @param parm
     * @return
     */
    public CoreReturnObject doReport(ArrayList<Object> parm) {

        CoreReturnObject cro = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        List<String> listL = new ArrayList<String>(); // 合同行PK值
        List<String> listH = new ArrayList<String>(); // 合同头PK值

        try {
            con.setAutoCommit(false);
            CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();
            for (int i = 0; i < parm.size(); i++) {

                String jsonStr = parm.get(i).toString();
                JSONObject json = JSONObject.fromObject(jsonStr);

                ReportOrderLineDelivery reportModel = (ReportOrderLineDelivery) JSONObject
                        .toBean(json, ReportOrderLineDelivery.class);

                CoreOrderStatus cos = cou.getOrderLineDeliveryStatus(con,
                        reportModel.getOrdLnDlyPk());

                SqlBuilder b = new SqlBuilder("CoreOrderInfoUpdate.getSlmOrderLine");
                b.Fill(new String[]{reportModel.getOrdLnPk()});
                SlmOrderLineCopy line = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmOrderLineCopy.class);
                if(line == null){
                    cro.setV_errCode(-1);
                    cro.setResult("未找到有效的合同行，不能提报！");
                    con.rollback();
                    return cro;
                }

                if(!reportModel.getJzFileIfAll().equals(line.getProducerFl())
                    || !reportModel.getPrdcrNo().equals(line.getPrdcrNo())){
                    cro.setV_errCode(-1);
                    cro.setResult("合同行信息不一致，请尝试刷新，重新提报！");
                    con.rollback();
                    return cro;
                }

                if (!cos.getDeliveryStatus().equals("12020301")
                        && !cos.getDeliveryStatus().equals("12020302")) {
                    cro.setV_errCode(-1);
                    cro.setResult("合同状态不是‘生效/放行生效’状态，不能提报！");
                    con.rollback();
                    return cro;
                }
                else {

                    if (!listL.contains(reportModel.getOrdLnPk())) {
                        listL.add(reportModel.getOrdLnPk());
                    }

                    if (!listH.contains(reportModel.getOrdPk())) {
                        listH.add(reportModel.getOrdPk());
                    }
                    /*String[] craftInfo = PlnHelper.getArray(con,
    						"CorePlnSaleOrder.queryOrdCraftOrdDesign",
    						" AND T.VALIDFLAG = '1'",
    						new String[] { reportModel.getOrdLnPk() }, new String[] {
    								"CRAFT_SEQ", "DESGIN_KEY", "CRAFT_NAME",
    								"CRAFT_NO", "CRAFT_NO_V" });
    				if (craftInfo == null || craftInfo.length == 0) {
    					cro.setV_errCode(-1);
                        cro.setResult("未找到有效的工艺评审！");
                        con.rollback();
                        return cro;
    				}*/
                    //2020-05-06新增商品坯验证逻辑
                    // 查找工艺
/*    				String[] craftInfo = PlnHelper.getArray(con,
    						"CorePlnSaleOrder.queryOrdCraftOrdDesign",
    						" AND T.VALIDFLAG = '1'",
    						new String[] { reportModel.getOrdLnPk() }, new String[] {
    								"CRAFT_SEQ", "DESGIN_KEY", "CRAFT_NAME",
    								"CRAFT_NO", "CRAFT_NO_V" });
    				if (craftInfo == null || craftInfo.length == 0) {
    					cro.setV_errCode(-1);
                        cro.setResult("未找到有效的工艺评审！");
                        con.rollback();
                        return cro;
    				}
    				String desginKey = craftInfo[1];
    				// 查询工艺评审制程
    				List<CraftOrdDesignMscPlEntityO> mscPlList = PlnHelper
    						.getEntityDatas(con, new String[] { desginKey,
    								desginKey }, "CorePlnSaleOrder.queryDesginPl",
    								CraftOrdDesignMscPlEntityO.class);
    				if (mscPlList == null || mscPlList.size() == 0) {
    					cro.setV_errCode(-1);
                        cro.setResult("未找到制程，请查看工艺评审。");
                        con.rollback();
    				}
    				for (CraftOrdDesignMscPlEntityO mscPlEntity : mscPlList) {

    					String endgxCode = mscPlEntity.getWholeBacklog().substring(mscPlEntity.getWholeBacklog()
    							.length() - 1);
    					String lengthMin="";
    					String lengthMax="";
    					if("商品坯".equals(CoreOrdBase.produceSort(endgxCode,reportModel.getPrdCls(), "", ""))){
    						String sqlcic = CoreXmlSqlParsersFactory
    								.getSql("CoreOrderReport.getSelectCicGroup");
    						PreparedStatement pst = con.prepareStatement(sqlcic);
    						// pst.setObject(2, ordProcEntity.getIndexSeq());
    						ResultSet rst = pst.executeQuery();
    						if (rst.next()) {
    							lengthMin = rst.getString("length_min");
    							lengthMax = rst.getString("length_max");
    						}
    						rst.close();
    						pst.close();
    						if(!"".equals(lengthMin)){
    							double Pmin=Double.parseDouble(lengthMin);//生产产线
    							double Pmax=Double.parseDouble(lengthMax);//生产产线
    							double Lmin=Double.parseDouble(reportModel.getLengthmin());//合同
    							double Lmax=Double.parseDouble(reportModel.getLengthmax());//合同
    							if(Lmin<Pmin||Lmax>Pmax){
    								cro.setV_errCode(-1);
    		                        cro.setResult("合同长度超出生产产线范围");
    		                        con.rollback();
    							}
    						}
    					
    					}

    				}*/
                    /*
                     * Object[] params = new Object[] { reportModel.getOrdPk(),
                     * reportModel.getOrdLnPk(), reportModel.getOrdLnDlyPk(),
                     * reportModel.getOrderNo(), reportModel.getOrderSeq(),
                     * reportModel.getDeliveryNo(), reportModel.getPrdCls(),
                     * reportModel.getProduccode(), reportModel.getProducname(),
                     * reportModel.getStdCode(), reportModel.getStdName(),
                     * reportModel.getSteelcode(), reportModel.getSteelname(),
                     * reportModel.getSpecCode(), reportModel.getSpecName(),
                     * reportModel.getOutdiameter(), reportModel.getWallthick(),
                     * reportModel.getLenNo(), reportModel.getLengthmin(),
                     * reportModel.getLengthmax(), reportModel.getLengthdisc(),
                     * reportModel.getModelCode(), reportModel.getModelDesc(),
                     * reportModel.getOrderUnit(), reportModel.getOrderQty(),
                     * reportModel.getOrderweight(), reportModel.getOrdernum(),
                     * reportModel.getTotlength(),
                     * reportModel.getDelvryRangeTpe(),
                     * reportModel.getDelvryRangeMin(),
                     * reportModel.getDelvryRangeMax(),
                     * reportModel.getBuyerId(), reportModel.getBuyerName(),
                     * reportModel.getCustAlphaNo(),
                     * reportModel.getOrderSpecialDesc(),
                     * reportModel.getAddAskNo(), reportModel.getOrderAddDesc(),
                     * reportModel.getOrderfrom(), reportModel.getFinalUser(),
                     * reportModel.getFinalUserDesc(),
                     * reportModel.getUpperlimit(),
                     * reportModel.getDelvryBdate(),
                     * reportModel.getDelvryEdate(),
                     * reportModel.getLatestProdDate(),
                     * reportModel.getOrdercontact(),
                     * reportModel.getPrdcrDesc(), reportModel.getPsc(),
                     * reportModel.getMsc(), reportModel.getJzFileIfAll(),
                     * reportModel.getPrdcrNo(), reportModel.getMaterialNo(),
                     * reportModel.getMaterialDesc(),
                     * reportModel.getShrtLenRato(), reportModel.getShortest(),
                     * reportModel.getLongLenRato(), reportModel.getLongest(),
                     * reportModel.getSiglLen(), reportModel.getCreateName(),
                     * reportModel.getLenUnit(), reportModel.getOutsBilletFl(),
                     * reportModel.getUseCode(), reportModel.getUseDesc(),
                     * reportModel.getEndLenSpecStd(),
                     * reportModel.getAvgLenMin(), reportModel.getShrtStove(),
                     * reportModel.getDifrncLenMax(),
                     * reportModel.getStdStyleDesc(),
                     * reportModel.getOutsStlPipeFl(),
                     * reportModel.getRollMonth(), reportModel.getRollMonth(),
                     * reportModel.getDelvryQty(), reportModel.getChargeNum(),
                     * reportModel.getChargeWgt(), reportModel.getChargeLen(),
                     * reportModel.getElimNum(), reportModel.getElimWgt(),
                     * reportModel.getElimLen() };
                     */

                    Object[] params1 = new Object[] { reportModel.getOrdPk(),
                            reportModel.getOrdLnPk(),
                            reportModel.getOrdLnDlyPk(),
                            reportModel.getOrderNo(), reportModel.getOrderSeq(),
                            reportModel.getDeliveryNo(),
                            reportModel.getPrdCls(),
                            reportModel.getProduccode(),
                            reportModel.getProducname(),
                            reportModel.getStdCode(), reportModel.getStdName(),
                            reportModel.getSteelcode(),
                            reportModel.getSteelname(),
                            reportModel.getSpecCode(),
                            reportModel.getSpecName(),
                            reportModel.getOutdiameter(),
                            reportModel.getWallthick(), reportModel.getLenNo(),
                            reportModel.getLengthmin(),
                            reportModel.getLengthmax(),
                            reportModel.getLengthdisc(),
                            reportModel.getModelCode(),
                            reportModel.getModelDesc(),
                            reportModel.getOrderUnit(),
                            reportModel.getOrderQty(),
                            reportModel.getOrderweight(),
                            reportModel.getOrdernum(),
                            reportModel.getTotlength(),
                            reportModel.getDelvryRangeTpe(),
                            reportModel.getDelvryRangeMin(),
                            reportModel.getDelvryRangeMax(),
                            reportModel.getBuyerId(),
                            reportModel.getBuyerName(),
                            reportModel.getOrderSpecialDesc(),
                            reportModel.getAddAskNo(),
                            reportModel.getOrderAddDesc(),
                            reportModel.getOrderfrom(),
                            reportModel.getFinalUser(),
                            reportModel.getFinalUserDesc(),
                            reportModel.getDelvryEdate(),
                            reportModel.getOrdercontact(),
                            reportModel.getPrdcrDesc(), reportModel.getPsc(),
                            reportModel.getMsc(), reportModel.getJzFileIfAll(),
                            reportModel.getPrdcrNo(),
                            reportModel.getMaterialNo(),
                            reportModel.getMaterialDesc(),
                            reportModel.getShrtLenRato(),
                            reportModel.getShortest(),
                            reportModel.getLongLenRato(),
                            reportModel.getLongest(), reportModel.getSiglLen(),
                            reportModel.getCreateName(),
                            reportModel.getLenUnit(),
                            reportModel.getOutsBilletFl(),
                            reportModel.getUseCode(), reportModel.getUseDesc(),
                            reportModel.getEndLenSpecStd(),
                            reportModel.getAvgLenMin(),
                            reportModel.getShrtStove(),
                            reportModel.getDifrncLenMax(),
                            reportModel.getStdStyleDesc(),
                            reportModel.getOutsStlPipeFl(),
                            reportModel.getRollMonth(),
                            reportModel.getRollMonth(),
                            reportModel.getDelvryQty(),
                            reportModel.getChargeNum(),
                            reportModel.getChargeWgt(),
                            reportModel.getChargeLen(),
                            reportModel.getElimNum(), reportModel.getElimWgt(),
                            reportModel.getElimLen(),reportModel.getLenUnit(),
                            reportModel.getSupplyUnitCode(),
                            reportModel.getSupplyUnit(),
                            reportModel.getDelvryAddr(),
                            reportModel.getTypeFlag()};

                    /*
                     * String sql = CoreXmlSqlParsersFactory
                     * .getSql("CoreOrderReport.InsertPlnSaleOrder");
                     * PreparedStatement ps = con.prepareStatement(sql); for
                     * (int j = 0; j < params.length; j++) { ps.setObject(j + 1,
                     * params[j]); } ps.executeUpdate(); ps.close();
                     */
                    // 新表 PlnSaleOrd
                    String sqlnew = CoreXmlSqlParsersFactory
                            .getSql("CoreOrderReport.InsertPlnSaleOrd");
                    PreparedStatement ps = con.prepareStatement(sqlnew);
                    for (int j = 0; j < params1.length; j++) {
                        ps.setObject(j + 1, params1[j]);
                    }
                    ps.executeUpdate();
                    ps.close();
                    // 将量写入进程表
                    String sql1 = CoreXmlSqlParsersFactory
                            .getSql("CoreOrderReport.UpdateProcessOrderApp");
                    ps = con.prepareStatement(sql1);
                    ps.setObject(1, reportModel.getOrderQty());
                    ps.setObject(2, reportModel.getOrderUnit());
                    ps.setObject(3, reportModel.getOrdLnDlyPk());
                    ps.executeUpdate();
                    ps.close();

                    CoreOrderStatusCommFun
                            .updateOrderDeliveryLineStatusOrdLnDlyPk(con,
                                    reportModel.getOrdLnDlyPk(), "12020402");
                    // CoreOrderStatusCommFun.updateOrderLineStatus(con,
                    // reportModel.getOrdLnPk(), "12020401");
                    // CoreOrderStatusCommFun.updateOrderHeadStatusReport(con,
                    // reportModel.getOrdPk(), "12020401", "已开始提报");
                    //crm合同表
                    cou.doCrmEvent(con,"","",reportModel.getOrdLnDlyPk(),"1");
                    //crm进程表
                    CrmOrderProduceService crmOrderProduceService = new CrmOrderProduceService();
                    crmOrderProduceService.insertCrmOrderProduce(con,reportModel.getCreateName(),reportModel.getOrdLnDlyPk(),"1");
                }
            }

            // 修改合同行状态，合同头状态
            for (int k = 0; k < listL.size(); k++) {
                String sqlD = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderReport.GetOrderDeliveryStatus");
                PreparedStatement ps = con.prepareStatement(sqlD);
                ps.setObject(1, listL.get(k));
                ResultSet rs = ps.executeQuery();
                if (!rs.next()) {
                    CoreOrderStatusCommFun.updateOrderLineStatus(con,
                            listL.get(k), "12020402");
                }
                else {
                    CoreOrderStatusCommFun.updateOrderLineStatus(con,
                            listL.get(k), "12020401");
                }
                rs.close();
                ps.close();
                // 2016-01-21 修改合同号下的最后一个交货行允许补量标志
                String sql1 = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderReport.UpdatePlnSaleOrdEndDly");
                ps = con.prepareStatement(sql1);
                ps.setObject(1, listL.get(k));
                ps.executeUpdate();
                ps.close();
            }

            for (int n = 0; n < listH.size(); n++) {
                String sqlL = CoreXmlSqlParsersFactory
                        .getSql("CoreOrderReport.GetOrderHeadStatus");
                PreparedStatement ps = con.prepareStatement(sqlL);
                ps.setObject(1, listH.get(n));
                ResultSet rs = ps.executeQuery();
                if (!rs.next()) {
                    CoreOrderStatusCommFun.updateOrderHeadStatusReport(con,
                            listH.get(n), "12020402", "提报完毕");
                }
                else {
                    CoreOrderStatusCommFun.updateOrderHeadStatusReport(con,
                            listH.get(n), "12020401", "开始提报");
                }
                rs.close();
                ps.close();
            }
            con.commit();
            cro.setV_errCode(0);
        }
        catch (SQLException e) {

            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setResult(e.getMessage());
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
            finally {
                try {
                    con.close();
                }
                catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        }

        return cro;
    }

    /**
     * 取消提报
     * @param parm
     * @return
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doClearReport(ArrayList<Object> parm) {

        CoreReturnObject cro = new CoreReturnObject();
        CoreOrderInfoUpdate cou = new CoreOrderInfoUpdate();

        Connection con = null;
        // List<String> listL = new ArrayList<String>(); // 合同行PK值
        // List<String> listH = new ArrayList<String>(); // 合同头PK值
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            for (int i = 0; i < parm.size(); i++) {

                ArrayList<Object> list = (ArrayList<Object>) parm.get(i);
                CoreOrderStatus cos = cou.getOrderLineDeliveryStatus(con,
                        list.get(2).toString()); // 交货行状态

                String status = getPlnSaleOrderStatus(con,
                        list.get(0).toString(), list.get(1).toString(),
                        list.get(2).toString()); // 在PLN_SALEORDER表中的状态

                if (cos.getDeliveryStatus().equals("12020402")
                        && status.equals("0")) {

                    // if (!listL.contains(list.get(1).toString())) {
                    // listL.add(list.get(1).toString());
                    // }
                    //
                    // if (!listH.contains(list.get(0).toString())) {
                    // listH.add(list.get(0).toString());
                    // }
                    // 先删除PLN_SALEORDER中交货行记录。
                    /*
                     * String sql = CoreXmlSqlParsersFactory
                     * .getSql("CoreOrderReport.DeletePlnSaleOrderLine");
                     * PreparedStatement ps = con.prepareStatement(sql);
                     * ps.setObject(1, list.get(0)); ps.setObject(2,
                     * list.get(1)); ps.setObject(3, list.get(2));
                     * ps.executeUpdate(); ps.close();
                     */
                    // 清除新表PLNSALEORD
                    String sqlnew = CoreXmlSqlParsersFactory
                            .getSql("CoreOrderReport.DeletePlnSaleOrdLine");
                    PreparedStatement ps = con.prepareStatement(sqlnew);
                    ps.setObject(1, list.get(0));
                    ps.setObject(2, list.get(1));
                    ps.setObject(3, list.get(2));
                    ps.executeUpdate();
                    ps.close();
                    // 清空进程信息的提报量
                    String sql1 = CoreXmlSqlParsersFactory
                            .getSql("CoreOrderReport.ClearProcessOrderApp");
                    ps = con.prepareStatement(sql1);
                    ps.setObject(1, list.get(2));
                    ps.executeUpdate();
                    ps.close();
                    // 更新状态
                    String bestatus = CoreOrderStatusCommFun
                            .getOrderDeliveryLineStatus(con,
                                    list.get(2).toString());

                    CoreOrderStatusCommFun.updateDeliveryLineStatus(con,
                            list.get(2).toString(), "12020402");

                    String sqlL = CoreXmlSqlParsersFactory
                            .getSql("CoreOrderReport.GetDeliveryOrderStatus");
                    PreparedStatement ps1 = con.prepareStatement(sqlL);
                    ps1.setObject(1, list.get(1));
                    ResultSet rs = ps1.executeQuery();
                    if (rs.next()) {
                        CoreOrderStatusCommFun.updateOrderLineStatus(con,
                                list.get(1).toString(), "12020401");
                    }
                    else {
                        CoreOrderStatusCommFun.updateLineStatusWithOrdLnDlyPk(
                                con, list.get(1).toString(), bestatus);
                    }
                    rs.close();
                    ps1.close();
                    String sqlH = CoreXmlSqlParsersFactory.getSql(
                            "CoreOrderReport.GetDeliveryOrderStatusWithOrdPk");
                    PreparedStatement ps2 = con.prepareStatement(sqlH);
                    ps2.setObject(1, list.get(1));
                    ResultSet rs1 = ps2.executeQuery();

                    if (rs1.next()) {
                        cou.updateOrderHeadStatus(con, list.get(0).toString(),
                                "12020401", "已开始提报");
                    }
                    else {
                        CoreOrderStatusCommFun.updateHeadStatusWithOrdLnDlyPk(
                                con, list.get(0).toString(), bestatus);
                    }
                    rs1.close();
                    ps2.close();

                    //crm合同表
                    cou.doCrmEvent(con,"","",list.get(2).toString(),"1");
                    //crm进程表
                    CrmOrderProduceService crmOrderProduceService = new CrmOrderProduceService();
                    crmOrderProduceService.insertCrmOrderProduce(con,list.get(3).toString(),list.get(2).toString(),"1");
                }
                else {
                    String errMsg = "";
                    if (!cos.getDeliveryStatus().equals("12020402")) {
                        errMsg = "合同状态不是‘提报完毕’，不能进行撤销提报！";
                    }
                    else {
                        errMsg = "选择的合同，‘生产管理’已接收，不能进行撤销提报！";
                    }
                    con.rollback();
                    cro.setV_errCode(-1);
                    cro.setResult(errMsg);
                    return cro;
                }
            }

            con.commit();
            cro.setV_errCode(0);

        }
        catch (SQLException e) {
            try {
                con.rollback();
                cro.setV_errCode(-1);
                cro.setResult(e.getMessage());
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        finally {
            try {
                con.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 获取交货行状态
     * @param includeDeleted 是否包含已删除数据
     * @param name 专用线描述
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject GetDeliverySts(String ordPk, String ordLnPk,
            String ordLnDlyPk) {
        Object[] params = new Object[] { ordPk, ordLnPk, ordLnDlyPk };
        return this.getDataBySqlID("CoreOrderReport.GetDeliverySts", params);
    }
    
	/**
	 * 未提报合同与本地、异地（出库未结）库存查询
	 */
	public CoreReturnObject doQuery(String orderNo,
            String orderStart, String orderEnd, String[] arr,String customInfo,String reportStartTime,
            String reportEndTime) {
        String strSts = "";
        String strOrderNo = "";
		if(orderNo.equals("")){
            strOrderNo = "";            
        }else{
            strOrderNo = "AND LOWER(C.ORDER_NO) LIKE '%"+orderNo+"%'";
        }
        //Object[] params = new Object[] { orderNo };//orderSts,orderStart, orderEnd
        String condition = CoreConverter.toSqlConditionString("CREATE_DEPT",
                arr);
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrderReport.doQueryImproveWithMats");
        if("120504".equals(customInfo)){
        	condition+=" AND C.SUPPLY_UNIT='120504' ";
        }
        sql = sql.replaceAll("#CONDITION#", condition);
        sql = sql.replaceAll("#DELIVERY_STATUS#", strSts);
        sql = sql.replaceAll("#ORDER_NO#", strOrderNo);

        if(StringUtils.isEmpty(orderNo) && !StringUtils.isEmpty(orderStart) && !StringUtils.isEmpty(orderEnd)){
//            sql += " and CREATE_TIME >= '"+orderStart+"' AND CREATE_TIME <= '"+orderEnd+"'";
            sql = sql.replaceAll("#SEARCH_DATE#", " and A.CREATE_TIME >= TO_DATE('"+orderStart+"', 'YYYY-MM-DD HH24:MI:SS') AND A.CREATE_TIME <= TO_DATE('"+orderEnd+"', 'YYYY-MM-DD HH24:MI:SS')");
        }else{
            sql = sql.replaceAll("#SEARCH_DATE#", "");

        }
        if(StringUtils.isEmpty(orderNo) && !StringUtils.isEmpty(reportStartTime) && !StringUtils.isEmpty(reportEndTime)){
//            sql += " and CREATE_TIME >= '"+orderStart+"' AND CREATE_TIME <= '"+orderEnd+"'";
            sql = sql.replaceAll("#REPORT_DATE#", " and D.CREATE_TIME >= TO_DATE('"+reportStartTime+"', 'YYYY-MM-DD HH24:MI:SS') AND D.CREATE_TIME <= TO_DATE('"+reportEndTime+"', 'YYYY-MM-DD HH24:MI:SS')");
        }else{
            sql = sql.replaceAll("#REPORT_DATE#", "");

        }
        sql += "  ORDER BY ORDER_NO,ORDER_SEQ,DELVRY_EDATE ";
        return this.getData(sql);
	}
	

    /**
     * 获取合同行主信息
     * @param includeDeleted 是否包含已删除数据
     * @param name 专用线描述
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject doQuery(String orderNo, String orderSts,
                                    String orderStart, String orderEnd, String[] arr,String customInfo) {
        return doQuery(orderNo,orderSts,orderStart,orderEnd,arr,customInfo,"","");
    }
    public CoreReturnObject doQuery(String orderNo, String orderSts,
            String orderStart, String orderEnd, String[] arr,String customInfo,String reportStartTime,
            String reportEndTime) {
        String strSts = "";
        String strOrderNo = "";
        if(orderSts.equals("")){
            strSts = "AND A.DELIVERY_STATUS IN ('12020301', '12020302', '12020402')";
        }else if(orderSts.equals("12020301")){
            strSts = "AND A.DELIVERY_STATUS = '12020301'";
        }else if(orderSts.equals("12020302")){
            strSts = "AND A.DELIVERY_STATUS = '12020302'";
        }else if(orderSts.equals("12020402")){
            strSts = "AND A.DELIVERY_STATUS = '12020402'";
        }
        if(orderNo.equals("")){
            strOrderNo = "";            
        }else{
            strOrderNo = "AND LOWER(C.ORDER_NO) LIKE '%"+orderNo+"%'";
        }
        //Object[] params = new Object[] { orderNo };//orderSts,orderStart, orderEnd
//        String condition = CoreConverter.toSqlConditionString("CREATE_DEPT",
//                arr);
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrderReport.doQueryImproveWithMat");
//        if("120504".equals(customInfo)){
//        	condition+=" AND C.SUPPLY_UNIT='120504' ";
//        }
      //  sql = sql.replaceAll("#CONDITION#", condition);
        sql = sql.replaceAll("#DELIVERY_STATUS#", strSts);
        sql = sql.replaceAll("#ORDER_NO#", strOrderNo);

        if(StringUtils.isEmpty(orderNo) && !StringUtils.isEmpty(orderStart) && !StringUtils.isEmpty(orderEnd)){
//            sql += " and CREATE_TIME >= '"+orderStart+"' AND CREATE_TIME <= '"+orderEnd+"'";
            sql = sql.replaceAll("#SEARCH_DATE#", " and A.CREATE_TIME >= TO_DATE('"+orderStart+"', 'YYYY-MM-DD HH24:MI:SS') AND A.CREATE_TIME <= TO_DATE('"+orderEnd+"', 'YYYY-MM-DD HH24:MI:SS')");
        }else{
            sql = sql.replaceAll("#SEARCH_DATE#", "");

        }
        if(StringUtils.isEmpty(orderNo) && !StringUtils.isEmpty(reportStartTime) && !StringUtils.isEmpty(reportEndTime)){
//            sql += " and CREATE_TIME >= '"+orderStart+"' AND CREATE_TIME <= '"+orderEnd+"'";
            sql = sql.replaceAll("#REPORT_DATE#", " and D.CREATE_TIME >= TO_DATE('"+reportStartTime+"', 'YYYY-MM-DD HH24:MI:SS') AND D.CREATE_TIME <= TO_DATE('"+reportEndTime+"', 'YYYY-MM-DD HH24:MI:SS')");
        }else{
            sql = sql.replaceAll("#REPORT_DATE#", "");

        }
        sql += "  ORDER BY ORDER_NO,ORDER_SEQ,DELVRY_EDATE ";
        System.out.println(sql);
        return this.getData(sql);

    }

    /**
     * 绑定提报状态
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject GetSts() {
        return this.getDataBySqlID("CoreOrderReport.GetSts");
    }
    
    /**
     * 绑定提报状态
     * @return CoreReturnObject 必须返回CoreReturnObject
     */
    public CoreReturnObject GetStsNew() {
        return this.getDataBySqlID("CoreOrderReport.GetStsNew");
    }

    /**
     * 获取交货行在生产管理的状态
     * @param ordPk
     * @param ordLnPk
     * @param ordLnDlyPk
     * @return
     */
    public String getPlnSaleOrderStatus(Connection con, String ordPk,
            String ordLnPk, String ordLnDlyPk) throws SQLException {
        String status = "";
        // Object[] obj = new Object[] { ordPk, ordLnPk, ordLnDlyPk };
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrderReport.GetPLNSaleOrderStatus");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, ordPk);
        ps.setObject(2, ordLnPk);
        ps.setObject(3, ordLnDlyPk);
        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            status = rs.getString(1);
        }
        rs.close();
        ps.close();
        return status;
    }

    public CoreReturnObject getPrdcrIsNull(String ordLnPk) {
        Object[] obj = new Object[] { ordLnPk };
        return this.getDataBySqlID("CoreOrderReport.SelecttPrdCrNull", obj);
    }

    public CoreReturnObject getPrdcrNotNull(String ordLnPk) {
        Object[] obj = new Object[] { ordLnPk };
        return this.getDataBySqlID("CoreOrderReport.SelecttPrdCrNotNull", obj);
    }

    public CoreReturnObject getServerTime() {
        return this.getDataBySqlID("CoreOrderReport.GetServerTime");
    }

    public CoreReturnObject getOrderType(String ordPk) {
        Object[] obj = new Object[] { ordPk };
        return this.getDataBySqlID("CoreOrderReport.GetOrderType", obj);
    }

    /**
     * 获取合同行的锁定状态
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject getOrderLineLock(String ordLnPk) {
        Object[] obj = new Object[] { ordLnPk };
        return this.getDataBySqlID("CoreOrderReport.GetOrderLineLock", obj);
    }

    public CoreReturnObject getProcessOrderInfo(String ordLnDlyPk) {
        Object[] obj = new Object[] { ordLnDlyPk };
        return this.getDataBySqlID("CoreOrderReport.GetProcessOrder", obj);
    }

    /**
     * 查询合同相关库存信息
     * @param parm
     * @param saleOrg 销售组织
     * @return
     */
    public CoreReturnObject queryMatInfo(ArrayList<Object> parm,
            String saleOrg,String suppUnit) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrderReport.queryMatInfo");
        String str = "";
        if (saleOrg.equals("100101") || saleOrg.equals("100103")) {
            str = " AND T1.BELONG_CODE IN ('100101','100103')";
        }
        else if (saleOrg.equals("100102")) {
            str = " AND T1.BELONG_CODE  = '100102'";
        }
        if(!suppUnit.equals("")){
        	sql+= " AND T1.SUPPLY_UNIT_CODE='" + suppUnit + "' ";
        }
        sql += str;
        sql += " GROUP BY T1.BELONG_CODE,T1.BELONG_NAME,T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.PRODUCT_FLAG,T1.MAT_STATUS,T1.SPEC_CODE,T1.SPEC_NAME,"
                + "T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,T1.PRODUCCODE,T1.PRODUCNAME,T1.MATERIAL_NO,T1.MATERIAL_NAME,T1.STEELCODE,T1.STEELNAME,T1.JUDGE_STD_NAME,"
                + "T1.STD_CODE,T1.STD_NAME,T1.ORDER_NO,T1.ORDER_SEQ,T1.ORDER_SEQ_NO,T1.ORD_PK,T1.ORD_LN_PK,T1.ORD_LN_DLY_PK,T1.PRO_ORDER_NO,T1.PRO_ORDER_ID,T1.LOCK_FLAG,T1.MNG_LOCK_FLAG,"
                + "T1.MEMO,T1.JUDGE_RESULT_CODE,T1.JUDGE_RESULT,T2.STORAGE_NO,T1.MODEL_CODE,T1.MODEL_DESC,T1.STD_STYLE,T1.STD_STYLE_DESC ORDER BY T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.ORDER_NO,"
                + "T1.ORDER_SEQ,T1.ORDER_SEQ_NO,MIN(T1.INSTOCK_TIME)";
        return this.getData(sql, parm.toArray());
    }

    public CoreReturnObject queryMatInfo1(ArrayList<Object> parm,
                                         String saleOrg,String suppUnit) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreOrderReport.queryMatInfo1");
        String str = "";
        if (saleOrg.equals("100101") || saleOrg.equals("100103")) {
            str = " AND T1.BELONG_CODE IN ('100101','100103')";
        }
        else if (saleOrg.equals("100102")) {
            str = " AND T1.BELONG_CODE  = '100102'";
        }
        if(!suppUnit.equals("")){
            sql+= " AND T1.SUPPLY_UNIT_CODE='" + suppUnit + "' ";
        }
        sql += str;
        sql += " GROUP BY T1.BELONG_CODE,T1.BELONG_NAME,T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.PRODUCT_FLAG,T1.MAT_STATUS,T1.SPEC_CODE,T1.SPEC_NAME,"
                + "T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,T1.PRODUCCODE,T1.PRODUCNAME,T1.MATERIAL_NO,T1.MATERIAL_NAME,T1.STEELCODE,T1.STEELNAME,T1.JUDGE_STD_NAME,"
                + "T1.STD_CODE,T1.STD_NAME,T1.ORDER_NO,T1.ORDER_SEQ,T1.ORDER_SEQ_NO,T1.ORD_PK,T1.ORD_LN_PK,T1.ORD_LN_DLY_PK,T1.PRO_ORDER_NO,T1.PRO_ORDER_ID,T1.LOCK_FLAG,T1.MNG_LOCK_FLAG,"
                + "T1.MEMO,T1.JUDGE_RESULT_CODE,T1.JUDGE_RESULT,T2.STORAGE_NO,T1.MODEL_CODE,T1.MODEL_DESC,T1.STD_STYLE,T1.STD_STYLE_DESC ORDER BY T1.JUDGE_STOVE_NO,T1.BATCH_NO,T1.BATCH_GROUD_NO,T1.ORDER_NO,"
                + "T1.ORDER_SEQ,T1.ORDER_SEQ_NO,MIN(T1.INSTOCK_TIME)";
        return this.getData(sql, parm.toArray());
    }

    /**
     * 判断是否利库
     * @param ordLnDlyPk
     * @return
     */
    public CoreReturnObject queryIsLiKu(String ordLnDlyPk) {
        Object[] obj = new Object[] { ordLnDlyPk };
        return this.getDataBySqlID("CoreOrderReport.queryIsLiKuByDlyPk", obj);
    }

    /**
     * 是否有可以利库的资源
     * @param parm
     * @return
     */
    public CoreReturnObject queryIsExistsMat(ArrayList<Object> parm,
            String saleOrg,String CustomInfo) {
    	parm.add(CustomInfo);
        parm.add(saleOrg);
        return this.getDataBySqlID("CoreOrderReport.queryIsExistsMat",
                parm.toArray());
    }

    /**
     * 更新利库标志
     * @param ordLnDlyPk
     * @param reviewMemo
     * @return
     */
    public CoreReturnObject updateLKFlag(String ordLnDlyPk, String reviewMemo) {
        Object[] obj = new Object[] { reviewMemo, "L", ordLnDlyPk };
        return this.setDataBySqlID("CoreOrderReport.updateLKFlag", obj);
    }

    /**
     * 查询利库状态
     * @param ordLnDlyPk
     * @return
     */
    public CoreReturnObject queryLKFlag(String ordLnDlyPk) {
        Object[] obj = new Object[] { ordLnDlyPk };
        return this.getDataBySqlID("CoreOrderReport.queryLKFlag", obj);
    }

    /**
     * 获取交货行的利库和脱单ID集合
     * @param ordLnDlyPk
     * @return
     */
    public CoreReturnObject queryDlyLkTd(String ordLnDlyPk) {
        Object[] obj = new Object[] { ordLnDlyPk };
        return this.getDataBySqlID("CoreOrderReport.queryDlyLkTd", obj);
    }

    /**
     * 判断利库是否审核
     * @param ordLnDlyPk
     * @param lkId
     * @return
     */
    public CoreReturnObject queryMatCheck(String ordLnDlyPk, String lkId) {
        Object[] obj = new Object[] { ordLnDlyPk, lkId };
        return this.getDataBySqlID("CoreOrderReport.queryMatCheck", obj);
    }

    /**
     * 判断是否全部生效
     * @param ordLnDlyPk
     * @param lkId
     * @return
     */
    public CoreReturnObject getAllEffect(String ordPk) {
        Object[] obj = new Object[] { ordPk };
        return this.getDataBySqlID("CoreOrderReport.queryAllEffect", obj);
    }
    
    /**
     * 获取工艺状态
     * @return
     */
    public CoreReturnObject getCraftState(String ordLnPk){
    	SqlBuilder b = new SqlBuilder("CoreOrderReport.getCraftState");
    	b.Fill(new String[]{ ordLnPk });
    	return this.getData(b.toString());
    }

    public CoreReturnObject UpdatePresentStatus(ArrayList<Object> pram) {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement ps = null;
        try {
            con.setAutoCommit(false);
            for (int i = 0; i < pram.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) pram.get(i);
                String update = " UPDATE SLM_ORDER_LINE_DELIVERY T SET T.PRESENT_STATUS=DECODE(?,'不可提报','1','可提报','2','') WHERE T.ORD_LN_DLY_PK=?";
                ps = con.prepareStatement(update);
                ps.setObject(1, list.get(1));
                ps.setObject(2, list.get(0));
                ps.executeUpdate();
                ps.close();
            }
            core.setV_errMsg("修改成功！");
            con.commit();
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (con != null)
                    con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return core;
    }
}