package com.steering.pss.ydm.Report;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
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.data.ComBaseInfo;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.StringTool;
import com.steering.pss.ydm.entity.MatZcMEntity1;

import core.stlmes.server.sale.util.Convert;

public class FrmrptStoveBatchStorage extends DBCommon{

	/***
	 * 获取期初时间
	 * @param list
	 * @return
	 */
    public CoreReturnObject getOriginaldate(ArrayList<String> list)
    {
    	return this.getDataBySqlID("FrmrptStoveBatchStorage.getOriginaldate", list.toArray());
    }
    
    /**
     * 获取期初重量
     * @param strWhere
     * @return
     */
    public CoreReturnObject getOriginalLast(String time,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.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";
    	return this.getData(sql,new Object[]{time});
    }
    
    
    /***
     * 上期入库量
     * @param
     * @return
     */
    public CoreReturnObject getLastIn(String strOriginalLast,String strDateFrom,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.getLastIn").replace("#condtions#", strWhere);
    	sql += CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
    	sql += " group by t.JUDGE_STOVE_NO,t.BATCH_NO,t.BATCH_GROUD_NO";
    	return this.getData(sql, new Object[]{strOriginalLast,strDateFrom});
    }
    
    /***
     * 上期出库量
     * @param strOriginalLast
     * @param strDateFrom
     * @param strWhere
     * @return
     */
    public CoreReturnObject getLastOut(String strOriginalLast,String strDateFrom,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.getLastOut").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";
    	return this.getData(sql, new Object[]{strOriginalLast,strDateFrom});
    }
    
    /***
     * 本期入库量
     * @param strOriginal
     * @param strDateFrom
     * @param strDateTo
     * @param strWhere
     * @return
     */
    public CoreReturnObject getThisIn(String strOriginal,String strDateFrom,String strDateTo,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.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";
    	return this.getData(sql, new Object[]{strDateTo,strDateTo,strDateFrom,strDateTo,strDateFrom,strDateTo,strOriginal,strDateTo});
    }
    
    /***
     * 本期出库量
     * @param strOriginal
     * @param strDateFrom
     * @param strDateTo
     * @param strWhere
     * @return
     */
    public CoreReturnObject getThisOut(String strOriginal,String strDateFrom,String strDateTo,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.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";
    	return this.getData(sql, new Object[]{strDateTo,strDateTo,strDateFrom,strDateTo,strDateFrom,strDateTo,strOriginal,strDateTo});
    }
    
    /***
     * 调差量
     * @param strDateFrom
     * @param strDateTo
     * @param strWhere
     * @return
     */
    public CoreReturnObject getAdjust(String strDateFrom,String strDateTo,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.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";
    	return this.getData(sql,new Object[]{strDateFrom,strDateTo});
    }
    
