package com.steering.pss.ydm.pipemanage;

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.base.MeanValueCalculation;
import com.steering.pss.ydm.entity.MatZcMEntity1;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FrmPipeAdjust extends DBCommon{
	/***
	 * 根据数据权限查询库存信息
	 * @param list
	 * @param arr
	 * @return
	 */
       public CoreReturnObject getStorgeData(ArrayList<String> list,String[] arr,String supplyUnit)
       {
    	   String sql = CoreXmlSqlParsersFactory.getSql("FrmPipeAdjust.getStorgeData");
    	   sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
    	   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 += " group by T.judge_stove_no,T.batch_no,T.batch_groud_no,T.order_no,T.order_seq,T.order_seq_no, B.STORAGE_NO, T.MEMO,MAT_STATUS,product_flag,judge_result,IN_MOLD,FINISHPRO_MOLD"
       +",T.SUPPLY_UNIT_CODE,T.SUPPLY_UNIT,T.PROCESS_CDOE,T.PROCESS_DESC ORDER BY t.judge_stove_no ASC";
    	   return this.getData(sql, list.toArray());
       }
       
       /***
        * 查询调差实绩
        * @param list
        * @return
        */
       public CoreReturnObject getAdjustData(ArrayList<String> list,String[] arr,String supplyUnit)
       {
    	   String sql  = CoreXmlSqlParsersFactory.getSql("FrmPipeAdjust.getAdjustData");
    	   sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
           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 += " group by t.judge_stove_no, t.batch_no,t.STEELCODE,t.STEELNAME,t.STORAGE_NO,t.LOCATION_NO,t.STOCKTAKING_DOC,t.batch_groud_no,t.STOCKTAKING_RSN_CODE,t.BAL_YEAR_MONTH"
                   +",T.SUPPLY_UNIT_CODE,T.SUPPLY_UNIT";
    	   return this.getData(sql, list.toArray());
       }
       
       /***
        * 查询调整重量原因
        * @return
        */
       public CoreReturnObject getAdjustReason()
       {
    	   return this.getDataBySqlID("FrmPipeAdjust.getAdjustReason");
       }
       
       /***
        * 修改结转年月
        * @param list
        * @return
        */
       public CoreReturnObject updateYear(ArrayList<String> list)
       {
    	   return this.setDataBySqlID("FrmPipeAdjust.updateYear", list.toArray());
       }
       /***
        * 查询调差单号
        * @param list
        * @return
        */
       public CoreReturnObject queryAdjustList(ArrayList<String> list) {
           return this.getDataBySqlID("FrmPipeAdjust.queryAdjustList", list
                   .toArray());
       }
       
       /***
        * 每支材料对应的调查（调差）流水号
        * @param conn
        * @param strlist
        * @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(dt));
           psta.setString(2,strlist);
           ResultSet rs = psta.executeQuery();
           if (rs.next()) {
               String res = rs.getString(1);
               if (res == null) {
                   res = strlist + "0001";
               }
               else {
                   seq = Integer.parseInt(res.substring(13, 17));
               }
           }
           rs.close();
           psta.close();
           return strlist + StringTool.formatDecimal(++seq, "0000");
       }
       
       /**
        * 每支材料对应的调差单号
        * @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");
       }
       
       /***
        * 增加调整实绩、
        * @param
        * @return
        */
       public CoreReturnObject addAdjustData(ArrayList<ArrayList<String>> parm)
       {
    	   
    	   CoreReturnObject cro= new CoreReturnObject();
    	   Connection connection  = this.getDao(CoreConstantData.sysbeanstr).getConnection();
    	   PreparedStatement psta = null;
    	   String sql = "";
    	   ResultSet rs = null;
    	   Date now = new Date();
    	   SimpleDateFormat dateFormat = new SimpleDateFormat(
           "yyyyMM");
            //String systime = dateFormat.format(now);

           try {
               connection.setAutoCommit(false); // 取消自动提交事务
               String updateMatNoSql = CoreXmlSqlParsersFactory.getSql("FrmPipeAdjust.updateActWgt");
               PreparedStatement updateMatNopsta = connection.prepareStatement(updateMatNoSql);
               String insertStockSql = CoreXmlSqlParsersFactory.getSql("FrmPipeAdjust.AddJustWgt");
               PreparedStatement insertStockpsta = connection.prepareStatement(insertStockSql);
               String adjustWgtSql = CoreXmlSqlParsersFactory.getSql("FrmPipeAdjust.updateProcess");
               PreparedStatement adjustWgtpsta = connection.prepareStatement(adjustWgtSql);
               
               for(int i = 0; i<parm.size();i++)
               {
            	   ArrayList<String> list = parm.get(i);
            	   double oldWgt = Double.parseDouble(list.get(22));//原总重量
            	   int abc = Integer.parseInt(list.get(0));//总支数
                   double wgt  = Double.parseDouble(list.get(10));//调差量
                   int n = 1;
                   String adjustDoc = queryAdjustDoc(connection,list.get(19),list.get(20));
                   ArrayList<String>  storeWgtList = new ArrayList<String>();
					List<double[]> listwgt = MeanValueCalculation
							.MeanCalculation(oldWgt + wgt, 
									abc);// 重量
					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());
							}
						}
					}
						
                   sql = CoreXmlSqlParsersFactory.getSql("FrmPipeAdjust.getMatNo");
                   psta = connection.prepareStatement(sql);
                   psta.setString(1, list.get(1));
                   psta.setString(2, list.get(2));
                   psta.setString(3, list.get(3));
                   psta.setString(4, list.get(7));
                   psta.setString(5, list.get(26));
                   psta.setString(6, list.get(25));//交货行PK
                   psta.setString(7, list.get(27));//交货行PK
                   psta.setString(8, list.get(28));
                   psta.setString(9, list.get(29));
                   rs = psta.executeQuery();
                   List<MatZcMEntity1> matZcEntity = EntityTool
					.getEntitysByRs(rs, MatZcMEntity1.class);
                   rs.close();
                   psta.close();
                   if(matZcEntity == null)
                   {
                	   cro.setV_errMsg("不存在需要调差的炉批库存信息!");
                	   return cro;
                   }
                   String systime = "120504".equals(matZcEntity.get(0).getSupplyUnitCode())? ComBaseInfo.GetBalYear_2416(now): ComBaseInfo.GetBalYear(now);

                   for(MatZcMEntity1 matZctity:matZcEntity)
                   {
                       //修改材料表重量
                	   updateMatNopsta.setString(1, storeWgtList.get(n-1));
                	   updateMatNopsta.setString(2, matZctity.getMatNo());
                	   updateMatNopsta.addBatch();
                	   n++;
                   }
                    insertStockpsta.setString(1, list.get(17));
  					insertStockpsta.setString(2, list.get(18));
  					insertStockpsta.setString(3, adjustDoc);
  					insertStockpsta.setString(4, querySendSql(connection,
  							adjustDoc));
  					
  					insertStockpsta.setString(5, list.get(19));
  					insertStockpsta.setString(6, "量差调整");
  					insertStockpsta.setString(7, list.get(11));
  					insertStockpsta.setString(8, list.get(21));
  					
  					insertStockpsta.setString(9, list.get(1));
  					insertStockpsta.setString(10, list.get(2));
  					insertStockpsta.setString(11, list.get(3));
  					insertStockpsta.setString(12, String.valueOf(wgt));
  					insertStockpsta.setString(13, list.get(23));
  					insertStockpsta.setString(14, list.get(24));
  					insertStockpsta.setString(15, list.get(15));
  					insertStockpsta.setString(16, list.get(16));
  					insertStockpsta.setString(17, list.get(14));
  					insertStockpsta.setString(18, list.get(22));
  					insertStockpsta.setString(19, systime);
  					insertStockpsta.setString(20, matZcEntity.get(0).getProduccode());
  					insertStockpsta.setString(21, matZcEntity.get(0).getProducname());
  					insertStockpsta.setString(22, matZcEntity.get(0).getSteelcode());
  					insertStockpsta.setString(23, matZcEntity.get(0).getSteelname());
  					insertStockpsta.setString(24, matZcEntity.get(0).getSpecCode());
  					insertStockpsta.setString(25, matZcEntity.get(0).getSpecName());
  					insertStockpsta.setString(26, matZcEntity.get(0).getModelCode());
  					insertStockpsta.setString(27, matZcEntity.get(0).getModelDesc());
  					insertStockpsta.setString(28, matZcEntity.get(0).getStdStyle());
  					insertStockpsta.setString(29, matZcEntity.get(0).getStdStyleDesc());
  					insertStockpsta.setString(30, matZcEntity.get(0).getStorageNo());
  					insertStockpsta.setString(31,list.get(30));
                    insertStockpsta.setString(32,list.get(31));
                    insertStockpsta.setString(33,matZcEntity.get(0).getProcessCdoe());
                    insertStockpsta.setString(34,matZcEntity.get(0).getProcessDesc());
                    insertStockpsta.setString(35,matZcEntity.get(0).getGradecode());
                    insertStockpsta.setString(36,matZcEntity.get(0).getGradename());
                    insertStockpsta.setString(37,matZcEntity.get(0).getPlineCode());
                    insertStockpsta.setString(38,matZcEntity.get(0).getPlineName());

  					insertStockpsta.addBatch();
  					
  					adjustWgtpsta.setString(1, list.get(10).toString());
  					adjustWgtpsta.setString(2, list.get(25).toString());
  					adjustWgtpsta.addBatch();
               }
               updateMatNopsta.executeBatch();
               insertStockpsta.executeBatch();
               adjustWgtpsta.executeBatch();
               connection.commit();
               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 list
        * @return
        */
       public CoreReturnObject selectYearMoth(ArrayList<String> list,String[] arr,String custom)
       {
    	   String sql = CoreXmlSqlParsersFactory.getSql("FrmPipeAdjust.selectYearMoth");
    	   sql  = sql.replace("#SUPPLY_UNIT_CODE#",custom);
    	   sql += CoreConverter.toSqlConditionString("T.BELONG_CODE", arr);
    	   return this.getData(sql,list.toArray());
       }
} 
       

