package com.steering.pss.ydm.Report;


import java.sql.BatchUpdateException;
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.db.DBCommon;

import com.steering.pss.ydm.entity.MatZcMEntity1;
import core.stlmes.server.sale.util.Convert;

public class FrmRunTimeRpt extends DBCommon{
	
	
	public CoreReturnObject getQueryData(String yearMoth,String[] arr,String supplyUnit,String ssq)
	{
	    String strSupplyUnit = "";
        if(supplyUnit.equals("120501"))
        {
            strSupplyUnit = " AND (T.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T.SUPPLY_UNIT_CODE IS NULL)";
        }else if(supplyUnit.equals("120504")){
            strSupplyUnit = " AND T.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
        }
        String ssqrkString = "";
        String ssqckString = "";
        if(ssq.equals("1")){
        	ssqrkString = " AND INSTOCK_TYPE_CODE IN ('800701', '800702', '800704', '800706', '800707', '800712') ";
        	ssqckString = " AND OUTSTOCK_TYPE_CODE IN ('800805', '800804', '800802', '800808', '800806', '800812') ";
        }else{
        	ssqrkString = " AND INSTOCK_TYPE_CODE IN ('800701', '800702', '800704', '800706', '800707') ";
        	ssqckString = " AND OUTSTOCK_TYPE_CODE IN ('800805', '800804', '800802', '800808', '800806') ";
        }
		String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getQueryData");
		String str = CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
		sql = sql.replace("#CONDTIONS#", str + strSupplyUnit);
		sql = sql.replace("#BAL_YEAR_MONTH#", yearMoth);
		sql = sql.replace("#ssqrkString#", ssqrkString);
		sql = sql.replace("#ssqckString#", ssqckString);
		return this.getData(sql);
	}
	
	public CoreReturnObject getQueryDataXs(String yearMoth,String[] arr,String supplyUnit,String type)
	{
	    String strSupplyUnit = "";
	    String sql = "";
        if(supplyUnit.equals("120501"))
        {
            strSupplyUnit = " AND (T.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR T.SUPPLY_UNIT_CODE IS NULL)";
        }else if(supplyUnit.equals("120504")){
            strSupplyUnit = " AND T.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
        }
         sql = type.equals("XS") ? CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getQueryDataXs") 
        		 : CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getQueryDataXn");
		String str = CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
		sql = sql.replace("#CONDTIONS#", str + strSupplyUnit);
		sql = sql.replace("#BAL_YEAR_MONTH#", yearMoth);
		return this.getData(sql);
	}
	
	/**
     * 获取期初重量
     * @param strWhere
     * @return
     */
    public CoreReturnObject getOriginalLast(String time,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getOriginalLast").replace("#condtions#", strWhere);
    	sql += CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
    	sql += " group by t.JUDGE_STOVE_NO,t.BATCH_NO,t.BATCH_GROUD_NO,T.PRODUCNAME,T.STD_STYLE_DESC,T.STEELNAME,T.SPEC_NAME,T.MODEL_DESC";
    	return this.getData(sql,new Object[]{time});
    }
    
    /***
     * 本期入库量
     * @param strOriginal
     * @param
     * @param
     * @param strWhere
     * @return
     */
    public CoreReturnObject getThisIn(String strOriginal,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getThisIn").replace("#condtions#", strWhere);
    	sql += CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
    	sql += " group by t.JUDGE_STOVE_NO,t.BATCH_NO,t.BATCH_GROUD_NO,T.PRODUCNAME,T.STD_STYLE_DESC,T.STEELNAME,T.SPEC_NAME,T.MODEL_DESC";
    	return this.getData(sql, new Object[]{strOriginal,strOriginal,strOriginal});
    }
    
