package com.steering.pss.qcm;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.comm.tools.StringTool;
import com.steering.pss.qcm.model.ComMscStdChemEntity;
import com.steering.pss.qcm.model.StdChemObject;
import com.steering.pss.qcm.model.StdCicObject;
import net.sf.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 化学成分标准 类
 * @author Administrator PDY 20214-11-12
 * @version v1.0
 */
public class CoreChemStandard extends DBCommon {

    /**
     * 成分标准索引号表 查询
     * @param params 查询条件：标准名称 冶金规范码 是否有效
     * @param style '1'订货标准 '2'内控 '3'Alpha '4'其它标准
     * @param cic 成分索引号
     * @return 数据集
     */
    public CoreReturnObject getCoreChemStandard(ArrayList<String> params, String style,
    		String cic, String msc, String codeJg, ArrayList<String> listSteel, 
    		String produccodeNk, String steelcodeNk, String processCode, String modelCode) {
            String sql = "";
            if(style.equals("1")){
            	sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.QUERYG");
            }else{
            	sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.QUERYOTHER");
            }
            sql = StringTool.ReplaceAll(sql, "#MSC#", params.get(1));
            sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", params.get(2));
            sql = StringTool.ReplaceAll(sql, "#STD_CODE_NK#", params.get(3));
            sql = StringTool.ReplaceAll(sql, "#CIC#", cic);
            sql = StringTool.ReplaceAll(sql, "#MSC2#", msc);
            sql = StringTool.ReplaceAll(sql, "#CODE_JG#", codeJg);
            sql = StringTool.ReplaceAll(sql, "#STD_NAME#", params.get(0));
            sql = StringTool.ReplaceAll(sql, "#STD_NAME_NK#", params.get(0));
            sql = StringTool.ReplaceAll(sql, "#STDSTYLE#", style);
            sql = StringTool.ReplaceAll(sql, "#PRODUCCODE_NK#", produccodeNk);
            sql = StringTool.ReplaceAll(sql, "#STEELCODE_NK#", steelcodeNk);
            sql = StringTool.ReplaceAll(sql, "#PROCESS_CODE#", processCode);
            sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
            
            String sqlWhere = "";
            if(listSteel.size() > 0){
            	sqlWhere = "AND (1 <> 1 ";
                for(String str : listSteel){
                	sqlWhere += " OR NVL(INSTR(C.GRADECODE, '"+ str +"'), 1) > 0";
                }
                sqlWhere += ")";
            }
            sql = sql.replaceAll("#WHERE#", sqlWhere);
            return this.getData(sql);
    }

    /**
     * 成分标准表 查询
     * @param params 查询条件
     * @param style '1'订货标准 '2'内控 '3'Alpha '4'其它标准
     * @param cic 成分索引号
     * @return 数据集
     */
    public CoreReturnObject getCoreChemStandardC(ArrayList<String> params,
            String style, String cic, String msc, String codeJg,
            ArrayList<String> listSteels, String produccodeNk, 
            String steelcodeNk, String processCode, String modelCode) {
        String sql;
        if(style.equals("1")){
        	sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.QUERYCG");
        }else{
        	sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.QUERYCOTHER");
        }
        
        sql = StringTool.ReplaceAll(sql, "#STD_NAME_NK#", params.get(0));
        sql = StringTool.ReplaceAll(sql, "#MSC#", params.get(1));
        sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", params.get(2));
        sql = StringTool.ReplaceAll(sql, "#STD_CODE_NK#", params.get(3));
        sql = StringTool.ReplaceAll(sql, "#CIC#", cic);
        sql = StringTool.ReplaceAll(sql, "#MSC2#", msc);
        sql = StringTool.ReplaceAll(sql, "#CODE_JG#", codeJg);
        sql = StringTool.ReplaceAll(sql,"#PRODUCCODE_NK#", produccodeNk);
        sql = StringTool.ReplaceAll(sql, "#STDSTYLE#", style);
        sql = StringTool.ReplaceAll(sql, "#STEELCODE_NK#", steelcodeNk);
        sql = StringTool.ReplaceAll(sql, "#PROCESS_CODE#", processCode);
        sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
        
        String sqlWhere = "";
        if(listSteels.size() > 0){
        	sqlWhere = "AND (1 <> 1 ";
            for(String str : listSteels){
            	sqlWhere += " OR NVL(INSTR(B.GRADECODE, '"+ str +"'), 1) > 0";
            }
            sqlWhere += ")";
        }
        
        sql = sql.replaceAll("#WHERE#", sqlWhere);
        
        return this.getData(sql);
    }
    