    /***
     * 实时库存量
     * @param strDateFrom
     * @param strDateTo
     * @param strWhere
     * @param arr
     * @return
     */
    public CoreReturnObject getMatData(String strDateFrom,String strDateTo,String strWhere,String[] arr)
    {
    	String sql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.getMatData").replace("#condtions#", strWhere);
    	sql += CoreConverter.toSqlConditionString("t.BELONG_CODE", arr);
    	sql += " group by t.JUDGE_STOVE_NO,t.BATCH_NO,t.BATCH_GROUD_NO";
    	return this.getData(sql);
    }
    
    
    /***
     * 当前年月上一个月
     * @param date
     * @return
     */
    private static Date getLastDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, -1);
        return cal.getTime();
    }

    
    /***
     * 批量调差
     * @param list
     * @return
     */
    public CoreReturnObject insertAdjustData(ArrayList<ArrayList<String>> list,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(
        "yyyyMM");
 	    SimpleDateFormat dateF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         String systime = dateF.format(now);
         String bathYear = dateFormat.format(now);
 	     //String systime = "201511";
         SimpleDateFormat matter2 = new SimpleDateFormat("yyMMdd");
         String time = matter2.format(now);//调差单号时间
         String judgeNo = "";
         List<MatZcMEntity1> matZcEntity = null;
         String supplyCode = "";
         String supplyUnit = "";
    	try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String adjustDoc = queryAdjustDoc(connection, list.get(0).get(4),list.get(0)
					.get(5));
            int g = Integer.parseInt(adjustDoc.substring(adjustDoc.length() - 5,adjustDoc.length()));
            String insertAdjustsql = CoreXmlSqlParsersFactory.getSql("FrmrptStoveBatchStorage.insertAdjustData");
            PreparedStatement insertAdjustpsta = connection.prepareStatement(insertAdjustsql);
            //PreparedStatement insertAdjustpsta = null;
            supplyCode = custom;
            if(custom.equals("120501"))
            {
                supplyUnit = "天津钢管制造有限公司";
            }else if(custom.equals("120504"))
            {
                supplyUnit = "江苏天淮钢管有限公司";
            }
            for(int i= 0;i<list.size();i++)
            {
            	matZcEntity = null;
				ArrayList<String> parm = list.get(i);
				
//				String adjustDoc = queryAdjustDoc(connection, list.get(0).get(4),list.get(0)
//						.get(5));
//	            int g = Integer.parseInt(adjustDoc.substring(adjustDoc.length() - 5,adjustDoc.length()));
				sql = CoreXmlSqlParsersFactory
						.getSql("FrmrptStoveBatchStorage.SelectMatNo");
				//sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
				psta = connection.prepareStatement(sql);
				psta.setString(1, parm.get(0));
				psta.setString(2, parm.get(1));
				/*psta.setString(3, parm.get(2));2025-02-07 注释组织组号
                psta.setString(4, parm.get(11));*/
                //psta.setString(4, parm.get(11));
				rs = psta.executeQuery();
				matZcEntity = EntityTool.getEntitysByRs(rs,
						MatZcMEntity1.class);
				rs.close();
				psta.close();
				if(matZcEntity.size() == 0)
				{
					judgeNo = parm.get(0);
					sql = CoreXmlSqlParsersFactory
							.getSql("FrmrptStoveBatchStorage.SelectMatNo_1");
					sql = sql.replace("#BELONG_CODE#", CoreConverter.toSqlConditionString("T.BELONG_CODE", arr));
					psta = connection.prepareStatement(sql);
					psta.setString(1, parm.get(0));
					psta.setString(2, parm.get(1));
					/*psta.setString(3, parm.get(2));2025-02-07 注释组织组号
                    psta.setString(4, parm.get(11));*/
					psta.setString(3, parm.get(0));
                    psta.setString(4, parm.get(1));
                    /*psta.setString(7, parm.get(2));2025-02-07 注释组织组号
                    psta.setString(8, parm.get(11));*/

                    psta.setString(5, parm.get(0));
                    psta.setString(6, parm.get(1));
                    /*psta.setString(11, parm.get(2));2025-02-07 注释组织组号
                    psta.setString(12, parm.get(11));*/
					rs = psta.executeQuery();
					matZcEntity = EntityTool.getEntitysByRs(rs,
							MatZcMEntity1.class);
					rs.close();
					psta.close();
//					sql = CoreXmlSqlParsersFactory
//							.getSql("FrmrptStoveBatchStorage.insertAdjustData");
//                    insertAdjustpsta = connection.prepareStatement(sql);
					insertAdjustpsta.setString(1, parm.get(6));
					insertAdjustpsta.setString(2, parm.get(7));
					insertAdjustpsta.setString(3, "TC"+time+StringTool.formatDecimal(g, "00000"));
					insertAdjustpsta.setString(4, querySendSql(connection, "TC"+time+StringTool.formatDecimal(g, "00000")));

					insertAdjustpsta.setString(5, parm.get(4));
					insertAdjustpsta.setString(6, "批量调差");
					insertAdjustpsta.setString(7, "");
					insertAdjustpsta.setString(8, "");

					insertAdjustpsta.setString(9, parm.get(0));
					insertAdjustpsta.setString(10, parm.get(1));
					insertAdjustpsta.setString(11, parm.get(2));
					if (Double.parseDouble(parm.get(3)) < 0) {
						insertAdjustpsta.setString(12, String.valueOf(Math.abs(Double
								.parseDouble(parm.get(3)))));// 重量
					} else {
						insertAdjustpsta.setString(12, "-" + parm.get(3));// 重量
					}
					insertAdjustpsta.setString(13, matZcEntity.get(0).getBelongCode());// 销售组织
					insertAdjustpsta.setString(14, matZcEntity.get(0).getBelongName());
					insertAdjustpsta.setString(15, systime);
					insertAdjustpsta.setString(16, matZcEntity.get(0).getMaterialNo());
					insertAdjustpsta.setString(17, matZcEntity.get(0).getMaterialName());
					insertAdjustpsta.setString(18, parm.get(10));
					
					insertAdjustpsta.setString(19, systime);
					insertAdjustpsta.setString(20, parm.get(3));
					
					insertAdjustpsta.setString(21, bathYear);
					
					insertAdjustpsta.setString(22, matZcEntity.get(0).getProduccode());
					insertAdjustpsta.setString(23, matZcEntity.get(0).getProducname());
					insertAdjustpsta.setString(24, matZcEntity.get(0).getSteelcode());
					insertAdjustpsta.setString(25, matZcEntity.get(0).getSteelname());
					insertAdjustpsta.setString(26, matZcEntity.get(0).getSpecCode());
					insertAdjustpsta.setString(27, matZcEntity.get(0).getSpecName());
					insertAdjustpsta.setString(28, matZcEntity.get(0).getModelCode());
					insertAdjustpsta.setString(29, matZcEntity.get(0).getModelDesc());
					insertAdjustpsta.setString(30, matZcEntity.get(0).getStdStyle());
					insertAdjustpsta.setString(31, matZcEntity.get(0).getStdStyleDesc());
					insertAdjustpsta.setString(32, matZcEntity.get(0).getStorageNo());
					insertAdjustpsta.setString(33, systime);
					insertAdjustpsta.setString(34, parm.get(8));
					insertAdjustpsta.setString(35, parm.get(9));
					insertAdjustpsta.setString(36, supplyCode);
					insertAdjustpsta.setString(37,supplyUnit);
					insertAdjustpsta.setString(38,matZcEntity.get(0).getIsDealer());
					insertAdjustpsta.setString(39,matZcEntity.get(0).getPlineCode());
					insertAdjustpsta.setString(40,matZcEntity.get(0).getPlineName());
					insertAdjustpsta.setString(41,matZcEntity.get(0).getGradecode());
					insertAdjustpsta.setString(42,matZcEntity.get(0).getGradename());
					insertAdjustpsta.setString(43,matZcEntity.get(0).getProcessCdoe());
					insertAdjustpsta.setString(44,matZcEntity.get(0).getProcessDesc());
					//insertAdjustpsta.executeUpdate();
					insertAdjustpsta.addBatch();
					//insertAdjustpsta.close();
					g++;
				}
			
            }
            insertAdjustpsta.executeBatch();
            connection.commit();
            cro.setV_errMsg("调差成功!");
    	}
        catch (Exception e) {
            System.out.println(e.getMessage() + judgeNo);
            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
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public String querySendSql(Connection conn, String strlist)  throws Exception {
        int seq = 0;
        PreparedStatement psta = null;
        Date dt = new Date();
        SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmPipeAdjust.queryAdjustList1");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1,matter1.format(FrmrptStoveBatchStorage.getLastDate(dt)));
        psta.setString(2,strlist);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            String res = rs.getString(1);
            if (res == null) {
                res = strlist + "00001";
            }
            else {
                seq = Integer.parseInt(res.substring(13, 17));
            }
        }
        rs.close();
        psta.close();
        return strlist + StringTool.formatDecimal(++seq, "00000");
    }
    
    /**
     * 每支材料对应的调差单号
     * @param conn c
     * @param strlist 传递参数
     * @return obj
     * @throws Exception 异常处理
     */
    public String queryAdjustDoc(Connection conn, String strlist,String memo)
            throws Exception {
        int seq = 0;
         PreparedStatement psta = null;
         Date dt = new Date();
         SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
         SimpleDateFormat matter2 = new SimpleDateFormat("yyMMdd");
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmPipeAdjust.queryAdjustList");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1, matter1.format(dt));
        psta.setString(2, strlist);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            String res = rs.getString(1);
            if (res == null) {
                res = memo + matter2.format(dt) + "00001";
            }
            else {
                seq = Integer.parseInt(res.substring(8, 13));
            }
        }
        rs.close();
        psta.close();
        return  memo + matter2.format(dt) + StringTool.formatDecimal(++seq, "00000");
    }
  
    public CoreReturnObject getTest(String date1,String date2,String time,String[] arr,String supplyUnit,String ssq)
    {
        String strSuppplyUnit2="";
        String strSuppplyUnit3="";
        String strSuppplyUnit4="";
        String strSuppplyUnit5="";
        String strSuppplyUnit6="";
        if(supplyUnit.equals("120501"))
        {
            strSuppplyUnit2 += " AND (t.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR t.SUPPLY_UNIT_CODE IS NULL)";
            strSuppplyUnit3 += " AND (SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR SUPPLY_UNIT_CODE IS NULL)";
            strSuppplyUnit4 += " AND (SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR SUPPLY_UNIT_CODE IS NULL)";
            strSuppplyUnit5 += " AND (e.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR e.SUPPLY_UNIT_CODE IS NULL)";
            strSuppplyUnit6 += " AND (F.SUPPLY_UNIT_CODE = '"+supplyUnit+"' OR F.SUPPLY_UNIT_CODE IS NULL)";
        }else if(supplyUnit.equals("120504")){
            strSuppplyUnit2 += " AND t.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
            strSuppplyUnit3 += " AND SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
            strSuppplyUnit4 += " AND SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
            strSuppplyUnit5 += " AND e.SUPPLY_UNIT_CODE = '"+supplyUnit+"'";
            strSuppplyUnit6 += " AND F.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("FrmrptStoveBatchStorage.getTest");
    	String str = CoreConverter.toSqlConditionString("BELONG_CODE", arr);
    	sql = sql.replace("#condtions#", str);
        sql = sql.replace("#condtions2#", strSuppplyUnit2);
        sql = sql.replace("#condtions3#", strSuppplyUnit3);
        sql = sql.replace("#condtions4#", strSuppplyUnit4);
        sql = sql.replace("#condtions5#", strSuppplyUnit5);
        sql = sql.replace("#condtions6#", strSuppplyUnit6);
        sql = sql.replace("#ssqrkString#", ssqrkString);
		sql = sql.replace("#ssqckString#", ssqckString);
        System.out.println(sql);
    	CoreReturnObject cro = this
				.getData(sql,
						new Object[] { date2, date2, date1, date2, date1,
								date2, date2, date2, date1, date2, date1,
								date2, time, date1, date2,date1, date2,date1,date2 });
    	return cro;
    }
}