    /***
     * 本期出库量
     * @param strOriginal
     * @param
     * @param
     * @param strWhere
     * @return
     */
    public CoreReturnObject getThisOut(String strOriginal,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getThisOut").replace("#condtions#", strWhere);
    	sql = sql.replace("#condtions1#", strWhere);
    	sql += CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
    	sql += " group by t.JUDGE_STOVE_NO,t.BATCH_NO,t.BATCH_GROUD_NO,T.PRODUCNAME,T.STD_STYLE_DESC,T.STEELNAME,T.SPEC_NAME,T.MODEL_DESC";
    	return this.getData(sql, new Object[]{strOriginal,strOriginal,strOriginal});
    }
    
    /***
     * 调差量
     * @param strDateFrom
     * @param
     * @param strWhere
     * @return
     */
    public CoreReturnObject getAdjust(String strDateFrom,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getAdjust").replace("#condtions#", strWhere);
    	sql += CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
    	sql += " group by t.JUDGE_STOVE_NO,t.BATCH_NO,t.BATCH_GROUD_NO,T.PRODUCNAME,T.STD_STYLE_DESC,T.STEELNAME,T.SPEC_NAME,T.MODEL_DESC";
    	return this.getData(sql,new Object[]{strDateFrom});
    }
    
    
    /***
     * 查询中转信息
     * @param yearMoth
     * @param heatNo
     * @return
     */
    public CoreReturnObject getTal(String yearMoth,String heatNo,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getTal");
    	sql += CoreConverter.toSqlConditionString("BELONG_CODE", arr);
    	return this.getData(sql, new Object[]{yearMoth,heatNo});
    }
    
