package com.steering.pss.plnsaleord.order;

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.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.order.model.PlnSaleorderRNumEntity;

/**
 * 合同补量申请
 * 
 * @author xiaohai
 * @date 2015.10.12
 */
public class CoreReqRequest extends DBCommon {
	/**
	 * 查询合同
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject querySaleOrder(ArrayList<Object> list,
			Boolean isConfirm) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreReqRequest.querySaleOrder");
		if (isConfirm) {
			sql += " AND (SELECT SUM(B.REQWEIGHT)"
					+ " FROM PLN_SALEORDER_R_NUM B"
					+ " WHERE B.ORD_LN_DLY_PK = T.ORD_LN_DLY_PK) != 0";
		}
		cro = this.getData(sql, list.toArray());
		return cro;
	}

	/**
	 * 查询合同补量申请
	 * 
	 * @return
	 */
	public CoreReturnObject getOrdRNum(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreRequestR.getOrdRNum",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询最后一个交货行拆分信息
	 * 
	 * @return
	 */
	public CoreReturnObject getLastPlnOrdProc(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreRequestR.getLastPlnOrdProc",
				new Object[] { str, str });
		return cro;
	}

	/**
	 * 查询补量合同
	 * 
	 * @return
	 */
	public CoreReturnObject getReqOrder(ArrayList<String> list) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.getReqOrder");
		if (!list.get(list.size() - 1).equals("1")) {
			sql += " AND T1.PLAN_DEAL_NAME IS NULL";
		}
		list.remove(list.size() - 1);
		cro = this.getData(sql, list.toArray());
		return cro;
	}

	/**
	 * 新增合同补量申请
	 * 
	 * @return
	 */
	public CoreReturnObject addOrderRNum(ArrayList<PlnSaleorderRNumEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.addOrderRNum");
		String sqlUp = EntityTool.fillSqlByEntity(sql, list.get(0));
		cro = this.setData(sqlUp);
		return cro;
	}

	/**
	 * 删除合同补量申请
	 * 
	 * @return
	 */
	public CoreReturnObject deleteOrderRNum(ArrayList<String> list) {
		CoreReturnObject cro = new CoreReturnObject();
		ArrayList<String> sqllist = new ArrayList<String>();
		ArrayList<Object[]> parmlist = new ArrayList<Object[]>();

		Connection conn = null;
		PreparedStatement psta = null;
		try {
			String sql = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.getOrdRNumbyid")
					+ " AND T.PLAN_DEAL_NAME IS NOT NULL";

			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			for (int i = 0; i < list.size(); i++) {
				psta = conn.prepareStatement(sql);
				psta.setObject(1, list.get(i));
				ResultSet rs = psta.executeQuery();
				if (rs.next()) {
					cro.setV_errMsg("补量合同：" + list.get(i) + "，已确认，不能删除！");
					cro.setResult(1);
					return cro;
				}
				rs.close();
				psta.close();
			}
			conn.commit();
		} catch (SQLException sqle) {
			try {
				cro.setV_errMsg(sqle.getLocalizedMessage());
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		for (int i = 0; i < list.size(); i++) {
			sqllist.add("CoreRequestR.deleteOrderRNum");
			parmlist.add(new Object[] { list.get(i) });
		}
		cro = this.setDataById(sqllist, parmlist);
		return cro;
	}

	/**
	 * 修改合同补量申请
	 * 
	 * @return
	 */
	public CoreReturnObject doModify(PlnSaleorderRNumEntity rNumEntity) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory.getSql("CoreRequestR.doModify");
		String sqlUp = EntityTool.fillSqlByEntity(sql, rNumEntity);

		Connection conn = null;
		PreparedStatement psta = null;
		try {
			String sqlId = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.getOrdRNumbyid")
					+ " AND T.PLAN_DEAL_NAME IS NOT NULL";

			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			psta = conn.prepareStatement(sqlId);
			psta.setObject(1, rNumEntity.getRNumId());
			ResultSet rs = psta.executeQuery();
			if (rs.next()) {
				cro.setV_errMsg("补量合同：" + rNumEntity.getRNumId() + "，已确认，不能修改！");
				cro.setResult(1);
				return cro;
			}
			rs.close();
			psta.close();
			conn.commit();
		} catch (SQLException sqle) {
			try {
				cro.setV_errMsg(sqle.getLocalizedMessage());
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		cro = this.setData(sqlUp);
		return cro;
	}

	/**
	 * 合同补量申请确认
	 * 
	 * @return
	 */
	public CoreReturnObject setConfirm(ArrayList<PlnSaleorderRNumEntity> list) {
		CoreReturnObject cro = new CoreReturnObject();

		Connection conn = null;
		PreparedStatement psta = null;
		try {
			String sqlUpdate = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.confirmOrderRNum");
			String sqlAddProc = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.ordRNumToPlnProc");
			String sqlUpProc = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.updateOrdRNumProc");
			String sqlQuery = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.queryIsConfrimProc");
			String sqlPk = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.queryRequestOrdPk");

			String sql = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.getOrdRNumbyid");
			String sqlAcp = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.getAcceptNum");

			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);

			PreparedStatement ps = conn.prepareStatement(sqlAcp);
			ResultSet result = ps.executeQuery();
			if (result.next()) {
				if (result.getString("ACCEPTNO") != null) {
					String acceptNo = result.getString("ACCEPTNO");
					for (PlnSaleorderRNumEntity rNumEntity : list) {
						psta = conn.prepareStatement(sql);
						psta.setObject(1, rNumEntity.getRNumId());
						ResultSet rs = psta.executeQuery();
						if (rs.next()) {
							if (rs.getDouble("REP_QTY") != Double
									.valueOf(rNumEntity.getRepQty())) {
								cro.setV_errMsg("补量合同："
										+ rNumEntity.getRNumId()
										+ "，申请量有变化，请刷新后再确认。");
								return cro;
							}
						} else {
							cro.setV_errMsg("补量合同：" + rNumEntity.getRNumId()
									+ "，未找到记录，请刷新后再确认。");
							return cro;
						}
						rs.close();
						psta.close();
					}

					for (PlnSaleorderRNumEntity rNumEntity : list) {
						boolean isConfirm = false;
						double confirmWt = Double.parseDouble(rNumEntity
								.getConfirmWt());
						double reqWeight = Double.parseDouble(rNumEntity
								.getReqweight());
						double orderQty = Double.parseDouble(rNumEntity
								.getRepQty());
						String region = CorePlnSaleOrder.getOrdRegion(conn,
								rNumEntity.getOrdLnDlyPk());// 国内外

						orderQty = orderQty * confirmWt / reqWeight;
						rNumEntity.setRepQty(String.valueOf(orderQty));
						rNumEntity.setAcceptNo(acceptNo);

						String sqlUp = EntityTool.fillSqlByEntity(sqlUpdate,
								rNumEntity);
						String sqlAdd = EntityTool.fillSqlByEntity(sqlAddProc,
								rNumEntity);
						sqlAdd = sqlAdd.replace("#IF_EXPORT#", region);
						psta = conn.prepareStatement(sqlUp);
						psta.executeUpdate();
						psta.close();

						psta = conn.prepareStatement(sqlQuery);
						psta.setObject(1, rNumEntity.getRNumId());
						ResultSet rs = psta.executeQuery();
						if (rs.next()) {
							isConfirm = true;
							if (!rs.getString("PLANSTATUS").equals("1")) {
								cro.setV_errCode(-1);
								cro.setV_errMsg("补量需求已经排产下发，不能修改！");
								return cro;
							}
						}
						rs.close();
						psta.close();

						if (isConfirm) {
							psta = conn.prepareStatement(sqlUpProc);
							psta.setObject(1, rNumEntity.getConfirmWt());
							psta.setObject(2, rNumEntity.getConfirmWt());
							psta.setObject(3, rNumEntity.getRepQty());
							psta.setObject(4, rNumEntity.getRNumId());
							psta.executeUpdate();
							psta.close();
						} else {
							psta = conn.prepareStatement(sqlAdd);
							psta.executeUpdate();
							psta.close();
						}

						// 补量后修改交货行状态
						psta = conn.prepareStatement(sqlPk);
						psta.setObject(1, rNumEntity.getRNumId());
						rs = psta.executeQuery();
						if (rs.next()) {
							if (rs.getString("ORD_LN_DLY_PK") != null
									&& rs.getString("ORD_LN_PK") != null) {
								String ordLnDlyPk = rs
										.getString("ORD_LN_DLY_PK");
								String ordLnPk = rs.getString("ORD_LN_PK");
								setRequestOrdLnDly(conn, ordLnPk, ordLnDlyPk);
							}
						}
						rs.close();
						psta.close();

						psta = conn.prepareStatement(sqlQuery);
						psta.setObject(1, rNumEntity.getRNumId());
						rs = psta.executeQuery();
						if (rs.next()) {
							PreparedStatement pst = null;
							int planNum = 0;
							double planTotLen = 0;
							double aimlen = rs.getDouble("AIM_LEN_END");
							double weigthMi = rs.getDouble("WEIGHT_PER_M");

							double delvryRangeMax = 0;// 交货量差上限
							double delvryRangeMin = 0;// 交货量差下限
							if (rs.getString("DELVRY_RANGE_TPE").trim()
									.equals("绝对值")) {
								delvryRangeMax = (rs
										.getDouble("DELVRY_RANGE_MAX") / orderQty) * 100;
								delvryRangeMin = (rs
										.getDouble("DELVRY_RANGE_MIN") / orderQty) * 100;
							} else {
								delvryRangeMax = rs
										.getDouble("DELVRY_RANGE_MAX");
								delvryRangeMin = rs
										.getDouble("DELVRY_RANGE_MIN");
							}

							double rate = 0;
							double rateMin = 0;// 最小排产系数
							double putRate = 1;// 排产原则
							// rate = ((delvryRangeMax + delvryRangeMin) * 1 -
							// delvryRangeMin) / 100;
							rate = 1 + ((delvryRangeMax + delvryRangeMin)
									* putRate - delvryRangeMin) / 100;
							rateMin = 1 - delvryRangeMin / 100;
							if(weigthMi!=0){
								planTotLen = confirmWt / weigthMi;
							}
							if (confirmWt % (aimlen * weigthMi) < 0.00000001) {
								planNum = (int) (confirmWt / (aimlen * weigthMi));
							} else {
								planNum = (int) (confirmWt / (aimlen * weigthMi + 1));
							}

							// 排产量
							double reqPcWt = (confirmWt - planNum
									* rs.getDouble("WEIGHT_JG") / 1000)
									* (rate);

							String sqlupdate = CoreXmlSqlParsersFactory
									.getSql("CoreRequestR.updateOrdProcNum");
							pst = conn.prepareStatement(sqlupdate);
							pst.setObject(1, planNum);
							pst.setObject(2, planTotLen);
							pst.setObject(3, reqPcWt);
							pst.setObject(4, reqPcWt * rateMin);
							pst.setObject(5, rNumEntity.getRNumId());
							pst.executeUpdate();
							pst.close();
						}
						rs.close();
						psta.close();
					}
				}
			}
			result.close();
			ps.close();
			conn.commit();
		} catch (SQLException sqle) {
			try {
				cro.setV_errMsg(sqle.getLocalizedMessage());
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			cro.setV_errCode(-1);
			cro.setV_errMsg(sqle.getMessage());
			return cro;
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 取消确认
	 * 
	 * @param list
	 * @return
	 */
	public CoreReturnObject canCelConfirm(ArrayList<String> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection conn = null;
		try {
			conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			conn.setAutoCommit(false);
			PreparedStatement ps = null;
			String sqlu = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.canCelConfirmRNum");
			String sqldel = CoreXmlSqlParsersFactory
					.getSql("CoreRequestR.canCelOrdProcReq");

			for (String rNumId : list) {
				String planStrat = "";
				String planStratName = "";
				String sql = CoreXmlSqlParsersFactory
						.getSql("CoreRequestR.QueryPlnSproc");
				PreparedStatement ps1 = conn.prepareStatement(sql);
				ps1.setObject(1, rNumId);
				ResultSet rs1 = ps1.executeQuery();
				if (rs1.next()) {
					planStrat = rs1.getString("PLANSTATUS");
					planStratName = rs1.getString("PLANSTATUSNAME");
				}
				rs1.close();
				ps1.close();
				if (planStrat.equals("")) {
					cro.setResult("该补量合同是未确认,不允许取消！");
					return cro;
				}
				if (!planStrat.equals("1")) {
					cro.setResult("该补量合同是" + planStratName + "状态,不允许取消确认！");
					return cro;
				}

				ps = conn.prepareStatement(sqlu);
				ps.setObject(1, rNumId);
				ps.executeUpdate();
				ps.close();

				ps = conn.prepareStatement(sqldel);
				ps.setObject(1, rNumId);
				ps.executeUpdate();
				ps.close();

				String sqlPk = CoreXmlSqlParsersFactory
						.getSql("CoreRequestR.queryRequestOrdPkCX");
				ps = conn.prepareStatement(sqlPk);
				ps.setObject(1, rNumId);
				ResultSet rs2 = ps.executeQuery();
				if (rs2.next()) {
					if (rs2.getString("ORD_LN_DLY_PK") != null
							&& rs2.getString("ORD_LN_PK") != null) {
						String ordLnDlyPk = rs2.getString("ORD_LN_DLY_PK");
						String ordLnPk = rs2.getString("ORD_LN_PK");
						String pnDivideId = "";
						CoreOrdFinishSet.setPlnOrdStatus(conn, ordLnPk,
								ordLnDlyPk, "4", pnDivideId,"");
					}
				}
				rs2.close();
				ps.close();
				conn.commit();
			}
			cro.setResult("操作成功！");
		} catch (SQLException sqle) {
			try {
				cro.setV_errCode(-1);
				cro.setV_errMsg(sqle.getLocalizedMessage());
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (ParseException pe) {
			// TODO Auto-generated catch block
			try {
				cro.setV_errCode(-1);
				cro.setV_errMsg(pe.getLocalizedMessage());
				conn.rollback();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} finally {
			try {
				if (conn != null && !conn.isClosed()) {
					conn.close();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return cro;
	}

	/**
	 * 回退交货行、合同行状态
	 * 
	 * @param conn
	 * @param ordLnPk
	 * @param ordLnDlyPk
	 * @throws SQLException
	 */
	public void setRequestOrdLnDly(Connection conn, String ordLnPk,
			String ordLnDlyPk) throws SQLException {
		PreparedStatement psta = null;
		String sqlUp = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.setModifySale");
		String sqlUpProc = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.setModifySaleProc");
		String sqlDelivery = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.setLineDeliveryStatus");
		String sqlQuery = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.queryLineStatus");
		String sqlUpLine = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.setOrdLineStatus");
		psta = conn.prepareStatement(sqlUp);
		psta.setObject(1, "3");
		psta.setObject(2, ordLnDlyPk);
		psta.executeUpdate();
		psta.close();

		psta = conn.prepareStatement(sqlUpProc);
		psta.setObject(1, "5");
		psta.setObject(2, ordLnDlyPk);
		psta.executeUpdate();
		psta.close();

		psta = conn.prepareStatement(sqlDelivery);
		psta.setObject(1, "12020501");
		psta.setObject(2, ordLnDlyPk);
		psta.executeUpdate();
		psta.close();

		PreparedStatement ps = conn.prepareStatement(sqlQuery);
		ps.setObject(1, ordLnPk);
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {
			if (rs.getString("ORDER_LN_STATUS") != null
					&& rs.getString("ORDER_LN_STATUS") == "12020502") {
				// 已开始生产
				psta = conn.prepareStatement(sqlUpLine);
				psta.setObject(1, "12020501");
				psta.setObject(2, ordLnPk);
				psta.executeUpdate();
				psta.close();
			}
		}
		rs.close();
		ps.close();
	}

	/**
	 * 查询合同行补量上限
	 * 
	 * @param str
	 *            合同行pk
	 * @return
	 */
	public CoreReturnObject getPlnOrdLineReqQtyMax(String str) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreRequestR.getPlnOrdLineReqQtyMax",
				new Object[] { str });
		return cro;
	}

	/**
	 * 查询合同行补量申请量总和
	 * 
	 * @param ordLnPk
	 *            合同行pk
	 * @return
	 */
	public CoreReturnObject getLineReqQtySum(String ordLnPk) {
		CoreReturnObject cro = new CoreReturnObject();
		cro = this.getDataBySqlID("CoreRequestR.getLineReqQtySum",
				new Object[] { ordLnPk });
		return cro;
	}

	/**
	 * 查询合同行补量申请量总和
	 * 
	 * @param ordLnPk
	 *            合同行pk
	 * @param rNumId
	 *            补量申请Id
	 * @return
	 */
	public CoreReturnObject getLineReqQtySum(String ordLnPk, String rNumId) {
		CoreReturnObject cro = new CoreReturnObject();
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreRequestR.getLineReqQtySum");
		sql += " AND R.R_NUM_ID != '" + rNumId + "'";
		cro = this.getData(sql, new Object[] { ordLnPk });
		return cro;
	}
}