    public CoreReturnObject getPurchaseAgreementCic(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreChemStandard.getPurchaseAgreementCic");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }
    
    public CoreReturnObject getPurchaseAgreementChem(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreChemStandard.getPurchaseAgreementChem");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }
    

    /**
     * 成分保存
     * @param baseList 主表数据
     * @param childList 从表数据
     * @param style 类型 国标 内控 Alpha
     * @return 执行条数
     */
    public CoreReturnObject saveCoreChemStandard(ArrayList<Object> baseList,
            ArrayList<Object> childList, String style) {
    	Connection con = null;
    	try{
    		con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
    		// sql语句
            ArrayList<String> sqlIdList = new ArrayList<String>();
            // 字段集合
            ArrayList<Object[]> params = new ArrayList<Object[]>();
            // 虚拟成分索引号和真实成分索引号
            HashMap<String, String> cicHash = new HashMap<String, String>();
            String sql = CoreXmlSqlParsersFactory
                    .getSql("CoreChemStandard.MAXCICG");
            if (style.equals("N") || style.equals("L")) {
                sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.MAXCICN");
            }

            if (style.equals("K")) {
                sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.MAXCICK");
            }

            if (style.equals("S")) {
                sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.MAXCICS");
            }

            try {
                // 主表查询最大成分索引号 ,如果没有,数字部分为0
            	PreparedStatement ps = con.prepareStatement(sql);
            	ResultSet rs = ps.executeQuery();
                //ResultSet rs = this.getDao("TgDao").ExceuteQueryForResultSet(sql);
                int cicPart = 0;
                if (rs.next()) {
                    cicPart = Integer.parseInt(rs.getString(1));
                }
                rs.close();
                ps.close();
                for (int i = 0; i < baseList.size(); i++) {
                    // 将JSON字符串转化成对象
                    String baseStr = baseList.get(i).toString();
                    JSONObject json = JSONObject.fromObject(baseStr);
                    StdCicObject com = (StdCicObject) JSONObject.toBean(json,
                            StdCicObject.class);
                    // 存操作字段字符串
                    Object[] param = null;
                    // 创建时间：如果为空 则新增 否则修改
                    if (com.getValidflag().equals("")) {
                        // 新生成cic"CICN000001"类型的字符串 "CIC"+类型+六位数字
                        DecimalFormat df = new DecimalFormat("000000");
                        String stdStyle = style;
                        String cic = "CIC" + style + df.format(cicPart + 1);
                        cicHash.put(com.getCic(), cic);
                        cicPart += 1;
                        param = new Object[] { cic, com.getPsc(), com.getMsc(),
                                com.getStdsStyle(), com.getStdCodeNk(),
                                com.getStdNameNk(), com.getProcessCode(),
                                com.getProcessDesc(), com.getGradeCode(),
                                com.getGradeName(), com.getStdCode(),
                                com.getStdName(), com.getCreateName(),
                                com.getModelCode(), com.getModelDesc(),
                                com.getMemo(), com.getProducHead(),
                                com.getCodeJg(), com.getSteelcodeNk(), com.getSteelnameNk(),
                                com.getModelCodeNk(), com.getModelNameNk(),
                                com.getProduccodeNk(), com.getProducnameNk(),
                                com.getSmeltingCnt(), com.getProductCnt(),
                                com.getMinD(), com.getMaxD(), com.getMinH(), com.getMaxH(),
                                com.getMinDSign(), com.getMaxDSign(), com.getMinHSign(),
                                com.getMaxHSign(), com.getRate() };
                        sqlIdList.add("CoreChemStandard.ADD");
                        params.add(param);
                    }
                    else {
                        param = new Object[] { com.getCic(), com.getPsc(),
                                com.getMsc(), com.getStdsStyle(),
                                com.getStdCodeNk(), com.getStdNameNk(),
                                com.getProcessCode(), com.getProcessDesc(),
                                com.getGradeCode(), com.getGradeName(),
                                com.getStdCode(), com.getStdName(),
                                com.getUpdateName(), com.getModelCode(),
                                com.getModelDesc(), com.getMemo(), 
                                com.getProducHead(),
                                com.getCodeJg(),
                                com.getSteelcodeNk(), com.getSteelnameNk(),
                                com.getModelCodeNk(), com.getModelNameNk(),
                                com.getProduccodeNk(), com.getProducnameNk(),
                                com.getSmeltingCnt(), com.getProductCnt(),
                                com.getMinD(), com.getMaxD(), com.getMinH(), com.getMaxH(),
                                com.getMinDSign(), com.getMaxDSign(), com.getMinHSign(),
                                com.getMaxHSign(), com.getRate(),
                                com.getCic() };
                        sqlIdList.add("CoreChemStandard.UPDATE");
                        params.add(param);
                    }
                }
                // 从表成分索引号与与之对应的序号
                HashMap<String, Integer> hasC = new HashMap<String, Integer>();
                for (int i = 0; i < childList.size(); i++) {
                    // 将JSON字符串转化成对象
                    String childStr = childList.get(i).toString();
                    JSONObject json = JSONObject.fromObject(childStr);
                    StdChemObject com = (StdChemObject) JSONObject.toBean(json,
                            StdChemObject.class);
                    Object[] param = null;
                    // 创建时间：如果为空 则新增 否则修改
                    if (com.getValidflag().equals("")) {
                        String cic = com.getCic();
                        // 如果ckcHash包括cic，则证明子表数据的成分索引号是新生成的
                        if (cicHash.containsKey(cic)) {
                            cic = cicHash.get(cic);
                        }
                        // 同一个成分索引号下的序号只查询一次,存在我多个则自动加1
                        if (!hasC.containsKey(cic)) {
                            Object[] obj = new Object[] { cic };
                            String sqlc = CoreXmlSqlParsersFactory
                                    .getSql("CoreChemStandard.MAXINDEXSEQ");
                            PreparedStatement psC = con.prepareStatement(sqlc);
                            psC.setObject(1, cic);
                        	ResultSet rsC = psC.executeQuery();
//                            ResultSet rsC = this.getDao("TgDao")
//                                    .ExceuteQueryForResultSet(sqlc, obj);
                            int xh = 1;
                            if (rsC.next()) {
                                xh = rsC.getInt(1) + 1;
                            }
                            rsC.close();
                            psC.close();
                            hasC.put(cic, xh);
                        }
                        else {
                            hasC.put(cic, hasC.get(cic) + 1);
                        }
                        param = new Object[] { cic, hasC.get(cic),
                                com.getChemCode(), com.getChemName(),
                                com.getChemType(), com.getChemFormula(),
                                com.getIsCheck(), com.getIsjudge(),
                                com.getIsQuote(), com.getComplexType(),
                                com.getStdMinSign(), com.getStdMin(),
                                com.getStdMaxSign(), com.getStdMax(),
                                com.getStdTarget(), com.getModelCode(),
                                com.getModelDesc(), com.getStdMemo(),
                                com.getEleCode(), com.getEleName(),
                                com.getEleMinSign(), com.getEleMin(),
                                com.getEleMaxSign(), com.getEleMax(),
                                com.getSizeCode2(), com.getSizeName2(),
                                com.getSizeMinSign2(), com.getSizeMin2(),
                                com.getSizeMaxSign2(), com.getSizeMax2(),
                                com.getSizeCode(), com.getSizeName(),
                                com.getSizeMinSign(), com.getSizeMin(),
                                com.getSizeMaxSign(), com.getSizeMax(),
                                com.getSpecJg(), com.getSpecJgDesc(),
                                com.getCreateName(), com.getRepCode(),
                                com.getRepName(), com.getRepMinSign(),
                                com.getRepMin(), com.getRepMaxSign(),
                                com.getRepMax(), com.getRepVal() };
                        sqlIdList.add("CoreChemStandard.ADD1");
                    }
                    else {
                        param = new Object[] { com.getCic(), com.getIndexSeq(),
                                com.getChemCode(), com.getChemName(),
                                com.getChemType(), com.getChemFormula(),
                                com.getIsCheck(), com.getIsjudge(),
                                com.getIsQuote(), com.getComplexType(),
                                com.getStdMinSign(), com.getStdMin(),
                                com.getStdMaxSign(), com.getStdMax(),
                                com.getStdTarget(), com.getModelCode(),
                                com.getModelDesc(), com.getStdMemo(),
                                com.getEleCode(), com.getEleName(),
                                com.getEleMinSign(), com.getEleMin(),
                                com.getEleMaxSign(), com.getEleMax(),
                                com.getSizeCode2(), com.getSizeName2(),
                                com.getSizeMinSign2(), com.getSizeMin2(),
                                com.getSizeMaxSign2(), com.getSizeMax2(),
                                com.getSizeCode(), com.getSizeName(),
                                com.getSizeMinSign(), com.getSizeMin(),
                                com.getSizeMaxSign(), com.getSizeMax(),
                                com.getSpecJg(), com.getSpecJgDesc(),
                                com.getCreateName(), com.getRepCode(),
                                com.getRepName(), com.getRepMinSign(),
                                com.getRepMin(), com.getRepMaxSign(),
                                com.getRepMax(), com.getRepVal(), com.getCic(),
                                com.getIndexSeq()};
                        sqlIdList.add("CoreChemStandard.UPDATE1");
                    }
                    params.add(param);
                }
            }
            catch (SQLException e) {

            }

            return this.setDataById(sqlIdList, params);
    	}catch(Exception ex){
    		CoreReturnObject cro = new CoreReturnObject();
    		cro.setV_errMsg(ex.getMessage());
    		return cro;
    	}finally{
    		if(con != null){
    			try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	}
        
    }

    /**
     * 化学元素 作废或者恢复
     * @param baseList 主表数据
     * @param childList 从表数据
     * @param flag 有效标识
     * @return 执行条数
     */
    public CoreReturnObject deleteOrResume(ArrayList<Object> baseList,
            ArrayList<Object> childList, Boolean flag) {
        ArrayList<String> sqlIDlist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        // 主表作废或者恢复
        for (int i = 0; i < baseList.size(); i++) {
            // JSON字符串转化成对象
            String baseStr = baseList.get(i).toString();
            JSONObject json = JSONObject.fromObject(baseStr);
            StdCicObject com = (StdCicObject) JSONObject.toBean(json,
                    StdCicObject.class);
            Object[] param = null;
            if (flag) {
                sqlIDlist.add("CoreChemStandard.DELETE");
                param = new Object[] { com.getDeleteName(), com.getCic() };
            }
            else {
                sqlIDlist.add("CoreChemStandard.RESUME");
                param = new Object[] { com.getCic() };
            }
            params.add(param);
        }
        // 从表作废或者恢复
        for (int i = 0; i < childList.size(); i++) {
            String childStr = childList.get(i).toString();
            JSONObject json = JSONObject.fromObject(childStr);
            StdChemObject com = (StdChemObject) JSONObject.toBean(json,
                    StdChemObject.class);
            Object[] param = null;
            if (flag) {
                sqlIDlist.add("CoreChemStandard.DELETE1");
                param = new Object[] { com.getDeleteName(), com.getCic(),
                        com.getIndexSeq() ,com.getCic()};
            }
            else {
                sqlIDlist.add("CoreChemStandard.RESUME1");
                param = new Object[] { com.getCic(), com.getIndexSeq() };
            }
            params.add(param);
        }
        return this.setDataById(sqlIDlist, params);
    }
    
    /**
     * 通过主键查询成分表
     * @param cic
     * @return obj
     */
    public CoreReturnObject getMscCicByCic(String cic){
    	String sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.getMscCicByCic");
    	sql = StringTool.ReplaceAll(sql, "#CIC#", cic);
    	
    	return this.getData(sql);
    }
    
    /**
     * 新增成分索引码与品名关系
     * @param list
     * @param cic
     * @param name
     * @return
     */
    private void insertComMscStdCicRProduct(String productCodes, String cic, String name,
    		ArrayList<String> sqllist, ArrayList<Object[]> parms){
    	if(!productCodes.equals("")){
	    	sqllist.add("CoreChemStandard.deleteComMscStdCicRProduct");
	    	parms.add(new Object[]{cic});
	    	String[] arrProductCodes = productCodes.split(",");
	    	for(String str : arrProductCodes){
	        	sqllist.add("CoreChemStandard.insertComMscStdCicRProduct");
	        	parms.add(new Object[]{cic, str, name});
	    	}
    	}
    }
    
    /**
     * 获取索引码与品名关系。
     * @param cic
     * @return
     */
    public CoreReturnObject queryMscStdCicRProductByCic(String cic){
    	String sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.queryMscStdCicByCic");
    	sql = StringTool.ReplaceAll(sql, "#CIC#", cic);
    	
    	return this.getData(sql);
    }
    
    /**
     * 获取成分
     * @param chems
     * @param stdCodeNk
     * @param gradeCode
     * @return
     */
    public CoreReturnObject getChemByGrade(ArrayList<String> chems, String stdCodeNk,
    		String gradeCode, String cic, String action){
    	CoreReturnObject cro = new CoreReturnObject();
    	SqlBuilder b = new SqlBuilder("CoreChemStandard.getChemByGrade");
    	b.Fill(new String[]{ stdCodeNk, gradeCode, cic });
    	List<ComMscStdChemEntity> allChems = EntityTool.getEntitysBySql(b.toString(), this.getDao(
    			 CoreConstantData.sysbeanstr).getConnection(), ComMscStdChemEntity.class);
    	HashMap<String, List<ComMscStdChemEntity>> mapChems = new HashMap<String, List<ComMscStdChemEntity>>();
    	for(ComMscStdChemEntity allChem : allChems){
    		if(mapChems.containsKey(allChem.getCic())){
    			List<ComMscStdChemEntity> tmpChems = mapChems.get(allChem.getCic());
    			tmpChems.add(allChem);
    		}else{
    			List<ComMscStdChemEntity> tmpChems = new ArrayList<ComMscStdChemEntity>();
    			tmpChems.add(allChem);
    			mapChems.put(allChem.getCic(), tmpChems);
    		}
    	}
    	
    	for(String key : mapChems.keySet()){
    		boolean same = true;
    		List<ComMscStdChemEntity> tmpChems = mapChems.get(key);
    		if(tmpChems.size() == chems.size()){
    			for(ComMscStdChemEntity tmpChem : tmpChems){
    				if(!chems.contains(tmpChem.getChemCode())){
    					same = false;
    					break;
    				}
    			}
    			if(same){
    				cro.setResult("将要"+ action +"的成分内控与成分索引码：" + key + "的项目重复！");
    				return cro;
    			}
    		}
    	}
    	
    	return cro;
    }
    
    /**
     * 分组
     * @param index
     * @param cic
     * @param groupSeq
     * @return
     */
    public CoreReturnObject group(ArrayList<String> index, String cic, String groupSeq){
    	String indexs = "";
    	for(String str : index){
    		indexs += ", '" + str + "'";
    	}
    	SqlBuilder b = new SqlBuilder("CoreChemStandard.group");
    	b.Fill(new String[]{ groupSeq, cic });
    	b.Replace("INDEX_SEQ", indexs);
    	
    	return this.setData(b.toString());
    }
    
    /**
     * 取消分组
     * @param index
     * @param cic
     * @param groupSeq
     * @return
     */
    public CoreReturnObject cancelGroup(ArrayList<String> index, String cic){
    	String indexs = "";
    	for(String str : index){
    		indexs += ", '" + str + "'";
    	}
    	SqlBuilder b = new SqlBuilder("CoreChemStandard.cancelGroup");
    	b.Fill(new String[]{ cic });
    	b.Replace("INDEX_SEQ", indexs);
    	
    	return this.setData(b.toString());
    }

    public CoreReturnObject getComChemNK(String msc) {
        String sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.getComChemNK");
        sql = StringTool.ReplaceAll(sql, "#MSC#", msc);
        return this.getData(sql);
    }

    public CoreReturnObject getComChemNKC(String msc) {
        String sql = CoreXmlSqlParsersFactory.getSql("CoreChemStandard.getComChemNKC");
        sql = StringTool.ReplaceAll(sql, "#MSC#", msc);
        return this.getData(sql);
    }
}
