package com.steering.mes.zgmil.coup;

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

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.StringTool;
import com.steering.common.EntityTool;
import com.steering.mes.signature.MeanValueCalculation;
import com.steering.mes.zgmil.entity.FeedRowPlan;

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

/**
 * 试轧料
 * 
 * @author Administrator
 * 
 */
public class FrmTryRollingMaterial extends DBCommon {

	/**
	 * 按条件试轧料查询
	 * 
	 * @param SteelName
	 *            钢种
	 * @param Length
	 *            单倍长
	 * @param Section
	 *            断面或直径
	 * @param PlineCode
	 * @param date
	 * @return
	 */
	public CoreReturnObject getRollingMaterial(String SteelName, String Length,
			String Section, String PlineCode, String date, String JudgeNo,
			String deptid) {
		String sql = "";
		String sqlStr = "";
		if (!SteelName.equals("")) {
			sqlStr += " AND T.GRADENAME = '" + SteelName + "' ";
		}
		if (!Section.equals("")) {
			sqlStr += " AND T.DIMATER = '" + Section + "' ";
		}
		if (!Length.equals("")) {
			sqlStr += " AND T.ACT_LEN = '" + Length + "' ";
		}
		if (!JudgeNo.equals("")) {
			sqlStr += " AND T.JUDGE_STOVE_NO = '" + JudgeNo + "' ";
		}
		if (!date.equals("")) {
			sqlStr += " AND TO_CHAR(T.CREATE_TIME,'YYYYMMDD') = '" + date
					+ "' ";
		}
		if (deptid.equals("002")) {

		} else {
			sqlStr += " AND T.SUPPLY_UNIT_CODE = DECODE(SUBSTR('" + deptid
					+ "',1,6),'002001','120501','002023','120504') ";
		}

		sql = CoreXmlSqlParsersFactory
				.getSql("FrmTryRollingMaterial.getRollingMaterial");
		sql = sql.replace("#SomeThing#", sqlStr);
		return this.getData(sql);
	}

	/**
	 * 查询库存信息
	 * 
	 * @param SteelName
	 * @param Length
	 * @param Section
	 * @param PlineCode
	 * @return
	 */
	public CoreReturnObject getRollingMaterialDetail(String SteelName,
			String Length, String Section, String PlineCode, String JudgeNo) {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmTryRollingMaterial.getRollingMaterialDetail");
		return this.getData(sql, new Object[] { SteelName, Section, Length,
				JudgeNo });
	}

	/**
	 * 查询已组炉试轧料计划
	 * 
	 * @param JudgeStoveNo
	 * @param PlineCode
	 * @return
	 */
	public CoreReturnObject getBackSlabPlan(String JudgeStoveNo,
			String PlineCode) {
		String sql = "";
		String sqlStr = "";
		if (!JudgeStoveNo.equals("")) {
			sqlStr += " AND T.JUDGE_STOVE_NO = '" + JudgeStoveNo + "' ";
		}
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmTryRollingMaterial.getBackSlabPlan");
		sql = sql.replace("#SomeThing#", sqlStr);
		return this.getData(sql, new Object[] { PlineCode });
	}

	/**
	 * 查询已组炉试轧料计划2
	 * 
	 * @param JudgeStoveNo
	 * @param PlineCode
	 * @return
	 */
	public CoreReturnObject getBackSlabForJudgeStoveNo(String JudgeStoveNo,
			String PlineCode) {
		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmTryRollingMaterial.getBackSlabForJudgeStoveNo");
		return this.getData(sql, new Object[] { JudgeStoveNo, PlineCode });
	}

