package com.steering.pss.sale.order;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.ParseException;
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.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.comm.tools.TransctionTool;
import com.steering.pss.qcm.model.GenericEntity;
import com.steering.pss.sale.order.model.*;


public class CoreWellAdjust extends DBCommon{
    /**
     * 按年查询产能井占用情况
     * 参数[0]='年'
     * @return
     */
    public CoreReturnObject getWellUseInfo(String[] params) {
       return this.getDataBySqlID("CoreWellAdjust.getWellUse", params);
    }
    
    /**
     * 查询产能井基础信息
     * 
     * @return
     */
    public CoreReturnObject getBaseWell(String[] params) {
        return this.getDataBySqlID("CoreWellAdjust.getBaseWell", params);         
    }
    
    /**
     * 按年查询产能井合同情况
     * 参数[0]='年'，参数[1]='月'，参数[2]='产能井号'
     * @return
     */
    public CoreReturnObject getWellOrderInfo(String[] params) {
        return this.getDataBySqlID("CoreWellAdjust.getWellOrder", params);
    }
    
    /**
     * 解析二级工序代码
     * processCode=工序代码，pCodes=制程对应工序代码，p2Codes=制程对应二级工序代码
     * @return
     */
    private String getL2CodeNo(String processCode, String pCodes,String p2Codes){
        String strL2No = "";
        int intPot = 0;        
        //获取二级工序
        String [] strPCode = pCodes.split("-");
        for(int i = 0;i < strPCode.length; i++){
            if(strPCode[i].equals(processCode)){
                intPot = i;
                break;
            }
        }
        for(int k = 0;k<p2Codes.length()/4;k++){
            if(k == intPot){
                strL2No =  p2Codes.substring(k*4, k*4+3);
                break;
            }            
        }
        return strL2No;
    }
    
    /**
     * 修改产能井
     * @param parms
     * @param wellCode
     * @return
     */
    public CoreReturnObject updateWell(ArrayList<String> parms, String wellCode){
    	TransctionTool transction = new TransctionTool();
    	CoreReturnObject cro = transction.getReturnObject();
    	Connection con = transction.getCon();
    	try{
		String process = GetProcessByWellCode(wellCode, con);
		SqlBuilder b;
		b = new SqlBuilder("CoreWellAdjust.getMaxUseCode");
		GenericEntity maxUseCode = EntityTool.getEntityBySqlNoClsCon(
				b.toString(), con, GenericEntity.class);
    	for(String parm : parms){
    		List<SlmWellUseEntity> wellEntitys = new ArrayList<SlmWellUseEntity>();
    		SlmWellUseEntity wellUse = EntityTool.getEntityByJSONStr(parm, SlmWellUseEntity.class);
    		if(process.equals("A")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeA");
    		}else if(process.equals("B")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeB");
    		}else if(process.equals("C")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeC");
    		}else if(process.equals("D")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeD");
    		}else if(process.equals("E")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeE");
    		}else if(process.equals("F")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeF");
    		}else if(process.equals("G")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeG");
    		}else if(process.equals("H")){
    			b = new SqlBuilder("CoreWellAdjust.GetNewWellCodeH");
    		}else{
    			cro.SetErrInfo("通过产能井代码" + wellCode + "找不到对应的工序!" );
				return cro;
    		}
    		b.Fill(new String[]{ wellUse.getOrdLnPk() });
			wellEntitys = EntityTool.getEntitysBySqlNoClsCon(
					b.toString(), con, SlmWellUseEntity.class);
			if(!isSameWell(wellEntitys)){
				SetErrMsg(wellEntitys, cro);
				return cro;
			}else if(wellEntitys.size() == 0){
				cro.setV_errMsg("没有找到产能井！");
				return cro;
			}
    		
    		SlmWellUseEntity wellEntity = wellEntitys.get(0);
    		if(!wellEntity.getWellCode().equals(wellUse.getWellCode())){
    			b = new SqlBuilder("CoreWellAdjust.UpdateWell");
        		b.Fill(new String[]{ wellEntity.getWellCode(), wellEntity.getWellName(), 
        				maxUseCode.getValue(), wellUse.getWellCode(), wellUse.getOrdLnPk()});
        		boolean result = transction.ExcuteTransction(b.toString());
        		if(!result){
        			return transction.getReturnObject();
        		}
    		}
    	}
    	}catch(Exception ex){
    		cro = transction.rollBack();
			cro.setV_errMsg(ex.getMessage());
			return cro;
    	}
    	
    	return transction.commit();
    }
    
