package com.steering.pss.ydm.pipemanage;

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

import com.steering.comm.HttpUrlConnectionUtil;
import com.steering.comm.LoggableStatement;
import com.steering.comm.UrlConfig;
import com.steering.comm.XsSql;
import com.google.gson.Gson;
import com.steering.comm.DefaultWebServiceRequest;
import com.steering.comm.ServiceToCx;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.data.ComBaseInfo;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.comm.tools.StringTool;
import com.steering.pss.judge.model.MatZcMEntity;
import com.steering.pss.judge.model.MatZcMSEntity;
import com.steering.pss.plnsaleord.order.model.PlnSaleordEntity;
import com.steering.pss.ydm.base.MeanValueCalculation;
import com.steering.pss.ydm.entity.QcmZgJugdeApplyEntity;
import com.steering.pss.ydm.entity.YdmZcChangebelongEntity;
import com.steering.pss.ydm.entity.YdmZcInlistEntity;

import net.sf.json.JSONObject;

import org.apache.commons.lang.time.DateFormatUtils;

import com.steering.pss.ydm.entity.YdmZcButtressEntity;

import net.sf.json.JSONArray;

import org.jboss.util.Strings;

import java.util.HashMap;	
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FrmFinishAfrim extends DBCommon{
	
	/***
	 * 查询判定数据
	 * @param list
	 * @param startTim
	 * @param endTim
	 * @param valueFlag
	 * @return
	 */
	public CoreReturnObject doQueryApplyJudge(ArrayList<String> list,String startTim,String endTim,String valueFlag,String[] arr,String supplyUnit
		,String orderNo)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.doQueryApplyJudge");
		if(!list.get(0).equals(""))
		{
			sql += " AND T.JUDGE_STOVE_NO = '"+list.get(0)+"'";
		}
		if(!StringUtils.isEmpty(orderNo))
		{
			sql += " AND T.PRO_ORDER_NO like '%"+orderNo+"%'";
		}
		if(!startTim.equals(""))
		{
			sql += " AND T.JUDGE_TOLRESULT_TIME >= TO_DATE('"+startTim+"','YYYY-MM-DD HH24:MI:SS') AND T.JUDGE_TOLRESULT_TIME <= TO_DATE('"+endTim+"','YYYY-MM-DD HH24:MI:SS') ";
		}
		if(!valueFlag.equals("")&&!valueFlag.equals("2"))
		{
			sql += " AND T.INSTOCK_FLAG = '"+valueFlag+"'";
		}
		sql += " AND T.SUPPLY_UNIT = '"+supplyUnit+"'";
		sql +=CoreConverter.toSqlConditionString("T.BELONG_CODE_JUGDE", arr);
		return this.getData(sql);
	}
	/***
	 * 查询缴库实绩
	 * @param list
	 * @param startTim
	 * @param endTim
	 * @param arr
	 * @return
	 */
	public CoreReturnObject doQueryInList(ArrayList<String> list,String startTim,String endTim,String[]arr ,String supplyUnit)
	{
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmFinishAfrim.doQueryInList");
		sql += CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
		if (!startTim.equals("")) {
			sql += " AND TRUNC(IN_TIME_F)>=TO_DATE('" + startTim
					+ "','YYYY-MM-DD') AND TRUNC(IN_TIME_F)<= TO_DATE('"
					+ endTim + "','YYYY-MM-DD')";
		}
		if (!list.get(0).equals("")) {
			sql += " AND T.JUDGE_STOVE_NO = '" + list.get(0) + "'";
		}
		if (!list.get(1).equals("")) {
			sql += " AND T.ORDER_NO = '" + list.get(1) + "'";
		}
		if (!list.get(2).equals("")) {
			sql += " AND T.BAL_YEAR_MONTH = '" + list.get(2) + "'";
		}
		if(supplyUnit.equals("120501"))
		{
			//sql += " AND (T.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T.SUPPLY_UNIT_CODE IS NULL)";
		}else if(supplyUnit.equals("120504")){
			sql += " AND T.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
		}
		sql += " group by t.JUDGE_STOVE_NO,t.BATCH_NO,t.INSTOCK_DOC,t.PRODUCCODE,t.PRODUCNAME,t.STD_CODE,t.STD_NAME,t.STEELCODE,t.STEELNAME,t.STD_STYLE,t.STD_STYLE_DESC,t.SPEC_CODE,t.SPEC_NAME,t.JUDGE_STD_CODE,t.JUDGE_STD_NAME,t.GRADECODE,t.GRADENAME,t.BAL_YEAR_MONTH,t.PIPMEMO,t.BATCH_GROUD_NO,T.ORD_LN_DLY_PK,T.STOVE_NO,T.LOT_NO,T.MATERIAL_NO,T.MATERIAL_NAME,T.PRO_ORDER_NO,T.STORAGE_NO,";
		sql += " t.MODEL_DESC,t.ACT_DIMATER,t.ACT_HEIGHT,t.ACT_LEN_MIN,t.ACT_LEN_MAX,t.BELONG_CODE,t.BELONG_NAME,s.STORAGE_NAME,t.MEMO,t.CREATE_NAME,t.ORDER_NO,t.ORDER_SEQ,t.DELIVERY_NO,t.MODEL_CODE,t.PRODUCT_FLAG,t.ZB_RCDID,t.PLINE_CODE,t.PLINE_NAME,d.SALE_AREA_DESC,d.create_name,m.basename,t.SUPPLY_UNIT,t.SUPPLY_UNIT_CODE,T.PROCESS_CDOE,T.PROCESS_DESC,D.ORDER_TYP_DESC,T.JUGDE_APPLY_CODE,T.INSTOCK_TYPE_CODE";
		sql += " order by t.instock_doc desc";

		return this.getData(sql);
	}
	/***
	 * 查询转移单数据
	 * @return
	 */
	public CoreReturnObject doQueryChangeData(ArrayList<String> list,String startTim,String endTim,String valueFlag,String[] arr)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.doQueryChangeData");
		if(!list.get(0).equals(""))
		{
			sql += " AND T.JUDGE_STOVE_NO = '"+list.get(0)+"'";
		}
		if(!startTim.equals(""))
		{
			sql += " AND T.CREATE_TIME >= TO_DATE('"+startTim+"','YYYY-MM-DD HH24:MI:SS') AND T.CREATE_TIME <= TO_DATE('"+endTim+"','YYYY-MM-DD HH24:MI:SS') ";
		}
		if(valueFlag.equals("0"))
		{
			sql += " AND T.FRIM_FLAG = '0'";
		}else if(valueFlag.equals("1"))
		{
			sql += " AND T.FRIM_FLAG IN('1','2')";
		}
		sql +=CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
		return this.getData(sql);
	}
	
	/***
	 * 查询排产合同号
	 * @param orderNo
	 * @param orderSeq
	 * @param ordLnDlnPk
	 * @return
	 */
	public CoreReturnObject doQueryOrderNo(String orderNo,String orderSeq,String ordLnDlnPk)
	{
		return this.getDataBySqlID("FrmFinishAfrim.doQueryOrderNo",new Object[]{orderNo,ordLnDlnPk});
	}
	
	/***
     * 获取合同下缴库总量、估算总量、订货总量
     * @param orderNo
     * @return
     */
    public CoreReturnObject getOrderWgt(String orderNo)
    {
    	return this.getDataBySqlID("FrmFinishAfrim.getOrderWgt", new Object[]{orderNo});
    }
    /***
     * 缴库
     * @param qcmEntity
     * @param orderEntity
     * @param parmList
     * @return
     */
    public CoreReturnObject doFrim(String qcmEntity,String orderEntity,ArrayList<String> parmList)
    {
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		String bathYear = df.format(now);
		String inStockDoc = "";// 入库单号
		String matCount = "0";
		String matNo = "";//材料号
		int payNum = 0;
		double payWgt = 0;
		double payLen = 0;
		String storageNo = "";
		String locationNo = "";
		String orderNo = "";
	/////TZH 10.30 ZL add
		List<YdmZcInlistEntity> ydmZcInlistEntities = new ArrayList<>();
		/////
		try {
			//connection.setAutoCommit(false);
			ArrayList<String> sqllist = new ArrayList<String>();
			QcmZgJugdeApplyEntity qcmZgEntity = EntityTool.getEntityByJSONStr(
					qcmEntity, QcmZgJugdeApplyEntity.class);
			inStockDoc = getInListDoc(connection, "800701");
			PlnSaleordEntity plnSaleEntity = EntityTool.getEntityByJSONStr(
					orderEntity, PlnSaleordEntity.class);
			SqlBuilder b = new SqlBuilder("QcmZgJugdeApplyDAL.QueryByBatchNo");
			b.Fill(new String[]{qcmZgEntity.getJugdeApplyCode(), qcmZgEntity.getJudgeStoveNo(), qcmZgEntity.getBatchNo()});
			com.steering.pss.judge.model.QcmZgJugdeApplyEntity judgeApply = EntityTool.getEntityBySqlNoClsCon(
					b.toString(), connection, com.steering.pss.judge.model.QcmZgJugdeApplyEntity.class);
			if (StringUtils.isEmpty(judgeApply.getJudgeTolresultCode())) {
				cro.setV_errMsg("此炉批没有成品判定结果，不能缴库！可能已撤销判定，请重新查询刷新数据！");
				return cro;
			}
			
	//tzh 24.11.12 加入状态判定
	
			
			String sqlL = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.QueryByLocation");
			sqlL = EntityTool.fillSqlByEntity(sqlL, qcmZgEntity);
 
			//System.out.print(qcmZgEntity.getJudgeStoveNo()+';'+qcmZgEntity.getJugdeApplyCode()+';'+qcmZgEntity.getJugdeApplySequeno());
			
			//System.out.print(qcmZgEntity.getBatchGroudNo()+';'+qcmZgEntity.getBatchNo());
			
				psta = connection.prepareStatement(sqlL);
				rs = psta.executeQuery();
				if(rs.next())
				{
					matCount = rs.getString("COUNT_L");
				}
			    rs.close();
				psta.close();
				if(Integer.parseInt(matCount) > 0)
				{
				cro.setV_errMsg("没有料位信息不允许缴库！");
				return cro;
				 }
				
				/////////
			
	

			boolean isFlagTh = false;
			if(!qcmZgEntity.getProcessCode().equals("H"))
			{
				sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectBcMatCount");//查询是否在途
				sql = EntityTool.fillSqlByEntity(sql, qcmZgEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					matCount = rs.getString("ACT_COUNT");
				}
				rs.close();
				psta.close();
//				if(Integer.parseInt(matCount) > 0)
//				{
//					cro.setV_errMsg("存在在途管材，不允许缴库!");
//					return cro;
//				}
				
				YdmZcInlistEntity ydmInListEntity = new YdmZcInlistEntity();
				ydmInListEntity.setInstockDoc(inStockDoc);
				ydmInListEntity.setProcessCdoe(qcmZgEntity.getProcessCode());
				ydmInListEntity.setJugdeApplyCode(qcmZgEntity.getJugdeApplyCode());
				ydmInListEntity.setJudgeStoveNo(qcmZgEntity.getJudgeStoveNo());
				ydmInListEntity.setBatchNo(qcmZgEntity.getBatchNo());
				ydmInListEntity.setBatchGroudNo(qcmZgEntity.getBatchGroudNo());
				ydmInListEntity.setInstockTypeCode("800701");
				ydmInListEntity.setInstockTypeName("产出入库");
				ydmInListEntity.setStorageNo(parmList.get(0));
				ydmInListEntity.setLocationNo(parmList.get(0) + "10101");
				ydmInListEntity.setLaryNo("1");
				ydmInListEntity.setFinishproMold(parmList.get(1));

				ydmInListEntity.setMemo(qcmZgEntity.getMemo());
				ydmInListEntity.setPackNo(parmList.get(2));
				ydmInListEntity.setPipmemo(parmList.get(3));
				ydmInListEntity.setCreateName(parmList.get(4));
				ydmInListEntity.setManagementNo(parmList.get(5));
				ydmInListEntity.setManagementName(parmList.get(6));
				ydmInListEntity.setDepartmentCode(parmList.get(7));
				ydmInListEntity.setDepartmentDesc(parmList.get(8));
				ydmInListEntity.setCreateTime(systime);
				ydmInListEntity.setBalYearMonth(qcmZgEntity.getBalYearMonth());
				ydmInListEntity.setBelongCode(qcmZgEntity.getBelongCodeJugde());
				ydmInListEntity.setBelongName(qcmZgEntity.getBelongNameJugde());
				ydmInListEntity.setInLengthType(qcmZgEntity.getInLengthType());
				ydmInListEntity.setOrderNo(plnSaleEntity.getOrderNo());
				ydmInListEntity.setOrderSeq(plnSaleEntity.getOrderSeq());
				ydmInListEntity.setDeliveryNo(plnSaleEntity.getDeliveryNo());
				ydmInListEntity.setOrdPk(plnSaleEntity.getOrdPk());
				ydmInListEntity.setOrdLnPk(plnSaleEntity.getOrdLnPk());
				ydmInListEntity.setOrdLnDlyPk(plnSaleEntity.getOrdLnDlyPk());
				if(Integer.parseInt(parmList.get(9))>=0)
				{
					ydmInListEntity.setProductFlag("801403");
					ydmInListEntity.setMatStatus("80150301");
					ydmInListEntity.setInMold("801703");
					// 方案2 修改mat_zc_m,ydm_zc_inlist合同信息
					if(plnSaleEntity.getOrderNo().startsWith("TH")){ // 天淮成品合同（缴库改为天管合同）
						b = new SqlBuilder("FrmFinishAfrim.getCustmOrderNoByOrderNo");
						b.Fill(new String[]{plnSaleEntity.getOrderNo(),plnSaleEntity.getOrderSeq(),plnSaleEntity.getDeliveryNo()});
						YdmZcInlistEntity ydmEntity =EntityTool.getEntityBySqlNoClsCon(b.toString(), connection,  YdmZcInlistEntity.class);
						if(ydmEntity != null) {
							isFlagTh = true;
							ydmInListEntity.setOrderNo(ydmEntity.getOrderNo());
							ydmInListEntity.setOrderSeq(ydmEntity.getOrderSeq());
							ydmInListEntity.setDeliveryNo(ydmEntity.getDeliveryNo());
							ydmInListEntity.setOrdPk(ydmEntity.getOrdPk());
							ydmInListEntity.setOrdLnPk(ydmEntity.getOrdLnPk());
							ydmInListEntity.setOrdLnDlyPk(ydmEntity.getOrdLnDlyPk());
							ydmInListEntity.setBelongCode(ydmEntity.getBelongCode());
							ydmInListEntity.setBelongName(ydmEntity.getBelongName());
						}
					}
				}else 
				{
					ydmInListEntity.setProductFlag("801402");
					ydmInListEntity.setMatStatus("80150202");
					ydmInListEntity.setInMold("801702");
					
				}
//				if(qcmZgEntity.getIsAllScrap().equals("离线转压库")||qcmZgEntity.getIsAllScrap().equals("余材转压库"))
//				{
//					ydmInListEntity.setInMold("801705");
//				}
//				if(qcmZgEntity.getInLengthType().equals("短尺"))
//				{
//					ydmInListEntity.setInMold("801707");
//				}
//				if(qcmZgEntity.getInLengthType().equals("长尺"))
//				{
//					ydmInListEntity.setInMold("801706");
//				}
				
				ydmInListEntity.setActCount(qcmZgEntity.getActCount());
	            ydmInListEntity.setJudgeResultTime(qcmZgEntity.getJudgeResultTime());
	            ydmInListEntity.setZbRcdid(qcmZgEntity.getJugdeTolconvicted());
				ydmInListEntity.setFrmCount(parmList.get(9));
				ydmInListEntity.setSpecCode(plnSaleEntity.getSpecCode());
				ydmInListEntity.setSpecName(plnSaleEntity.getSpecName());
	            ydmInListEntity.setJugdeApplySequeno(qcmZgEntity.getJugdeApplySequeno());
	            ydmInListEntity.setStorageNo(parmList.get(0));

				ydmInListEntity.setSupplyUnit(qcmZgEntity.getSupplyUnitDesc());
				ydmInListEntity.setSupplyUnitCode(qcmZgEntity.getSupplyUnit());
				ydmInListEntity.setIsAllScrap(qcmZgEntity.getIsAllScrap());
                orderNo = ydmInListEntity.getOrderNo();
				sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectBcMatCount1");//查半成品支数
				sql = EntityTool.fillSqlByEntity(sql, qcmZgEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					matCount = rs.getString("ACT_COUNT");
				}
				rs.close();
				psta.close();
				if(Integer.parseInt(matCount) < Integer.parseInt(ydmInListEntity.getActCount()))
				{
					cro.setV_errMsg("库存与判定支数不一致，不允许缴库!");
					return cro;
				}
				/////TZH 10.30 ZL add
				ydmZcInlistEntities.add(ydmInListEntity);
				/////
				
				String insertInListSql = CoreXmlSqlParsersFactory
						.getSql("FrmFinishAfrim.insertInList");
				if(isFlagTh){
					// 方案2 修改mat_zc_m,ydm_zc_inlist合同信息
					String updatePlnSaleord = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updatePlnSaleord1");
					updatePlnSaleord = EntityTool.fillSqlByEntity(updatePlnSaleord, plnSaleEntity);
					insertInListSql = insertInListSql.replaceAll("#UPDATE_PLNSALEORD_TH#",updatePlnSaleord);
				} else {
					insertInListSql = insertInListSql.replaceAll("#UPDATE_PLNSALEORD_TH#","");
				}
				insertInListSql = EntityTool.fillSqlByEntity(insertInListSql,
						ydmInListEntity);
				System.out.println(insertInListSql);
				sqllist.add(insertInListSql);
				
				// 方案1 只修改mat_zc_m合同信息
//				if(plnSaleEntity.getOrderNo().startsWith("TH")){ // 天淮成品合同（缴库改为天管合同）
//					SqlBuilder b = new SqlBuilder("FrmFinishAfrim.getCustmOrderNoByOrderNo");
//					b.Fill(new String[]{plnSaleEntity.getOrderNo(),plnSaleEntity.getOrderSeq(),plnSaleEntity.getDeliveryNo()});
//					YdmZcInlistEntity ydmEntity =EntityTool.getEntityBySqlNoClsCon(b.toString(), connection,  YdmZcInlistEntity.class);
//					if(ydmEntity != null){
//						ydmEntity.setJugdeApplyCode(qcmZgEntity.getJugdeApplyCode());
//						ydmEntity.setJugdeApplySequeno(qcmZgEntity.getJugdeApplySequeno());
//						ydmEntity.setJudgeStoveNo(qcmZgEntity.getJudgeStoveNo());
//						ydmEntity.setBatchNo(qcmZgEntity.getBatchNo());
//						ydmEntity.setBatchGroudNo(qcmZgEntity.getBatchGroudNo());
////						ydmEntity.setMatNo(ydmInListEntity.getMatNo());
//						String updateMatZcMOrder = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateMatZcMOrder");//修改材料表合同
//						updateMatZcMOrder = EntityTool.fillSqlByEntity(updateMatZcMOrder, ydmEntity);
//						updateMatZcMOrder += "AND T1.MAT_NO = MYROW.MAT_NO";
////						sqllist.add(updateMatZcMOrder);
//						insertInListSql = insertInListSql.replaceAll("#UPDATE_MAT_ZC#",updateMatZcMOrder);
//					}
//				} else {
//					insertInListSql = insertInListSql.replaceAll("#UPDATE_MAT_ZC#","");
//				}
			}
			else
			{
				sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectButtress");
				sql = EntityTool.fillSqlByEntity(sql,qcmZgEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					storageNo = rs.getString("STORAGE_NO");
					locationNo = rs.getString("LOCATION_NO");
				}
				rs.close();
				psta.close();
				int Num = 0;
				matNo = queryMatNoM1(connection, qcmZgEntity.getJudgeStoveNo(), qcmZgEntity.getBatchNo());
				int g = Integer.parseInt(matNo.substring(matNo.length() - 4, matNo.length()));
				String inListSeq = querySendSql(connection,inStockDoc); //入库流水号
                int n = Integer.parseInt(inListSeq.substring(inListSeq.length() - 4, inListSeq.length()));
                List<double[]> list = MeanValueCalculation.MeanCalculation(
                        Double.parseDouble(qcmZgEntity.getActWeight()), Integer
                                .parseInt(qcmZgEntity.getActCount()));
                ArrayList<String> lengthList = null;
                if(!qcmZgEntity.getActLen().equals(""))
                {
                	lengthList = new ArrayList<String>();
                    List<double[]> lenList = MeanValueCalculation.MeanCalculation(Double.parseDouble(qcmZgEntity.getActLen()), Integer.parseInt(qcmZgEntity.getActCount()));
                    for(int k = 0;k<lenList.size();k++)
                    {
                    	double[] conLen = lenList.get(k);
                    	if((int)conLen[0]>0)
                    	{
                    		for(int x = 0;x<(int)conLen[0];x++)
                    		{
                    			DecimalFormat dt = new DecimalFormat("0.000");
                    			lengthList.add(dt.format(conLen[1]));
                    		}
                    	}
                    }
                }
                for (int j = 0; j < list.size(); j++) {
                    double[] conW = list.get(j);
                    if ((int) conW[0] >= 0) {
						for (int z = 0; z < (int) conW[0]; z++) {
							YdmZcInlistEntity ydmZcJgEntity = new YdmZcInlistEntity();
							ydmZcJgEntity.setInstockSqe(inStockDoc
						                + StringTool.formatDecimal(n, "0000"));
							ydmZcJgEntity.setInstockDoc(inStockDoc);
							ydmZcJgEntity.setMatNo((qcmZgEntity.getJudgeStoveNo() + qcmZgEntity.getBatchNo())
					                + StringTool.formatDecimal(g, "0000"));
						
							ydmZcJgEntity.setProcessCdoe(qcmZgEntity.getProcessCode());
							ydmZcJgEntity.setJugdeApplyCode(qcmZgEntity.getJugdeApplyCode());
							ydmZcJgEntity.setJugdeApplySequeno(qcmZgEntity.getJugdeApplySequeno());
							ydmZcJgEntity.setJudgeStoveNo(qcmZgEntity.getJudgeStoveNo());
							ydmZcJgEntity.setBatchNo(qcmZgEntity.getBatchNo());
							ydmZcJgEntity.setBatchGroudNo(qcmZgEntity.getBatchGroudNo());
							ydmZcJgEntity.setInstockTypeCode("800701");
							ydmZcJgEntity.setInstockTypeName("产出入库");
							ydmZcJgEntity.setStorageNo(storageNo);
							ydmZcJgEntity.setLocationNo(locationNo);
							ydmZcJgEntity.setLaryNo("1");
							ydmZcJgEntity.setActCount("1");
							ydmZcJgEntity.setActWeight(String.valueOf(conW[1]));
							if(!qcmZgEntity.getActLen().equals(""))
							{
								ydmZcJgEntity.setActLen(String.valueOf(lengthList.get(Num)));
							}
							else
							{
								ydmZcJgEntity.setActLen("");
							}
							
							ydmZcJgEntity.setMemo(qcmZgEntity.getJudgeTolmemo());
							ydmZcJgEntity.setPackNo(parmList.get(2));
							ydmZcJgEntity.setPipmemo(parmList.get(3));
							ydmZcJgEntity.setCreateName(parmList.get(4));
							ydmZcJgEntity.setManagementNo(parmList.get(5));
							ydmZcJgEntity.setManagementName(parmList.get(6));
							ydmZcJgEntity.setDepartmentCode(parmList.get(7));
							ydmZcJgEntity.setDepartmentDesc(parmList.get(8));
							ydmZcJgEntity.setCreateTime(systime);
							ydmZcJgEntity.setBalYearMonth(qcmZgEntity.getBalYearMonth());

							ydmZcJgEntity.setSupplyUnit(qcmZgEntity.getSupplyUnitDesc());
							ydmZcJgEntity.setSupplyUnitCode(qcmZgEntity.getSupplyUnit());
							
							if(Integer.parseInt(parmList.get(9)) > 0 && Num < Integer.parseInt(parmList.get(9)))
							{
								ydmZcJgEntity.setProductFlag("801403");
								ydmZcJgEntity.setMatStatus("80150301");
								ydmZcJgEntity.setOrderNo(plnSaleEntity.getOrderNo());
								ydmZcJgEntity.setOrderSeq(plnSaleEntity.getOrderSeq());
								ydmZcJgEntity.setDeliveryNo(plnSaleEntity.getDeliveryNo());
								ydmZcJgEntity.setOrdPk(plnSaleEntity.getOrdPk());
								ydmZcJgEntity.setOrdLnPk(plnSaleEntity.getOrdLnPk());
								ydmZcJgEntity.setOrdLnDlyPk(plnSaleEntity.getOrdLnDlyPk());
								ydmZcJgEntity.setInMold("801703");
								ydmZcJgEntity.setInType("802205");
								
								payWgt = payWgt + conW[1];
								if(!qcmZgEntity.getActLen().equals(""))
								{
									payLen = payLen + Double.parseDouble(lengthList.get(Num));
								}else
								{
									payLen = 0;
								}
								
								payNum = payNum + 1;
							
							}
							else
							{
								ydmZcJgEntity.setProductFlag("801402");
								ydmZcJgEntity.setMatStatus("80150202");
								ydmZcJgEntity.setOrderNo("");
								ydmZcJgEntity.setOrderSeq("");
								ydmZcJgEntity.setDeliveryNo("");
								ydmZcJgEntity.setOrdPk("");
								ydmZcJgEntity.setOrdLnPk("");
								ydmZcJgEntity.setOrdLnDlyPk("");
								ydmZcJgEntity.setInMold("801702");
								ydmZcJgEntity.setInType("802201");
							}

							sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectJgZbs");
							psta = connection.prepareStatement(sql);
							psta.setObject(1,qcmZgEntity.getJugdeApplyCode());
							rs = psta.executeQuery();
							if(rs.next())
							{
								ydmZcJgEntity.setZbsId(rs.getString("ZBS_ID"));
								ydmZcJgEntity.setZbsFlag(rs.getString("ZBS_FLAG"));
							}
							rs.close();
							psta.close();

							ydmZcJgEntity.setIsAllScrap(qcmZgEntity.getIsAllScrap());
							/////TZH 10.30 ZL add
							ydmZcInlistEntities.add(ydmZcJgEntity);
							/////
							String insertYdmJgSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.insertInListJG");
							insertYdmJgSql = EntityTool.fillSqlByEntity(insertYdmJgSql, ydmZcJgEntity);
							sqllist.add(insertYdmJgSql);
							Num++;
							g++;
							n++;
						}
					}
                }
                YdmZcInlistEntity ydmEntity = new YdmZcInlistEntity();
                ydmEntity.setJugdeApplyCode(qcmZgEntity.getJugdeApplyCode());
                ydmEntity.setJugdeApplySequeno(qcmZgEntity.getJugdeApplySequeno());
                ydmEntity.setJudgeStoveNo(qcmZgEntity.getJudgeStoveNo());
                ydmEntity.setBatchNo(qcmZgEntity.getBatchNo());
                ydmEntity.setBatchGroudNo(qcmZgEntity.getBatchGroudNo());
                ydmEntity.setOrderNo(plnSaleEntity.getOrderNo());
                ydmEntity.setOrderSeq(plnSaleEntity.getOrderSeq());
                ydmEntity.setDeliveryNo(plnSaleEntity.getDeliveryNo());
                ydmEntity.setOrdPk(plnSaleEntity.getOrdPk());
                ydmEntity.setOrdLnPk(plnSaleEntity.getOrdLnPk());
                ydmEntity.setOrdLnDlyPk(plnSaleEntity.getOrdLnDlyPk());
                
                ydmEntity.setCreateName(parmList.get(4));
                ydmEntity.setManagementNo(parmList.get(5));
                ydmEntity.setManagementName(parmList.get(6));
                ydmEntity.setDepartmentCode(parmList.get(7));
                ydmEntity.setDepartmentDesc(parmList.get(8));
                ydmEntity.setCreateTime(systime);
                ydmEntity.setBalYearMonth(qcmZgEntity.getBalYearMonth());
                ydmEntity.setPayNum(String.valueOf(payNum));
                ydmEntity.setPayLen(String.valueOf(payLen));
                ydmEntity.setPayWgt(String.valueOf(payWgt));
                
                String deleteMatSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.deleteJg");
                deleteMatSql = EntityTool.fillSqlByEntity(deleteMatSql, ydmEntity);
                sqllist.add(deleteMatSql);
			}
			
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			String json = doExectObjectJson(plnSaleEntity,qcmZgEntity.getJudgeStoveNo(),psta,connection, "I",qcmZgEntity.getJugdeApplyCode()+qcmZgEntity.getJugdeApplySequeno(),qcmZgEntity.getBatchNo());
			DefaultWebServiceRequest request = new DefaultWebServiceRequest();
			//System.out.println(json);
			if(json==null||json.equals("null")||json.equals("[]")){
				cro.setV_errMsg("接口信息上传失败，请联系技术人员处理！");
				cro.setResult(1);
				connection.rollback();
				return cro;
			}
			Gson gson =  new Gson();
		    request.setServiceId("MESTHPM010");
		 	request.setMsgBody(json);
			String result = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx",request,
						"receiveMessage","");
			// ps 执行日志表插入：
			psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
			psta.setString(1, "MESTHPM010");
			psta.setString(2, json);
			psta.setString(3, plnSaleEntity.getOrderNo()+plnSaleEntity.getOrderSeq()+"-"+qcmZgEntity.getJudgeStoveNo());
			psta.setString(4, result);
			psta.execute();
		   if(!result.equals("200")) {
			   cro.setV_errMsg("接口信息上传失败！");
			   cro.setResult(1);
			   connection.rollback();
				return cro;
		   }
//			if (cro.getV_errMsg().equals("")) {
//				cro.setV_errMsg("缴库成功!");
//			}
			/////TZH 10.30 ZL add
				if (cro.getV_errMsg().equals("")) {
					//调用接口传递数据
					try {
						String sql0 = "select count(1) cut from slm_order_head t where customer_nm like '%天津钢管%' and order_no = ?";
						psta = connection.prepareStatement(sql0);
						psta.setString(1,plnSaleEntity.getOrderNo());
						rs = psta.executeQuery();
						if(rs.next()){
							String string = rs.getString(1);
							if(Integer.parseInt(string)>0){
								String str = "";
								for (YdmZcInlistEntity ydmZcInlistEntity : ydmZcInlistEntities) {
									str += "'"+ydmZcInlistEntity.getMatNo()+"',";
								}
								str = str.substring(0,str.length()-1);
								String sql1 = "select * from mat_zc_m t where t.mat_no in ("+str+")";
								psta = connection.prepareStatement(sql1);
								rs = psta.executeQuery();
								ArrayList<MatZcMEntity> matZcMEntities = EntityTool.getEntitysByRs(rs,
										MatZcMEntity.class);
								sql1 = "select * from YDM_ZC_BUTTRESS t where t.mat_no in ("+str+")";
								psta = connection.prepareStatement(sql1);
								rs = psta.executeQuery();
								ArrayList<YdmZcButtressEntity> ydmZcButtressEntities = EntityTool.getEntitysByRs(rs,
										YdmZcButtressEntity.class);
								HashMap<String,Object> map = new HashMap<>();
								map.put("ydmZcButtresses",ydmZcButtressEntities);
								map.put("ydmZcInlists",ydmZcInlistEntities);
								map.put("matZcMS",matZcMEntities);
								HttpUrlConnectionUtil.post(UrlConfig.BASE_URL+"/v1/matZcM/add",map);
								// ps 执行日志表插入：
								psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
								psta.setString(1, "matZcM/add");
								psta.setString(2, JSONObject.fromObject(map).toString());
								psta.setString(3, plnSaleEntity.getOrderNo()+plnSaleEntity.getOrderSeq()+"-"+qcmZgEntity.getJudgeStoveNo());
								psta.setString(4, "操作成功");
								psta.execute();
							}
						}
					}catch (Exception e){
						// ps 执行日志表插入：
						psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
						psta.setString(1, "matZcM/add");
						psta.setString(2, e.toString());
						psta.setString(3, plnSaleEntity.getOrderNo()+plnSaleEntity.getOrderSeq()+"-"+qcmZgEntity.getJudgeStoveNo());
						psta.setString(4, "操作失败");
						psta.execute();
						e.printStackTrace();
					}

					cro.setV_errMsg("缴库成功!");
				}
			/////
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					cro.setV_errMsg(e.getMessage());
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    
    private String doExectObjectJson(PlnSaleordEntity entity,String judgeStoveNo,PreparedStatement psta,Connection connection,String flag
    		,String JugdeApplyCode,String BatchNo) {
    	if(entity.getOrderNo().equals("") || null == entity.getOrderNo()) {
    		return null;
    	}
    	String orderNo = entity.getOrderNo(); 
    	if (orderNo != null && orderNo.length() > 2) {
    		orderNo = orderNo.substring(2); 
    	}
    	String returnJosn = null;
    	String sql = "SELECT T.INSTOCK_DOC,\n" +
    			"       T.INSTOCK_TYPE_CODE,\n" +
    			"       T.INSTOCK_TYPE_NAME,\n" +
    			"       T.INSTOCK_BAR_CODE,\n" +
    			"       T.ICCAR_NO,\n" +
    			"       T.VEHICLE_NO,\n" +
    			"       T.MAT_NO,\n" +
    			"       T.LOT_NO,\n" +
    			"       T.STOVE_NO,\n" +
    			"       T.JUDGE_STOVE_NO,\n" +
    			"       T.BATCH_NO,\n" +
    			"       T.BATCH_GROUD_NO,\n" +
    			"       T.MATERIAL_NO,\n" +
    			"       T.MATERIAL_NAME,\n" +
    			"       T.PRODUCCODE,\n" +
    			"       T.PRODUCNAME,\n" +
    			"       T.STD_CODE,\n" +
    			"       T.STD_NAME,\n" +
    			"       T.GRADECODE,\n" +
    			"       T.GRADENAME,\n" +
    			"       T.STEELCODE,\n" +
    			"       T.STEELNAME,\n" +
    			"       T.STD_STYLE,\n" +
    			"       T.STD_STYLE_DESC,\n" +
    			"       T.SPEC_CODE,\n" +
    			"       T.SPEC_NAME,\n" +
    			"       T.MODEL_CODE,\n" +
    			"       T.MODEL_DESC,\n" +
    			"       T.PRO_ORDER_NO,\n" +
    			"       T.PLINE_CODE,\n" +
    			"       T.PLINE_NAME,\n" +
    			"       T.ACT_DIMATER,\n" +
    			"       T.ACT_HEIGHT,\n" +
    			"       T.ACT_LEN,\n" +
    			"       T.ACT_LEN_MIN,\n" +
    			"       T.ACT_LEN_MAX,\n" +
    			"       T.ACT_COUNT,\n" +
    			"       T.ACT_WEIGHT,\n" +
    			"       T.ACT_THEORY_WEIGHT,\n" +
    			"       T.BELONG_CODE,\n" +
    			"       T.BELONG_NAME,\n" +
    			"       T.STORAGE_NO,\n" +
    			"       T.LOCATION_NO,\n" +
    			"       T.LARY_NO,\n" +
    			"       T.LOC_NO,\n" +
    			"       T.STORAGE_ATTR,\n" +
    			"       T.STORAGE_ATTR_NAME,\n" +
    			"       T.STORAGE_TYPE_NO,\n" +
    			"       T.STORAGE_TYPE_NAME,\n" +
    			"       T.MANAGEMENT_NO,\n" +
    			"       T.MANAGEMENT_NAME,\n" +
    			"       T.RPO_TIME,\n" +
    			"       T.PRO_BC,\n" +
    			"       T.PRO_BZ,\n" +
    			"       T.INSTOCK_TIME,\n" +
    			"       T.IN_BC,\n" +
    			"       T.IN_BZ,\n" +
    			"       T.BAR_CODE,\n" +
    			"       T.HAND_FLAG,\n" +
    			"       T.MEMO,\n" +
    			"       T.VALIDFLAG,\n" +
    			"       T.CREATE_NAME,\n" +
    			"       T.CREATE_TIME,\n" +
    			"       T.UPDATE_NAME,\n" +
    			"       T.UPDATE_TIME,\n" +
    			"       T.DELETE_NAME,\n" +
    			"       T.DELETE_TIME,\n" +
    			"       T.ORD_PK,\n" +
    			"       T.ORD_LN_PK,\n" +
    			"       T.ORD_LN_DLY_PK,\n" +
    			"       T.DEPARTMENT_CODE,\n" +
    			"       T.DEPARTMENT_DESC,\n" +
    			"       T.ORDER_NO,\n" +
    			"       T.ORDER_SEQ,\n" +
    			"       T.DELIVERY_NO,\n" +
    			"       T.PRODUCT_FLAG,\n" +
    			"       T.MAT_STATUS,\n" +
    			"       T.ZB_RCDID,\n" +
    			"       T.JUDGE_STD_NAME,\n" +
    			"       T.JUDGE_STD_CODE,\n" +
    			"       T.IN_TIME_F,\n" +
    			"       T.BAL_YEAR_MONTH,\n" +
    			"       T.LEN_NO,\n" +
    			"       T.LEN_DESC,\n" +
    			"       T.LEN_UNIT,\n" +
    			"       T.PIPMEMO,\n" +
    			"       T.SOURE_CODE,\n" +
    			"       T.SOURE_NAME,\n" +
    			"       T.MAT_ORIGIN_CODE,\n" +
    			"       T.MAT_ORIGIN_NAME,\n" +
    			"       T.AFFIRM_LOG,\n" +
    			"       T.M_BILL_NO,\n" +
    			"       T.ZG_STOVE_SQE,\n" +
    			"       T.FINISHPRO_MOLD,\n" +
    			"       T.IN_MOLD,\n" +
    			"       T.PACK_NO,\n" +
    			"       T.QCM_STAUS,\n" +
    			"       T.PRO_PLAN_ID,\n" +
    			"       T.GX_PLAN_NO,\n" +
    			"       T.SUBCONTRACT_NO,\n" +
    			"       T.JUGDE_APPLY_CODE,\n" +
    			"       T.SUPPLY_UNIT_CODE,\n" +
    			"       T.SUPPLY_UNIT,\n" +
    			"       T.IS_DEALER,\n" +
    			"       T.PROCESS_CDOE,\n" +
    			"       T.PROCESS_DESC,\n" +
    			"       T.IS_ALL_SCRAP,\n" +
    			"       T.IN_TYPE,\n" +
    			"       nvl(aa.act_count, 0) nojk,\n" +
    			"       nvl(bb.act_count, 0)+nvl(aa.act_count, 0) alljk\n" + //前面提供的总支数缺少了剩余支数 考虑到可能是在同一事务中 入库还没修改  需要加一下
    			"  FROM YDM_ZC_INLIST T\n" +
    			"  LEFT JOIN YDM_BS_STORAGE S\n" +
    			"    ON T.STORAGE_NO = S.STORAGE_NO\n" +
    			"  LEFT JOIN SLM_ORDER_HEAD D\n" +
    			"    ON T.ORD_PK = D.ORD_PK\n" +
    			"  LEFT JOIN (SELECT M.PLINE_CODE, G.BASENAME\n" +
    			"               FROM COM_BASE_PLINE M, COM_BASE_INFO G\n" +
    			"              WHERE M.GROUP_PAY = G.BASECODE) M\n" +
    			"    ON M.PLINE_CODE = T.PLINE_CODE\n" +
    			"  left join (select sum(t.act_count) act_count, T.Judge_Stove_No\n" +
    			"               from QCM_ZG_JUGDE_APPLY t\n" +
    			"              WHERE T.IS_FLAG = '0'\n" +
    			"                AND T.IS_ALL_SCRAP IN ('0', '6', '7', '8')\n" +
    			"                AND T.TARGET = 'A'\n" +
    			"                AND T.JUDGE_TOLRESULT_CODE IN ('40740701', '40740709')\n" +
    			"                AND T.INSTOCK_FLAG = '0'\n" +
    			"                AND T.SUPPLY_UNIT = '120504'\n" +
    			"                AND T.BELONG_CODE_JUGDE IN ('100101', '100102', '100105')\n" +
    			"              group by t.Judge_Stove_No) aa\n" +
    			"    on aa.Judge_Stove_No = t.judge_stove_no\n" +
    			"  left join (select sum(t.act_count) act_count, T.Judge_Stove_No\n" +
    			"               from YDM_ZC_INLIST t\n" +
    			"              WHERE (T.INSTOCK_TYPE_CODE = '800701' OR\n" +
    			"                    (T.INSTOCK_TYPE_CODE = '800704' and T.memo = '过磅'))\n" +
    			"                AND T.HAND_FLAG = '0'\n" +
    			"                AND T.BELONG_CODE IN ('100101', '100102', '100105')\n" +
    			"                AND T.SUPPLY_UNIT_CODE = '120504'\n" +
    			"              group by t.Judge_Stove_No) bb\n" +
    			"    on bb.Judge_Stove_No = t.judge_stove_no\n" +
    			" WHERE (T.INSTOCK_TYPE_CODE = '800701' OR\n" +
    			"       (T.INSTOCK_TYPE_CODE = '800704' and T.memo = '过磅'))\n" +
    			"   AND T.HAND_FLAG = '0'\n" +
    			"   AND T.BELONG_CODE IN ('100101', '100102', '100105')\n" +
    			"   AND (T.ORDER_NO like '%"+orderNo+"' or T.Pro_Order_No  like '%"+orderNo+"%') \r\n" +
    			"   AND T.JUDGE_STOVE_NO = '"+judgeStoveNo+"'\r\n" +
    			"   AND T.jugde_apply_code = '"+JugdeApplyCode+"'\r\n" +
    			"   AND T.batch_no = '"+BatchNo+"'\r\n" +
    			"   AND T.SUPPLY_UNIT_CODE = '120504'\n" +
    			" group by s.STORAGE_NAME,\n" +
    			"          d.SALE_AREA_DESC,\n" +
    			"          d.create_name,\n" +
    			"          m.basename,\n" +
    			"          D.ORDER_TYP_DESC,\n" +
    			"          T.INSTOCK_SQE,\n" +
    			"          T.INSTOCK_DOC,\n" +
    			"          T.INSTOCK_TYPE_CODE,\n" +
    			"          T.INSTOCK_TYPE_NAME,\n" +
    			"          T.INSTOCK_BAR_CODE,\n" +
    			"          T.ICCAR_NO,\n" +
    			"          T.VEHICLE_NO,\n" +
    			"          T.MAT_NO,\n" +
    			"          T.LOT_NO,\n" +
    			"          T.STOVE_NO,\n" +
    			"          T.JUDGE_STOVE_NO,\n" +
    			"          T.BATCH_NO,\n" +
    			"          T.BATCH_GROUD_NO,\n" +
    			"          T.MATERIAL_NO,\n" +
    			"          T.MATERIAL_NAME,\n" +
    			"          T.PRODUCCODE,\n" +
    			"          T.PRODUCNAME,\n" +
    			"          T.STD_CODE,\n" +
    			"          T.STD_NAME,\n" +
    			"          T.GRADECODE,\n" +
    			"          T.GRADENAME,\n" +
    			"          T.STEELCODE,\n" +
    			"          T.STEELNAME,\n" +
    			"          T.STD_STYLE,\n" +
    			"          T.STD_STYLE_DESC,\n" +
    			"          T.SPEC_CODE,\n" +
    			"          T.SPEC_NAME,\n" +
    			"          T.MODEL_CODE,\n" +
    			"          T.MODEL_DESC,\n" +
    			"          T.PRO_ORDER_NO,\n" +
    			"          T.PLINE_CODE,\n" +
    			"          T.PLINE_NAME,\n" +
    			"          T.ACT_DIMATER,\n" +
    			"          T.ACT_HEIGHT,\n" +
    			"          T.ACT_LEN,\n" +
    			"          T.ACT_LEN_MIN,\n" +
    			"          T.ACT_LEN_MAX,\n" +
    			"          T.ACT_COUNT,\n" +
    			"          T.ACT_WEIGHT,\n" +
    			"          T.ACT_THEORY_WEIGHT,\n" +
    			"          T.BELONG_CODE,\n" +
    			"          T.BELONG_NAME,\n" +
    			"          T.STORAGE_NO,\n" +
    			"          T.LOCATION_NO,\n" +
    			"          T.LARY_NO,\n" +
    			"          T.LOC_NO,\n" +
    			"          T.STORAGE_ATTR,\n" +
    			"          T.STORAGE_ATTR_NAME,\n" +
    			"          T.STORAGE_TYPE_NO,\n" +
    			"          T.STORAGE_TYPE_NAME,\n" +
    			"          T.MANAGEMENT_NO,\n" +
    			"          T.MANAGEMENT_NAME,\n" +
    			"          T.RPO_TIME,\n" +
    			"          T.PRO_BC,\n" +
    			"          T.PRO_BZ,\n" +
    			"          T.INSTOCK_TIME,\n" +
    			"          T.IN_BC,\n" +
    			"          T.IN_BZ,\n" +
    			"          T.BAR_CODE,\n" +
    			"          T.HAND_FLAG,\n" +
    			"          T.MEMO,\n" +
    			"          T.VALIDFLAG,\n" +
    			"          T.CREATE_NAME,\n" +
    			"          T.CREATE_TIME,\n" +
    			"          T.UPDATE_NAME,\n" +
    			"          T.UPDATE_TIME,\n" +
    			"          T.DELETE_NAME,\n" +
    			"          T.DELETE_TIME,\n" +
    			"          T.ORD_PK,\n" +
    			"          T.ORD_LN_PK,\n" +
    			"          T.ORD_LN_DLY_PK,\n" +
    			"          T.DEPARTMENT_CODE,\n" +
    			"          T.DEPARTMENT_DESC,\n" +
    			"          T.ORDER_NO,\n" +
    			"          T.ORDER_SEQ,\n" +
    			"          T.DELIVERY_NO,\n" +
    			"          T.PRODUCT_FLAG,\n" +
    			"          T.MAT_STATUS,\n" +
    			"          T.ZB_RCDID,\n" +
    			"          T.JUDGE_STD_NAME,\n" +
    			"          T.JUDGE_STD_CODE,\n" +
    			"          T.IN_TIME_F,\n" +
    			"          T.BAL_YEAR_MONTH,\n" +
    			"          T.LEN_NO,\n" +
    			"          T.LEN_DESC,\n" +
    			"          T.LEN_UNIT,\n" +
    			"          T.PIPMEMO,\n" +
    			"          T.SOURE_CODE,\n" +
    			"          T.SOURE_NAME,\n" +
    			"          T.MAT_ORIGIN_CODE,\n" +
    			"          T.MAT_ORIGIN_NAME,\n" +
    			"          T.AFFIRM_LOG,\n" +
    			"          T.M_BILL_NO,\n" +
    			"          T.ZG_STOVE_SQE,\n" +
    			"          T.FINISHPRO_MOLD,\n" +
    			"          T.IN_MOLD,\n" +
    			"          T.PACK_NO,\n" +
    			"          T.QCM_STAUS,\n" +
    			"          T.PRO_PLAN_ID,\n" +
    			"          T.GX_PLAN_NO,\n" +
    			"          T.SUBCONTRACT_NO,\n" +
    			"          T.JUGDE_APPLY_CODE,\n" +
    			"          T.SUPPLY_UNIT_CODE,\n" +
    			"          T.SUPPLY_UNIT,\n" +
    			"          T.IS_DEALER,\n" +
    			"          T.PROCESS_CDOE,\n" +
    			"          T.PROCESS_DESC,\n" +
    			"          T.IS_ALL_SCRAP,\n" +
    			"          T.IN_TYPE,\n" +
    			"          aa.act_count,\n" +
    			"          bb.act_count\n" +
    			" order by t.instock_doc desc\n";
    	try {
			psta = connection.prepareStatement(sql);
			ResultSet rs = psta.executeQuery();
			List<YdmZcInlistEntity> ydmZcInlistEntities=  EntityTool.getEntitysByRs(rs, YdmZcInlistEntity.class);
			 List<JSONObject> objects = new ArrayList<>();
			 for (YdmZcInlistEntity  ydmInListEntity: ydmZcInlistEntities) {
				 JSONObject jsonObj = new JSONObject();
					jsonObj.put("form_code", "MESTHPM010");
					jsonObj.put("form_name", "缴库");
					jsonObj.put("form_time", ydmInListEntity.getCreateTime());
					jsonObj.put("operate_flag", flag);
					jsonObj.put("mat_no", ydmInListEntity.getMatNo());
					jsonObj.put("pack_no",ydmInListEntity.getPackNo() );
					jsonObj.put("in_stock_code", ydmInListEntity.getInstockSqe());
					jsonObj.put("in_stock_name", "");
					jsonObj.put("in_stock_area", "");
					jsonObj.put("in_stock_loca", "");
					jsonObj.put("in_stock_floor", "");
					jsonObj.put("mat_netwt", ydmInListEntity.getActWeight());
					jsonObj.put("mat_grosswt", "");
					jsonObj.put("mat_theorywt", ydmInListEntity.getActTheoryWeight());
					jsonObj.put("mat_actwt", ydmInListEntity.getActWeight());
					jsonObj.put("mat_discrepwt", "");
					jsonObj.put("mat_num", ydmInListEntity.getActCount());
					jsonObj.put("mat_kind", ydmInListEntity.getMaterialName());
					jsonObj.put("mat_thick", ydmInListEntity.getActHeight());
					jsonObj.put("mat_width", ydmInListEntity.getActDimater());
					jsonObj.put("mat_len", ydmInListEntity.getActLen());
					jsonObj.put("order_no", ydmInListEntity.getOrderNo());
					jsonObj.put("order_detail_no", ydmInListEntity.getOrderSeq());
					jsonObj.put("stacking_no", "");
					jsonObj.put("product_code", "");
					jsonObj.put("product_name", "");
					jsonObj.put("wt_mode", "");
					jsonObj.put("export_flag", "");
					jsonObj.put("consign_user_code", "");
					jsonObj.put("consign_user_name", "");
					jsonObj.put("order_cust_code", "");
					jsonObj.put("order_cust_cname", "");
					jsonObj.put("balance_user_code", "");
					jsonObj.put("balance_user_name", "");
					jsonObj.put("mat_move_status", "");
					jsonObj.put("psc", "");
					jsonObj.put("prod_code", ydmInListEntity.getProduccode());
					jsonObj.put("prod_cname", ydmInListEntity.getProducname());
					jsonObj.put("sgsign", ydmInListEntity.getGradename());
					jsonObj.put("complex_decide_code", "");
					jsonObj.put("sample_lotno", "");
					jsonObj.put("stno", "");
					jsonObj.put("pack_type_code", "");
					jsonObj.put("carrier_no", "");
					jsonObj.put("red_cause_code", "");
					jsonObj.put("red_cause_desc", "");
					jsonObj.put("msc", "");
					jsonObj.put("apn", "");
					jsonObj.put("heat_treat_no", "");
					jsonObj.put("company_code", "");
					jsonObj.put("cust_mat_specs", ydmInListEntity.getSpecName());
					jsonObj.put("prod_class_code", ydmInListEntity.getProductFlag());
					jsonObj.put("prod_class_desc", "");
					jsonObj.put("proc_status", "");
					jsonObj.put("matqty", "");
					jsonObj.put("spec", "");
					jsonObj.put("msc_lineno", "");
					jsonObj.put("len_from", ydmInListEntity.getActLenMin());
					jsonObj.put("lento", ydmInListEntity.getActLenMax());
					jsonObj.put("complex_decide_maker", ydmInListEntity.getCreateName());
					jsonObj.put("statuc", "J");
					jsonObj.put("heat_no", ydmInListEntity.getStoveNo());
					jsonObj.put("lineNo", ydmInListEntity.getJudgeStoveNo()+ydmInListEntity.getBatchNo());
					jsonObj.put("lot_no", ydmInListEntity.getBatchNo());
					jsonObj.put("ready_time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					jsonObj.put("stockCode", ydmInListEntity.getStorageNo());
					jsonObj.put("remainNum", ydmInListEntity.getNojk());
					jsonObj.put("totalNum", ydmInListEntity.getAlljk());
					jsonObj.put("finishFlag", ydmInListEntity.getNojk().equals("0")?"1":"0");
					jsonObj.put("steelNo", ydmInListEntity.getSteelname());
					//2025.06.25 新增 lrl
					jsonObj.put("modelCode",ydmInListEntity.getModelCode());
					jsonObj.put("modelDesc",ydmInListEntity.getModelDesc());
					jsonObj.put("sgStd", ydmInListEntity.getStdName());
					objects.add(jsonObj);
			}
			 returnJosn = objects.toString();
			 return returnJosn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnJosn;
    	
    }
    private String querySendSql(Connection connection, String inStockDoc) throws SQLException {
    	int seq = 0;
        String inListDocSeq = "";
         PreparedStatement psta = null;
         Date dt = new Date();
         SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmFinishAfrim.getInListDoc1");
        psta = connection.prepareStatement(sqlLovsqe);
        psta.setString(1, inStockDoc);
        psta.setString(2, inStockDoc);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {

        	inListDocSeq = rs.getString("INSTOCK_SQE");
        }
        rs.close();
        psta.close();
        return inListDocSeq;
	}
	/**
     * 根据炉号、批号自动生成材料号
     * @param conn c
     * @param strLcode 传递参数
     * @return obj
     * @throws Exception 异常处理
     */
    public String queryMatNoM1(Connection conn, String strLcode, String strBatch)
            throws Exception {
        String matNo = "";
        PreparedStatement psta = null;
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmFinishAfrim.QueryMatNoM1");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1, strLcode);
        psta.setString(2, strBatch);
        psta.setString(3, strLcode);
        psta.setString(4, strBatch);
        psta.setString(5, strLcode);
        psta.setString(6, strBatch);
        psta.setString(7, strLcode);
        psta.setString(8, strBatch);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
        	matNo = rs.getString("MAT_NO");
        }
        rs.close();
        psta.close();
        return matNo;
    }
    
    
    /***
     * 撤销确认
     * @param parmList
     * @return
     */
    public CoreReturnObject canceDoFrim(ArrayList<String> parmList)
    {
    	CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		String bathYear = df.format(now);
		int matCount = 0;
		String SYNC_FLAG = "0";
		try {
			//connection.setAutoCommit(false);
			ArrayList<String> sqllist = new ArrayList<String>();
			/////TZH 10.30 ZL add
			ArrayList<String> matNos = new ArrayList<>();
			String orderNo = "";
			//////
			for(String str : parmList)
			{
				YdmZcInlistEntity ydmInListEntity = EntityTool.getEntityByJSONStr(str, YdmZcInlistEntity.class);
				/////TZH 10.30 ZL add
				orderNo = ydmInListEntity.getOrderNo();
				if(orderNo.equals("")){
					orderNo = ydmInListEntity.getProOrderNo().substring(0, ydmInListEntity.getProOrderNo().indexOf("/"));
				}
				//////
				if(ydmInListEntity.getProductFlag().equals("成品"))
				{
					ydmInListEntity.setProductFlag("801402");
				}else
				{
					ydmInListEntity.setProductFlag("801403");
				}
				if(!ydmInListEntity.getProducname().contains("成品接箍"))
				{
					sql  = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectMatCount");
					sql = EntityTool.fillSqlByEntity(sql,ydmInListEntity);
					psta = connection.prepareStatement(sql);
					rs = psta.executeQuery();
					if(rs.next())
					{
						matCount = Integer.parseInt(rs.getString("ACOUNT"));
					}
					rs.close();;
					psta.close();;
					/*PlnSaleordEntity plnSaleEntity = new PlnSaleordEntity();
					plnSaleEntity.setOrderNo(ydmInListEntity.getOrderNo());
					String json = doExectObjectJson(plnSaleEntity,ydmInListEntity.getJudgeStoveNo(),psta,connection,"D");
					DefaultWebServiceRequest request = new DefaultWebServiceRequest();
					System.out.println(json);
					Gson gson =  new Gson();
					   request.setServiceId("MESTHPM010");
			            request.setMsgBody(json);
			            String result = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx",request,
								"receiveMessage",json);	
				    if(!result.equals("200")) {
						  cro.setV_errMsg("接口信息上传失败！");
						  cro.setResult(1);
						  connection.rollback();
						  return cro;
					}*/
					if(Integer.parseInt(ydmInListEntity.getActCount()) >matCount)
					{
						cro.setV_errMsg("库存支数与缴库支数不符,不能撤销!");
						return  cro;
					}

					if(ydmInListEntity.getProductFlag().equals("801403"))
					{
						sql  = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectMatBill");
						sql = EntityTool.fillSqlByEntity(sql,ydmInListEntity);
						psta = connection.prepareStatement(sql);
						rs = psta.executeQuery();
						if(rs.next())
						{
							matCount = Integer.parseInt(rs.getString("ACOUNT"));
						}
						rs.close();;
						psta.close();;
						if(matCount > 0)
						{
							cro.setV_errMsg("库存有已编提单支数,不能撤销!");
							return  cro;
						}
					}

				}
				ydmInListEntity.setCreateTime(systime);
				if(ydmInListEntity.getProducname().contains("成品接箍"))
				{
					//查询财务系统同步信息
					sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectSyncFlagZcIn");
	                sql = EntityTool.fillSqlByEntity(sql, ydmInListEntity);
	                psta = connection.prepareStatement(sql);
	                rs = psta.executeQuery();
	                if(rs.next())
	                {
	                	SYNC_FLAG = rs.getString("SYNC_FLAG");
	                }
	                rs.close();
	                psta.close();
	                if (SYNC_FLAG.equals("1")) {
	                	cro.setV_errMsg("财务系统同步成品入库信息，请联系财务撤销同步信息!");
	    				return cro;
	    			}
	                String cancelSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.deleteFmisZcIn");
	            	cancelSql = EntityTool.fillSqlByEntity(cancelSql, ydmInListEntity);
	            	sqllist.add(cancelSql);
	            	
					String deleteJgMatSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.canceDoFrimJG");
					deleteJgMatSql = EntityTool.fillSqlByEntity(deleteJgMatSql, ydmInListEntity);
					sqllist.add(deleteJgMatSql);
				}else
				{
					//查询财务系统同步信息
					sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectSyncFlagZcIn");
	                sql = EntityTool.fillSqlByEntity(sql, ydmInListEntity);
	                psta = connection.prepareStatement(sql);
	                rs = psta.executeQuery();
	                if(rs.next())
	                {
	                	SYNC_FLAG = rs.getString("SYNC_FLAG");
	                }
	                rs.close();
	                psta.close();
	                if (SYNC_FLAG.equals("1")) {
	                	cro.setV_errMsg("财务系统同步坯料出库信息，请联系财务撤销同步信息!");
	    				return cro;
	    			}
	                String cancelSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.deleteFmisZcIn");
	            	cancelSql = EntityTool.fillSqlByEntity(cancelSql, ydmInListEntity);
	            	sqllist.add(cancelSql);
	            	
					String deleteMatSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.canceDoFrim");
					deleteMatSql = EntityTool.fillSqlByEntity(deleteMatSql, ydmInListEntity);
					// 查询是否为天管给天淮的成品合同  
					SqlBuilder b = new SqlBuilder("FrmFinishAfrim.getOrderNoByCustmOrderNo");
					b.Fill(new String[]{ydmInListEntity.getOrderNo(),ydmInListEntity.getOrderSeq(),ydmInListEntity.getDeliveryNo()});
					YdmZcInlistEntity ydmEntity =EntityTool.getEntityBySqlNoClsCon(b.toString(), connection,  YdmZcInlistEntity.class);
					/////
					PlnSaleordEntity plnSaleEntity = new PlnSaleordEntity();
					plnSaleEntity.setOrderNo(orderNo);
					String json = doExectObjectJson(plnSaleEntity,ydmInListEntity.getJudgeStoveNo(),psta,connection,"D",ydmInListEntity.getJugdeApplyCode(),ydmInListEntity.getBatchNo());
					DefaultWebServiceRequest request = new DefaultWebServiceRequest();
					System.out.println(json);
					if(json==null||json.equals("null")||json.equals("[]")){
						cro.setV_errMsg("接口信息上传失败，请联系技术人员处理！");
						cro.setResult(1);
						connection.rollback();
						return cro;
					}
					Gson gson =  new Gson();
				   	request.setServiceId("MESTHPM010");
					request.setMsgBody(json);
					String result = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx",request,
								"receiveMessage","");
					// ps 执行日志表插入：
					psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
					psta.setString(1, "MESTHPM010");
					psta.setString(2, json);
					psta.setString(3, plnSaleEntity.getOrderNo()+plnSaleEntity.getOrderSeq()+"-"+ydmInListEntity.getJudgeStoveNo());
					psta.setString(4, result);
					psta.execute();
				    if(!result.equals("200")) {
						  cro.setV_errMsg("接口信息上传失败！");
						  cro.setResult(1);
						  connection.rollback();
						  return cro;
					}
					if(ydmEntity == null || !ydmEntity.getOrderNo().startsWith("TH")){
						deleteMatSql = deleteMatSql.replaceAll("#UPDATE_PLNSALEORD_TH#","");
						sqllist.add(deleteMatSql);
		                System.out.println(deleteMatSql);
						continue;
					}
					// 修改天淮合同排产信息
					String updatePlnSaleord = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updatePlnSaleord");
					updatePlnSaleord = EntityTool.fillSqlByEntity(updatePlnSaleord, ydmEntity);
					deleteMatSql = deleteMatSql.replaceAll("#UPDATE_PLNSALEORD_TH#",updatePlnSaleord);
					sqllist.add(deleteMatSql);
	                System.out.println(deleteMatSql);
				}
				/////TZH 10.30 ZL add
				matNos.add(ydmInListEntity.getMatNo());
				
			}
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
//			new SQLException("");
//			if(cro.getV_errMsg().equals(""))
//			{
//				cro.setV_errMsg("撤销成功!");
//			}
			/////TZH 10.30 ZL add
			if(cro.getV_errMsg().equals(""))
			{
				try {
					String sql0 = "select count(1) cut from slm_order_head t where customer_nm like '%天津钢管%' and order_no = ?";
					psta = connection.prepareStatement(sql0);
					psta.setString(1,orderNo);
					rs = psta.executeQuery();
					if(rs.next()){
						String string = rs.getString(1);
						if(Integer.parseInt(string)>0){
							//调用接口传递数据
							HttpUrlConnectionUtil.post(UrlConfig.BASE_URL+"/v1/matZcM/delete",matNos);
							// ps 执行日志表插入：
							psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
							psta.setString(1, "matZcM/delete");
							psta.setString(2, JSONArray.fromObject(matNos).toString());
							psta.setString(3, Strings.join(matNos.toArray(),","));
							psta.setString(4, "操作成功");
							psta.execute();
						}
					}
					cro.setV_errMsg("撤销成功!");
				} catch (Exception e) {
					// ps 执行日志表插入：
					psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
					psta.setString(1, "matZcM/delete");
					psta.setString(2, e.toString());
					psta.setString(3, Strings.join(matNos.toArray(),","));
					psta.setString(4, "操作失败");
					psta.execute();
					e.printStackTrace();
				}
			}
		/////
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					cro.setV_errMsg(e.getMessage());
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    
    /***
     * 调整结转年月
     * @param parmList
     * @return
     */
    public CoreReturnObject updateCarryOverDate(ArrayList<String> parmList)
    {
    	CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		String bathYear = df.format(now);
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for(String str : parmList)
			{
				YdmZcInlistEntity ydmInListEntity = EntityTool.getEntityByJSONStr(str, YdmZcInlistEntity.class);
				if(ydmInListEntity.getProductFlag().equals("商品"))
				{
					ydmInListEntity.setProductFlag("801403");
				}else
				{
					ydmInListEntity.setProductFlag("801402");
				}
				String updateInListSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateCarryOverDate");
				updateInListSql = EntityTool.fillSqlByEntity(updateInListSql, ydmInListEntity);
				sqllist.add(updateInListSql);
			}
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			if(cro.getV_errMsg().equals(""))
			{
				cro.setV_errMsg("调整成功!");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					cro.setV_errMsg(e.getMessage());
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    /***
     * 获取实时期末库存
     */
    public CoreReturnObject getRealTimeStore(String[] arr,String bathYear,String custom)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.getRealTimeStore");
    	String str  = CoreConverter.toSqlConditionString("F.BELONG_CODE", arr);
    	String str1  = CoreConverter.toSqlConditionString("T1.BELONG_CODE", arr);
    	sql = sql.replace("#CONDITIONS#", str);
    	sql = sql.replace("#CONDITIONS1#", str1);
    	sql = sql.replace("#CUSTOM#",custom);
    	sql = sql.replace("#BAL_YEAR_MONTH#",bathYear);
    	return this.setData(sql,new Object[]{bathYear});
    }
    /***
     * 查询是否有期初数据
     * @param arr
     * @param bathYear
     * @return
     */
    public CoreReturnObject selectNowInial(String[] arr,String bathYear)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectNowInial");
    	sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
    	return this.getData(sql, new Object[]{bathYear});
    }
    /**
     * 库存查询
     * @param pram 参数
     * @return 平台统一返回对象
     */
    public CoreReturnObject queryMat(ArrayList<String> pram,String[] arr,String startTim,String endTim,String supplyUnit) {
		String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.QUERYMAT");
		sql += CoreConverter.toSqlConditionString("T1.BELONG_CODE", arr);
		if (!startTim.equals("")) {
			sql += " AND T1.INSTOCK_TIME >=TO_DATE('"
					+ startTim
					+ "', 'YYYY-MM-DD HH24:MI:SS')AND T1.INSTOCK_TIME <=TO_DATE('"
					+ endTim + "', 'YYYY-MM-DD HH24:MI:SS')";
		}
		if(!pram.get(0).equals(""))
		{
			sql += " AND T1.JUDGE_STOVE_NO = '"+pram.get(0)+"'"; 
		}
		if(!pram.get(1).equals(""))
		{
			sql += " AND T1.ORDER_NO = '"+pram.get(1)+"'";
		}
		if(supplyUnit.equals("120501"))
		{
			sql += " AND (T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T1.SUPPLY_UNIT_CODE IS NULL)";
		}else if(supplyUnit.equals("120504")){
			sql += " AND T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
		}
		sql += " GROUP BY T1.JUDGE_STOVE_NO, T1.BATCH_NO, T1.BATCH_GROUD_NO,T1.PRODUCCODE,T1.PRODUCNAME,T1.STEELCODE,T1.STEELNAME,T1.SPEC_CODE,T1.SPEC_NAME,T1.MODEL_CODE,T1.GRADECODE,T1.GRADENAME,T1.STD_STYLE,T1.STD_STYLE_DESC,T1.PIPMEMO,T1.OLD_ORDER_NO,T1.MAT_STATUS,";
		sql += " T1.MODEL_DESC,T1.STD_CODE,T1.STD_NAME,T1.ORDER_NO,T1.ORDER_SEQ,T1.ORDER_SEQ_NO,T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.LEN_NO,T1.LEN_DESC,T1.LEN_UNIT,T1.BELONG_CODE,T1.BELONG_NAME,T1.PLINE_CODE,T1.PLINE_NAME,T1.BAL_YEAR_MONTH,T1.FINISHPRO_MOLD,T1.IN_MOLD,T1.IN_TYPE,";
		sql += " T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,T1.CREATE_NAME,T2.STORAGE_NO,S.STORAGE_NAME,T1.MEMO,T1.PRODUCT_FLAG,T1.JUDGE_STD_CODE,T1.JUDGE_STD_NAME,T1.SUPPLY_UNIT,T1.SUPPLY_UNIT_CODE  ORDER BY T1.BAL_YEAR_MONTH DESC";

        return this.getData(sql);
    }

	public CoreReturnObject SelectMatNo1(ArrayList<Object> parm) {
		String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.SelectMatNo1");
		return this.getData(sql,parm.toArray());
	}

	public CoreReturnObject SelectMatNo2(String jsonStr) {
		JSONObject json = JSONObject.fromObject(jsonStr);
		com.steering.pss.ydm.entity.MatZcMEntity matZcMEntity = (com.steering.pss.ydm.entity.MatZcMEntity) JSONObject
				.toBean(json, com.steering.pss.ydm.entity.MatZcMEntity.class);
		String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.SelectMatNo2");
		sql = EntityTool.fillSqlByEntity(sql, matZcMEntity);
		return this.getData(sql);
	}

	/***
	 * 修改入库备注
	 * @param
	 * @return
	 */
	public CoreReturnObject updatePipMemo1(ArrayList<ArrayList<Object>> list) {
		ArrayList<String> sqllist = new ArrayList<String>();
		ArrayList<Object[]> params = new ArrayList<Object[]>();
		for (ArrayList<Object> o : list) {
			String sql = CoreXmlSqlParsersFactory
					.getSql("FrmFinishAfrim.updatePipMemo");
			Object[] param = o.toArray();
			sqllist.add(sql);
			params.add(param);
		}
		return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist, params);
	}

    /***
     * 修改入库备注
     * @param parm
     * @return
     */
    public CoreReturnObject updatePipMemo(ArrayList<Object> parm)
    {
    	CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
     
        ArrayList<String> list = new ArrayList<String>();
        String sqlupdate="";
        try {
        	 connection.setAutoCommit(false); // 取消自动提交事务
			for (int i = 0; i < parm.size(); i++) {
				list = (ArrayList<String>)parm.get(i);
				 ArrayList<String> matNo = new ArrayList<String>();//保存材料号
				String strSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.SelectMatNo");
				psta = connection.prepareStatement(strSql);
				psta.setString(1, list.get(4));
				psta.setString(2, list.get(5));
				psta.setString(3, list.get(6));
				psta.setString(4, list.get(7));
				psta.setString(5, list.get(8));
				psta.setString(6, list.get(9));
				//psta.setString(7, new DecimalFormat("0.00").format(Double.parseDouble(list.get(11))));
				//psta.setString(8, new DecimalFormat("0.00").format(Double.parseDouble(list.get(12))));
				psta.setString(7, list.get(13));
				psta.setString(8, list.get(14));
				psta.setString(9, list.get(15));
				psta.setString(10, list.get(16));
				psta.setString(11,list.get(17));
				ResultSet rs =  psta.executeQuery();
				while(rs.next())
				{
					matNo.add(rs.getString(1));
				}
				rs.close();
				psta.close();
				if(matNo.size()>0)
				{
					for(int j=0;j<matNo.size();j++)
					{
						String sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updatePipMemo");
						psta = connection.prepareStatement(sql);
						psta.setString(1, list.get(0));
						psta.setString(2, matNo.get(j));
						psta.executeUpdate();
						psta.close();
					}
				}else
				{
					cro.setV_errMsg("此炉【"+list.get(4)+"】已做提单计划,不允许修改入库备注!");
					return cro;
				}
			}
			cro.setResult(1);
			cro.setV_errMsg("修改成功!");
			connection.commit();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    /***
     * 转移所属权
     * @param parmList
     * @return
     */
	public CoreReturnObject updateBelong(ArrayList<ArrayList<String>> parmList,String userName,String belongCode,String belongName)
	{
		return updateBelong(parmList,userName,belongCode,belongName,"");
	}
    public CoreReturnObject updateBelong(ArrayList<ArrayList<String>> parmList,String userName,String belongCode,String belongName,String customInfo)
    {
    	CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		//String bathYear = df.format(now);
		String bathYear = "120504".equals(customInfo)? ComBaseInfo.GetBalYear_2416(now): ComBaseInfo.GetBalYear(now);
		String inDoc = "";
		String outDoc = "";
        try {
        	ArrayList<String> sqllist = new ArrayList<String>();
        	inDoc = getInListDoc(connection, "800712");
        	outDoc = getOutListDoc(connection, "800812");
        	for(int i = 0;i<parmList.size();i++)
        	{
        		if(parmList.get(i).get(6).equals("商品"))
        		{
        			cro.setV_errMsg("只允许成品转移所属权!");
        			return cro;
        		}
        		YdmZcChangebelongEntity ydmZcChangEntity = new YdmZcChangebelongEntity();
        		ydmZcChangEntity.setJudgeStoveNo(parmList.get(i).get(0));
        		ydmZcChangEntity.setBatchNo(parmList.get(i).get(1));
        		ydmZcChangEntity.setBatchGroudNo(parmList.get(i).get(2));
        		ydmZcChangEntity.setActCount(parmList.get(i).get(3));
        		ydmZcChangEntity.setCreateName(userName);
        		ydmZcChangEntity.setBalYearMonth(bathYear);
        		ydmZcChangEntity.setCreateTime(systime);
        		ydmZcChangEntity.setBelongCodeBefor(parmList.get(i).get(4));//转移前所属权
        		ydmZcChangEntity.setBelongNameBefor(parmList.get(i).get(5));
        		ydmZcChangEntity.setBelongCode(belongCode);//转移后所属权
        		ydmZcChangEntity.setBelongName(belongName);
        		
        		
        		String insertYdmBelongSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.insertChangeBelong");
        		insertYdmBelongSql = EntityTool.fillSqlByEntity(insertYdmBelongSql, ydmZcChangEntity);
        		sqllist.add(insertYdmBelongSql);
        		
        	}
        	cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
        	if(cro.getV_errMsg().equals(""))
        	{
        		cro.setV_errMsg("转移成功!");
        	}
        } catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    /***
     * 修改库存位置
     * @param parm
     * @return
     */
    public CoreReturnObject updateStoreNo(ArrayList<Object> parm)
    {
    	CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
     
        ArrayList<String> list = new ArrayList<String>();
        String sqlupdate="";
        try {
        	 connection.setAutoCommit(false); // 取消自动提交事务
        	 String updateStoreSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateStoreNo");
        	 PreparedStatement updateStorepsta = connection.prepareStatement(updateStoreSql);
        	 String updateButessSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateButessStoreNo");
        	 PreparedStatement updateButesspsta = connection.prepareStatement(updateButessSql);
			for (int i = 0; i < parm.size(); i++) {
				list = (ArrayList<String>)parm.get(i);
				 ArrayList<String> matNo = new ArrayList<String>();//保存材料号
				String strSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.SelectMatNo");
				psta = connection.prepareStatement(strSql);
//				psta.setString(1, list.get(1));
//				psta.setString(2, list.get(2));
//				psta.setString(3, list.get(3));
				psta.setString(1, list.get(4));
				psta.setString(2, list.get(5));
				psta.setString(3, list.get(6));
				//psta.setString(4, list.get(7));
				psta.setString(4, list.get(7));
				psta.setString(5, list.get(8));
				psta.setString(6, list.get(9));
				psta.setString(7, list.get(13));
				psta.setString(8, list.get(14));
				psta.setString(9, list.get(15));
				psta.setString(10, list.get(16));
				psta.setString(11,list.get(17));
				//psta.setString(11, list.get(15));
				ResultSet rs =  psta.executeQuery();
				while(rs.next())
				{
					matNo.add(rs.getString(1));
				}
				rs.close();
				psta.close();
				if(matNo.size()>0)
				{
					for(int j=0;j<matNo.size();j++)
					{
						updateStorepsta.setString(1, list.get(0));
						updateStorepsta.setString(2, matNo.get(j));
						updateStorepsta.addBatch();
						
						updateButesspsta.setString(1, list.get(0));
						updateButesspsta.setString(2, list.get(0)+"10101");
						updateButesspsta.setString(3, matNo.get(j));
						updateButesspsta.addBatch();
					}
				}else
				{
					cro.setV_errMsg("此炉【"+list.get(4)+"】已做提单计划,不允许修改库存地!");
					return cro;
				}
			}
			cro.setResult(1);
			updateStorepsta.executeBatch();
			updateButesspsta.executeBatch();
			connection.commit();
			cro.setV_errMsg("修改成功!");
		} catch (SQLException e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    /***
     * 修改成品区分
     * @param parm
     * @return
     */
    public CoreReturnObject updateFinishedProduct(ArrayList<ArrayList<String>> parm)
    {
    	CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        ArrayList<String> list = new ArrayList<String>();
        try {
        	 connection.setAutoCommit(false); // 取消自动提交事务
        	 String updateProductSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateFinishedProduct");
        	 PreparedStatement updateProductPsta = connection.prepareStatement(updateProductSql);
			for (int i = 0; i < parm.size(); i++) {
				list = (ArrayList<String>)parm.get(i);
				updateProductPsta.setString(1, list.get(0));
				updateProductPsta.setString(2, list.get(1));
				updateProductPsta.setString(3, list.get(2));
				updateProductPsta.setString(4, list.get(3));
				updateProductPsta.setString(5, list.get(4));
				updateProductPsta.setString(6, list.get(5));
				updateProductPsta.setString(7, list.get(6));
				updateProductPsta.addBatch();
			}
			updateProductPsta.executeBatch();
			cro.setV_errMsg("修改成功!");
			connection.commit();
        } catch (SQLException e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    
    /***
     * 审批通过
     * @param ydmTity
     * @param userName
     * @return
     */
	public CoreReturnObject changePass(String ydmTity,String userName)
	{
		return changePass(ydmTity,userName,"");
	}
    public CoreReturnObject changePass(String ydmTity,String userName,String customInfo)
    {
    	CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        ResultSet rs = null;
        String sql  = "";
        String flag = "";
        String inDoc = "";
        String outDoc = "";
        Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		//String bathYear = df.format(now);
		String bathYear = "120504".equals(customInfo)? ComBaseInfo.GetBalYear_2416(now): ComBaseInfo.GetBalYear(now);
        ArrayList<String> sqllist = new ArrayList<String>();
        try {
        	YdmZcChangebelongEntity ydmEntity = EntityTool.getEntityByJSONStr(ydmTity, YdmZcChangebelongEntity.class);
        	sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectBelongFlag");
        	sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
        	psta = connection.prepareStatement(sql);
        	rs = psta.executeQuery();
        	if(rs.next())
        	{
        		flag = rs.getString("FRIM_FLAG");
        	}
        	rs.close();
        	psta.close();
        	if(!flag.equals("0"))
        	{
        		cro.setV_errMsg("此转移单已审批,不允许再次审批!");
        		return cro;
        	}
        	inDoc = getInListDoc(connection, "800712");
        	outDoc = getOutListDoc(connection, "800812");
    		MatZcMEntity matZcEntity =  new MatZcMEntity();
    		matZcEntity.setJudgeStoveNo(ydmEntity.getJudgeStoveNo());
    		matZcEntity.setBatchNo(ydmEntity.getBatchNo());
    		matZcEntity.setBatchGroudNo(ydmEntity.getBatchGroudNo());
    		matZcEntity.setActCount(ydmEntity.getActCount());
    		matZcEntity.setBalYearMonth(bathYear);
    		matZcEntity.setCreateTime(systime);
    		matZcEntity.setInstockDoc(inDoc);
    		matZcEntity.setOutstockDoc(outDoc);
    		matZcEntity.setBelongCode(ydmEntity.getBelongCodeBefor());
    		matZcEntity.setBelongName(ydmEntity.getBelongNameBefor());
    		matZcEntity.setSbelongCode(ydmEntity.getBelongCode());
    		matZcEntity.setSbelongName(ydmEntity.getBelongName());
    		matZcEntity.setCreateName(userName);
    		matZcEntity.setChangeDoc(ydmEntity.getChangeDoc());
    		String updateBelongSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateBelong");
    		updateBelongSql = EntityTool.fillSqlByEntity(updateBelongSql, matZcEntity);
    		sqllist.add(updateBelongSql);
        	
    		cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
    		if(cro.getV_errMsg().equals(""))
    		{
    			cro.setV_errMsg("审批成功!");
    		}
        	
        	
        } catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    
    /***
     * 审批通过
     * @param ydmTity
     * @param userName
     * @return
     */
    public CoreReturnObject changeNoPass(String ydmTity,String userName)
    {
    	CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        ResultSet rs = null;
        String sql  = "";
        String flag = "";
        String inDoc = "";
        String outDoc = "";
        Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		String bathYear = df.format(now);
        ArrayList<String> sqllist = new ArrayList<String>();
        try {
        	YdmZcChangebelongEntity ydmEntity = EntityTool.getEntityByJSONStr(ydmTity, YdmZcChangebelongEntity.class);
        	sql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.selectBelongFlag");
        	sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
        	psta = connection.prepareStatement(sql);
        	rs = psta.executeQuery();
        	if(rs.next())
        	{
        		flag = rs.getString("FRIM_FLAG");
        	}
        	rs.close();
        	psta.close();
        	if(!flag.equals("0"))
        	{
        		cro.setV_errMsg("此转移单已审批,不允许再次审批!");
        		return cro;
        	}
        	ydmEntity.setFrimName(userName);
    		String updateChangeSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateChange");
    		updateChangeSql = EntityTool.fillSqlByEntity(updateChangeSql, ydmEntity);
    		sqllist.add(updateChangeSql);
        	
    		cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
    		if(cro.getV_errMsg().equals(""))
    		{
    			cro.setV_errMsg("审批成功!");
    		}
        	
        	
        } catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
    }
    
    /***
	 * 获取入库单号
	 * 
	 * @param conn
	 * @param strInbound
	 * @return
	 * @throws SQLException
	 */
	public String getInListDoc(Connection conn, String strInbound)
			throws SQLException {
		String inListDoc = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmFinishAfrim.getInListDoc");
		PreparedStatement psta = conn.prepareStatement(sql);
		psta.setString(1, strInbound);
		psta.setString(2, strInbound);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			inListDoc = rs.getString("INSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return inListDoc;
	}
	
	/***
	 * 获取出库单号
	 * 
	 * @param conn
	 * @param
	 * @return
	 * @throws SQLException
	 */
	public String getOutListDoc(Connection conn, String strOutbound)
			throws SQLException {
		String outListDoc = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmFinishAfrim.getOutListDoc");
		PreparedStatement psta = conn.prepareStatement(sql);
		psta.setString(1, strOutbound);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			outListDoc = rs.getString("OUTSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return outListDoc;
	}

	/***
	 * 确认接收
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doQRJSH(String json,String userName)
	{
		CoreReturnObject cro = new CoreReturnObject();
		ArrayList<String> sqllist = new ArrayList<String>();
		try {
			com.steering.pss.judge.model.QcmZgJugdeApplyEntity entity = EntityTool.getEntityByJSONStr(json, com.steering.pss.judge.model.QcmZgJugdeApplyEntity.class);
			entity.setInStorageFlag("1");
			entity.setInStorageConfirm(userName);
			entity.setInStorageTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));

			String updateSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateInStorageFlag");
			updateSql = EntityTool.fillSqlByEntity(updateSql, entity);
			sqllist.add(updateSql);

			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			if(cro.getV_errMsg().equals(""))
			{
				cro.setV_errMsg("确认接收成功!");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
		}
		return cro;
	}

	/***
	 * 取消接收
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doQXJSH(String json,String userName)
	{
		CoreReturnObject cro = new CoreReturnObject();
		ArrayList<String> sqllist = new ArrayList<String>();
		try {
			com.steering.pss.judge.model.QcmZgJugdeApplyEntity entity = EntityTool.getEntityByJSONStr(json, com.steering.pss.judge.model.QcmZgJugdeApplyEntity.class);
			entity.setInStorageFlag("0");
			entity.setInStorageConfirm(userName);
			entity.setInStorageTime(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));

			String updateSql = CoreXmlSqlParsersFactory.getSql("FrmFinishAfrim.updateInStorageFlag");
			updateSql = EntityTool.fillSqlByEntity(updateSql, entity);
			sqllist.add(updateSql);

			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			if(cro.getV_errMsg().equals(""))
			{
				cro.setV_errMsg("取消接收成功!");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
		}
		return cro;
	}
}
