package com.steering.pss.ydm.pipemanage;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
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.pss.ydm.base.MeanValueCalculation;
import com.steering.pss.ydm.entity.MatZcMEntity;
import com.steering.pss.ydm.entity.YdmZcOutlistEntity;

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

public class FrmScrapOutList extends DBCommon{
	/***
	 * 查询库存信息
	 * @param startTim
	 * @param endTim
	 * @param jugeNo
	 * @param arr
	 * @return
	 */
	public CoreReturnObject doQueryMat(String startTim,String endTim,String jugeNo,String[]arr,String supplyUnit)
	{
	      String sql = CoreXmlSqlParsersFactory.getSql("FrmScrapOutList.doQueryMat");
	      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(!jugeNo.equals(""))
	      {
	    	  sql += " AND T1.JUDGE_STOVE_NO = '"+ jugeNo +"'";
	      }
	      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.BELONG_CODE,T1.BELONG_NAME,T1.PLINE_CODE,T1.PLINE_NAME,T1.MATERIAL_NAME,T1.MATERIAL_NO,S.STORAGE_NO,";
			sql += " T1.ACT_LEN_MIN,T1.ACT_LEN_MAX,S.STORAGE_NAME,T1.MEMO,T1.PRODUCT_FLAG,T1.JUDGE_STD_CODE,T1.JUDGE_STD_NAME ";
	      return this.getData(sql);
	}
	/***
	 * 查询回废出库记录
	 * @param startTim
	 * @param endTim
	 * @param jugeNo
	 * @param arr
	 * @return
	 */
	public CoreReturnObject doQueryOutList(String startTim,String endTim,String jugeNo,String[]arr,String supplyUnit)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmScrapOutList.doQueryOutList");
	      sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
	      if(!startTim.equals(""))
	      {
	    	  sql += " AND T.OUTSTOCK_TIME >=TO_DATE('" + startTim
				+ "', 'YYYY-MM-DD HH24:MI:SS')AND T.OUTSTOCK_TIME <=TO_DATE('"
				+ endTim + "', 'YYYY-MM-DD HH24:MI:SS')";
	      }
	      if(!jugeNo.equals(""))
	      {
	    	  sql += " AND T.JUDGE_STOVE_NO = '"+ jugeNo +"'";
	      }
		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.OUTSTOCK_DOC,T.OUTSTOCK_TYPE_CODE,T.OUTSTOCK_TYPE_NAME,T.ICCAR_NO,T.VEHICLE_NO,T.LOT_NO,T.STOVE_NO,T.JUDGE_STOVE_NO,T.BATCH_NO,T.BATCH_GROUD_NO,T.MATERIAL_NO,T.MATERIAL_NAME,T.PRODUCCODE,T.PRODUCNAME,T.STD_CODE,";
	      sql += " T.STD_NAME,T.GRADECODE,T.GRADENAME,T.STEELCODE,T.STEELNAME,T.STD_STYLE,T.STD_STYLE_DESC,T.SPEC_CODE,T.SPEC_NAME,T.MODEL_CODE,T.MODEL_DESC,T.PLINE_CODE,T.PLINE_NAME,T.ACT_DIMATER,T.ACT_HEIGHT,T.ACT_LEN_MIN,T.ACT_LEN_MAX,T.BELONG_CODE,";
	      sql += " T.BELONG_NAME,T.OUTSTOCK_TIME,T.ORD_PK,T.CREATE_NAME,T.ORD_LN_PK,T.ORD_LN_DLY_PK,T.ORDER_NO,T.ORDER_SEQ,T.DELIVERY_NO,T.PRODUCT_FLAG,T.MAT_STATUS,T.JUDGE_STD_NAME,T.BAL_YEAR_MONTH";
	      return this.getData(sql);
	}
	/***
	 * 回废出库
	 * @param parm
	 * @return
	 * @throws Exception 
	 */
	public CoreReturnObject scrapMat(ArrayList<String> parm) throws Exception
	{
		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 yearMoth = df.format(now);
		String outDoc = "";
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		try {
			connection.setAutoCommit(false); // 取消自动提交事务
			outDoc = querySendSqlDoc(connection, "800804", "OD");
			for(String str : parm)
			{
				MatZcMEntity matZcTity = EntityTool.getEntityByJSONStr(str, MatZcMEntity.class);
				String yearMoth = "120504".equals(matZcTity.getSupplyUnitCode())? ComBaseInfo.GetBalYear_2416(new Date()): ComBaseInfo.GetBalYear(new Date());

				matZcTity.setOutstockDoc(outDoc);
				matZcTity.setBalYearMonth(yearMoth);
				String deleteSql = CoreXmlSqlParsersFactory.getSql("FrmScrapOutList.scrapMat");
				deleteSql = EntityTool.fillSqlByEntity(deleteSql, matZcTity);
				PreparedStatement deletePsta = connection.prepareStatement(deleteSql);
				deletePsta.executeUpdate();
				deletePsta.close();
				
				sql = CoreXmlSqlParsersFactory.getSql("FrmScrapOutList.SelectYdmOutList");
				sql = EntityTool.fillSqlByEntity(sql, matZcTity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				List<YdmZcOutlistEntity> ydmOut = EntityTool.getEntitysByRs(rs, YdmZcOutlistEntity.class);
				
				List<double[]> list = MeanValueCalculation.MeanCalculation(
                        matZcTity.getPonderGrossWt(), Integer.parseInt(String.valueOf(matZcTity.getActCount())));
				int m = 0;
				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++) {
							YdmZcOutlistEntity ydmOutEntity = new YdmZcOutlistEntity();
							ydmOutEntity.setOutstockDoc(outDoc);
							ydmOutEntity.setJudgeStoveNo(matZcTity.getJudgeStoveNo());
							ydmOutEntity.setBatchNo(matZcTity.getBatchNo());
							ydmOutEntity.setBatchGroudNo(matZcTity.getBatchGroudNo());
							ydmOutEntity.setOutstockTypeCode("800804");
							ydmOutEntity.setMatNo(ydmOut.get(m).getMatNo());
							ydmOutEntity.setPonderGrossWt(String.valueOf(conW[1]));
							if(conW[1]>0)
							{
								ydmOutEntity.setPonderNo("HK");
							}
							String updateYdmOutListSql = CoreXmlSqlParsersFactory.getSql("FrmScrapOutList.updateYdmOutList");
							updateYdmOutListSql = EntityTool.fillSqlByEntity(updateYdmOutListSql, ydmOutEntity);
							PreparedStatement updateYdmOutListPsta = connection.prepareStatement(updateYdmOutListSql);
							updateYdmOutListPsta.executeUpdate();
							updateYdmOutListPsta.close();
							m++;
						}
                    }
				}
				
			}
			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 parm
	 * @return
	 */
	public CoreReturnObject cancelScrapMat(ArrayList<String> parm) throws SQLException
	{
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for(String str : parm)
			{
				// 查询是否被财务系统接收
				YdmZcOutlistEntity ydmOutListEntity = EntityTool.getEntityByJSONStr(str, YdmZcOutlistEntity.class);
				String getFmisOutList = CoreXmlSqlParsersFactory.getSql("FrmScrapOutList.GetFmisOutList");
				getFmisOutList = EntityTool.fillSqlByEntity(getFmisOutList, ydmOutListEntity);
				YdmZcOutlistEntity entityBySql = EntityTool.getEntityBySql(getFmisOutList, connection, YdmZcOutlistEntity.class);
				if (entityBySql != null) {
					cro.setV_errMsg("财务系统同步出库信息，请联系财务撤销同步信息!");
					return cro;
				}

				String cancelScrapSql = CoreXmlSqlParsersFactory.getSql("FrmScrapOutList.cancelScrapMat");
				cancelScrapSql = EntityTool.fillSqlByEntity(cancelScrapSql, ydmOutListEntity);
				sqllist.add(cancelScrapSql);
			}
			this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			cro.setV_errMsg("撤销成功!");
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
			
		
	}
	/**
     * 每支材料对应的出库单号
     * @param conn c
     * @param strlist 传递参数
     * @return obj
     * @throws Exception 异常处理
     */
    public String querySendSqlDoc(Connection conn, String strlist,String memo)
            throws Exception {
        int seq = 0;
        String outListDoc = "";
         PreparedStatement psta = null;
         Date dt = new Date();
         SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
         SimpleDateFormat matter2 = new SimpleDateFormat("yyMMdd");
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmScrapOutList.querySendSqlDoc");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1, memo);
        psta.setString(2, strlist);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
        	outListDoc = rs.getString("OUTSTOCK_DOC");
        }
        rs.close();
        psta.close();
        //return  memo + matter2.format(dt) + StringTool.formatDecimal(++seq, "00000");
        return outListDoc;
    }
}