    private boolean isSameWell(List<SlmWellUseEntity> wellEntitys){
    	List<String> wells = new ArrayList<String>();
    	for(SlmWellUseEntity well : wellEntitys){
    		if(wells.size() != 0 && !wells.contains(well.getWellCode())){
    			return false;
    		}
    	}
    	return true;
    }
    
    private void SetErrMsg(List<SlmWellUseEntity> wellEntitys, CoreReturnObject cro){
    	String err = "";
		for(SlmWellUseEntity well : wellEntitys){
			if(err.equals("")){
				err = "生产产线适用规格主键：" + well.getIndexSeq();
			}else{
				err += ", " + well.getIndexSeq();
			}
		}
		cro.setV_errMsg(err + "所对应的产能井不一致！");
    }
    
    private String GetProcessByWellCode(String wellCode, Connection con){
    	SqlBuilder b = new SqlBuilder("CoreWellAdjust.GetProcessByWellCode");
    	b.Fill(new String[]{wellCode});
    	GenericEntity a = EntityTool.getEntityBySqlNoClsCon(b.toString(), con, GenericEntity.class);
    	return a.getValue();
    }
    
    /**
     * 根据质量设计结果获取产线信息，再根据产线信息获取对应产能井号与投井的产能井号比对，若不一致则换井
     * @param parm (交货行PK，产能井号、年、月)
     * @return
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doUpWell(ArrayList<Object> parm) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection con = null;
             
        try{
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();  
            con.setAutoCommit(false);
            for (int i = 0; i < parm.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) parm.get(i);
                String strDevPk = list.get(0);
                String strWellNo = list.get(1);
                String strYear = list.get(2);
                String strMonth = list.get(3);
              //获取交货行信息
                String strOrderLinPk = "";
                String strModel = "";
                String strProcessCode = "";                
                String sqlquery = CoreXmlSqlParsersFactory
                        .getSql("CoreWellAdjust.getOrder");
                PreparedStatement psta = con.prepareStatement(sqlquery);
                psta.setObject(1, strDevPk);
                ResultSet rs = psta.executeQuery();
                if(rs.next()){
                    strOrderLinPk = rs.getString("ORD_LN_PK");
                    strModel = rs.getString("MODEL_CODE");
                }                
                rs.close();
                psta.close();              
              //获取工序号
                sqlquery = CoreXmlSqlParsersFactory
                .getSql("CoreWellAdjust.getProcessCode");
                PreparedStatement ppare = con.prepareStatement(sqlquery);
                ppare.setObject(1, strWellNo);
                ResultSet rsSet = ppare.executeQuery();
                if(rsSet.next()){
                    strProcessCode = rsSet.getString("PROCESS_CDOE");                    
                }                
                rsSet.close();
                ppare.close();  
              //获取DESIGNkey和制程号
                sqlquery = CoreXmlSqlParsersFactory
                .getSql("CoreWellAdjust.getDesignKey");
                PreparedStatement pare1 = con.prepareStatement(sqlquery);
                pare1.setObject(1, strOrderLinPk);
                ResultSet rsSet1 = pare1.executeQuery();
                while (rsSet1.next()){
                  //工序适用产线：SLM_ORD_DESIGN_MSC_PL_GX_PRL
                    sqlquery = CoreXmlSqlParsersFactory
                    .getSql("CoreWellAdjust.getDesignPline");
                    PreparedStatement pare2 = con.prepareStatement(sqlquery);
                    pare2.setObject(1, rsSet1.getString("DESGIN_KEY"));
                    pare2.setObject(2, rsSet1.getString("MSC_PLINE"));
                    pare2.setObject(3, strProcessCode);
                    ResultSet rsSet2 = pare2.executeQuery();                    
                    ArrayList<String> lisPlies = new ArrayList<String> ();
                    while(rsSet2.next()){                           
                        lisPlies.add(rsSet2.getString("PLINE_CODE"));                       
                    }
                    rsSet2.close();
                    pare2.close();
                    //通过合同行PK+制程号，获取BOM清单信息
                    ArrayList<SlmOrdDesignBomEntity> boms = new ArrayList<SlmOrdDesignBomEntity>();
                     sqlquery = CoreXmlSqlParsersFactory
                            .getSql("CoreWellAdjust.getBom");
                    PreparedStatement pBom = con.prepareStatement(sqlquery);
                    pBom.setObject(1, strOrderLinPk);
                    pBom.setObject(2, rsSet1.getString("MSC_PLINE"));
                    ResultSet rsBom = pBom.executeQuery();
                    boms = EntityTool.getEntitysByRs(rsBom,SlmOrdDesignBomEntity.class);
                    rsBom.close();
                    pBom.close();
                    ArrayList<String> zgSpecs = new ArrayList<String> ();//轧管规格代码
                    ArrayList<String> dzSpecs = new ArrayList<String> ();//锻造规格代码
                    ArrayList<String> zzSpecs = new ArrayList<String> ();//铸造规格代码
                    String l2ProCode = "";//二级工序代码      
                    String strD = "";//外径
                    String strH = "";//壁厚
                    for (SlmOrdDesignBomEntity bom : boms) {
                        if(strProcessCode.equals("B")){
                            //铸造
                            zzSpecs.add(bom.getSpecCodeZ());
                        }else if(strProcessCode.equals("C")){
                            //锻造
                            dzSpecs.add(bom.getSpecCodeD());
                        }else if(strProcessCode.equals("D")){
                            //轧管
                            zgSpecs.add(bom.getSpecCodeR());
                        }
                        if(!l2ProCode.equals(this.getL2CodeNo(strProcessCode, bom.getWholeBacklogDesc(), bom.getProcessCodeCs()))){
                            l2ProCode = this.getL2CodeNo(strProcessCode, bom.getWholeBacklogDesc(), bom.getProcessCodeCs());
                        }                            
                    }
                    String strConditions = "";
                    String[] strPlines = lisPlies.toArray(new String[lisPlies.size()]);
                    if(strProcessCode.equals("B")){
                        //铸造
                        strConditions = CoreConverter.toSqlConditionString("SPEC_CODE", zzSpecs.toArray(new String[zzSpecs.size()]));
                        strConditions += CoreConverter.toSqlConditionString("PLINE_CODE", strPlines);
                    }else if(strProcessCode.equals("C")){
                        //锻造
                        strConditions = CoreConverter.toSqlConditionString("SPEC_CODE", dzSpecs.toArray(new String[dzSpecs.size()]));
                        strConditions += CoreConverter.toSqlConditionString("PLINE_CODE", strPlines);
                    }else if(strProcessCode.equals("D")){
                        //轧管
                        int intCount = 0;
                        strConditions = "AND (#)";
                        String strTemp = "";
                        for(String zgSpec : zgSpecs){
                            sqlquery = CoreXmlSqlParsersFactory.getSql("CoreWellAdjust.getDH");
                            PreparedStatement pDH = con.prepareStatement(sqlquery);
                            pDH.setObject(1, zgSpec);                            
                            ResultSet rsDH = pDH.executeQuery();
                            if(rsDH.next()){
                                if(!strD.equals(rsSet.getString("DIMATER")) && !strH.equals(rsSet.getString("HEIGHT")) ){
                                    strD = rsSet.getString("DIMATER");
                                    strH = rsSet.getString("HEIGHT");
                                    if(intCount == 0){                                        
                                        strTemp += "((" + strD + ">= MIN_D AND"+ strD + "<=MAX_D ) AND"+"(" + strH + ">= MIN_H AND"+ strH + "<=MAX_H ))";
                                    }else{
                                        strTemp += "OR ((" + strD + ">= MIN_D AND"+ strD + "<=MAX_D ) AND"+"(" + strH + ">= MIN_H AND"+ strH + "<=MAX_H ))";
                                    }
                                    strConditions.replaceAll("#", strTemp);
                                    intCount++;
                                }                               
                            }                            
                        }//for
                        if(!zzSpecs.get(0).equals("")){
                            strConditions += CoreConverter.toSqlConditionString("SPEC_CODE", zzSpecs.toArray(new String[zzSpecs.size()]));
                        }else if(!dzSpecs.get(0).equals("")){
                            strConditions += CoreConverter.toSqlConditionString("SPEC_CODE", dzSpecs.toArray(new String[dzSpecs.size()]));
                        }
                        strConditions += CoreConverter.toSqlConditionString("PLINE_CODE", strPlines);
                    }//else if
                    
                    
                  //通过产线代码在产线规格表中获取产能井代码
                    
                    sqlquery = CoreXmlSqlParsersFactory.getSql("CoreWellAdjust.getPlineWell");
                    sqlquery += CoreConverter.toSqlConditionString("T.PLINE_CODE", strPlines);
                    PreparedStatement pare3 = con.prepareStatement(sqlquery);
                    pare3.setObject(1, "1");
                    ResultSet rsSet3 = pare3.executeQuery();
                    String strDesingWellNo = "";
                    String strDesingWellNanme = "";
                    String strPline = "";
                    int intCount = 0;
                    while(rsSet3.next()){                           
                        if(intCount == 0){
                            strDesingWellNo = rsSet3.getString("WELL_CODE");
                            strDesingWellNanme = rsSet3.getString("WELL_NAME");
                            strPline = rsSet3.getString("PLINE_NAME");
                        }
                        if(intCount > 0){
                            if(!strDesingWellNo.equals(rsSet3.getString("WELL_CODE"))){
                                cro.setV_errMsg("生产产线："+strPline+","+rsSet3.getString("PLINE_NAME")+"产能井不一致");
                                cro.setResult(-1);
                                return cro;
                            }
                        }
                        intCount++;
                    }
                    rsSet3.close();
                    pare3.close();
                    sqlquery = CoreXmlSqlParsersFactory.getSql("CoreWellAdjust.setUseWell");
                    PreparedStatement pare4 = con.prepareStatement(sqlquery);
                    if(!strDesingWellNo.equals(strWellNo)){
                      //产能井号与传入的当前产能井号是否一致,若产能井号不一致则更新对应产能井号,更新产能井号                        
                        pare4.setObject(1, strDesingWellNo);
                        pare4.setObject(2, strDesingWellNanme);
                        pare4.setObject(3, strDevPk);
                        pare4.setObject(4, strWellNo);
                        pare4.setObject(5, strYear);
                        pare4.setObject(6, strMonth);
                        pare4.addBatch();
                    }
                    pare4.executeBatch();
                    pare4.close();
                }
                rsSet1.close();
                pare1.close();
            }
            
            con.commit();
            cro.setV_errMsg("调整成功!");
            cro.setResult(1);
            
        }catch (Exception e) {
            cro.setV_errMsg(e.getMessage());
            cro.setV_errCode(-1);
            try {
                    con.rollback(); // 回滚事务
            }
            catch (Exception e2) {
            }            
        }
        finally {
            try {
                if (con != null && !con.isClosed()) {
                    con.close();
                }
            }
            catch (Exception e2) {
            }
        }

        return cro;
    }
    
    /**
     * 调整产能井、年、月
     * @param parm
     * @return
     */
    public CoreReturnObject Save(ArrayList<String[]> parms){
    	CoreReturnObject cro = new CoreReturnObject();
    	TransctionTool transction = new TransctionTool();
    	Connection con = transction.getCon();
    	try{
    		for(String[] parm : parms){
        		SqlBuilder b;
        		String wellCode = parm[0];
        		String wellYear = parm[1];
        		String wellMonth = parm[2];
        		String useCode = parm[3];
        		String ordLnDlyPk = parm[4];
        		String newWellCode = parm[5];
        		String newWellName = parm[6];
        		String newWellYear = parm[7];
        		String newWellMonth = parm[8];
        		String ordLnPk = parm[9];
        		String wellMonth2 = String.format("%02d", Integer.parseInt(wellMonth));
				String newWellMonth2 = String.format("%02d", Integer.parseInt(newWellMonth));
        		
//        		int iWellYear = Integer.parseInt(wellYear);
//        		int iWellMonth = Integer.parseInt(wellMonth);
//        		int iNewWellYear = Integer.parseInt(newWellYear);
//        		int iNewWellMonth = Integer.parseInt(newWellMonth);
        		
        		//得出相差月
        		//int months = Math.abs((iNewWellYear - iWellYear)) * 12 + Math.abs(iNewWellMonth - iWellMonth);
        		
        		String[] processes = new String[]{ "A", "B", "C", "D", "E", "F", "G", "H" };
        		for(String process : processes){
        			SlmWellUseListEntity wellUse = getWellByProcess(ordLnDlyPk, process, con);
        			if(wellUse == null) continue;
        			SimpleDateFormat s = new SimpleDateFormat("yyyyMM");
        			long adjustTime = 0;
        			try {
    					long time = s.parse(newWellYear + newWellMonth2).getTime() - s.parse(wellYear + wellMonth2).getTime();
    					adjustTime = s.parse(wellUse.getWellYear() + String.format("%02d", Integer.parseInt(wellUse.getUseMonth()))).getTime() + time;
    				} catch (ParseException e) {
    					cro.setV_errMsg(e.getMessage());
    					return cro;
    				}
        			
        			Calendar c = Calendar.getInstance(); 
        			c.setTimeInMillis(adjustTime); 
        			Date date = c.getTime();
        			String adjustWellYear = s.format(date).substring(0, 4);
        			String adjustWellMonth = s.format(date).substring(4, 6).replaceAll("0", "");
        			
        			double wellAbility = getWellAbility(newWellCode, adjustWellYear, adjustWellMonth, con);
        			double wellWgt = getWellUseWgt(newWellCode, adjustWellYear, adjustWellMonth, con);
        			double wellWgtDly = Double.parseDouble(wellUse.getUseWgt());
        			if(wellWgtDly + wellWgt > wellAbility){
            			cro.setV_errMsg(newWellName + newWellYear + "年" + newWellMonth + "月产能井能力不足" 
            					+"，不能把交货行PK" + ordLnDlyPk + "投入到该产能井");
            		}
        			
        			b = new SqlBuilder("CoreWellAdjust.save");
                	b.Fill(new String[]{ wellUse.getWellCode(), wellUse.getWellYear(), wellUse.getUseMonth(),
                			wellUse.getUseCode(), wellUse.getOrdLnDlyPk(), adjustWellYear, adjustWellMonth});
                	if(!transction.ExcuteTransction(b.toString())){
                		return transction.getReturnObject();
                	}
        		}
        		
        		//修改生产周期
        		b = new SqlBuilder("CoreWellAdjust.UpdatePlPcList");
        		b.Fill(new String[]{ ordLnDlyPk, ordLnPk, newWellYear + newWellMonth2, wellYear + wellMonth2});
        		if(!transction.ExcuteTransction(b.toString())){
            		return transction.getReturnObject();
            	}
        	}
    		return transction.commit();
    	}catch(Exception ex){
    		cro = transction.rollBack();
    		cro.setV_errMsg(ex.getMessage());
    		return cro;
    	}
    }
    
