package com.steering.pss.plnsaleord.processOrder;

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

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

import com.steering.comm.db.DBCommon;
import com.steering.pss.plnsaleord.base.PlnHelper;
import com.steering.pss.plnsaleord.processOrder.base.BaseHelper;
import com.steering.pss.plnsaleord.processOrder.base.ProducHelperBean;
import com.steering.pss.plnsaleord.processOrder.entity.PlnOrderRclSEntity;
import com.steering.pss.plnsaleord.processOrder.entity.TimeEntity;

/**
 * 热处理工序合同
 * 
 * @author xiaohai
 */
public class CorePlnProcOrdRcl extends DBCommon {
	/**
	 * 查询热处理合同
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlnRclOrd(ArrayList<Object> list,
			String strFinish) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnProcOrdRcl.queryPlnRclOrd");
		if (strFinish.equals("0")) {
			sql = sql + " AND (T2.PLANSTATUS IN ('1', '2', '3') OR "
					+ "(T2.PLANSTATUS IN ('4', '5') AND "
					+ "TO_DATE(T1.ROLL_MONTH, 'YYYY-MM') = "
					+ "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
		} else if (strFinish.equals("1")) {
			sql = sql + " AND (T2.PLANSTATUS IN ('1', '2', '3', '4') OR "
					+ "(T2.PLANSTATUS = '5' AND "
					+ "TO_DATE(T1.ROLL_MONTH, 'YYYY-MM') = "
					+ "TO_DATE(TO_CHAR(SYSDATE, 'YYYY-MM'), 'YYYY-MM')))";
		}
		cro = this.getData(sql, list.toArray());
		return cro;
	}

	/**
	 * 查询工序基础表
	 * 
	 * @return
	 */
	public CoreReturnObject queryBaseProcess() {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnProcOrdRcl.queryBaseProcess");
		return cro;
	}

