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.PlnOrderJgxSEntity;
import com.steering.pss.plnsaleord.processOrder.entity.TimeEntity;

/**
 * 管加工工序合同
 * 
 * @author xiaohai
 * 
 */
public class CorePlnProcOrdJgx extends DBCommon {
	/**
	 * 查询管加工合同
	 * 
	 * @return
	 */
	public CoreReturnObject queryPlnJgxOrd(ArrayList<Object> list,
			String strFinish, Boolean haveJg) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CorePlnProcOrdJgx.queryPlnJgxOrd");
		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')))";
		}
		if (haveJg) {
			sql = sql + " AND T1.JGORD_IS_OK != '2'";
		}
		cro = this.getData(sql, list.toArray());
		return cro;
	}

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

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

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

	/**
	 * 查询管加工工序可用产线
	 * 
	 * @return
	 */
	public CoreReturnObject queryJgxProcPine(String proOrderNo) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnProcOrdJgx.queryJgxProcPine",
				new Object[] { proOrderNo });
		return cro;
	}

	/**
	 * 查询管加工物料可选产线
	 * 
	 * @return
	 */
	public CoreReturnObject queryJgxProcMaterialPine(String proOrderNo) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnProcOrdJgx.queryJgxProcMaterialPine",
				new Object[] { proOrderNo });
		return cro;
	}

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

	/**
	 * 查询接箍合同
	 * 
	 * @return
	 */
	public CoreReturnObject queryJgOrdInf(String orderNo, String orderSeq,
			String deliveryNo) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CorePlnProcOrdJgx.queryJgOrdInf",
				new Object[] { orderNo, orderSeq, deliveryNo });
		return cro;
	}

	/**
	 * 修改管加工产线
	 * 
	 * @return
	 * @throws ParseException
	 */
	public CoreReturnObject updateJgxOrdPline(ArrayList<PlnOrderJgxSEntity> 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("CorePlnProcOrdJgx.updateJgxOrdPline");
			for (PlnOrderJgxSEntity jgxsEntity : list) {
				String[] info = new String[1];
				modifyPine(conn, jgxsEntity, info);

				ps = conn.prepareStatement(sql);
				ps.setObject(1, jgxsEntity.getPlineCode());
				ps.setObject(2, jgxsEntity.getPlineCode());
				ps.setObject(3, jgxsEntity.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<PlnOrderJgxSEntity> 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("CorePlnProcOrdJgx.updateJgxOrdPline");
			String sqlUp = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcOrdJgx.updateGroupJgxOrd");
			String sqlUpE = CoreXmlSqlParsersFactory
					.getSql("CorePlnProcOrdJgx.updateGroupPlnOrdProc");
			PreparedStatement ps = null;

			for (PlnOrderJgxSEntity jgxsEntity : list) {
				String[] info = new String[1];
				String groupPlan = "";
				ps = conn.prepareStatement(CoreXmlSqlParsersFactory
						.getSql("CorePlnProcOrdJgx.queryPineBaseId"));
				ps.setObject(1, jgxsEntity.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("CorePlnProcOrdJgx.queryProcOrderNo"));
				ps.setObject(1, jgxsEntity.getProOrderNo());
				rs = ps.executeQuery();
				while (rs.next()) {
					if (!rs.getString("GX_PLAN_NO").equals(
							jgxsEntity.getGxPlanNo())) {
						if (!groupPlan.equals(rs.getString("PLINE_GROUP"))) {
							errMessage = "合同：" + jgxsEntity.getProOrderNo()
									+ "排产序号：" + rs.getString("GX_PLAN_NO")
									+ "的产线不在" + groupPlan + "组。";
							continue;
						}
					}
				}
				rs.close();
				ps.close();

				if (!modifyPine(conn, jgxsEntity, 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, jgxsEntity.getPlineCode());
				ps.setObject(2, jgxsEntity.getPlineCode());
				ps.setObject(3, jgxsEntity.getProOrderNo());
				ps.executeUpdate();
				ps.close();
				// 修改工序分组
				ps = conn.prepareStatement(sqlUp);
				ps.setObject(1, jgxsEntity.getPlineCode());
				ps.setObject(2, jgxsEntity.getProOrderNo());
				ps.executeUpdate();
				ps.close();
				// 修改排产分组
				ps = conn.prepareStatement(sqlUpE);
				ps.setObject(1, jgxsEntity.getPlineCode());
				ps.setObject(2, jgxsEntity.getProOrderNo());
				ps.setObject(3, jgxsEntity.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) {
				// 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 conn
	 * @param jgxsEntity
	 * @param message
	 * @return
	 * @throws SQLException
	 * @throws ParseException
	 */
	public boolean modifyPine(Connection conn, PlnOrderJgxSEntity jgxsEntity,
			String[] message) throws SQLException, ParseException {
		String plineCode = "";
		ProducHelperBean helperBean = new ProducHelperBean();
		PlnOrderJgxSEntity jgxsEntityN = PlnHelper.getEntityData(conn,
				new String[] { jgxsEntity.getProPlanId(),
						jgxsEntity.getGxPlanNo() },
				"AND T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?",
				PlnOrderJgxSEntity.class);
		if (jgxsEntityN == null) {
			message[0] = "加工线合同编号(" + jgxsEntity.getProOrderNo() + ")、工序排产序号("
					+ jgxsEntity.getGxPlanNo() + ")数据发生变化,不能产线变更!";
			return false;

		}
		plineCode = jgxsEntityN.getPlineCode();
		// 验证状态
		if (!jgxsEntityN.getExeStatus().equals("0")) {
			message[0] = "加工线合同编号(" + jgxsEntity.getProOrderNo() + ")、工序排产序号("
					+ jgxsEntity.getGxPlanNo() + ")不是计划状态,不能产线变更!";
			return false;
		}
		// 如果产线与数据库没有发生变化,则不作操作
		if (jgxsEntity.getPlineCode().equals(jgxsEntityN.getPlineCode())) {
			return false;
		}
		// 生产顺序号
		int maxGxProSeq = helperBean.getMaxGxProSeq(conn, jgxsEntity
				.getPlineCode(), "F", jgxsEntity.getProMonth());
		// 调整后的计划开始时间
		String maxEndTime = helperBean.getMaxPlanTimeE(conn, jgxsEntity
				.getPlineCode(), "G", jgxsEntity.getProMonth(), maxGxProSeq);
		// 产线能力
		double[] capacity = helperBean.getPlineCapacity(conn, jgxsEntityN
				.getInwlId(), jgxsEntityN.getOutwlId(), jgxsEntity
				.getPlineCode(), "G");
		// 重算用时与结束时间
		String beignTime = maxEndTime;
		TimeEntity time = new TimeEntity();

		time = BaseHelper.calculateTime(
				Integer.parseInt(jgxsEntityN.getNumS()), String
						.valueOf(capacity[0]), beignTime);
		// 修改产线(序号调至该产线最大)
		PlnHelper.deleteOrUpdate(conn, "CorePlnProcOrdJgx.plineChange",
				new Object[] { time.getBeginTime(), time.getEndTime(),
						time.getUserTime(), jgxsEntity.getPlineCode(),
						jgxsEntity.getPlineCode(), maxGxProSeq,
						jgxsEntity.getProPlanId(), jgxsEntity.getGxPlanNo() });
		// 修改顺序序号
		helperBean.seqIncrease(conn, plineCode, Integer.parseInt(jgxsEntityN
				.getGxProSeq()), -1, -1, "G");
		return true;
	}

}