package com.steering.pss.plnsaleord.jggxpln;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plan.order.model.PlnOrderJgEntity;

/**
 * 接箍合同利库
 * 
 * @author 2018.06.11 tjg
 * 
 */
public class FrmJgOrderLk extends DBCommon {

	/**
	 * 查询接箍合同
	 * 
	 * @return
	 */
	public CoreReturnObject queryJgOrder(String jgOrderNo, String orderNo,
			String codeJg, String[] jgStart, String[] pcStart) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmJgOrderLk.queryJgOrder");
		if (!jgOrderNo.equals("")) {
			sql += " AND T2.JG_ORDERNO LIKE '%" + jgOrderNo + "%'";
		}
		if (!orderNo.equals("")) {
			sql += " AND T2.ORDER_NO||'/'||T2.ORDER_SEQ LIKE '%" + orderNo
					+ "%'";
		}
		if (!codeJg.equals("")) {
			sql += " AND T2.CODE_JG='" + codeJg + "'";
		}
		if (jgStart.length > 0) {
			sql += CoreConverter.toSqlConditionString("T2.STATUS", jgStart);
		}
		if (pcStart.length > 0) {
			sql += CoreConverter.toSqlConditionString("T2.EXE_STATUS", pcStart);
		}
		return this.getData(sql);
	}

	/**
	 * 查询库存
	 * 
	 * @return
	 */
	public CoreReturnObject QueryMatM(String codeJg, String judgeStoveNo) {
		String sql = CoreXmlSqlParsersFactory.getSql("FrmJgOrderLk.QueryMatM");
		// if (!jgOrderNo.equals("")) {
		// sql += " AND M.JG_ORDERNO ='" + jgOrderNo + "' AND B.LOCK_LIKU='1'";
		// } else {
		// sql += " AND B.LOCK_LIKU!='1'";
		// }
		if(!judgeStoveNo.equals("")){
			 sql += " AND M.JUDGE_STOVE_NO ='" + judgeStoveNo + "'";
		}
		if (!codeJg.equals("")) {
			sql += " AND (M.CODE_JG='" + codeJg + "'OR M.CODE_JG IS NULL)";
		}
		sql += " ) WHERE PIECES>'0' ORDER BY CODE_JG ASC";
		return this.getData(sql);
	}

	/**
	 * 查询库存已挂合同
	 * 
	 * @return
	 */
	public CoreReturnObject QueryMatJgOrder(String codeJg, String jgOrderNo,
			String orderNo,String judgeNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmJgOrderLk.QueryMatJgOrder");
		if (!codeJg.equals("")) {
			sql += "    AND M.CODE_JG = '" + codeJg + "'";
		}
		if (!jgOrderNo.equals("")) {
			sql += "   AND P.JG_ORDERNO LIKE '%'||'" + jgOrderNo + "'||'%'";
		}
		if (!orderNo.equals("")) {
			sql += "   AND P.ORDER_NO||'/'||P.ORDER_SEQ LIKE '%'||'" + orderNo
					+ "'||'%'";
		}
		if (!judgeNo.equals("")) {
			sql += "   AND M.JUDGE_STOVE_NO LIKE '%'||'" + judgeNo
					+ "'||'%'";
		}
		return this.getData(sql);
	}

	/**
	 * 查询库存个数
	 */
	public static <T> T getQureyMatButt(Connection con, String matNo,
			String matNoXh, Class<T> cls) throws SQLException {
		String sql = "SELECT T.* FROM COUPLING_MAT_BUTTRESS T WHERE 1=1";
		sql += "  AND T.MAT_NO ='" + matNo + "' ";
		sql += "  AND T.MAT_NO_XH ='" + matNoXh + "' ";
		PreparedStatement ps = con.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 查询接箍合同信息
	 */
	public static <T> T getQureyJgOrder(Connection con, String JgOrderNo,
			Class<T> cls) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmJgOrderLk.getQureyJgOrder");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, JgOrderNo);
		ResultSet rs = ps.executeQuery();
		T t = EntityTool.getEntityByRs(rs, cls);
		rs.close();
		ps.close();
		return t;
	}

	/**
	 * 获取材料最大序号
	 * 
	 * @param con
	 * @return
	 * @throws SQLException
	 */
	public static String getMaxMatNoXh(Connection con, String matNo)
			throws SQLException {
		String matNoXh = "0001";
		String sql = " SELECT LPAD(SUBSTR(NVL(MAX(T.MAT_NO_XH),'0000'),-4,4) + 1, 4, '0') AS MAT_NO_XH FROM COUPLING_MAT_BUTTRESS T WHERE T.MAT_NO=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, matNo);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			matNoXh = rs.getString("MAT_NO_XH");
		}
		rs.close();
		ps.close();
		return matNoXh;
	}

	/**
	 * 利库
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doAdd(ArrayList<ArrayList<String>> jslist,
			String userName, String jgOrderNo) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			// 获取数据库当前时间
			// String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);

			PlnOrderJgEntity orderJg = getQureyJgOrder(conn, jgOrderNo,
					PlnOrderJgEntity.class);
			if (orderJg == null) {
				cro.setV_errMsg("无接箍合同信息!");
				return cro;
			}
			// 循环炉计划信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String codeJg = list.get(0);
				String matNo = list.get(1);
				String matNoXh = list.get(2);
				int koreNum = Integer.parseInt(list.get(3));
				// String koreWt = list.get(4);
				String woid = list.get(5);
				if (codeJg.equals("")) {
					cro.setV_errMsg("库存接箍码为空,不能利库!");
					return cro;
				}
				// 修改接箍合同利库个
				String updateOrder = "UPDATE COUPLING_MAT_M T SET T.CODE_JG=? WHERE T.MAT_NO=? ";
				ps = conn.prepareStatement(updateOrder);
				ps.setObject(1, codeJg);
				ps.setObject(2, matNo);
				ps.executeUpdate();
				ps.close();
				// 查询库存个和已挂合同个(余材个)
				int materNum = 0;
				double singleweight = 0;
				String sqlMatMidd = CoreXmlSqlParsersFactory
						.getSql("FrmJgOrderLk.getQureyMatMidd");
				ps = conn.prepareStatement(sqlMatMidd);
				ps.setObject(1, matNo);
				ps.setObject(2, matNoXh);
				rs = ps.executeQuery();
				if (rs.next()) {
					materNum = rs.getInt("PRO_NUM");
					singleweight = rs.getDouble("SINGLEWEIGHT");
				}
				rs.close();
				ps.close();
				if (materNum == 0) {
					cro.setV_errMsg("无可利库库存信息!");
					return cro;
				}
				// // 查询库存支数可利个数
				// CouplingMatButtressEntity matButt = getQureyMatButt(conn,
				// matNo, matNoXh, CouplingMatButtressEntity.class);
				// if (matButt == null) {
				// cro.setV_errMsg("无库存信息!");
				// return cro;
				// }
				//
				// int pieces = 0;
				// if (!matButt.getPieces().equals("")) {
				// pieces = Integer.parseInt(matButt.getPieces());
				// }

				int num = 0;
				if (materNum - koreNum <= 0) {
					num = materNum;
				} else {
					num = koreNum;
				}
				// 查询是否存在同炉号同炉号，同工单号的工单详情表
				int count = 0;
				String sqlMidd = "SELECT  COUNT(*) COUNT FROM PLN_ZY_JG_MIDDLE T WHERE NVL(T.WO_ID,'/')=NVL(?,'/') AND T.ORD_LN_DLY_PK=?  AND T.MAT_NO=?  AND T.MAT_NO_XH=? AND T.STATUS='1'";
				ps = conn.prepareStatement(sqlMidd);
				ps.setObject(1, woid);
				ps.setObject(2, orderJg.getOrdLnDlyPk());
				ps.setObject(3, matNo);
				ps.setObject(4, matNoXh);
				rs = ps.executeQuery();
				if (rs.next()) {
					count = rs.getInt("COUNT");
				}
				rs.close();
				ps.close();

				if (count == 0) {
					// 新增接箍工单详细表
					String addPlnMidd = CoreXmlSqlParsersFactory
							.getSql("FrmJgOrderLk.AddPlnZyJgMidd");
					ps = conn.prepareStatement(addPlnMidd);
					ps.setObject(1, orderJg.getJgOrderno());
					ps.setObject(2, num);
					ps.setObject(3, num);
					ps.setObject(4, "");
					ps.setObject(5, userName);
					ps.setObject(6, orderJg.getOrderNo());
					ps.setObject(7, orderJg.getOrderSeq());
					ps.setObject(8, orderJg.getDeliveryNo());
					ps.setObject(
							9,
							orderJg.getOrdLnDlyPk().substring(0,
									orderJg.getOrdLnDlyPk().length() - 6));
					ps.setObject(
							10,
							orderJg.getOrdLnDlyPk().substring(0,
									orderJg.getOrdLnDlyPk().length() - 3));
					ps.setObject(11, orderJg.getOrdLnDlyPk());
					ps.setObject(12, orderJg.getCraftSeq());
					ps.setObject(13, orderJg.getCraftFileNo());
					ps.setObject(14, matNoXh);
					ps.setObject(15, orderJg.getDemandCopper());
					ps.setObject(16, orderJg.getDemandDetection());
					ps.setObject(17, orderJg.getDemandBlast());
					ps.setObject(18, orderJg.getDemandBonderizing());					
					ps.setObject(19, matNo);
					ps.executeUpdate();
					ps.close();
				} else {
					// 修改接箍工单详情表
					String updateMidd = CoreXmlSqlParsersFactory
							.getSql("FrmJgOrderLk.updatePlnZyJgMidd");
					ps = conn.prepareStatement(updateMidd);
					ps.setObject(1, num);
					ps.setObject(2, num * (singleweight / 1000));
					ps.setObject(3, woid);
					ps.setObject(4, orderJg.getOrdLnDlyPk());
					ps.setObject(5, matNo);
					ps.setObject(6, matNoXh);
					ps.executeUpdate();
					ps.close();
				}
				// 修改接箍合同利库个
				String updateOrderJ = "UPDATE PLN_ORDER_JG T SET T.HANGKC_NUM=TO_NUMBER(NVL(T.HANGKC_NUM,0))+TO_NUMBER(?) WHERE T.JG_ORDERNO=?";
				ps = conn.prepareStatement(updateOrderJ);
				ps.setObject(1, num);
				ps.setObject(2, orderJg.getJgOrderno());
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("利库成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 撤销利库
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doDelete(ArrayList<ArrayList<String>> jslist,
			String userName) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			ResultSet rs = null;
			// 获取数据库当前时间
			// String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
			//
			// PlnOrderJgEntity orderJg = getQureyJgOrder(conn, jgOrderNo,
			// PlnOrderJgEntity.class);
			// if (orderJg == null) {
			// cro.setV_errMsg("无接箍合同信息!");
			// return cro;
			// }
			// 循环炉计划信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				// String codeJg = list.get(0);
				// String matNo = list.get(1);
				// String matNoXh = list.get(2);
				// String woId = list.get(3);
				String guid = list.get(4);
				String jgOrderNo = list.get(4);
				int num = 0;
				// 查询接箍工单详情表
				String sql = "SELECT T.PLAN_NUM FROM PLN_ZY_JG_MIDDLE T WHERE T.GUID=?";
				ps = conn.prepareStatement(sql);
				ps.setObject(1, guid);
				rs = ps.executeQuery();
				if (rs.next()) {
					num = rs.getInt("PLAN_NUM");
				}
				rs.close();
				ps.close();
				if (num == 0) {
					cro.setV_errMsg("选中的利库库存信息已删除!");
					return cro;
				}
				// 删除接箍工单详情表
				String deleteMidd = "DELETE PLN_ZY_JG_MIDDLE WHERE GUID = ?";
				ps = conn.prepareStatement(deleteMidd);
				ps.setObject(1, guid);
				ps.executeUpdate();
				ps.close();

				// 修改接箍合同利库个
				String updateOrderJ = "UPDATE PLN_ORDER_JG T SET T.HANGKC_NUM=TO_NUMBER(NVL(T.HANGKC_NUM,0))+TO_NUMBER(?) WHERE T.JG_ORDERNO=?";
				ps = conn.prepareStatement(updateOrderJ);
				ps.setObject(1, num);
				ps.setObject(2, jgOrderNo);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("撤销成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改库存接箍码
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doUpdate(ArrayList<ArrayList<String>> jslist,
			String userNam) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			// ResultSet rs = null;
			// 循环炉计划信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String codeJg = list.get(0);
				// String judgeStoveNo = list.get(1);
				// String batchNo = list.get(2);
				String matNo = list.get(3);

				// 修改接箍合同利库个
				String updateOrder = "UPDATE COUPLING_MAT_M T SET T.CODE_JG=? WHERE T.MAT_NO=? ";
				ps = conn.prepareStatement(updateOrder);
				ps.setObject(1, codeJg);
				ps.setObject(2, matNo);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 修改库存接箍码
	 * 
	 * @param jslist
	 * @param userName
	 * @return
	 */
	public CoreReturnObject doUpdateDelte(ArrayList<ArrayList<String>> jslist,
			String userNam) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			// ResultSet rs = null;
			// 循环炉计划信息
			for (int i = 0; i < jslist.size(); i++) {
				ArrayList<String> list = (ArrayList<String>) jslist.get(i);
				String matNo = list.get(0);

				// 修改接箍合同利库个
				String updateOrder = "UPDATE COUPLING_MAT_M T SET T.CODE_JG='' WHERE T.MAT_NO=? ";
				ps = conn.prepareStatement(updateOrder);
				ps.setObject(1, matNo);
				ps.executeUpdate();
				ps.close();
			}
			cro.setV_errMsg("修改成功!");
			conn.commit();
		} catch (SQLException sqle) {
			try {
				if (conn != null) {
					conn.rollback();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			cro.setV_errMsg(sqle.getMessage());
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return cro;
	}
}