package com.steering.ydm.bc;

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

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

import com.steering.comm.converter.EntityTool;
import com.steering.comm.db.DBCommon;
import com.steering.common.StringTool;
import com.steering.mes.mcp.entity.MatBcMEntity;
import com.steering.mes.mcp.entity.YdmBcOutlistEntity;

public class FrmLoadMatData extends DBCommon{

	/***
	 * 查询库存信息
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject doQueryMatM(ArrayList<String> parmList)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmLoadMatData.doQueryMatM");
		if(!parmList.get(0).equals(""))
		{
			sql = sql.replace("#JUDGE_STOVE_NO#", "AND T.JUDGE_STOVE_NO = '"+parmList.get(0)+"'");
		}else
		{
			sql = sql.replace("#JUDGE_STOVE_NO#", "");
		}
		return this.getData(sql);
	}
	/***
	 * 查询投料出库信息
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject doQueryOutList(ArrayList<String> parmList)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmLoadMatData.doQueryOutList");
		if(!parmList.get(0).equals(""))
		{
			sql += " AND T.JUDGE_STOVE_NO = '"+parmList.get(0)+"'";
		}
		if(!parmList.get(1).equals(""))
		{
			sql += " AND T.BAL_YEAR_MONTH = '"+parmList.get(1)+"'";
		}
		sql += " GROUP BY T.OUTSTOCK_DOC,T.LOT_NO,T.STOVE_NO,T.JUDGE_STOVE_NO,T.BATCH_NO,T.BATCH_GROUD_NO,T.MEMO";
		return this.getData(sql);
	}
	/***
	 * 查询产线
	 * @return
	 */
	public CoreReturnObject doQueryPline()
	{
		return this.getDataBySqlID("FrmLoadMatData.doQueryPline");
	}
	/***
	 * 回废出库
	 * @param parmList
	 * @param userName
	 * @param userOrder
	 * @param userGroup
	 * @param loadPlineCode
	 * @param loadPlineName
	 * @return
	 */
	public CoreReturnObject crushData(ArrayList<String> parmList,String userName,String userOrder,String userGroup,String loadPlineCode,String loadPlineName)
	{
		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 outTlDoc = "";
		String outCqDoc = "";
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			outTlDoc = getOutListDoc(connection, "800804");
			outCqDoc = getOutListDoc(connection, "800809");
			for(String str : parmList)
			{
				MatBcMEntity matBcEntity = EntityTool.getEntityByJSONStr(str, MatBcMEntity.class);
				if(Integer.parseInt(matBcEntity.getLoadActCount()) > Integer.parseInt(matBcEntity.getActCount()))
				{
					cro.setV_errMsg("回废支数不能大于库存支数!");
					return cro;
				}
				matBcEntity.setOutstockTypeCode("800804");
				matBcEntity.setOutstockTypeName("回废出库");
				matBcEntity.setLoadPlineCode(loadPlineCode);
				matBcEntity.setLoadPlineName(loadPlineName);
				matBcEntity.setTlOutstockDoc(outTlDoc);
				matBcEntity.setCqOutstockDoc(outCqDoc);
				matBcEntity.setOutstockTime(systime);
				matBcEntity.setBalYearMonth(bathYear);
				matBcEntity.setCreateName(userName);
				matBcEntity.setProBc(userOrder);
				matBcEntity.setProBz(userGroup);
				
				String loadDataSql = CoreXmlSqlParsersFactory.getSql("FrmLoadMatData.loadMatBcMDataCrush");
				loadDataSql = EntityTool.fillSqlByEntity(loadDataSql, matBcEntity);
				sqllist.add(loadDataSql);
			}
			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;
	}
	
