package com.steering.mes.signature;

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;

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

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.StringTool;
import com.steering.common.EntityTool;
import com.steering.mes.zgmil.entity.FeedRowPlan;
import com.steering.mes.zgmil.entity.MilPlanEntity;
import com.steering.mes.zgmil.entity.MilSlabScrapSeqEntity;

public class FrmUpdatePlan extends DBCommon{

	/***
	 * 查询炉计划
	 * @param list
	 * @return
	 */
	public CoreReturnObject queryMilPlan(ArrayList<String> list)
	{
	     return this.getDataBySqlID("FrmUpdatePlan.queryMilPlan", list.toArray());	
	}
	/***
	 * 查询是否已产生分切实绩
	 * @param id
	 * @param jugeNo
	 * @return
	 */
	public CoreReturnObject doQuerySawResult(String id,String jugeNo)
	{
		return this.getDataBySqlID("FrmUpdatePlan.doQuerySawResult", new Object[]{id,jugeNo});
	}
	/**
	 * 查询是否分批取样
	 * @param id
	 * @param jugeNo
	 * @return
	 */
	public CoreReturnObject doQuerySamplePipe(String id,String jugeNo)
	{
		return this.getDataBySqlID("FrmUpdatePlan.doQuerySamplePipe", new Object[]{id,jugeNo});
	}
	/***
	 * 修改分切数
	 * @param tity
	 * @return
	 */
	public CoreReturnObject updateSawNum(String tity)
	{
//		ArrayList<String> sqllist = new ArrayList<String>();
//		String updateSql = CoreXmlSqlParsersFactory.getSql("FrmUpdatePlan.updateSawNum");
//		MilPlanEntity milPlan = EntityTool.getEntityByJSONStr(tity, MilPlanEntity.class);
//		updateSql = EntityTool.fillSqlByEntity(updateSql, milPlan);
//		sqllist.add(updateSql);
//		return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
		
		CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        PreparedStatement scrapProcessPsta = null;
        String sql = "";
        ResultSet rs = null;
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss");
        String systime = dateFormat.format(now);
        int macount = 0;
        int acount = 0;
        String sawNum = "";
        String yearMoth = "";
        int seq = 1;
        String[] arr = null;
        double strWgt = 0;
		double inPutWgt = 0;// 上料量
		int inPutNum = 0;// 总支数
		int m = 0;
		String proPlanID = ""; // 轧管订单编号
		String gxPlanNO = ""; // 工序排产序号
		String backSlabFlag = "0"; //回炉坯标识
        try {
			connection.setAutoCommit(false); // 取消自动提交事务
			String updateSql = CoreXmlSqlParsersFactory.getSql("FrmUpdatePlan.updateSawNum");//修改计划分切数
			PreparedStatement updatePsta = connection.prepareStatement(updateSql);
			String insertPortBatchSql = CoreXmlSqlParsersFactory.getSql("FeedResult.insertProcess");//生成进程表、剔除管坯
			PreparedStatement insertPortBatchPsta = connection.prepareStatement(insertPortBatchSql);
			
			//回写计划表中预计支吨
			String sql4 = CoreXmlSqlParsersFactory
			.getSql("FrmUpdatePlan.UpdatePlanPredict");
			PreparedStatement updatePlanPredict = connection.prepareStatement(sql4);
			
			MilPlanEntity milPlan = EntityTool.getEntityByJSONStr(tity, MilPlanEntity.class);
			
			updatePsta.setString(1, milPlan.getSawNum());
			updatePsta.setString(2, milPlan.getId());
			updatePsta.setString(3, milPlan.getJudgeStoveNo());
			updatePsta.setString(4, milPlan.getId());
			updatePsta.setString(5, milPlan.getJudgeStoveNo());
			updatePsta.addBatch();
			updatePsta.executeBatch();
			
			
			updatePlanPredict.setString(1, milPlan.getJudgeStoveNo());
			updatePlanPredict.setString(2, milPlan.getProPlanId());
			updatePlanPredict.setString(3, milPlan.getGxPlanNo());
			updatePlanPredict.addBatch();
			updatePlanPredict.executeBatch();
			
			sql = CoreXmlSqlParsersFactory.getSql("FeedResult.SelectFeedNum");
			sql = EntityTool.fillSqlByEntity(sql, milPlan).replace("#RESULT_NO#", milPlan.getId());
			psta = connection.prepareStatement(sql);
			
			rs = psta.executeQuery();
			List<FeedRowPlan> list = EntityTool.getEntitysByRs(rs,
					FeedRowPlan.class);

			rs.close();
			psta.close();
			arr = new String[2];
			sql = CoreXmlSqlParsersFactory
					.getSql("FeedResult.SelectContractNo");
			psta = connection.prepareStatement(sql);
			psta.setString(1, milPlan.getJudgeStoveNo());
			rs = psta.executeQuery();
			if (rs.next()) {
				arr[0] = rs.getString("OUTDIAMETER");
				arr[1] = rs.getString("AIMWALLTHICK");
			}
			rs.close();
			psta.close();
			if (arr[0] == null || arr[1] == null) {
				// cro.setV_errMsg("外径/控制壁厚为空,请联系系统管理员!");
				// return cro;
				arr = list.get(0).getPipeSize().split("[*]");
			}

			sql = CoreXmlSqlParsersFactory
					.getSql("FeedResult.SelectFeedToalWgt");
			sql = EntityTool.fillSqlByEntity(sql, milPlan);
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			if (rs.next()) {
				inPutWgt = Double.parseDouble(rs.getString("MAT_TOTAL_HEIGHT"));
			}
			rs.close();
			psta.close();

			sql = CoreXmlSqlParsersFactory
					.getSql("FeedResult.SelectFeedToalNum");
			sql = EntityTool.fillSqlByEntity(sql, milPlan);
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			if (rs.next()) {
				inPutNum = Integer.parseInt(rs.getString("ACT_COUNT"));
			}
			rs.close();
			psta.close();

			sql = CoreXmlSqlParsersFactory
					.getSql("FeedResult.SelectProPlanId1"); //查询轧管订单编号
			sql = EntityTool.fillSqlByEntity(sql, milPlan).replace("#RESULT_NO#", milPlan.getId());
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			if (rs.next()) {
				proPlanID = rs.getString("PRO_PLAN_ID");
				gxPlanNO = rs.getString("GX_PLAN_NO");
				backSlabFlag = rs.getString("BACK_SLAB_FLAG");
				yearMoth = rs.getString("START_TIME");
			}
			rs.close();
			psta.close();

			List<double[]> list1 = MeanValueCalculation.MeanCalculation(
					inPutWgt, inPutNum);// 分配上料重量

			ArrayList<String> wgtList = new ArrayList<String>();
			List<double[]> lenList = MeanValueCalculation.MeanCalculation(
					inPutWgt, inPutNum);
			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");
						wgtList.add(dt.format(conLen[1]));
					}
				}
			}

			String mMatNo = queryMatNoM(connection, milPlan
					.getJudgeStoveNo(), milPlan.getLotNo(), milPlan.getId()); // 母坯材料号
			int g = Integer.parseInt(mMatNo.substring(mMatNo.length() - 3,
					mMatNo.length()));

			for (int k = 0; k < list.size(); k++) {
				FeedRowPlan feedPlan = list.get(k);
				for (int s = 0; s < Integer.parseInt(feedPlan.getFeedNum()); s++) {
					// arr = feedPlan.getPipeSize().split("[*]");
					strWgt = 0.02466
							* Double.parseDouble(arr[1])
							* (Double.parseDouble(arr[0]) - Double
									.parseDouble(arr[1]))
							* Double.parseDouble(feedPlan.getTargetLength())
							/ 1000;
					for (int i = 1; i < Integer.parseInt(feedPlan.getDbNum()) + 1; i++) {
						for (int j = 1; j < Integer.parseInt(feedPlan
								.getSawNum()) + 1; j++) {
							insertPortBatchPsta.setString(1, milPlan
									.getId());
							insertPortBatchPsta.setString(2, milPlan
									.getLotNo());
							insertPortBatchPsta.setString(3, milPlan
									.getStoveNo());
							insertPortBatchPsta.setString(4, milPlan
									.getJudgeStoveNo());
							insertPortBatchPsta.setString(5, milPlan
									.getPlineCode());
							insertPortBatchPsta.setString(6, String.valueOf(seq));
							insertPortBatchPsta.setString(7, (milPlan
									.getJudgeStoveNo().replaceFirst("-.*", ""))
									+ StringTool.formatDecimal(g, "000")
									+ i
									+ j);// 子管材料号
							insertPortBatchPsta.setString(8, "");// 定尺长度
							// new DecimalFormat("0.000").format(strWgt)
							insertPortBatchPsta.setString(9, "");// 重量
							insertPortBatchPsta.setString(10, systime);
							insertPortBatchPsta.setString(11, (milPlan
									.getJudgeStoveNo().replaceFirst("-.*", ""))
									+ StringTool.formatDecimal(g, "000") + i);// 母管材料号
							insertPortBatchPsta.setString(12, (milPlan
									.getJudgeStoveNo().replaceFirst("-.*", ""))
									+ StringTool.formatDecimal(g, "000"));// 母坯材料号
							insertPortBatchPsta.setString(13, String
									.valueOf(wgtList.get(m)));// 投料量
							insertPortBatchPsta.setString(14, yearMoth);
							insertPortBatchPsta.setString(15, proPlanID); //轧管订单编号
							insertPortBatchPsta.setString(16, gxPlanNO); //工序排产序号
							
							insertPortBatchPsta.addBatch();
							seq++;
							m++;
						}
					}
					g++;
				}
			}
			insertPortBatchPsta.executeBatch();
			
			sql = CoreXmlSqlParsersFactory.getSql("FrmUpdatePlan.SelectScrapNum");
			psta = connection.prepareStatement(sql);
			psta.setString(1, milPlan.getJudgeStoveNo());
			rs = psta.executeQuery();
			List<MilSlabScrapSeqEntity> scraplist = EntityTool.getEntitysByRs(
					rs, MilSlabScrapSeqEntity.class);

			rs.close();
			psta.close();
			String nodeStaus = "";//结炉状态
			for(int i = 0;i<scraplist.size();i++)
			{
				MilSlabScrapSeqEntity milSlabSeq = scraplist.get(i);
				sql = CoreXmlSqlParsersFactory.getSql("FrmUpdatePlan.SelectNodeStaus");
				if(milSlabSeq.getProcessNo().equals("0")||milSlabSeq.getProcessNo().equals("1"))
				{
					sql = sql.replace("#RESULT#", "MIL_FEEDSAW_RESULT");
				}else if(milSlabSeq.getProcessNo().equals("2"))
				{
					sql = sql.replace("#RESULT#", "MIL_FUR_RESULT");
				}else if(milSlabSeq.getProcessNo().equals("3"))
				{
					sql = sql.replace("#RESULT#", "MIL_PERFORATION_RESULT");
				}else if(milSlabSeq.getProcessNo().equals("4"))
				{
					sql = sql.replace("#RESULT#", "MIL_REFUR_RESULT");
				}else if(milSlabSeq.getProcessNo().equals("5"))
				{
					sql = sql.replace("#RESULT#", "MIL_ROLLING_RESULT");
				}else if(milSlabSeq.getProcessNo().equals("6"))
				{
					sql = sql.replace("#RESULT#", "MIL_SIZING_RESULT");
				}
				psta = connection.prepareStatement(sql);
				psta.setString(1, milSlabSeq.getJudgeStoveNo());
				rs = psta.executeQuery();
				if(rs.next())
				{
					nodeStaus = rs.getString("NODE_FUR_FLAG");
				}
				rs.close();
				psta.close();
				if(nodeStaus.equals("0"))
				{
					continue;
				}
				String scrapProcessSql = "";
				//锯切剔管
				if(milSlabSeq.getProcessNo().equals("0")||milSlabSeq.getProcessNo().equals("1"))
				{
					scrapProcessSql = CoreXmlSqlParsersFactory.getSql("FrmUpdatePlan.scarpPortBacth");//剔进程表
				}
				else
				{
					//热区其他工序剔管
					scrapProcessSql = CoreXmlSqlParsersFactory.getSql("FrmUpdatePlan.scarpPortBacth1");//剔进程表
					scrapProcessSql = scrapProcessSql.replace("#OP_PROCESS#", milSlabSeq.getProcessNo());
					scrapProcessSql = EntityTool.fillSqlByEntity(scrapProcessSql, milSlabSeq);
				}
				 scrapProcessPsta = connection.prepareStatement(scrapProcessSql);
				if(milSlabSeq.getProcessNo().equals("0")||milSlabSeq.getProcessNo().equals("1"))
				{
					scrapProcessPsta.setInt(1, Integer.parseInt(milSlabSeq
							.getProcessNo()));
					scrapProcessPsta.setString(2, milSlabSeq.getJudgeStoveNo());
					scrapProcessPsta.setString(3, milSlabSeq.getSeq());
					scrapProcessPsta.setString(4, "0");
					scrapProcessPsta.setString(5, milSlabSeq.getJudgeStoveNo());

					scrapProcessPsta.setInt(6, Integer.parseInt(milSlabSeq
							.getProcessNo()));
					scrapProcessPsta.setString(7, milSlabSeq.getJudgeStoveNo());
					scrapProcessPsta.setString(8, milSlabSeq.getSeq());
					scrapProcessPsta.setString(9, "0");
					scrapProcessPsta
							.setString(10, milSlabSeq.getJudgeStoveNo());
					scrapProcessPsta.addBatch();
				}else
				{
					scrapProcessPsta.executeUpdate();
					scrapProcessPsta.close();
				}
			}
			cro.setV_errMsg("修改成功!");
			connection.commit();
        }
	   	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 conn
	 *            c
	 * @param strLcode
	 *            传递参数
	 * @return obj
	 * @throws Exception
	 *             异常处理
	 */
	public String queryMatNoM(Connection conn, String strLcode,String lotNo,String resultNo)
			throws Exception {
		int count = 0;
		PreparedStatement psta = null;
		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("FeedResult.queryMatNoM");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, strLcode);
		psta.setString(2, lotNo);
		psta.setString(3, resultNo);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			String res = rs.getString(1);
			if (res == null) {
				res = strLcode.replaceFirst("-.*", "") + "001";
			} else {
				count = Integer.parseInt(res.substring(res.length() - 3, res
						.length()));
			}
		}
		rs.close();
		psta.close();
		return (strLcode.replaceFirst("-.*", ""))
				+ StringTool.formatDecimal(++count, "000");
	}
}
