package com.steering.mes.mcp.Mch;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.converter.EntityTool;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.StringTool;
import com.steering.common.HttpUrlConnectionUtil;
import com.steering.common.LoggableStatement;
import com.steering.common.UrlConfig;
import com.steering.common.XsSql;
import com.steering.mes.mcp.common.PlanService;
import com.steering.mes.mcp.entity.MchEntity.PlnZyJgxMEntity;
import com.steering.mes.mcp.entity.MchPathResultDEntity;
import com.steering.mes.mcp.entity.MchPathResultEntity;
import net.sf.json.JSONObject;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

/**
 * 通径实绩
 * 
 * @author SZL
 *
 */
public class FrmDriftDiameterResult extends DBCommon {
	private String perStuts = "";

	/**
	 * 查询通径实绩
	 */
	public CoreReturnObject getQueryExpandResult(String heatNo ,String BatchNo) {
		return this.getDataBySqlID("FrmDriftDiameterResult.getQueryExpandResult",
				new Object[] { heatNo,BatchNo});
	}

	/**
	 * 查询相同炉计划ID下通径实绩状态
	 */
	public CoreReturnObject getQueryExpandResultStuts(String heatNo,
			String plinCode) {
//		String sql = CoreXmlSqlParsersFactory.getSql("FrmDriftDiameterResult.getQueryExpandResultStuts");
//		sql += "AND T.HEAT_PLAN_NO = '"+heatNo+"'";
//		sql += CoreConverter.toSqlConditionString("T.PLINE_CODE", plinCode);
//		return this.getData(sql);
		return this.getDataBySqlID(
				"FrmDriftDiameterResult.getQueryExpandResultStuts",
				new Object[] { heatNo, plinCode });
	}

	/**
	 * 查询相同实绩编号下绝废支数
	 */
	public CoreReturnObject getQueryJFailNum(String resultNo, String heatNo,
			String plinCode) {
		return this.getDataBySqlID("FrmDriftDiameterResult.getQueryJFailNum",
				new Object[] { resultNo, heatNo, plinCode });
	}

	public CoreReturnObject doQuerypDetail(
			String[] ResultNo) {

		String sql = "";
		sql = CoreXmlSqlParsersFactory
				.getSql("FrmDriftDiameterResult.QueryDetail");
		sql += PlanService.toSqlConditionString("T.RESULT_NO", ResultNo);
		return this.getData(sql);
	}

	/**
	 * 查询通径实绩合格支数的和
	 * 
	 * @param heatNo
	 * @return
	 */
	public CoreReturnObject getQueryExpandResult1(String heatNo) {
		return this.getDataBySqlID(
				"FrmDriftDiameterResult.getQueryExpandResult1",
				new Object[] { heatNo });
	}

