package com.steering.pss.ydm.pipemanage;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import CoreFS.Util.StringUtils;
import com.steering.comm.data.ComBaseInfo;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.ydm.base.MeanValueCalculation;
import com.steering.pss.ydm.entity.MatZcMEntity;
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.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FrmFrimRedChong extends DBCommon{

	/***
	 * 获取所有产线
	 * @return
	 */
	public CoreReturnObject doQueryPline(String custom)
	{
		return  this.getDataBySqlID("FrmFrimRedChong.doQueryPline",new Object[]{custom});
	}
	/***
	 * 审核通过
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject doFrimBy(ArrayList<String> parmList,String userName)
	{
		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 = "";//审核状态
		String inDoc = "";//入库单号(销售)
		String inDocCx = "";//产权入库单号
		String insertMatBcSql = "";
		String insertMatBcSqlXs = "";
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			inDoc = getInListDoc(connection,"800704","AI"); //查询入库单号
			inDocCx = getInListDoc(connection, "800704", "QI");
			for(String str : parmList)
			{
				String sumCount = "";//总支数
				String sumWgt = "";//总重量
				String sumLen = "";//总长度
				int remainCount = 0;
				double remainWgt = 0.0;
				double remainLen = 0.0;
				
				
				YdmZcRedchongEntity ydmEntity = EntityTool.getEntityByJSONStr(str, YdmZcRedchongEntity.class);
				String bathYear = "120504".equals(ydmEntity.getSupplyUnitCode())? ComBaseInfo.GetBalYear_2416(now): ComBaseInfo.GetBalYear(now);
				ydmEntity.setFrimName(userName);
				ydmEntity.setFrimTime(systime);
				ydmEntity.setInstockDocR(inDoc);
				ydmEntity.setInstockDocCx(inDocCx);
				ydmEntity.setBalYearMonth(bathYear);
				sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.selectFrimFlag");
				sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					frimFlag = rs.getString("FRIM_FLAG");
				}
				rs.close();
				psta.close();
				if(!frimFlag.equals("0"))
				{
					cro.setV_errMsg("该信息已被审核,不允许再次审核!");
				}
				if(ydmEntity.getSupplyUnitCode().equals("120504"))
				{
					ydmEntity.setBelongCode("002023005");
					ydmEntity.setBelongName("产品制造部");
				}else
				{
					ydmEntity.setBelongCode("002001001");
					ydmEntity.setBelongName("生产计划部");
				}
				if(ydmEntity.getRedType().equals("1"))//按支红冲
				{
					insertMatBcSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.insertMatBcSeq");
					insertMatBcSql = EntityTool.fillSqlByEntity(insertMatBcSql, ydmEntity);
					sqllist.add(insertMatBcSql);
				}else
				{
					sql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.selectSumMatZc");//查询总支数、总重量、总长度
					sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
					psta = connection.prepareStatement(sql);
					rs = psta.executeQuery();
					if(rs.next())
					{
						sumCount = rs.getString("ACT_COUNT");
						sumWgt = rs.getString("ACT_WEIGHT");
						sumLen = rs.getString("ACT_LEN");
					}
					rs.close();
					psta.close();
					if(Integer.parseInt(sumCount) < Integer.parseInt(ydmEntity.getActCount()) || Double.parseDouble(sumWgt) < Double.parseDouble(ydmEntity.getActWeight()) || Double.parseDouble(sumLen) < Double.parseDouble(ydmEntity.getActLen()))
					{
						cro.setV_errMsg("红冲的支数、重量、长度不允许大于库存的支数、重量、长度!");
						return cro;
					}
					if(ydmEntity.getActCount().equals(sumCount))
					{
						insertMatBcSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.insertMatBcSeq");
						insertMatBcSql = EntityTool.fillSqlByEntity(insertMatBcSql, ydmEntity);
						sqllist.add(insertMatBcSql);
					}else
					{
						ArrayList<String> redWgtList = null;
						ArrayList<String> redLengthList = null;
						
						ArrayList<String> storeWgtList = null;
						ArrayList<String> storeLengthList = null;
						
						storeWgtList = new ArrayList<String>();
						List<double[]> listwgt = MeanValueCalculation
								.MeanCalculation(Double.parseDouble(sumWgt)-Double.parseDouble(ydmEntity.getActWeight()), Integer.parseInt(sumCount)
										- Integer.parseInt(ydmEntity.getActCount()));// 重量
						for (int k = 0; k < listwgt.size(); k++) {
							double[] conLen = listwgt.get(k);
							if ((int) conLen[0] > 0) {
								for (int x = 0; x < (int) conLen[0]; x++) {
									DecimalFormat dt = new DecimalFormat(
											"0.000");
									storeWgtList.add(dt.format(conLen[1])
											.toString());
								}
							}
						}
						
						storeLengthList = new ArrayList<String>();
						List<double[]> lenList = MeanValueCalculation
								.MeanCalculation(Double.parseDouble(sumLen)-Double.parseDouble(ydmEntity.getActLen()),
										Integer.parseInt(sumCount)
										- Integer.parseInt(ydmEntity.getActCount()));
						for (int k = 0; k < lenList.size(); k++) {
							double[] conLen = lenList.get(k);
							if ((int) conLen[0] > 0) {
								for (int x = 0; x < (int) conLen[0]; x++) {
									DecimalFormat dt = new DecimalFormat(
											"0.000");
									storeLengthList.add(dt
											.format(conLen[1]).toString());
								}
							}
						}
						

						redWgtList = new ArrayList<String>();
						List<double[]> redListwgt = MeanValueCalculation
								.MeanCalculation(Double.parseDouble(ydmEntity
										.getActWeight()), Integer
										.parseInt(ydmEntity.getActCount()));// 重量
						for (int s = 0; s < redListwgt.size(); s++) {
							double[] conLens = redListwgt.get(s);
							if ((int) conLens[0] > 0) {
								for (int x = 0; x < (int) conLens[0]; x++) {
									DecimalFormat dt = new DecimalFormat(
											"0.000");
									redWgtList.add(dt.format(conLens[1])
											.toString());
								}
							}
						}
						redLengthList = new ArrayList<String>();
						List<double[]> redLenList = MeanValueCalculation
								.MeanCalculation(Double.parseDouble(ydmEntity.getActLen()), Integer
										.parseInt(ydmEntity.getActCount()));
						for (int r = 0; r < redLenList.size(); r++) {
							double[] conLenr = redLenList.get(r);
							if ((int) conLenr[0] > 0) {
								for (int x = 0; x < (int) conLenr[0]; x++) {
									DecimalFormat dt = new DecimalFormat(
											"0.000");
									redLengthList.add(dt.format(conLenr[1])
											.toString());
								}
							}
						}
						
						ArrayList<String> matNoList = new ArrayList<String>();// 材料号(红冲)
						sql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.selectMatZcRed");
						sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
						psta = connection.prepareStatement(sql);
						rs = psta.executeQuery();
						while(rs.next())
						{
							matNoList.add(rs.getString("MAT_NO"));
						}
						rs.close();
						psta.close();
						
						for(int i = 0;i<matNoList.size(); i++)
						{
							MatZcMEntity matZcEntity = new MatZcMEntity();
							matZcEntity.setMatNo(matNoList.get(i));
							matZcEntity.setActWeight(Double.parseDouble(redWgtList.get(i)));
							matZcEntity.setActLen(Double.parseDouble(redLengthList.get(i)));
							matZcEntity.setInstockDoc(ydmEntity.getInstockDoc());
							String updateMatZcWgtSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.updateMatZcWgt");
							updateMatZcWgtSql = EntityTool.fillSqlByEntity(updateMatZcWgtSql, matZcEntity);
							String updateMatZcWgtSqlXs = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChongXs.updateMatZcWgt");
							updateMatZcWgtSqlXs = EntityTool.fillSqlByEntity(updateMatZcWgtSqlXs, matZcEntity);
							sqllist.add(updateMatZcWgtSql);
							sqllist.add(updateMatZcWgtSqlXs);
						}
						
						ArrayList<String> matNoListStorage = new ArrayList<String>();// 材料号(剩余)
						sql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.selectMatZcStorage");
						sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
						psta = connection.prepareStatement(sql);
						rs = psta.executeQuery();
						while(rs.next())
						{
							matNoListStorage.add(rs.getString("MAT_NO"));
						}
						rs.close();
						psta.close();
						for(int i = 0;i<matNoListStorage.size(); i++)
						{
							MatZcMEntity matZcEntity = new MatZcMEntity();
							matZcEntity.setMatNo(matNoListStorage.get(i));
							matZcEntity.setActWeight(Double.parseDouble(storeWgtList.get(i)));
							matZcEntity.setActLen(Double.parseDouble(storeLengthList.get(i)));
							String updateMatZcStorageWgtSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.updateMatZcWgtStorage");
							updateMatZcStorageWgtSql = EntityTool.fillSqlByEntity(updateMatZcStorageWgtSql, matZcEntity);
							String updateMatZcStorageWgtSqlXs = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChongXs.updateMatZcWgtStorage");
							updateMatZcStorageWgtSqlXs = EntityTool.fillSqlByEntity(updateMatZcStorageWgtSqlXs, matZcEntity);
							sqllist.add(updateMatZcStorageWgtSql);
							sqllist.add(updateMatZcStorageWgtSqlXs);

						}
						
						insertMatBcSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.insertMatBcSeq");
						insertMatBcSql = EntityTool.fillSqlByEntity(insertMatBcSql, ydmEntity);
						sqllist.add(insertMatBcSql);
					}
				}
				
				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 connection
	 * @param
	 * @param
	 * @return
	 * @throws SQLException 
	 */
	private String getInListDoc(Connection connection, String instockCode,
			String instockMemo) throws SQLException {
		String inDoc = "";
		String sql = "";
		PreparedStatement psta = null;
		ResultSet rs = null;
		if(instockMemo.equals("AI"))
		{
			sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.selectInStockDoc");
		}else if(instockMemo.equals("QI"))
		{
			sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.selectInStockDocCx");
		}
		psta = connection.prepareStatement(sql);
		psta.setString(1, instockMemo);
		psta.setString(2, instockCode);
		psta.setString(3, instockMemo);
		rs = psta.executeQuery();
		if(rs.next())
		{
			inDoc = rs.getString("INSTOCK_DOC");
		}
		rs.close();
		psta.close();
		return inDoc;
	}
	/***
	 * 审核不通过
	 * @param parmList
	 * @return
	 */
	public CoreReturnObject doFrimNot(ArrayList<String> parmList,String userName)
	{
		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);
				ydmRedEntity.setFrimName(userName);
				
				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("0"))
				{
					cro.setV_errMsg("该信息已被审核,不允许再次审核!");
				}
				String updateYdmRedSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.doFrimNot");
				updateYdmRedSql = EntityTool.fillSqlByEntity(updateYdmRedSql, ydmRedEntity);
				sqllist.add(updateYdmRedSql);
			}
			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
	 * @return
	 */
	public CoreReturnObject cancelFrim(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 acount = "";
		String frimFlag = "";
		try {
			ArrayList<String> sqllist = new ArrayList<String>();
			for(String str : parmList)
			{
			    YdmZcRedchongEntity ydmEntity = EntityTool.getEntityByJSONStr(str, YdmZcRedchongEntity.class);
			    sql = CoreXmlSqlParsersFactory.getSql("FrmRedChong.selectFrimFlag");
				sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
				psta = connection.prepareStatement(sql);
				rs = psta.executeQuery();
				if(rs.next())
				{
					frimFlag = rs.getString("FRIM_FLAG");
				}
				rs.close();
				psta.close();
				
				if(frimFlag.equals("0"))
				{
					cro.setV_errMsg("该信息未被审核,不允许撤销审核!");
				}
			    
			    
			    if(frimFlag.equals("1"))
			    {
			    	sql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.selectMatBcCount");
				    sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
				    psta = connection.prepareStatement(sql);
				    rs = psta.executeQuery();
				    if(rs.next())
				    {
				    	acount = rs.getString("ACT_COUNT");
				    }
				    rs.close();
				    psta.close();
				    if( Integer.parseInt(acount) < Integer.parseInt(ydmEntity.getActCount()))
				    {
				        cro.setV_errMsg("半成品库存状态已改变,请核实!");
				        return cro;
				    }
				    
				    acount = "0";
				    sql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.selectFmisZcCount");
				    sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
				    psta = connection.prepareStatement(sql);
				    rs = psta.executeQuery();
				    if(rs.next())
				    {
				    	acount = rs.getString("ACT_COUNT");
				    }
				    rs.close();
				    psta.close();
				    if(!StringUtils.isEmpty(acount) && Integer.parseInt(acount) == 0)
				    {
				        cro.setV_errMsg("财务系统已接收红冲数据，不能撤销红冲审核,请核实!");
				        return cro;
				    }
				    
			    	String insertMatZcSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.cancelFrim");
				    insertMatZcSql = EntityTool.fillSqlByEntity(insertMatZcSql, ydmEntity);
				    sqllist.add(insertMatZcSql);
			    }else
			    {
			    	sql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.selectMatZcCount");
				    sql = EntityTool.fillSqlByEntity(sql, ydmEntity);
				    psta = connection.prepareStatement(sql);
				    rs = psta.executeQuery();
				    if(rs.next())
				    {
				    	acount = rs.getString("ACT_COUNT");
				    }
				    rs.close();
				    psta.close();
				    if(!acount.equals(ydmEntity.getActCount()))
				    {
				        cro.setV_errMsg("成品库存状态已改变,请核实!");
				        return cro;
				    }
			    	
			    	String updateYdmRedSql = CoreXmlSqlParsersFactory.getSql("FrmFrimRedChong.cancelFrimNot");
			    	updateYdmRedSql = EntityTool.fillSqlByEntity(updateYdmRedSql, ydmEntity);
			    	sqllist.add(updateYdmRedSql);
			    }
			    
			}
			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;
	}
}