    /**
     * 通过工序获取产能井
     * @param processCode
     * @param ordLnDlyPk
     * @param con
     * @return
     */
    private SlmWellUseListEntity getWellByProcess(String ordLnDlyPk,
    		String processCode, Connection con){
    	SqlBuilder b = new SqlBuilder("CoreWellAdjust.getWellByProcess");
    	b.Fill(new String[]{ ordLnDlyPk, processCode });
    	return EntityTool.getEntityBySqlNoClsCon(b.toString(), con, SlmWellUseListEntity.class);
    }
    
    /**
     * 获取某个月产能井的占用情况
     * @param wellCode
     * @param wellYear
     * @param wellMonth
     * @param con
     * @return
     */
    private double getWellUseWgt(String wellCode, String wellYear, String wellMonth,
    		Connection con){
    	SqlBuilder b = new SqlBuilder("CoreWellAdjust.getWellUseWgt");
    	b.Fill(new String[]{ wellCode, wellYear, wellMonth });
    	SlmWellUseListEntity wellUse = EntityTool.getEntityBySqlNoClsCon(
    			b.toString(), con, SlmWellUseListEntity.class);
    	return Double.parseDouble(wellUse.getUseWgt());
    }
    
    /**
     * 通过交货行查询产能井的耗用情况
     * @param wellCode
     * @param wellYear
     * @param wellMonth
     * @param useCode
     * @param ordLnDlyPk
     * @param con
     * @return
     */
    private Double getWellUseWgtByDlyPk(String wellCode, String wellYear, String wellMonth,
    		String useCode, String ordLnDlyPk, Connection con){
    	SqlBuilder b = new SqlBuilder("CoreWellAdjust.getWellUseWgtByDlyPk");
    	b.Fill(new String[]{ wellCode, wellYear, wellMonth, useCode, ordLnDlyPk });
    	SlmWellUseListEntity wellUse = EntityTool.getEntityBySqlNoClsCon(
    			b.toString(), con, SlmWellUseListEntity.class);
    	return Double.parseDouble(wellUse.getUseWgt());
    }
    
    /**
     * 获取产能井的能力
     * @param wellCode
     * @param wellYear
     * @param wellMonth
     * @param con
     * @return
     */
    private double getWellAbility(String wellCode, String wellYear, String wellMonth, Connection con){
    	SqlBuilder b = new SqlBuilder("CoreWellAdjust.getWellAbility");
    	b.Fill(new String[]{ wellCode, wellYear, wellMonth });
    	GenericEntity value = EntityTool.getEntityBySqlNoClsCon(
    			b.toString(), con, GenericEntity.class);
    	return Double.parseDouble(value.getValue());
    }
    
    /**
     * 获取系统时间
     * @return
     */
    public CoreReturnObject getSYSDATE(){
    	return this.getDataBySqlID("CoreWellAdjust.getSYSDATE");
    }
}