	public CoreReturnObject DoAdd(String loadStr, String gx, ArrayList<String> ScrappedList, ArrayList<String> SuspiciousList,ArrayList<String> Details){
		CoreReturnObject core = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		PreparedStatement psta = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		String systime = dateFormat.format(now);

		try {
			connection.setAutoCommit(false); //



			String sqlupdatepln = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.updatePlnZyRclM2");// 修改加工计划表
			PreparedStatement patupdatepln = connection
					.prepareStatement(sqlupdatepln);

			String addPlnInfo = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.AddComInfoResultNew");// 新增公共信息
			PreparedStatement patsPlan = connection
					.prepareStatement(addPlnInfo);


			MchPathResultEntity Load = EntityTool.getEntityByJSONStr(loadStr,MchPathResultEntity.class);


			// 获取加工计划实体了
			PlnZyJgxMEntity pln = PlanService.getSendHttPlanCInfo3(connection,
					Load.getHeatPlanNo());


			//region 检查
			if (pln == null){
				core.setV_errMsg("找不到炉计划数据！");
				return core;
			}

			if (!pln.getPlanstatus().equals("20")) {
				core.setV_errMsg("炉计划不处于生产中状态！");
				return core;
			}


			String cutFalg = "";
			String sql = CoreXmlSqlParsersFactory
					.getSql("MchComm.queryComInfo");// 查询 工序是否是结炉状态
			psta = connection.prepareStatement(sql);
			psta.setString(1, Load.getHeatPlanNo());
			psta.setString(2, Load.getBatchNo());
			psta.setString(3, "701311");
			ResultSet rs = psta.executeQuery();
			if (rs.next()) {
				cutFalg = rs.getString("STATION_STATUS");
			}


			if (cutFalg.equals("2")) {
				core.setV_errMsg("下线已结炉,不允许此操作！");
				return core;
			}
			rs.close();
			psta.close();
			//endregion


			String resultNo = "";
			int count = 0;
			int detCount = 0;


			if(StringTool.isInteger(Load.getFailNum())){
				detCount = Integer.parseInt(Load.getFailNum());
			}
			if(StringTool.isInteger(Load.getProNum()) && StringTool.isInteger(Load.getReProNum())){
				count = Integer.parseInt(Load.getProNum()) +Integer.parseInt(Load.getReProNum());
			}


			if(count<=0){
				core.setV_errMsg("请输入正确的作业支数！");
				return core;
			}

			if(count<detCount){
				core.setV_errMsg("废品支数不能大于作业支数！");
				return core;
			}


			//获取最大实绩编号
			sql =   CoreXmlSqlParsersFactory
					.getSql("FrmDriftDiameterResult.queryResultNo");
			psta = connection.prepareStatement(sql);
			psta.setObject(1, pln.getPlineCode() + gx );
			psta.setObject(2, pln.getPlineCode() + gx );
			ResultSet rs1 = psta.executeQuery();
			if (rs1.next()) {
				resultNo = rs1.getString("RESULT_NO");
			}
			rs1.close();
			psta.close();


			Load.setResultNo(resultNo);

			String sqlAdd = CoreXmlSqlParsersFactory
					.getSql("FrmDriftDiameterResult.AddResult");// 新增上料实绩

			sqlAdd = com.steering.common.EntityTool.fillSqlByEntity(sqlAdd, Load);
			PreparedStatement patAdd = connection.prepareStatement(sqlAdd);
			patAdd.addBatch();

			String sqlAddD = CoreXmlSqlParsersFactory
					.getSql("FrmDriftDiameterResult.AddDetailResult");

			sqlAddD = com.steering.common.EntityTool.fillSqlByEntity(sqlAddD, Load);
			PreparedStatement patAddD = connection.prepareStatement(sqlAddD);


			for (int i = 0; i <Details.size() ; i++) {

				MchPathResultDEntity DEntity = EntityTool.getEntityByJSONStr(Details.get(i),MchPathResultDEntity.class);
				patAddD.setObject(1,i);
				patAddD.setObject(2,DEntity.getMeasurementTime());
				patAddD.setObject(3,DEntity.getDriftModelNo());
				patAddD.setObject(4,DEntity.getDriftModelLen());
				patAddD.setObject(5,DEntity.getMeasuredEndPart());
				patAddD.setObject(6,DEntity.getMeasuredMiddlePart());
				patAddD.setObject(7,DEntity.getMeasuredTailPart());
				patAddD.addBatch();
			}


			// 新增加工公共信息
			patsPlan.setObject(1, resultNo);
			patsPlan.setObject(2, Load.getPlineCode());
			patsPlan.setObject(3, Load.getPlineName());
			patsPlan.setObject(4, gx);
			patsPlan.setObject(5, gx);
			patsPlan.setObject(6, Load.getBatchNo());
			patsPlan.setObject(7, Load.getProNum());
			patsPlan.setObject(8, Load.getProWt());
			patsPlan.setObject(9, Load.getFailNum());
			patsPlan.setObject(10, Load.getFailWt());
			patsPlan.setObject(11, Load.getProTime());
			patsPlan.setObject(12, Load.getProShift());
			patsPlan.setObject(13, Load.getProGroup());
			patsPlan.setObject(14, Load.getProUser());
			patsPlan.setObject(15, Load.getProUser());
			patsPlan.setObject(16, Load.getHeatPlanNo());
			patsPlan.addBatch();

             //00-上料开始,10-探伤开始，20-切管开始，30-车丝开始，40-螺纹检验开始，50拧接开始，60-通径开始,70-水压开始，80-倒凌开始，90-测量点开始，11-交库开始
			patupdatepln.setObject(1,"60");
			patupdatepln.setObject(2,Load.getHeatPlanNo());
			patupdatepln.setObject(3,Load.getBatchNo());
			patupdatepln.addBatch();

			patAdd.executeBatch();
			patAddD.executeBatch();
			patsPlan.executeBatch();
			patupdatepln.executeBatch();


			FrmMchBugD.AddMchWaste(connection,Load.getHeatPlanNo(),resultNo,Load.getPlineCode(),Load.getProUser(),gx,SuspiciousList, ScrappedList);

			core.setV_errMsg("新增成功！");
			core.setResult(1);
			connection.commit();
			try {
				String sql1 = "select count(1) cut from slm_order_head t where customer_nm like '%天津钢管%' and order_no = ?";
				psta = connection.prepareStatement(sql1);
				psta.setString(1,pln.getOrderNo());
				rs = psta.executeQuery();
				if(rs.next()) {
					String string = rs.getString(1);
					if (Integer.parseInt(string) > 0) {
						//===2024年9月21日新增调用外部接口传递数据
						//根据主键id查询数据
						sql="select * from MCH_PATH_RESULT t where t.result_no = ? ";
						psta = connection.prepareStatement(sql);
						psta.setString(1,Load.getResultNo());
						ResultSet rs2 = psta.executeQuery();
						// 获取结果集的元数据
						ResultSetMetaData rsmd = rs2.getMetaData();
						int columnCount = rsmd.getColumnCount();
						// 封装结果集到HashMap
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						HashMap<String, Object> map = new HashMap<String, Object>();
						if (rs2.next()) {
							for (int i = 1; i <= columnCount; i++) {
								if(rs2.getObject(i) instanceof Date){//日期格式转换
									map.put(com.steering.common.EntityTool.underlineToCamel(rsmd.getColumnName(i)), sdf.format(rs2.getObject(i)));
								}else{
									map.put(com.steering.common.EntityTool.underlineToCamel(rsmd.getColumnName(i)), rs2.getObject(i));
								}
							}
						}
						rs2.close();
						//调用接口传递数据
						HttpUrlConnectionUtil.post(UrlConfig.BASE_URL+"/v1/mchpathresults/add",map);
						// ps 执行日志表插入：
						psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
						psta.setString(1, "mchpathresults/add");
						psta.setString(2, JSONObject.fromObject(map).toString());
						psta.setString(3, Load.getResultNo());
						psta.setString(4, "操作成功");
						psta.execute();
						connection.commit();
					}
				}
			}catch (Exception e){
				// ps 执行日志表插入：
				psta = new LoggableStatement(connection, XsSql.InsertCxToMesLog);
				psta.setString(1, "mchpathresults/add");
				psta.setString(2, e.toString());
				psta.setString(3, Load.getResultNo());
				psta.setString(4, "操作失败");
				psta.execute();
				connection.commit();
			}finally {
				psta.close();
			}
		}
		catch (Exception e) {
			core.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 core;
	}

	/**
	 * 修改
	 * @return
	 */
	public CoreReturnObject DoUpdate(String result,ArrayList<String> Details){
		CoreReturnObject data = new CoreReturnObject();
		MchPathResultEntity batching = EntityTool.getEntityByJSONStr(result, MchPathResultEntity.class);
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		try {
			connection.setAutoCommit(false);
			// 修改实绩信息
			String sql = CoreXmlSqlParsersFactory.getSql("FrmDriftDiameterResult.UpdateResult");
			sql = EntityTool.fillSqlByEntity(sql, batching);
			PreparedStatement patAdd = connection.prepareStatement(sql);

			// 检测记录详情
			String DeleteDetailResultSql = CoreXmlSqlParsersFactory
					.getSql("FrmDriftDiameterResult.DeleteDetailResult");// 删除记录详情
			PreparedStatement deleteDetailResult = connection
					.prepareStatement(DeleteDetailResultSql);
			deleteDetailResult.setObject(1,batching.getResultNo());
			deleteDetailResult.addBatch();

			//添加
			String sqlAddD = CoreXmlSqlParsersFactory
					.getSql("FrmDriftDiameterResult.AddDetailResult");

			sqlAddD = EntityTool.fillSqlByEntity(sqlAddD, batching);
			PreparedStatement patAddD = connection.prepareStatement(sqlAddD);
			patAdd.addBatch();

			for (int i = 0; i <Details.size() ; i++) {

				MchPathResultDEntity DEntity = EntityTool.getEntityByJSONStr(Details.get(i),MchPathResultDEntity.class);
				patAddD.setObject(1,i);
				patAddD.setObject(2,DEntity.getMeasurementTime());
				patAddD.setObject(3,DEntity.getDriftModelNo());
				patAddD.setObject(4,DEntity.getDriftModelLen());
				patAddD.setObject(5,DEntity.getMeasuredEndPart());
				patAddD.setObject(6,DEntity.getMeasuredMiddlePart());
				patAddD.setObject(7,DEntity.getMeasuredTailPart());
				patAddD.addBatch();
			}

			patAdd.executeBatch();
			deleteDetailResult.executeBatch();
			patAddD.executeBatch();

			data.setV_errMsg("修改成功！");
			data.setResult(1);
			connection.commit();
		} catch (SQLException e) {
			data.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 data;
	}

	public CoreReturnObject DoDelete(String loadStr,String gx) {
		CoreReturnObject core = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		Date now = new Date();
		SimpleDateFormat dateFormat1 = new SimpleDateFormat(
				"yyyyMM", Locale.CHINA);
		String systime1 = dateFormat1.format(now);
		PreparedStatement psta = null;

		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		String systime = dateFormat.format(new Date());

		try {
			connection.setAutoCommit(false); // 取消自动提交事务

			String DeleteComInfoSql = CoreXmlSqlParsersFactory
					.getSql("FrmMcpLoading.deleteVrpResult");// 删除公共信息
			PreparedStatement patsDeleteComInfo = connection
					.prepareStatement(DeleteComInfoSql);

					String DeleteResultSql = CoreXmlSqlParsersFactory
					.getSql("FrmDriftDiameterResult.DeleteResult");// 删除实绩
			PreparedStatement patsDeleteResult = connection
					.prepareStatement(DeleteResultSql);

			String DeleteDetailResultSql = CoreXmlSqlParsersFactory
					.getSql("FrmDriftDiameterResult.DeleteDetailResult");// 删除实绩
			PreparedStatement patsDeleteDetailResult = connection
					.prepareStatement(DeleteDetailResultSql);



			MchPathResultEntity Load = EntityTool.getEntityByJSONStr(loadStr,MchPathResultEntity.class);

			PlnZyJgxMEntity pln = PlanService.getSendHttPlanCInfo3(connection,
					Load.getHeatPlanNo(),Load.getBatchNo());

			if(!pln.getPlineCode().equals(Load.getPlineCode())){
				core.setV_errMsg("不能删除其他产线生成的实绩！");
				return core;
			}


			//region 检查
			if (pln == null){
				core.setV_errMsg("找不到炉计划数据！");
				return core;
			}

			if (!pln.getPlanstatus().equals("20")) {
				core.setV_errMsg("炉计划不处于生产中状态！");
				return core;
			}


			String cutFalg = "";
			String sql = CoreXmlSqlParsersFactory
					.getSql("MchComm.queryComInfo");// 查询 工序是否是结炉状态
			psta = connection.prepareStatement(sql);
			psta.setString(1, Load.getHeatPlanNo());
			psta.setString(2, Load.getBatchNo());
			psta.setString(3, "701311");
			ResultSet rs = psta.executeQuery();
			if (rs.next()) {
				cutFalg = rs.getString("STATION_STATUS");
			}


			if (cutFalg.equals("2")) {
				core.setV_errMsg("下线已结炉,不允许此操作！");
				return core;
			}
			rs.close();
			psta.close();
			//endregion


			patsDeleteComInfo.setObject(1,Load.getResultNo());
			patsDeleteComInfo.addBatch();
			patsDeleteComInfo.executeBatch();



			patsDeleteResult.setObject(1,Load.getResultNo());
			patsDeleteResult.addBatch();
			patsDeleteResult.executeBatch();

			patsDeleteDetailResult.setObject(1,Load.getResultNo());
			patsDeleteDetailResult.addBatch();
			patsDeleteDetailResult.executeBatch();


			int detCount =0;
			if(StringTool.isInteger(Load.getFailNum())){
				detCount = Integer.parseInt(Load.getFailNum());
			}

			FrmMchBugD.DeleteMchWaste(connection, Load.getHeatPlanNo(),Load.getResultNo(), Load.getPlineCode(),gx,detCount);


			core.setV_errMsg("删除成功！");
			core.setResult(1);
			connection.commit();
		}
		catch (Exception e) {
			core.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 core;
	}


	public CoreReturnObject UpdatePath(String Path, String ResultNo){
		return	this.setDataBySqlID("FrmDriftDiameterResult.UpdatePath",new Object[]{Path,ResultNo});
	}


	/**
	 * 每支材料对应的入库单号
	 * 
	 * @param conn
	 *            c
	 * @param strlist
	 *            传递参数
	 * @return obj
	 * @throws Exception
	 *             异常处理
	 */
	public String querySendSqlDoc(Connection conn, String strlist, String memo)
			throws Exception {
		String seq = "";
		PreparedStatement psta = null;
		Date dt = new Date();
		SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat matter2 = new SimpleDateFormat("yyMMdd");
		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("FrmThreadingResult.getInListDoc");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, memo);
		psta.setString(2, matter2.format(dt));
		psta.setString(3, matter1.format(dt));
		psta.setString(4, strlist);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("INSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return seq;
	}

	/**
	 * 每支材料对应的入库流水号
	 * 
	 * @param conn
	 *            c
	 * @param strlist
	 *            传递参数
	 * @return obj
	 * @throws Exception
	 *             异常处理
	 */
	public String querySendSql(Connection conn, String strlist)
			throws Exception {
		String seq = "";
		PreparedStatement psta = null;
		String sqlLovsqe = CoreXmlSqlParsersFactory
				.getSql("FrmThreadingResult.getInListDoc1");
		psta = conn.prepareStatement(sqlLovsqe);
		psta.setString(1, strlist);
		ResultSet rs = psta.executeQuery();
		if (rs.next()) {
			seq = rs.getString("INSTOCK_SQE");
		}
		rs.close();
		psta.close();
		return seq;
	}
}