	/**
	 * 试轧料组炉
	 * 
	 * @param parm
	 * @param parm1
	 * @return
	 */
	public CoreReturnObject zpTryRollingMaterial(ArrayList<ArrayList> parm,
			ArrayList<String> parm1, String[] arr, FeedRowPlan FeedRowPlan1) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement psta = null;
		String sql = "";
		int acount = 0;
		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);
		int seq = 1;
		double inPutWgt = 0;// 上料量
		int inPutNum = 0;// 总支数
		int m = 0;
		ResultSet rs = null;
		try {
			connection.setAutoCommit(false); // 取消自动提交事务
			String sql1 = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.node"); // 管坯出库
			sql1 = sql1.replace("#something#", CoreConverter.toSqlConditionString("T2.STORAGE_NO", arr));
			PreparedStatement updateFurnaceReslut = connection
					.prepareStatement(sql1);

			String sql2 = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.insertMianPlan");// 插入主计划
			PreparedStatement insertMianPlan = connection
					.prepareStatement(sql2);

			String sql3 = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.insertFeedPlan");// 插入子计划
			PreparedStatement insertFeedPlan = connection
					.prepareStatement(sql3);

			String insertProcessSql = CoreXmlSqlParsersFactory
					.getSql("FeedResult.insertProcess");// 上料生成进程管号队列
			PreparedStatement insertProcessPsta = connection
					.prepareStatement(insertProcessSql);

			int result = FeedSawResult.comPareTime(systime,
					new SimpleDateFormat("yyyy-MM-dd").format(now)
							+ " 21:00:00");

			String supplyUnit = "";
			if(parm1.get(1).toString().equals("C072")){
				supplyUnit = "120504";
			}else{
				supplyUnit = "120501";
			}
			yearMoth = com.steering.common.StringTool.GetBalYear(now,com.steering.common.StringTool.GetSupplyUnit(parm1.get(1).toString()));//改25号结转


			String JudgeNo = parm1.get(0).toString();
			String LgJudgeNo = ""; // 炼钢判定炉号
			String pipeSection = ""; // 断面
			String plineCode = parm1.get(1).toString();
			String Shift = parm1.get(2).toString();
			String Group = parm1.get(3).toString();
			String UserName = parm1.get(4).toString();
			int MatNum = Integer.parseInt(parm1.get(5).toString());

			String gradeName = parm1.get(6).toString();
			String dimater = parm1.get(7).toString();
			int fixLen = Integer.parseInt(parm1.get(8).toString());
			int actLen = Integer.parseInt(parm1.get(9).toString());
			int fixNum = Integer.parseInt(parm1.get(10).toString());
			double actWeight = Double.parseDouble(parm1.get(11).toString());
			double dbWeight = actWeight / fixNum; // 单倍重

			for (ArrayList str : parm) {

				String BackFlag = "";// 库存坯料类型
				LgJudgeNo = str.get(1).toString(); // 炼钢判定炉号
				pipeSection = str.get(5).toString();// 断面
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmTryRollingMaterial.SelectKCZS");// 查询库存支数
				sql += CoreConverter.toSqlConditionString("T1.STORAGE_NO", arr);
				psta = connection.prepareStatement(sql);
				psta.setObject(1, str.get(1)); // 炼钢判定炉号
				psta.setObject(2, str.get(17)); // 申请判定单号
				psta.setObject(3, str.get(6)); // 坯长
				psta.setObject(4, str.get(7)); // 倍尺
				psta.setObject(5, str.get(2)); // 钢种
				psta.setObject(6, str.get(5)); // 断面
				rs = psta.executeQuery();
				if (rs.next()) {
					acount = Integer.parseInt(rs.getString("ACT_COUNT"));
				}
				rs.close();
				psta.close();
				if (Integer.parseInt(str.get(9).toString()) > acount) {
					cro.setV_errMsg("炉号'" + str.get(1) + "'库存不够!");
					return cro;
				}

				sql = CoreXmlSqlParsersFactory
						.getSql("FrmTryRollingMaterial.SelectBackFlag");// 查询库存坯料类型
				sql += CoreConverter.toSqlConditionString("T1.STORAGE_NO", arr);
				psta = connection.prepareStatement(sql);
				psta.setObject(1, str.get(1)); // 炼钢判定炉号
				psta.setObject(2, str.get(17)); // 申请判定单号
				psta.setObject(3, str.get(6)); // 坯长
				psta.setObject(4, str.get(7)); // 倍尺
				psta.setObject(5, str.get(2)); // 钢种
				psta.setObject(6, str.get(5)); // 断面
				rs = psta.executeQuery();
				if (rs.next()) {
					BackFlag = rs.getString("BACK_FLAG");
				}
				rs.close();
				psta.close();

				updateFurnaceReslut.setObject(1, str.get(1)); // 炼钢判定炉号
				updateFurnaceReslut.setObject(2, JudgeNo); // 组炉炉号
				updateFurnaceReslut.setObject(3, str.get(17)); // 申请判定单号
				updateFurnaceReslut.setObject(4, str.get(9)); // 支数
				updateFurnaceReslut.setObject(5, str.get(7)); // 倍尺
				updateFurnaceReslut.setObject(6, str.get(6)); // 坯长
				updateFurnaceReslut.setObject(7, yearMoth);
				updateFurnaceReslut.setObject(8, str.get(15)); // 仓库代码
				updateFurnaceReslut.addBatch();

				insertFeedPlan.setObject(1, JudgeNo + plineCode + fixNum);
				insertFeedPlan.setObject(2, JudgeNo);
				insertFeedPlan.setObject(3, plineCode);
				insertFeedPlan.setObject(4, str.get(7)); // 倍尺
				insertFeedPlan.setObject(5, str.get(11)); // 坯料量
				// 回炉坯，掉队坯不算投料量
				if (BackFlag.equals("1") || BackFlag.equals("3")) {
					insertFeedPlan.setObject(6, 0); // 来料重量
				} else {
					insertFeedPlan.setObject(6, str.get(10)); // 来料重量
				}
				insertFeedPlan.setObject(7, str.get(9)); // 支数
				insertFeedPlan.setObject(8, actLen);
				insertFeedPlan.setObject(9, actLen);
				insertFeedPlan.setObject(10, "");
				insertFeedPlan.setObject(11, "0");
				insertFeedPlan.setObject(12, "0");
				insertFeedPlan.setObject(13, fixLen);
				insertFeedPlan.setObject(14, dimater);
				insertFeedPlan.setObject(15, dbWeight); // 单倍重
				insertFeedPlan.setObject(16, UserName);
				insertFeedPlan.setObject(17, str.get(1));
				insertFeedPlan.setObject(18, str.get(9));
				insertFeedPlan.addBatch();

			}

			insertMianPlan.setString(1, JudgeNo + plineCode);
			insertMianPlan.setString(2, JudgeNo + plineCode);
			insertMianPlan.setString(3, JudgeNo);
			insertMianPlan.setString(4, plineCode);
			insertMianPlan.setInt(5, fixLen);
			insertMianPlan.setDouble(6, dbWeight); // 单倍重
			insertMianPlan.setString(7, "1");
			insertMianPlan.setString(8, pipeSection);
			insertMianPlan.setString(9, gradeName);
			insertMianPlan.setInt(10, fixNum);
			insertMianPlan.setString(11, "1");
			insertMianPlan.setInt(12, fixNum);
			insertMianPlan.setString(13, parm1.get(12).toString());
			insertMianPlan.setString(14, LgJudgeNo);
			insertMianPlan.setString(15, yearMoth);
			insertMianPlan.addBatch();

			updateFurnaceReslut.executeBatch();
			insertFeedPlan.executeBatch();
			insertMianPlan.executeBatch();

			// 上料生成进程管号队列
			sql = CoreXmlSqlParsersFactory.getSql("FeedResult.SelectFeedNum");
			sql = EntityTool.fillSqlByEntity(sql, FeedRowPlan1);
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			List<FeedRowPlan> list = EntityTool.getEntitysByRs(rs,
					FeedRowPlan.class);

			rs.close();
			psta.close();
			sql = CoreXmlSqlParsersFactory
					.getSql("FeedResult.SelectFeedToalWgt");
			sql = EntityTool.fillSqlByEntity(sql, FeedRowPlan1);
			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, FeedRowPlan1);
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			if (rs.next()) {
				inPutNum = Integer.parseInt(rs.getString("ACT_COUNT"));
			}
			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, FeedRowPlan1
					.getJudgeStoveNo(), FeedRowPlan1.getLotNo(), FeedRowPlan1
					.getResultNo()); // 母坯材料号
			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++) {
							// 上料生成进程管号队列
							insertProcessPsta.setString(1, FeedRowPlan1
									.getResultNo());
							insertProcessPsta.setString(2, FeedRowPlan1
									.getLotNo());
							insertProcessPsta.setString(3, FeedRowPlan1
									.getStoveNo());
							insertProcessPsta.setString(4, FeedRowPlan1
									.getJudgeStoveNo());
							insertProcessPsta.setString(5, FeedRowPlan1
									.getPlineCode());
							insertProcessPsta.setString(6, String.valueOf(seq));
							insertProcessPsta.setString(7, (FeedRowPlan1
									.getJudgeStoveNo().replaceFirst("-.*", ""))
									+ StringTool.formatDecimal(g, "000")
									+ i
									+ j);// 子管材料号
							insertProcessPsta.setString(8, "");// 定尺长度
							// new DecimalFormat("0.000").format(strWgt)
							insertProcessPsta.setString(9, "");// 重量
							insertProcessPsta.setString(10, systime);
							insertProcessPsta.setString(11, (FeedRowPlan1
									.getJudgeStoveNo().replaceFirst("-.*", ""))
									+ StringTool.formatDecimal(g, "000") + i);// 母管材料号
							insertProcessPsta.setString(12, (FeedRowPlan1
									.getJudgeStoveNo().replaceFirst("-.*", ""))
									+ StringTool.formatDecimal(g, "000"));// 母坯材料号
							insertProcessPsta.setString(13, String
									.valueOf(wgtList.get(m)));// 投料量
							insertProcessPsta.setString(14, yearMoth);
							insertProcessPsta.setString(15, FeedRowPlan1
									.getProPlanId()); // 轧管订单编号
							insertProcessPsta.setString(16, FeedRowPlan1
									.getGxPlanNo()); // 工序排产序号

							insertProcessPsta.addBatch();
							seq++;
							m++;
						}
					}
					g++;
				}
			}

			insertProcessPsta.executeBatch();
			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 parm
	 * @param parm2
	 * @return
	 */
	public CoreReturnObject BackFurSlab(ArrayList<ArrayList> parm,
			ArrayList<String> parm2) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement psta = null;
		String sql = "";
		ResultSet rs = null;
		String states = "";
		try {
			connection.setAutoCommit(false); // 取消自动提交事务
			String sql1 = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.nodeBack"); // 撤销出库
			PreparedStatement updateFurnaceReslut = connection
					.prepareStatement(sql1);

			String sql2 = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.deleteFeedPlan");// 删除轧管计划从表
			PreparedStatement deleteFeedPlan = connection
					.prepareStatement(sql2);

			String sql3 = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.deletePlan");// 删除轧管计划主表
			PreparedStatement deletePlan = connection.prepareStatement(sql3);

			String sql4 = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.deletePortMil");// 删除进程表管号队列
			PreparedStatement deletePortMil = connection.prepareStatement(sql4);

			sql = CoreXmlSqlParsersFactory
					.getSql("FrmTryRollingMaterial.SelectStatus");// 查询生产状态
			psta = connection.prepareStatement(sql);
			psta.setObject(1, parm2.get(0));
			psta.setObject(2, parm2.get(1));
			rs = psta.executeQuery();
			if (rs.next()) {
				states = rs.getString("STATUS");
			}
			rs.close();
			psta.close();
			if (!states.equals("00")) {
				cro.setV_errMsg("炉号'" + parm2.get(0) + "'已生产，不能组炉回退!");
				return cro;
			}

			for (ArrayList<String> aList : parm) {
				updateFurnaceReslut.setObject(1, aList.get(0));
				updateFurnaceReslut.setObject(2, aList.get(1));
				updateFurnaceReslut.setObject(3, aList.get(2));
				updateFurnaceReslut.setObject(4, aList.get(3));
				updateFurnaceReslut.setObject(5, aList.get(4));
				updateFurnaceReslut.addBatch();

				deleteFeedPlan.setObject(1, aList.get(0));
				deleteFeedPlan.setObject(2, aList.get(1));
				deleteFeedPlan.setObject(3, parm2.get(1));
				deleteFeedPlan.addBatch();

			}

			deletePlan.setObject(1, parm2.get(0));
			deletePlan.setObject(2, parm2.get(1));
			deletePlan.addBatch();

			deletePortMil.setString(1, parm2.get(0) + parm2.get(1));
			deletePortMil.setString(2, parm2.get(0));
			deletePortMil.setString(3, parm2.get(1));
			deletePortMil.addBatch();

			updateFurnaceReslut.executeBatch();
			deleteFeedPlan.executeBatch();
			deletePlan.executeBatch();
			deletePortMil.executeBatch();
			connection.commit();
			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
	 */
	private String getBalYearMoth(String systime) {
		String year = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdfS = new SimpleDateFormat("yyyyMM");
		try {
			Date date = sdf.parse(systime);
			Calendar calender = Calendar.getInstance();
			calender.setTime(date);
			calender.add(Calendar.DATE, 1);
			year = sdfS.format(calender.getTime());
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return year;

	}

	/**
	 * 根据炉号、批号自动生成材料号
	 * 
	 * @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");
	}

	/**
	 * 查询当月炉号数 并生成炉号 炉号为“E XX XX XXXX”
	 * 
	 * @return
	 */
	public CoreReturnObject queryCountJudgeStoveNo() {
		String sql = "SELECT 'E'||TO_CHAR(SYSDATE, 'YYMM')|| LPAD(NVL(SUBSTR(MAX(NUM),5, 9),0) + 1, 4, 0) AS NUM"
				+ "FROM ("
				+ "  SELECT SUBSTR(T.JUDGE_STOVE_NO, 1, 9) AS NUM"
				+ "  FROM MIL_PLAN T"
				+ "  WHERE T.PLINE_CODE = 'C072'"
				+ "    AND T.JUDGE_STOVE_NO LIKE 'E'||TO_CHAR(SYSDATE, 'YYMM')||'%'"
				+ "  UNION"
				+ "  SELECT T.FEED_HEAT_NO AS NUM"
				+ "  FROM PLN_ZY_ZG_M T"
				+ "  WHERE T.PLINE_CODE = 'C072'"
				+ "    AND T.FEED_HEAT_NO LIKE 'E'||TO_CHAR(SYSDATE, 'YYMM')||'%'"
				+ ")";
		return this.getData(sql);
	}

}
