package com.steering.ydm.bc;

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 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.comm.tools.StringTool;
import com.steering.mes.mcp.entity.MatBcMEntity;

public class FrmSplittingManage extends DBCommon{

	/***
	 * 查询
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject doQuery(ArrayList<String> parmList)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.doQuery");
		if(!parmList.get(0).equals(""))
		{
			sql = sql.replace("#BAL_YEAR_MONTH#", " AND T.BAL_YEAR_MONTH = '"+parmList.get(0)+"'");
		}else
		{
			sql = sql.replace("#BAL_YEAR_MONTH#", "");
		}
		if(!parmList.get(1).equals(""))
		{
			sql = sql.replace("#JUDGE_STOVE_NO#", " AND T.JUDGE_STOVE_NO = '"+parmList.get(1)+"'");
		}else
		{
			sql = sql.replace("#JUDGE_STOVE_NO#", "");
		}
		String str = " GROUP BY T.PRODUCT_FLAG,T.MAT_STATUS,T.LOT_NO,T.JUDGE_STOVE_NO,T.BATCH_NO,T.BATCH_GROUD_NO,T.STOVE_NO,T.MEMO,T.FLAG_STOVE_NO_ZG,";
		str += " T.PRO_ORDER_ID,T.QCM_STAUS,T.PRO_ORDER_NO,T.PRO_PLAN_ID_NEXT,T.GX_PLAN_NO_NEXT,S.STORAGE_NO,T.JUDGE_RESULT,T.MATERIAL_NO,T.MATERIAL_NAME,";
		str += " T.PROCESS_CDOE,T.PROCESS_DESC,T.PLINE_CODE,T.PLINE_NAME,T.BELONG_CODE,T.BELONG_NAME,T.GX_PLAN_NO";
		sql = sql.replace("#GROUP#", str);
		return this.getData(sql);
	}
	/***
	 * 分切
	 * @param matTity
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject doSpliting(String matTity,ArrayList<String> parmList,String userName)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		int aCount = 0;
		double wgt = 0.0;
		double len = 0.0;
		String matNo = "";
		String inDoc = "";//入库单号
		String outDoc = "";//出库单号
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("yyyyMM");
        String systime = dateFormat.format(now);
        String yearMoth = df1.format(now);
		try {
			
			ArrayList<String> sqllist = new ArrayList<String>();
			MatBcMEntity matBcEntity = EntityTool.getEntityByJSONStr(matTity, MatBcMEntity.class);
			sql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.doQueryCount");
			sql = EntityTool.fillSqlByEntity(sql, matBcEntity);
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			if(rs.next())
			{
				aCount = Integer.parseInt(rs.getString("ACOUNT"));
			}
			rs.close();
			psta.close();
			if(Integer.parseInt(matBcEntity.getActCount()) > aCount)
			{
				cro.setV_errMsg("分切投入管数不能大于库存管数!");
				return cro;
			}
			
			sql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.doQueryWgt");
			sql = EntityTool.fillSqlByEntity(sql, matBcEntity);
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			if(rs.next())
			{
				wgt = Double.parseDouble(rs.getString("ACT_WEIGHT"));
				len = Double.parseDouble(rs.getString("ACT_LEN"));
			}
			rs.close();
			psta.close();
			
			outDoc = doQueryOutDoc(connection);
			matBcEntity.setOutstockDoc(outDoc);
			matBcEntity.setCreateTime(systime);
			matBcEntity.setBalYearMonth(yearMoth);
			matBcEntity.setCreateName(userName);
			String insertOutSql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.insertOut");//原料出库 删除库存
			insertOutSql = EntityTool.fillSqlByEntity(insertOutSql,matBcEntity);
			sqllist.add(insertOutSql);
			
			matNo = doQueryMatNo(connection,matBcEntity.getJudgeStoveNo(),matBcEntity.getBatchNo());
			int m = Integer.parseInt(matNo.substring(matNo.length() - 4, matNo
                    .length()));
			
			inDoc = doQueryInDoc(connection);
			int n = Integer.parseInt(inDoc.substring(inDoc.length() - 4, inDoc
                    .length()));
			for(String str : parmList)
			{
				MatBcMEntity matBcEntityAct = EntityTool.getEntityByJSONStr(str, MatBcMEntity.class);
				for(int i = 0;i< Integer.parseInt(matBcEntityAct.getActCount());i++)
				{
					DecimalFormat df=new DecimalFormat("0.00");
					String actWgt = df.format(Double.parseDouble(String.valueOf(Math.round(Double.parseDouble(matBcEntityAct.getActLen()) * wgt*100/len)))/100);
					matBcEntity.setActCount("1");
					matBcEntity.setActWeight(actWgt);
					matBcEntity.setActTheoryWeight(actWgt);
					matBcEntity.setActLen(matBcEntityAct.getActLen());
					matBcEntity.setMatNo((matBcEntity.getJudgeStoveNo() + matBcEntity.getBatchNo())
							+ StringTool.formatDecimal(m, "0000"));
					matBcEntity.setInstockDoc(inDoc);
					matBcEntity.setInstockSqe(inDoc + StringTool.formatDecimal(n, "0000"));
					
					String insertMatBcSql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.insertMatBcSpilit");//分切后入库
					insertMatBcSql = EntityTool.fillSqlByEntity(insertMatBcSql,matBcEntity);
					sqllist.add(insertMatBcSql);
					m++;
					n++;
				}
			}
			
			
			
			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 scrapToOk(ArrayList<String> parmList,String plineCode,String plineName)
	{
		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 df1 = new SimpleDateFormat("yyyyMM");
        String systime = dateFormat.format(now);
        String yearMoth = df1.format(now);
        String processCode = "";
        String procrssName = "";
        String belongCode = "";
        String belongName = "";
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for(String str : parmList)
			{
				MatBcMEntity matBcEntity = EntityTool.getEntityByJSONStr(str, MatBcMEntity.class);
				matBcEntity.setNewPlineCode(plineCode);
				matBcEntity.setNewPlineName(plineName);
				if(!matBcEntity.getQcmStaus().equals("判废"))
				{
					cro.setV_errMsg("不合转合时，选择的应该是不合格状态的信息!");
					return cro;
				}
				sql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.selectProcess");//查询工序
				sql = EntityTool.fillSqlByEntity(sql, matBcEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					processCode = rs.getString("PROCESS_CODE");
					procrssName = rs.getString("PROCESS_DESC");
					belongCode = rs.getString("DEPARTMENT_CODE");
					belongName = rs.getString("DEPARTMENT_DESC");
				}
				rs.close();
				psta.close();
				
				matBcEntity.setProcessCdoe(processCode);
				matBcEntity.setProcessDesc(procrssName);
				matBcEntity.setQcmStaus("00");
				matBcEntity.setNextProcessCdoe("");
				matBcEntity.setNextProcessDesc("");
				matBcEntity.setBelongCode(belongCode);
				matBcEntity.setBelongName(belongName);
				
				
				String updateScrapToOkSql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.scrapToOk");
				updateScrapToOkSql = EntityTool.fillSqlByEntity(updateScrapToOkSql, matBcEntity);
				sqllist.add(updateScrapToOkSql);
			}
			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 connection
	 * @return
	 */
	private String doQueryOutDoc(Connection con) {
		String outDoc = "";
		String sql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.doQueryOutDoc");
		PreparedStatement psta = null;
		try {
			psta = con.prepareStatement(sql);
			ResultSet rs = psta.executeQuery();
			if(rs.next())
			{
				outDoc = rs.getString("OUTSTOCK_DOC");
			}
			rs.close();
			psta.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return outDoc;
	}
	/***
	 * 生成入库单号
	 * @param connection
	 * @return
	 */
	private String doQueryInDoc(Connection con) {
		String inDoc = "";
		String sql = CoreXmlSqlParsersFactory.getSql("FrmSplittingManage.doQueryInDoc");
		PreparedStatement psta = null;
		try {
			psta = con.prepareStatement(sql);
			ResultSet rs = psta.executeQuery();
			if(rs.next())
			{
				inDoc = rs.getString("INSTOCK_DOC");
			}
			rs.close();
			psta.close();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
		return inDoc;
	}
	/***
	 * 查询最大材料号
	 * @param connection
	 * @param judgeStoveNo
	 * @param batchNo
	 * @return
	 * @throws SQLException 
	 */
	private String doQueryMatNo(Connection conn, String strLcode,
			String strBatch) throws SQLException {
		String matNo = "";
        PreparedStatement psta = null;
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmSplittingManage.doQueryMatNo");
        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);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
        	matNo = rs.getString("MAT_NO");
        }
        rs.close();
        psta.close();
        return matNo;
	}
	/***
	 * 获取所有产线
	 * @return
	 */
	public CoreReturnObject doQueryPline()
	{
		return this.getDataBySqlID("FrmSplittingManage.doQueryPline");
	}
}