	/***
	 * 上料
	 * @return
	 */
	public CoreReturnObject loadMatBcMData(ArrayList<String> parmList,String userName,String userOrder,String userGroup,String loadPlineCode,String loadPlineName,String flag)
	{
		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 bathYear = ""; //改25号结转
		String outTlDoc = "";
		String outCqDoc = "";
		int inStoreFlagCount = 0;
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			outTlDoc = getOutListDoc(connection, "800801");
			outCqDoc = getOutListDoc(connection, "800809");
			for(String str : parmList)
			{
				MatBcMEntity matBcEntity = EntityTool.getEntityByJSONStr(str, MatBcMEntity.class);
				bathYear = StringTool.GetBalYear(now,StringTool.GetSupplyUnit(matBcEntity.getPlineCode())); //改25号结转
				sql = CoreXmlSqlParsersFactory.getSql("FrmLoadMatData.selectQcmFlag");//判断是否已确认
				sql = EntityTool.fillSqlByEntity(sql, matBcEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					inStoreFlagCount = Integer.parseInt(rs.getString("ACOUNT"));
				}
				rs.close();
				psta.close();
				if(inStoreFlagCount > 0)
				{
				     cro.setV_errMsg("该炉下存在未确认数据,不允许上料出库!");	
				     return cro;
				}
				
				if(flag.equals("0"))
				{
					matBcEntity.setLoadPlineCode(loadPlineCode);
					matBcEntity.setLoadPlineName(loadPlineName);
				}else
				{
					matBcEntity.setLoadPlineCode(matBcEntity.getPlineCodeNext());
					matBcEntity.setLoadPlineName(matBcEntity.getPlineNameNext());
				}
				if(Integer.parseInt(matBcEntity.getLoadActCount()) > Integer.parseInt(matBcEntity.getActCount()))
				{
					cro.setV_errMsg("上料支数不能大于库存支数!");
					return cro;
				}
				matBcEntity.setOutstockTypeCode("800801");
				matBcEntity.setOutstockTypeName("投料出库");
				matBcEntity.setTlOutstockDoc(outTlDoc);
				matBcEntity.setCqOutstockDoc(outCqDoc);
				matBcEntity.setOutstockTime(systime);
				matBcEntity.setBalYearMonth(bathYear);
				matBcEntity.setCreateName(userName);
				matBcEntity.setProBc(userOrder);
				matBcEntity.setProBz(userGroup);
				
				String loadDataSql = CoreXmlSqlParsersFactory.getSql("FrmLoadMatData.loadMatBcMData");
				loadDataSql = EntityTool.fillSqlByEntity(loadDataSql, matBcEntity);
				sqllist.add(loadDataSql);
			}
			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;
	}
	/***
	 * 撤销上料
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject cancelLoadData(ArrayList<String> parmList,String nowBathYear)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		String bathYear = "";
		SimpleDateFormat simple = new SimpleDateFormat("yyyyMM");
		SimpleDateFormat nextSimple = new SimpleDateFormat("yyyy-MM");
		int acount = 0;
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for(String str : parmList)
			{
				YdmBcOutlistEntity ydmBcEntity = EntityTool.getEntityByJSONStr(str, YdmBcOutlistEntity.class);
				
				Date s = simple.parse(ydmBcEntity.getBalYearMonth());
				ydmBcEntity.setBalYearMonth(getBalYearMoth(nextSimple.format(s)));
				sql = CoreXmlSqlParsersFactory.getSql("FrmLoadMatData.SelectOutBathYear");
				sql = EntityTool.fillSqlByEntity(sql, ydmBcEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					acount = Integer.parseInt(rs.getString("ACOUNT"));
				}
				
				rs.close();
				psta.close();
				if(acount > 0)
				{
					cro.setV_errMsg("已跨月结转封账，不允许撤销上料!");
					return cro;
				}
				
				String cancelLoadDataSql = CoreXmlSqlParsersFactory.getSql("FrmLoadMatData.cancelLoadData");
				cancelLoadDataSql = EntityTool.fillSqlByEntity(cancelLoadDataSql, ydmBcEntity);
				sqllist.add(cancelLoadDataSql);
			}
			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;
	}
	
	/**
	 * 生成年月下一年月
	 * 
	 * @param yearMoth
	 * @return
	 */
	public static String getBalYearMoth(String yearMoth) {
		String year = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		SimpleDateFormat sdfS = new SimpleDateFormat("yyyyMM");
		try {
			Date date = sdf.parse(yearMoth);
			Calendar calender = Calendar.getInstance();
			calender.setTime(date);
			calender.add(Calendar.MONTH, 1);
			year = sdfS.format(calender.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return year;

	}
	
	/***
	 * 获取出库单号
	 * 
	 * @param conn
	 * @param strInbound
	 * @return
	 * @throws SQLException
	 */
	public String getOutListDoc(Connection conn, String strInbound)
			throws SQLException {
		String inListDoc = "";
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmLoadMatData.getOutListDoc");
		PreparedStatement psta = conn.prepareStatement(sql);
		psta.setString(1, strInbound);
		psta.setString(2, strInbound);
		psta.setString(3, strInbound);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			inListDoc = rs.getString("OUTSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return inListDoc;
	}
}
