package com.steering.pss.ydm.pipemanage;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import net.sf.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.steering.comm.DefaultWebServiceRequest;
import com.steering.comm.ServiceToCx;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.data.ComBaseInfo;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.ydm.entity.MatZcMEntity;
import com.steering.pss.ydm.entity.YdmZcInlistEntity;
import com.steering.pss.ydm.entity.YdmZcRedchongEntity;

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 java.util.Objects;

public class FrmRedChong extends DBCommon{

	/***
	 * 查询成品库存信息
	 * @return
	 */
	public CoreReturnObject doQuery(ArrayList<String> parmList,String[] arr,String supplyUnit)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.doQuery");
		if(!parmList.get(0).equals(""))
		{
		    sql += " AND T1.BAL_YEAR_MONTH = '"+parmList.get(0)+"'";	
		}
		if(!parmList.get(1).equals(""))
		{
			sql += " AND T1.JUDGE_STOVE_NO = '"+parmList.get(1)+"'";
		}
		if(supplyUnit.equals("120501"))
		{
			sql += " AND T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T1.SUPPLY_UNIT_CODE = ''";
		}else if(supplyUnit.equals("120504")){
			sql += " AND T1.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
		}
		sql += CoreConverter.toSqlConditionString("T1.BELONG_CODE", arr);
		sql += " GROUP BY T1.JUDGE_STOVE_NO, T1.BATCH_NO, T1.BATCH_GROUD_NO,T1.PRODUCCODE,T1.PRODUCNAME,T1.STEELCODE,T1.STEELNAME,T1.SPEC_CODE,T1.SPEC_NAME,T1.MODEL_CODE,T1.GRADECODE,T1.GRADENAME,T1.STD_STYLE,T1.STD_STYLE_DESC,T1.MAT_STATUS,T1.MATERIAL_NO,T1.MATERIAL_NAME,";
		sql += " T1.MODEL_DESC,T1.STD_CODE,T1.STD_NAME,T1.ACT_DIMATER,T1.ACT_HEIGHT,T1.BELONG_CODE,T1.BELONG_NAME,T1.PLINE_CODE,T1.PLINE_NAME,T1.PRO_ORDER_NO,T1.SUPPLY_UNIT,T1.SUPPLY_UNIT_CODE,";
		sql += " T2.STORAGE_NO,S.STORAGE_NAME,T1.MEMO,T1.PRODUCT_FLAG,T1.STOVE_NO,T1.LOT_NO,T2.LOCATION_NO,T1.JUDGE_RESULT";
        return this.getData(sql);
	}
	
	/***
	 * 查询红冲实绩
	 * @param parmList
	 * @param arr
	 * @return
	 */
	public CoreReturnObject doQueryRedList(ArrayList<String> parmList,String[] arr,String supplyUnit)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.doQueryRedList");
		if(!parmList.get(0).equals(""))
		{
		    sql += " AND T.BAL_YEAR_MONTH = '"+parmList.get(0)+"'";	
		}
		if(!parmList.get(1).equals(""))
		{
			sql += " AND T.JUDGE_STOVE_NO = '"+parmList.get(1)+"'";
		}
		if(!parmList.get(2).equals(""))
		{
			sql += " AND T.FRIM_FLAG = '"+parmList.get(2)+"'";
		}
		if(supplyUnit.equals("120501"))
		{
			sql += " AND (T.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T.SUPPLY_UNIT_CODE IS NULL)";
		}else if(supplyUnit.equals("120504")){
			sql += " AND T.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
		}
		sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
		return this.getData(sql);
	}
	/***
	 * 查询红冲实绩
	 * @param parmList
	 * @param
	 * @return
	 */
	public CoreReturnObject doQueryRedListAll(ArrayList<String> parmList,String supplyUnit)
	{
		String sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.doQueryRedList");
		if(!parmList.get(0).equals(""))
		{
		    sql += " AND T.BAL_YEAR_MONTH = '"+parmList.get(0)+"'";	
		}
		if(!parmList.get(1).equals(""))
		{
			sql += " AND T.JUDGE_STOVE_NO = '"+parmList.get(1)+"'";
		}
		if(!parmList.get(2).equals(""))
		{
			sql += " AND T.FRIM_FLAG = '"+parmList.get(2)+"' ";
		}
		if(supplyUnit.equals("120501"))
		{
			sql += " AND (T.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T.SUPPLY_UNIT_CODE IS NULL)";
		}else if(supplyUnit.equals("120504")){
			sql += " AND T.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
		}
		return this.getData(sql);
	}
	
	/***
	 * 按支查询
	 * @return
	 */
	public CoreReturnObject doQuerySeq(String matZcEntity,String[] arr)
	{
        MatZcMEntity matZcTity = EntityTool.getEntityByJSONStr(matZcEntity, MatZcMEntity.class);
		String sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.doQuerySeq");
		sql = EntityTool.fillSqlByEntity(sql, matZcTity);
		sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
		sql += " ORDER BY T.MAT_NO ASC";
		return this.getData(sql);
	}
	
	/**
	 * 查询结转控制标识
	 * @param code
	 * @return
	 */
	public CoreReturnObject getState(String code)
	{
		return this.getDataBySqlID("FrmRedChong.getState",
                new Object[]{code});
	}
	
	/***
	 * 红冲
	 * @param matZcTity
	 * @param memo
	 * @param userName
	 * @return
	 */
	public CoreReturnObject redChong(String matZcTity,String memo,String userName,String redFlag)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		//String bathYear = df.format(now);
		String acount = "";//库存总支数
		String wgt = "";//库存总重量
		String aLen = "";//库存总长度
		String redDoc = "";//红冲单号
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			MatZcMEntity matZcEntity = EntityTool.getEntityByJSONStr(matZcTity, MatZcMEntity.class);
			String bathYear = "120504".equals(matZcEntity.getSupplyUnitCode())? ComBaseInfo.GetBalYear_2416(new Date()): ComBaseInfo.GetBalYear(new Date());

			redDoc = queryRedDoc(connection);
			sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.doQuerySum");
			sql = EntityTool.fillSqlByEntity(sql, matZcEntity);
			psta = connection.prepareStatement(sql);
			rs = psta.executeQuery();
			if(rs.next())
			{
				acount = rs.getString("ACT_COUNT");
				wgt = rs.getString("ACT_WEIGHT");
				aLen = rs.getString("ACT_LEN");
			}
			rs.close();
			psta.close();
			if(Integer.parseInt(matZcEntity.getRedcount()) > Integer.parseInt(acount) ||Double.parseDouble(matZcEntity.getRedweight()) > Double.parseDouble(wgt)||Double.parseDouble(matZcEntity.getLength()) > Double.parseDouble(aLen) )
			{
				cro.setV_errMsg("输入的红冲支数/重量/长度不能大于现存的库存信息!");
				return cro;
			}
			matZcEntity.setInstockDoc(redDoc);
			
			String updateMatZcSql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.updateMatZc");
			updateMatZcSql = EntityTool.fillSqlByEntity(updateMatZcSql, matZcEntity);
			sqllist.add(updateMatZcSql);

			YdmZcRedchongEntity ydmRedEntity = new YdmZcRedchongEntity();
			ydmRedEntity.setInstockDoc(redDoc);
			ydmRedEntity.setJudgeStoveNo(matZcEntity.getJudgeStoveNo());
			ydmRedEntity.setBatchNo(matZcEntity.getBatchNo());
			ydmRedEntity.setBatchGroudNo(matZcEntity.getBatchGroudNo());
			ydmRedEntity.setCreateName(userName);
			ydmRedEntity.setRedchongMemo(memo);
			ydmRedEntity.setBalYearMonth(bathYear);
			ydmRedEntity.setRedType("0");
			ydmRedEntity.setRedFlag(redFlag);
			ydmRedEntity.setSupplyUnit(matZcEntity.getSupplyUnit());
			ydmRedEntity.setSupplyUnitCode(matZcEntity.getSupplyUnitCode());
			String insertRedSql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.insertRedChong");
			insertRedSql = EntityTool.fillSqlByEntity(insertRedSql, ydmRedEntity);
			sqllist.add(insertRedSql);
			
			//cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			
			
			if(cro.getV_errMsg().equals(""))
			{
				cro.setV_errMsg("红冲成功!");
			}
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					cro.setV_errMsg(e.getMessage());
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
	}
	/***
	 * 按支红冲
	 * @param parmList
	 * @param memo
	 * @param userName
	 * @return
	 */
	public CoreReturnObject seqRedChong(ArrayList<String> parmList,String memo,String userName,String redFlag)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		String bathYear = df.format(now);
		int acount = 0;//库存总支数
		double wgt = 0.0;//库存总重量
		double aLen = 0.0;//库存总长度
		String redDoc = "";//红冲单号
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			redDoc = queryRedDoc(connection);
			for(String str : parmList)
			{
				MatZcMEntity matZcEntity = EntityTool.getEntityByJSONStr(str, MatZcMEntity.class);
				matZcEntity.setInstockDoc(redDoc);
				
				String updateMatZcSql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.updateMatZcSeq");
				updateMatZcSql = EntityTool.fillSqlByEntity(updateMatZcSql, matZcEntity);
				sqllist.add(updateMatZcSql);
				
				acount += 1;
				wgt = wgt + matZcEntity.getActWeight();
				aLen = aLen + matZcEntity.getActLen();
			}
			YdmZcRedchongEntity ydmRedEntity = new YdmZcRedchongEntity();
			ydmRedEntity.setInstockDoc(redDoc);
			ydmRedEntity.setJudgeStoveNo(EntityTool.getEntityByJSONStr(parmList.get(0), MatZcMEntity.class).getJudgeStoveNo());
			ydmRedEntity.setBatchNo(EntityTool.getEntityByJSONStr(parmList.get(0), MatZcMEntity.class).getBatchNo());
			ydmRedEntity.setBatchGroudNo(EntityTool.getEntityByJSONStr(parmList.get(0), MatZcMEntity.class).getBatchGroudNo());
			ydmRedEntity.setActCount(String.valueOf(acount));
			ydmRedEntity.setActWeight(String.valueOf(wgt));
			ydmRedEntity.setActTheoryWeight(String.valueOf(wgt));
			ydmRedEntity.setActLen(String.valueOf(aLen));
			ydmRedEntity.setCreateName(userName);
			ydmRedEntity.setRedchongMemo(memo);
			ydmRedEntity.setBalYearMonth(bathYear);
			ydmRedEntity.setRedType("1");
			ydmRedEntity.setRedFlag(redFlag);
			ydmRedEntity.setSupplyUnit(EntityTool.getEntityByJSONStr(parmList.get(0), MatZcMEntity.class).getSupplyUnit());
			ydmRedEntity.setSupplyUnitCode(EntityTool.getEntityByJSONStr(parmList.get(0), MatZcMEntity.class).getSupplyUnitCode());
			
			String insertRedSql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.insertRedChong");
			insertRedSql = EntityTool.fillSqlByEntity(insertRedSql, ydmRedEntity);
			sqllist.add(insertRedSql);
			String sqls = "SELECT *\r\n" + 
					"  FROM YDM_ZC_REDCHONG T\r\n" + 
					" WHERE 1 = 1\r\n" + 
					"   AND T.BAL_YEAR_MONTH = '202401'\r\n" + 
					"   AND T.SUPPLY_UNIT_CODE = '120504'\r\n" + 
					"   AND T.BELONG_CODE IN ('100101', '100102', '100105')\r\n" + 
					"   AND T.INSTOCK_DOC = '"+ydmRedEntity.getInstockDoc()+"'";
			psta  = connection.prepareStatement(sqls);
			ResultSet rs1 = psta.executeQuery();
			 List<JSONObject> objects = new ArrayList<>();
			if(rs1.next()) {
				 List<YdmZcRedchongEntity> ydmZcRedchongEntities=  EntityTool.getEntitysByRs(rs1, YdmZcRedchongEntity.class);
				 for (YdmZcRedchongEntity ydmZcRedchongEntity : ydmZcRedchongEntities) {
					 JSONObject jsonObj = new JSONObject();
					 jsonObj.put("form_code", "MESTHPM010");
						jsonObj.put("form_name", "红冲");
						jsonObj.put("form_time", ydmZcRedchongEntity.getCreateTime());
						jsonObj.put("operate_flag", "I");
						jsonObj.put("mat_no", ydmZcRedchongEntity.getInstockDoc());
						jsonObj.put("pack_no", "");
//						jsonObj.put("in_stock_code", ydmInListEntity.getInstockSqe());
//						jsonObj.put("in_stock_name", "");
//						jsonObj.put("in_stock_area", "");
//						jsonObj.put("in_stock_loca", "");
//						jsonObj.put("in_stock_floor", "");
						jsonObj.put("mat_netwt", ydmZcRedchongEntity.getActWeight());
						jsonObj.put("mat_grosswt", "");
						jsonObj.put("mat_theorywt", ydmZcRedchongEntity.getActTheoryWeight());
						jsonObj.put("mat_actwt", ydmZcRedchongEntity.getActWeight());
						jsonObj.put("mat_discrepwt", "");
						jsonObj.put("mat_num", ydmZcRedchongEntity.getActCount());
						jsonObj.put("mat_kind", ydmZcRedchongEntity.getMaterialName());
						jsonObj.put("mat_thick", ydmZcRedchongEntity.getActHeight());
						jsonObj.put("mat_width", "");
						jsonObj.put("mat_len", ydmZcRedchongEntity.getActLen());
						jsonObj.put("order_no", ydmZcRedchongEntity.getOrderNo());
						jsonObj.put("order_detail_no", ydmZcRedchongEntity.getOrderSeq());
						jsonObj.put("stacking_no", "");
						jsonObj.put("product_code", "");
						jsonObj.put("product_name", "");
						jsonObj.put("wt_mode", "");
						jsonObj.put("export_flag", "");
						jsonObj.put("consign_user_code", "");
						jsonObj.put("consign_user_name", "");
						jsonObj.put("order_cust_code", "");
						jsonObj.put("order_cust_cname", "");
						jsonObj.put("balance_user_code", "");
						jsonObj.put("balance_user_name", "");
						jsonObj.put("mat_move_status", "");
						jsonObj.put("psc", "");
						jsonObj.put("prod_code", ydmZcRedchongEntity.getProduccode());
						jsonObj.put("prod_cname", ydmZcRedchongEntity.getProducname());
						jsonObj.put("sgsign", ydmZcRedchongEntity.getGradename());
						jsonObj.put("complex_decide_code", "");
						jsonObj.put("sample_lotno", "");
						jsonObj.put("stno", "");
						jsonObj.put("pack_type_code", "");
						jsonObj.put("carrier_no", "");
						jsonObj.put("red_cause_code", "");
						jsonObj.put("red_cause_desc", "");
						jsonObj.put("msc", "");
						jsonObj.put("apn", "");
						jsonObj.put("heat_treat_no", "");
						jsonObj.put("company_code", "");
						jsonObj.put("cust_mat_specs", ydmZcRedchongEntity.getSpecName());
						jsonObj.put("prod_class_code", ydmZcRedchongEntity.getProductFlag());
						jsonObj.put("prod_class_desc", "");
						jsonObj.put("proc_status", "");
						jsonObj.put("matqty", "");
						jsonObj.put("spec", "");
						jsonObj.put("msc_lineno", "");
						jsonObj.put("len_from", ydmZcRedchongEntity.getActLenMin());
						jsonObj.put("lento", ydmZcRedchongEntity.getActLenMax());
						jsonObj.put("complex_decide_maker", ydmZcRedchongEntity.getCreateName());
						jsonObj.put("statuc", "J");
						objects.add(jsonObj);
				} 
			}
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			DefaultWebServiceRequest request = new DefaultWebServiceRequest();
			Gson gson =  new Gson();
			request.setServiceId("MESTHPM010");
            request.setMsgBody(gson.toJson(objects));
            String result = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx",request,"receiveMessage","");	
            
		   if(!result.equals("200")) {
			   connection.rollback();
			   cro.setV_errMsg("接口信息上传失败！");
			   cro.setResult(1);
			    return cro;
		   }
			if(cro.getV_errMsg().equals(""))
			{
				cro.setV_errMsg("红冲成功!");
			}
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					cro.setV_errMsg(e.getMessage());
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
	}
	/***
	 * 撤销红冲
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject cancelRed(ArrayList<String> parmList)
	{
		CoreReturnObject cro = new CoreReturnObject();
		Connection connection = this.getDao(CoreConstantData.sysbeanstr)
				.getConnection();
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
		String systime = dateFormat.format(now);
		String bathYear = df.format(now);
		String frimFlag = "";
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for(String str : parmList)
			{
				YdmZcRedchongEntity ydmRedEntity = EntityTool.getEntityByJSONStr(str, YdmZcRedchongEntity.class);
				sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.selectFrimFlag");
				sql = EntityTool.fillSqlByEntity(sql, ydmRedEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					frimFlag = rs.getString("FRIM_FLAG");
				}
				rs.close();
				psta.close();
				if(frimFlag.equals("1"))
				{
					cro.setV_errMsg("红冲信息已被制造部接收,不允许撤销!");
					return cro;
				}
				
				String deleteSql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.cancelRed");
				deleteSql = EntityTool.fillSqlByEntity(deleteSql, ydmRedEntity);
				sqllist.add(deleteSql);
			}
			cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
			if(cro.getV_errMsg().equals(""))
			{
				cro.setV_errMsg("撤销成功!");
			}
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
			if (connection != null) {
				try {
					cro.setV_errMsg(e.getMessage());
					connection.rollback(); // 回滚事务
				} catch (Exception e2) {
				}
			}
		} finally {
			try {
				if (connection != null && !connection.isClosed()) {
					connection.close();
				}
			} catch (Exception e2) {
			}
		}
		return cro;
	}
	
	/***
	 * 生成红冲单号
	 * @param con
	 * @return
	 * @throws SQLException 
	 */
	public static String queryRedDoc(Connection con) throws SQLException
	{
		String redDoc = "";
		String sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.queryRedDoc");
		PreparedStatement psta = con.prepareStatement(sql);
		ResultSet rs = psta.executeQuery();
		if(rs.next())
		{
			redDoc = rs.getString("INSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return redDoc;
	}
}