    /***
     * 插入中间表
     * @param list
     * @return
     */
    public CoreReturnObject insertTal(ArrayList<ArrayList<String>> list,String[] arr)
    {
    	CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        Date now = new Date();
        String exception  = "";
 	    SimpleDateFormat dateFormat = new SimpleDateFormat(
        "yyyyMMdd");
        String systime = dateFormat.format(now);
 	   //String systime = "20151201";
         List<MatZcMEntity1> matZcEntity = null;
    	try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String str = CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
            String insertTalsql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.insertTal_").replace("#condtions#", str);
            PreparedStatement insertTalpsta = connection.prepareStatement(insertTalsql);
            String updateQcmFlagSql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.updateQcmFlag").replace("#BELONG_CODE_JUDGE#", str);
            PreparedStatement updateQcmPsta = connection.prepareStatement(updateQcmFlagSql);
            for(int i=0;i<list.size();i++)
            {
//            	Integer count = 0;
//                double wgt = 0;
//                matZcEntity = null;
            	ArrayList<String> parm = list.get(i);
//            	sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.SelectMatZc");
//            	psta = connection.prepareStatement(sql);
//            	psta.setString(1, parm.get(0));
//            	psta.setString(2, parm.get(1));
//            	psta.setString(3, parm.get(2));
//            	rs = psta.executeQuery();
//                matZcEntity = EntityTool.getEntitysByRs(rs,
//						MatZcMEntity1.class);
//				rs.close();
//				psta.close();
//				if(matZcEntity == null)
//				{
//					cro.setV_errMsg("该炉【"+parm.get(0)+"】无库存数据,请核实!");
//					return cro;
//				}
////				for(MatZcMEntity1 matTity:matZcEntity)
////				{
////					
////					count += Integer.decode(matTity.getActCount());
////					wgt += Double.parseDouble(matTity.getActWeight());
////				}
//				exception = parm.get(0);
//				if(!(matZcEntity.get(0).getActCount().equals(parm.get(3))))
//				{
//					cro.setV_errMsg("中转的炉号【"+parm.get(0)+"】库存数据有变动,请重新中转!");
//					return cro;
//				}
				insertTalpsta.setString(1, parm.get(0));
				insertTalpsta.setString(2, parm.get(1));
				insertTalpsta.setString(3, parm.get(2));
				insertTalpsta.setString(4, parm.get(0));
				insertTalpsta.setString(5, parm.get(1));
				insertTalpsta.setString(6, parm.get(2));
				insertTalpsta.setString(7, parm.get(0));
				insertTalpsta.setString(8, parm.get(1));
				insertTalpsta.setString(9, parm.get(2));
				
				insertTalpsta.setString(10, parm.get(0));
				insertTalpsta.setString(11, parm.get(1));
				insertTalpsta.setString(12, parm.get(2));
				insertTalpsta.setString(13, parm.get(3));
				insertTalpsta.setString(14, parm.get(4));
				insertTalpsta.setString(15, systime);
				insertTalpsta.setString(16, parm.get(5));
				insertTalpsta.setString(17, "0");
				insertTalpsta.addBatch();
				
            }
            updateQcmPsta.setString(1, systime);
            
            insertTalpsta.executeBatch();
            updateQcmPsta.executeBatch();
            connection.commit();
            cro.setV_errMsg("期初数据中转成功!");
    	}
        catch (SQLException e) {
            System.out.println(e.getMessage() + exception);
            if(e instanceof BatchUpdateException){
            	//System.out.println(((BatchUpdateException) e).getUpdateCounts().length);
            	cro.setResult(((BatchUpdateException) e).getUpdateCounts().length);
            	cro.setV_errCode(-1);
            }
            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 list
     * @return
     */
    public CoreReturnObject insertInital(ArrayList<ArrayList<String>> list,String bathYear,String []arr,String custom)
    {
    	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(
        "yyyyMMdd");
         String systime = dateFormat.format(now);
 	    //String systime = "20151201";
         List<String> ids = new ArrayList<>();
         List<MatZcMEntity1> matZcEntity = null;
         String ss = "";
         String supplyUnit = "";
         int count = 0;
         try {
             connection.setAutoCommit(false); // 取消自动提交事务
             String str = CoreConverter.toSqlConditionString("T.BELONG_CODE",arr);
             String insertInitalsql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.insertInital1_");
             insertInitalsql = insertInitalsql.replace("#CONDITIONS#",str);
             PreparedStatement insertInitalpsta = connection.prepareStatement(insertInitalsql);
//             String updateTalSql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.updateTal");
//             PreparedStatement updateTalpsta = connection.prepareStatement(updateTalSql);
             if(custom.equals("120501"))
             {
                 supplyUnit = "天津钢管制造有限公司";
             }else if(custom.equals("120504"))
             {
                 supplyUnit = "江苏天淮钢管有限公司";
             }
             for(int i=0;i<list.size();i++)
             {
             	ArrayList<String> parm = list.get(i);
                sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.selectMatCount");
                sql = sql.replace("#CONDITIONS#",str);
                psta = connection.prepareStatement(sql);
                psta.setString(1, parm.get(0));
                psta.setString(2, parm.get(1));
                psta.setString(3, parm.get(2));
                psta.setString(4, parm.get(5));
                psta.setString(5, parm.get(6));
                psta.setString(6, parm.get(7));
                psta.setString(7, parm.get(8));
                psta.setString(8, parm.get(9));
                psta.setString(9, parm.get(12));

	             psta.setString(10, parm.get(0));
	             psta.setString(11, parm.get(1));
	             psta.setString(12, parm.get(2));
	             psta.setString(13, parm.get(5));
	             psta.setString(14, parm.get(6));
	             psta.setString(15, parm.get(7));
	             psta.setString(16, parm.get(8));
	             psta.setString(17, parm.get(9));
	             psta.setString(18, parm.get(12));
	             psta.setString(19, bathYear);
                rs = psta.executeQuery();
                if(rs.next())
                {
                	count = Integer.parseInt(rs.getString("ACOUNT"));
                }
                rs.close();
                psta.close();
                if(count < Integer.parseInt(parm.get(3)))
                {
                	ids.add(parm.get(0));
                	cro.setV_errMsg("炉号" + parm.get(0)+"无库存信息,请核实该炉号库存所属权或组号是否与期初/入库/出库所属权或组号一致!");
                	return cro;
                }
             	ss = parm.get(0);



				insertInitalpsta.setString(1, parm.get(0));
				insertInitalpsta.setString(2, parm.get(1));
				insertInitalpsta.setString(3, parm.get(2));
				insertInitalpsta.setString(4, parm.get(12));

				insertInitalpsta.setString(5, parm.get(5));
				insertInitalpsta.setString(6, parm.get(6));
				insertInitalpsta.setString(7, parm.get(7));
				insertInitalpsta.setString(8, parm.get(8));
				insertInitalpsta.setString(9, parm.get(9));



                 insertInitalpsta.setString(10, parm.get(0));
                 insertInitalpsta.setString(11, parm.get(1));
                 insertInitalpsta.setString(12, parm.get(2));
                 insertInitalpsta.setString(13, parm.get(12));

                 insertInitalpsta.setString(14, parm.get(5));
                 insertInitalpsta.setString(15, parm.get(6));
                 insertInitalpsta.setString(16, parm.get(7));
                 insertInitalpsta.setString(17, parm.get(8));
                 insertInitalpsta.setString(18, parm.get(9));
                 insertInitalpsta.setString(19, bathYear);

				insertInitalpsta.setString(20, parm.get(3));
				insertInitalpsta.setString(21, parm.get(4));
				insertInitalpsta.setString(22, parm.get(11));
				insertInitalpsta.setString(23, parm.get(10));
				insertInitalpsta.setString(24, parm.get(10));
				insertInitalpsta.setString(25,custom);
                 insertInitalpsta.setString(26,supplyUnit);
				insertInitalpsta.addBatch();
//				updateTalpsta.setString(1, parm.get(7));
//				updateTalpsta.addBatch();
             }
             for (String id : ids) {
				System.out.println(id);
			}
             insertInitalpsta.executeBatch();
             //updateTalpsta.executeBatch();
             connection.commit();
             cro.setV_errMsg("期初数据结转成功!");
         }
         catch (Exception e) {
             System.out.println(e.getMessage() + ss);
             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 list
     * @return
     */
    public CoreReturnObject insertInitalXs(ArrayList<ArrayList<String>> list,String bathYear,String []arr,String custom,String type)
    {
    	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(
        "yyyyMMdd");
         String systime = dateFormat.format(now);
 	    //String systime = "20151201";
         List<String> ids = new ArrayList<>();
         List<MatZcMEntity1> matZcEntity = null;
         String ss = "";
         String supplyUnit = "";
         String insertInitalsql = "";
         int count = 0;
         try {
             connection.setAutoCommit(false); // 取消自动提交事务
             String str = CoreConverter.toSqlConditionString("T.BELONG_CODE",arr);
             insertInitalsql = type.equals("XS") ? CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.insertInital1_Xs") : CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.insertInital1_Xn");
             insertInitalsql = insertInitalsql.replace("#CONDITIONS#",str);
             PreparedStatement insertInitalpsta = connection.prepareStatement(insertInitalsql);
//             String updateTalSql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.updateTal");
//             PreparedStatement updateTalpsta = connection.prepareStatement(updateTalSql);
             if(custom.equals("120501"))
             {
                 supplyUnit = "天津钢管制造有限公司";
             }else if(custom.equals("120504"))
             {
                 supplyUnit = "江苏天淮钢管有限公司";
             }
             for(int i=0;i<list.size();i++)
             {
             	ArrayList<String> parm = list.get(i);
                sql = type.equals("XS") ? CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.selectMatCountXs") : CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.selectMatCountXn");
                sql = sql.replace("#CONDITIONS#",str);
                psta = connection.prepareStatement(sql);
                psta.setString(1, parm.get(0));
                psta.setString(2, parm.get(1));
                psta.setString(3, parm.get(2));
                psta.setString(4, parm.get(5));
                psta.setString(5, parm.get(6));
                psta.setString(6, parm.get(7));
                psta.setString(7, parm.get(8));
                psta.setString(8, parm.get(9));
                psta.setString(9, parm.get(12));

	             psta.setString(10, parm.get(0));
	             psta.setString(11, parm.get(1));
	             psta.setString(12, parm.get(2));
	             psta.setString(13, parm.get(5));
	             psta.setString(14, parm.get(6));
	             psta.setString(15, parm.get(7));
	             psta.setString(16, parm.get(8));
	             psta.setString(17, parm.get(9));
	             psta.setString(18, parm.get(12));
	             psta.setString(19, bathYear);
                rs = psta.executeQuery();
                if(rs.next())
                {
                	count = Integer.parseInt(rs.getString("ACOUNT"));
                }
                rs.close();
                psta.close();
                if(count < Integer.parseInt(parm.get(3)))
                {
                	ids.add(parm.get(0));
                	cro.setV_errMsg("炉号" + parm.get(0)+"无库存信息,请核实该炉号库存所属权或组号是否与期初/入库/出库所属权或组号一致!");
                	return cro;
                }
             	ss = parm.get(0);



				insertInitalpsta.setString(1, parm.get(0));
				insertInitalpsta.setString(2, parm.get(1));
				insertInitalpsta.setString(3, parm.get(2));
				insertInitalpsta.setString(4, parm.get(12));

				insertInitalpsta.setString(5, parm.get(5));
				insertInitalpsta.setString(6, parm.get(6));
				insertInitalpsta.setString(7, parm.get(7));
				insertInitalpsta.setString(8, parm.get(8));
				insertInitalpsta.setString(9, parm.get(9));



                 insertInitalpsta.setString(10, parm.get(0));
                 insertInitalpsta.setString(11, parm.get(1));
                 insertInitalpsta.setString(12, parm.get(2));
                 insertInitalpsta.setString(13, parm.get(12));

                 insertInitalpsta.setString(14, parm.get(5));
                 insertInitalpsta.setString(15, parm.get(6));
                 insertInitalpsta.setString(16, parm.get(7));
                 insertInitalpsta.setString(17, parm.get(8));
                 insertInitalpsta.setString(18, parm.get(9));
                 insertInitalpsta.setString(19, bathYear);

				insertInitalpsta.setString(20, parm.get(3));
				insertInitalpsta.setString(21, parm.get(4));
				insertInitalpsta.setString(22, parm.get(11));
				insertInitalpsta.setString(23, parm.get(10));
				insertInitalpsta.setString(24, parm.get(10));
				insertInitalpsta.setString(25,custom);
                 insertInitalpsta.setString(26,supplyUnit);
				insertInitalpsta.addBatch();
//				updateTalpsta.setString(1, parm.get(7));
//				updateTalpsta.addBatch();
             }
             for (String id : ids) {
				System.out.println(id);
			}
             insertInitalpsta.executeBatch();
             //updateTalpsta.executeBatch();
             connection.commit();
             cro.setV_errMsg("期初数据结转成功!");
         }
         catch (Exception e) {
             System.out.println(e.getMessage() + ss);
             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 list
     * @return
     */
    public CoreReturnObject getIntal(ArrayList<String> list)
    {
    	return this.getDataBySqlID("FrmRunTimeRpt.getIntal", list.toArray());
    }
    
    
    /***
     * 查询结转数据是否存在
     * @param
     * @return
     */
    public CoreReturnObject getIntalJZ(String bathYear,String[] arr,String custom)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getIntalJZ");
    	sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
    	return this.getData(sql, new Object[]{bathYear,custom});
    }
    
    public CoreReturnObject getIntalJZXs(String bathYear,String[] arr,String custom,String type)
    {
    	String sql = type.equals("XS") ? CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getIntalJZXs") : CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.getIntalJZXn");
    	sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
    	return this.getData(sql, new Object[]{bathYear,custom});
    }
    
    public CoreReturnObject doQueryTail(String bathYear,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmRunTimeRpt.doQueryTail");
    	sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
    	return this.getData(sql, new Object[]{bathYear});
    }
}