	/**
	 * 查询产线基础信息
	 * 
	 * @return
	 */
	public CoreReturnObject queryPineBase(String ProcessCode) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnProcOrdRcl.queryPineBase",
				new Object[] { ProcessCode });
		return cro;
	}

	/**
	 * 查询热处理工序可用产线
	 * 
	 * @return
	 */
	public CoreReturnObject queryRclProcMaterialPine(String proOrderNo) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnProcOrdRcl.queryRclProcMaterialPine",
				new Object[] { proOrderNo });
		return cro;
	}

	/**
	 * 查询热处理工序状态
	 * 
	 * @return
	 */
	public CoreReturnObject queryProcOrdStatus(String proOrderNo,
			String gxPlanNo) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnProcOrdRcl.queryProcOrdStatus",
				new Object[] { proOrderNo, gxPlanNo });
		return cro;
	}

	/**
	 * 修改热处理产线
	 * 
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject updateRclOrdPline(ArrayList<PlnOrderRclSEntity> list)
			throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcOrdRcl.updateRclOrdPline");
			for (PlnOrderRclSEntity rclsEntity : list) {
				String[] info = new String[1];
				modifyPine(conn, rclsEntity, info);

				ps = conn.prepareStatement(sql);
				ps.setObject(1, rclsEntity.getPlineCode());
				ps.setObject(2, rclsEntity.getPlineCode());
				ps.setObject(3, rclsEntity.getProOrderNo());
				ps.executeUpdate();
				ps.close();

				conn.commit();
			}
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改热处理产线、分组
	 * 
	 * @param list
	 * @return
	 * @throws ParseException 
	 */
	public CoreReturnObject updatePlinGroup(ArrayList<PlnOrderRclSEntity> list) throws ParseException {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			String errMessage = "";
			int dealNum = 0;
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			String sql = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcOrdRcl.updateRclOrdPline");
			String sqlUp = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcOrdRcl.updateGroupJgxOrd");
			String sqlUpE = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcOrdRcl.updateGroupPlnOrdProc");
			PreparedStatement ps = null;

			for (PlnOrderRclSEntity rclsEntity : list) {
				String[] info = new String[1];
				String groupPlan = "";
				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CorePlnProcOrdJgx.queryPineBaseId"));
				ps.setObject(1, rclsEntity.getPlineCode());
				ResultSet rs = ps.executeQuery();
				if (rs.next()) {
					if (rs.getString("GROUP_PLAN") != null) {
						groupPlan = rs.getString("GROUP_PLAN");
					} else {
						errMessage = "未找到产线：" + rs.getString("PLINE_NAME")
								+ "对应分组。";
						continue;
					}
				}
				rs.close();
				ps.close();

				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CorePlnProcOrdRcl.queryProcOrderNo"));
				ps.setObject(1, rclsEntity.getProOrderNo());
				rs = ps.executeQuery();
				while (rs.next()) {
					if (!rs.getString("GX_PLAN_NO").equals(
							rclsEntity.getGxPlanNo())) {
						if (!groupPlan.equals(rs.getString("PLINE_GROUP"))) {
							errMessage = "合同：" + rclsEntity.getProOrderNo()
									+ "排产序号：" + rs.getString("GX_PLAN_NO")
									+ "的产线不在" + groupPlan + "组。";
							continue;
						}
					}
				}
				rs.close();
				ps.close();

				if (!modifyPine(conn, rclsEntity, info)) {
					try {
						conn.rollback();
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					errMessage = info[0];
					continue;
				}
				// 修改工序产线
				ps = conn.prepareStatement(sql);
				ps.setObject(1, rclsEntity.getPlineCode());
				ps.setObject(2, rclsEntity.getPlineCode());
				ps.setObject(3, rclsEntity.getProOrderNo());
				ps.executeUpdate();
				ps.close();
				// 修改工序分组
				ps = conn.prepareStatement(sqlUp);
				ps.setObject(1, rclsEntity.getPlineCode());
				ps.setObject(2, rclsEntity.getProOrderNo());
				ps.executeUpdate();
				ps.close();
				// 修改排产分组
				ps = conn.prepareStatement(sqlUpE);
				ps.setObject(1, rclsEntity.getPlineCode());
				ps.setObject(2, rclsEntity.getProOrderNo());
				ps.setObject(3, rclsEntity.getProOrderNo());
				ps.executeUpdate();
				ps.close();

				dealNum++;
				conn.commit();
			}
			cro.setResult(dealNum + "条操作成功，" + (list.size() - dealNum)
					+ "条操作失败。\n" + errMessage);
		} catch (SQLException sqle) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改产线
	 * 
	 * @param conn
	 * @param jgxsEntity
	 * @param message
	 * @return
	 * @throws SQLException
	 * @throws ParseException
	 */
	public boolean modifyPine(Connection conn, PlnOrderRclSEntity entity,
			String[] message) throws SQLException, ParseException {
		ProducHelperBean helperBean = new ProducHelperBean();
		String plineCode = "";
		PlnOrderRclSEntity entityN = PlnHelper.getEntityData(conn,
				new String[] { entity.getProPlanId(), entity.getGxPlanNo() },
				"ProducHelperBean.getPlanOrderF",
				"AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?",
				PlnOrderRclSEntity.class);
		if (entityN == null) {
			message[0] = "热处理合同编号(" + entity.getProOrderNo() + ")、工序排产序号"
					+ entity.getGxPlanNo() + "数据发生变化,请刷新数据!";
			return false;
		}
		plineCode = entityN.getPlineCode();

		// 验证状态
		if (!(entityN.getExeStatus().equals("计划") || entityN.getExeStatus()
				.equals("生产中"))) {
			message[0] = "热处理合同编号(" + entity.getProOrderNo() + ")、工序排产序号"
					+ entity.getGxPlanNo() + "不是计划或者生产状态!";
			return false;
		}
		// 如果产线与数据库没有发生变化,则不作操作
		if (entity.getPlineCode().equals(entityN.getPlineCode())) {
			return false;
		}
		// 生产顺序号
		int maxGxProSeq = helperBean.getMaxGxProSeq(conn,
				entity.getPlineCode(), "F", entityN.getProMonth());
		// 调整后的计划开始时间
		String maxEndTime = helperBean.getMaxPlanTimeE(conn, entity
				.getPlineCode(), "F", entityN.getProMonth(), maxGxProSeq);
		// 产线能力
		double[] capacity = helperBean.getPlineCapacity(conn, entityN
				.getInwlId(), entityN.getOutwlId(), entity.getPlineCode(), "F");
		// 重算用时与结束时间
		String beignTime = maxEndTime;
		TimeEntity time = new TimeEntity();
		if (capacity[0] <= 0) {
			time.setBeginTime(beignTime);
			time.setEndTime(beignTime);
			time.setUserTime("0");
		} else {
			time = BaseHelper.calculateTime(
					Integer.parseInt(entityN.getNumS()), String
							.valueOf(capacity[0]), beignTime);
		}

		// 修改产线(序号调至该产线最大)
		entity.setNumS(entityN.getNumS());
		entity.setWeigthS(entityN.getWeigthS());
		entity.setPlanTimeB(time.getBeginTime());
		entity.setPlanTimeE(time.getEndTime());
		entity.setPlanUsetime(time.getUserTime());

		entity.setGxProSeq(String.valueOf(maxGxProSeq));
		PlnHelper.deleteOrUpdateByEntity(conn,
				"ProducHelperBean.updatePlanOrderF", entity);
		// 修改顺序序号
		helperBean.seqIncrease(conn, plineCode, Integer.parseInt(entityN
				.getGxProSeq()), -1, -1, "F");
		return true;
	}

}