package com.steering.mes.mcp.CollarLibrary;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.converter.EntityTool;
import com.steering.comm.converter.QualityDesignTool;
import com.steering.comm.db.DBCommon;
import com.steering.mes.mcp.entity.CouplingMatButtressEntity;
import com.steering.mes.mcp.entity.CouplingMatDealEntity;
import com.steering.mes.mcp.entity.CouplingMatMEntity;
import com.steering.mes.mcp.entity.PlnOrderJgEntity;

/**
 * 接箍出库记录补录
 * 
 * @author tjg 2019/03/11
 * @version v1.0
 */
public class FrmDealOut extends DBCommon {

	/**
	 * 查询接箍合同表
	 * 
	 * @param list
	 *            传递参数
	 * @return 平台统一返回对象
	 */
	public CoreReturnObject getQuery() {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmDealOut.getQueryOrder");
		return this.getData(sql);
	}

	public CoreReturnObject getQueryOrder(String codeJg, String dealOrde,String ordLnDyPk,
			String codeJgBl,String gowhereName) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmDealOut.getQueryOrder");
		if (!codeJg.equals("")) {
			sql += " AND T.CODE_JG='" + codeJg + "'";
		}
		if (!gowhereName.equals("")) {
			sql += " and (SELECT MIN(S.PLINE_NAME) FROM PLN_ORDER_JGX_S S WHERE S.ORD_LN_DLY_PK=T.ORD_LN_DLY_PK)='" + gowhereName + "'";
		}
		sql+=" AND T.ORD_LN_DLY_PK <>'"+ordLnDyPk+"'";
//		if(!codeJgBl.equals("")){
//			sql += " AND  M.CODE_JG_BL='" + codeJgBl + "'";
//			
//		}
		if (!dealOrde.equals("")) {
			sql += " AND NVL(T.DEMAND_COPPER || T.DEMAND_DETECTION || T.DEMAND_BLAST || T.DEMAND_BONDERIZING,'/') ="
					+ " NVL((SELECT D.DEMAND_COPPER || D.DEMAND_DETECTION || D.DEMAND_BLAST || D.DEMAND_BONDERIZING  "
					+ " FROM COUPLING_MAT_DEAL D WHERE D.DEAL_ORDE = '"
					+ dealOrde + "'),'/')";
		}
		return this.getData(sql);
	}

	/**
	 * 查询交易表倒库实绩
	 * 
	 * @param list
	 *            传递参数
	 * @return 平台统一返回对象
	 */
	public CoreReturnObject queryOutPerfo(String strFurnace,
			String strRegStart, String strRegEnd) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("FrmDealOut.queryOutPerfo");
		sql += " AND t.judge_stove_no LIKE '%' || '" + strFurnace + "' || '%'";
		sql += " AND DECODE('" + strRegStart
				+ "', NULL, '1', t.create_time) BETWEEN DECODE('" + strRegStart
				+ "', NULL, '1', to_date('" + strRegStart
				+ "', 'YYYY-MM-DD HH24:MI:SS'))";
		sql += " AND DECODE('" + strRegEnd + "', NULL, '1', to_date('"
				+ strRegEnd + "', 'YYYY-MM-DD HH24:MI:SS')) ";
		sql += " AND t.DEAL_TYPE_CODE ='800801' AND T.OUT_FLAG='1'";
		sql += " ORDER BY CREATE_TIME DESC";
		return this.getData(sql);
	}

	/**
	 * 查询交易表信息
	 * 
	 * @param con
	 * @param sendPlanNo
	 * @return
	 * @throws SQLException
	 */
	public static CouplingMatDealEntity getSendMatDeal(Connection con,
			String dealNo) throws SQLException {
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoupMatCollarShar.QueryDeal");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, dealNo);
		ResultSet rs = ps.executeQuery();
		List<CouplingMatDealEntity> sendPlanCEntitys = EntityTool
				.getEntitysByRs(rs, CouplingMatDealEntity.class);
		rs.close();
		ps.close();
		if (sendPlanCEntitys == null || sendPlanCEntitys.size() == 0) {
			return null;
		} else {
			for (CouplingMatDealEntity sendPlanCEntity : sendPlanCEntitys) {
				QualityDesignTool.nullConverNullString(sendPlanCEntity);
			}
			return sendPlanCEntitys.get(0);
		}
	}

	/**
	 * 查询接箍合同信息
	 */
	public static PlnOrderJgEntity getSendOrderNo(Connection con,
			String jgOrderNo) throws SQLException {
		String sql = "SELECT T.* FROM PLN_ORDER_JG T WHERE T.JG_ORDERNO=?";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, jgOrderNo);
		ResultSet rs = ps.executeQuery();
		List<PlnOrderJgEntity> sendPlanCEntitys = EntityTool.getEntitysByRs(rs,
				PlnOrderJgEntity.class);
		rs.close();
		ps.close();
		if (sendPlanCEntitys == null || sendPlanCEntitys.size() == 0) {
			return null;
		} else {
			for (PlnOrderJgEntity sendPlanCEntity : sendPlanCEntitys) {
				QualityDesignTool.nullConverNullString(sendPlanCEntity);
			}
			return sendPlanCEntitys.get(0);
		}
	}

	/***
	 * 生成交易单号
	 * 
	 * @param plineCode
	 * @param zygNo
	 * @param connection
	 * @return
	 */
	public static String doAddDealOrde(String lx, String woId,
			Connection connection) {
		String resultNo = "";
		PreparedStatement psta = null;
		String sqlloading = CoreXmlSqlParsersFactory
				.getSql("FrmDealOut.queryMaxDealOrde");// 查询交易单号
		Date now = new Date();
		SimpleDateFormat date = new SimpleDateFormat("yyyyMMdd");
		SimpleDateFormat date1 = new SimpleDateFormat("yyyy-MM-dd");
		String systime = date.format(now);
		try {
			psta = connection.prepareStatement(sqlloading);
			psta.setObject(1, lx);
			psta.setObject(2, systime);
			psta.setObject(3, date1.format(now));
			psta.setObject(4, woId);
			ResultSet rs1 = psta.executeQuery();
			if (rs1.next()) {
				resultNo = rs1.getString("DEAL_ORDE");
			}
			rs1.close();
			psta.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return resultNo;
	}

	/**
	 * 新增
	 * 
	 * @param list
	 *            传递参数
	 * @return 平台统一返回对象
	 */
	public CoreReturnObject doAdd(ArrayList<String> list, String bc, String bz,
			String name) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			connection.setAutoCommit(false); // 取消自动提交事务
			Date now = new Date();
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String systime = dateFormat.format(now);

			String jgOrderNo = list.get(0);
			String judgerNo = list.get(1);
			String batchNo = list.get(2);
			String num = list.get(3);
			String wgt = list.get(4);

			// 获取接箍合同实体类
			PlnOrderJgEntity pln = getSendOrderNo(connection, jgOrderNo);
			if (pln == null) {
				cro.setV_errMsg("未找到接箍合同信息,请确认！");
				return cro;
			}

			CouplingMatDealEntity matDeal = new CouplingMatDealEntity();
			// 获取交易单号
			String dealOrde = doAddDealOrde("OA", "800801", connection);
			// 新增交易表
			matDeal.setDealOrde(dealOrde);
			matDeal.setDealTypeCode("800801");
			matDeal.setDealTypeName("投料出库");
			matDeal.setSourceCode("");
			matDeal.setSourceName("");
			matDeal.setTarCode("");
			matDeal.setTarName("");
			matDeal.setKepNo("");
			matDeal.setMatNo("");
			matDeal.setResultNo("");
			matDeal.setZyPlanId("");
			matDeal.setWoId(pln.getWoId());
			matDeal.setProPlanId(pln.getProPlanIdS());
			matDeal.setJgGroupId("");
			matDeal.setPlineCode("");
			matDeal.setPlineName("");
			matDeal.setMatOriginCode("");
			matDeal.setMatOriginName("");
			matDeal.setSoureCode("801302");
			matDeal.setSoureName("产线");
			matDeal.setJudgeStoveNo(judgerNo);
			matDeal.setBatchNo(batchNo);
			matDeal.setBlWlId("");
			matDeal.setBlWlDesc("");
			matDeal.setMinD("");
			matDeal.setMinH("");
			matDeal.setCodeJg(pln.getCodeJg());
			matDeal.setGradecode("");
			matDeal.setGradename("");
			matDeal.setSteelcode(pln.getSteelcode());
			matDeal.setSteelname(pln.getSteelname());
			matDeal.setModelCode(pln.getModelCode());
			matDeal.setModelDesc(pln.getModelDesc());
			matDeal.setOutdiameter(pln.getOutdiameter());
			matDeal.setWallthick(pln.getWallthick());
			matDeal.setSpecJg(pln.getSpecJg());
			matDeal.setSpecJgDesc(pln.getSpecJgDesc());
			matDeal.setStyleJg(pln.getStyleJg());
			matDeal.setDiameter(pln.getDiameter());
			matDeal.setCheckJVal(pln.getCheckJVal());
			matDeal.setAimlength(pln.getAimlength());
			matDeal.setSingleweight(pln.getSingleweight());
			matDeal.setMonitordemand(pln.getMonitordemand());
			matDeal.setIfMonitorJg(pln.getIfMonitorJg());
			matDeal.setPrdcrNo(pln.getPrdcrNo());
			matDeal.setProducer("");
			matDeal.setProducerTime("");
			matDeal.setMachNm("");
			matDeal.setMachNo("");
			matDeal.setDealNum(num);
			matDeal.setDealWt(wgt);
			matDeal.setBalYearMonth(systime.substring(0, 7));
			matDeal.setFInTime(systime);
			matDeal.setDealTime(systime);
			matDeal.setStorageNo("");
			matDeal.setLocationNo("");
			matDeal.setStorageAttr("");
			matDeal.setStorageAttrName("");
			matDeal.setStorageTypeNo("");
			matDeal.setStorageTypeName("");
			matDeal.setHandFlag("1");
			matDeal.setDemandBlast(pln.getDemandBlast());
			matDeal.setDemandBonderizing(pln.getDemandBonderizing());
			matDeal.setDemandCopper(pln.getDemandCopper());
			matDeal.setDemandDetection(pln.getDemandDetection());
			matDeal.setCustAlphaNo("");
			matDeal.setOrderSpecialDesc("");
			matDeal.setAlphaCode("");
			matDeal.setDeterNo("");
			matDeal.setDeterResults("");
			matDeal.setColOperator(name);
			matDeal.setMemo("");
			matDeal.setCreateName(name);
			matDeal.setCreateTime(systime);
			matDeal.setProductFlag("");
			matDeal.setMatStatus("");
			matDeal.setDeterStatus("");
			matDeal.setCodeJgBl("");
			matDeal.setCraftFileNo("");
			matDeal.setCraftSeq("");
			matDeal.setBelongCode("");
			matDeal.setBelongName("");
			if (pln.getDemandBonderizing().equals("")) {
				matDeal.setCoatType("0");
			} else if (pln.getDemandBonderizing().equals("40840201")) {
				matDeal.setCoatType("2");
			} else if (pln.getDemandBonderizing().equals("40840202")) {
				matDeal.setCoatType("1");
			}
			matDeal.setTarRecFlag("1");
			matDeal.setMatNoXh("");
			matDeal.setJgOrderno(pln.getJgOrderno());
			matDeal.setOrderNo(pln.getOrderNo());
			matDeal.setOrderSeq(pln.getOrderSeq());
			matDeal.setDeliveryNo(pln.getDeliveryNo());
			matDeal.setOrdPk(pln.getOrdLnDlyPk().substring(0,
					pln.getOrdLnDlyPk().length() - 6));
			matDeal.setOrdLnPk(pln.getOrdLnDlyPk().substring(0,
					pln.getOrdLnDlyPk().length() - 3));
			matDeal.setOrdLnDlyPk(pln.getOrdLnDlyPk());
			String sqlAddDeal = EntityTool
					.fillSqlByEntity(CoreXmlSqlParsersFactory
							.getSql("FrmDealOut.AddDealResult"), matDeal);// 新增交易信息
			ps = connection.prepareStatement(sqlAddDeal);
			ps.executeUpdate();
			ps.close();
			cro.setV_errMsg("补录出库成功！");
			connection.commit();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			cro.setV_errMsg(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
	}

	/**
	 * 撤销出库（倒库）实绩记录
	 * 
	 * @param list
	 *            传递参数
	 * @return obj
	 */
	public CoreReturnObject doDelete(ArrayList<ArrayList<String>> list) {
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement ps = null;
		// ResultSet rs = null;
		try {
			connection.setAutoCommit(false); // 取消自动提交事务
			Date now = new Date();
			// SimpleDateFormat dateFormat = new SimpleDateFormat(
			// "yyyy-MM-dd HH:mm:ss");
			// String systime = dateFormat.format(now);
			for (int i = 0; i < list.size(); i++) {
				ArrayList<String> pram = (ArrayList<String>) list.get(i);
				String dealNo = pram.get(0);

				// 查询交易表信息
				CouplingMatDealEntity pln = getSendMatDeal(connection, dealNo);
				if (pln == null) {
					cro.setV_errMsg("未找到交易信息,请确认！");
					return cro;
				}

				// 删除交易表
				String deleteMatDeal = "DELETE COUPLING_MAT_DEAL  WHERE DEAL_ORDE = ? ";
				ps = connection.prepareStatement(deleteMatDeal);
				ps.setObject(1, dealNo);
				ps.executeUpdate();
				ps.close();

			}
			cro.setV_errMsg("删除成功！");
			connection.commit();

		} catch (Exception e) {
			System.out.println(e.getMessage());
			cro.setV_errMsg(e.getMessage());
			if (connection != null) {
				try {
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
	}
}
