package com.steering.pss.qcm;

import CoreFS.SA01.CoreIComponent;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.SqlBuilder;
import com.steering.comm.tools.StringTool;
import com.steering.pss.qcm.model.ComMscStdProcessCEntity;
import com.steering.pss.qcm.model.ComMscStdProcessEntity;
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;

public class CoreComMscStdProcess extends DBCommon {

    public CoreReturnObject getStation() {
        return this.getDataBySqlID("CoreComMscStdProcess.GetStation");
    }

    public CoreReturnObject getProcess() {
        return this.getDataBySqlID("CoreComMscStdProcess.GetProcess");
    }

    /**
     * 成分标准索引号表 查询
     * @param params 查询条件：标准名称 冶金规范码 是否有效
     * @param style '1'订货标准 '2'内控 '3'Alpha '4'其它标准
     * @param cic 成分索引号
     * @return 数据集
     */
    public CoreReturnObject getMscStdProcess(ArrayList<String> params, String style, String gic,
    		String msc, String codeJg, String produccodeNk, String steelcodeNk, String processCode,
    		String modelCode) {
        String sql;
        if(style.equals("1")){
        	sql = CoreXmlSqlParsersFactory.getSql("CoreComMscStdProcess.QUERYG");
        }else{
        	sql = CoreXmlSqlParsersFactory.getSql("CoreComMscStdProcess.QUERYOTHER");
        }
        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, "#GIC#", gic);
        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, "#STDSTYLE#", style);
        sql = StringTool.ReplaceAll(sql, "#PRODUCCODE_NK#", produccodeNk);
        sql = StringTool.ReplaceAll(sql, "#STEELCODE_NK#", steelcodeNk);
        sql = StringTool.ReplaceAll(sql, "#PROCESS_CDOE#", processCode);
        sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
        
        return this.getData(sql);
    }
    
    public CoreReturnObject getPurchaseAgreementGic(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreComMscStdProcess.getPurchaseAgreementGic");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }
    
    public CoreReturnObject getPurchaseAgreementProc(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreComMscStdProcess.getPurchaseAgreementProc");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }

    /**
     * 成分标准表 查询
     * @param params 查询条件
     * @param style '1'订货标准 '2'内控 '3'Alpha '4'其它标准
     * @param cic 成分索引号
     * @return 数据集
     */
    public CoreReturnObject getMscStdProcessC(ArrayList<String> params,
            String style, String cic, String msc, String codeJg, String produccodeNk,
            String steelcodeNk, String processCode, String modelCode) {
    	String sql;
    	if(style.equals("1")){
    		sql = CoreXmlSqlParsersFactory.getSql("CoreComMscStdProcess.QUERYCG");
    	}else{
    		sql = CoreXmlSqlParsersFactory.getSql("CoreComMscStdProcess.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, "#GIC#", cic);
    	sql = StringTool.ReplaceAll(sql, "#MSC2#", msc);
    	sql = StringTool.ReplaceAll(sql, "#CODE_JG#", codeJg);
    	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_CDOE#", processCode);
    	sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
    	
    	return this.getData(sql);
    }

    /**
     * 成分保存
     * @param baseList 主表数据
     * @param childList 从表数据
     * @param style 类型 国标 内控 Alpha
     * @return 执行条数
     */
    public CoreReturnObject saveMscStdProcess(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("CoreComMscStdProcess.MAXCICG");
            if (style.equals("N") || style.equals("L")) {
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreComMscStdProcess.MAXCICN");
            }

            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();
                for (int i = 0; i < baseList.size(); i++) {
                    // 将JSON字符串转化成对象
                    String baseStr = baseList.get(i).toString();
                    JSONObject json = JSONObject.fromObject(baseStr);
                    ComMscStdProcessEntity com = (ComMscStdProcessEntity) JSONObject
                            .toBean(json, ComMscStdProcessEntity.class);
                    // 存操作字段字符串
                    Object[] param = null;
                    // 创建时间：如果为空 则新增 否则修改
                    if (com.getValidflag().equals("")) {
                        // 新生成gic"GICN000001"类型的字符串 "GIC"+类型+六位数字
                        DecimalFormat df = new DecimalFormat("000000");
                        String stdStyle = style;
                        String cic = "GIC" + stdStyle + df.format(cicPart + 1);
                        cicHash.put(com.getGic(), cic);
                        cicPart += 1;
                        param = new Object[] { cic, com.getPsc(), com.getMsc(),
                                com.getStdstyle(), com.getProcessCdoe(),
                                com.getProcessDesc(), com.getStdCodeNk(),
                                com.getStdNameNk(), com.getModelCode(),
                                com.getModelDesc(), com.getCreateName(),
                                com.getMemo(),
                                com.getProducHead(), com.getCodeJg(),
                                com.getSteelcodeNk(), com.getSteelnameNk(),
                                com.getModelCodeNk(), com.getModelDescNk(),
                                com.getProduccodeNk(), com.getProducnameNk()};
                        sqlIdList.add("CoreComMscStdProcess.ADD");
                    }
                    else {
                        param = new Object[] { com.getPsc(), com.getMsc(),
                                com.getStdstyle(), com.getProcessCdoe(),
                                com.getProcessDesc(), com.getStdCodeNk(),
                                com.getStdNameNk(), com.getModelCode(),
                                com.getModelDesc(), com.getUpdateName(),
                                com.getMemo(), com.getProducHead(), 
                                com.getCodeJg(), com.getSteelcodeNk(),
                                com.getSteelnameNk(), com.getModelCodeNk(),
                                com.getModelDescNk(), com.getProduccodeNk(),
                                com.getProducnameNk(),
                                com.getGic() };
                        sqlIdList.add("CoreComMscStdProcess.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);
                    ComMscStdProcessCEntity com = (ComMscStdProcessCEntity) JSONObject
                            .toBean(json, ComMscStdProcessCEntity.class);
                    Object[] param = null;
                    // 创建时间：如果为空 则新增 否则修改
                    if (com.getValidflag().equals("")) {
                        String cic = com.getGic();
                        // 如果ckcHash包括cic，则证明子表数据的成分索引号是新生成的
                        if (cicHash.containsKey(cic)) {
                            cic = cicHash.get(cic);
                        }
                        // 同一个成分索引号下的序号只查询一次,存在我多个则自动加1
                        if (!hasC.containsKey(cic)) {
                            Object[] obj = new Object[] { cic };
                            String sqlc = CoreXmlSqlParsersFactory
                                    .getSql("CoreComMscStdProcess.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.getStationCode(), com.getStationDesc(),
                                com.getProcessCdoe(), com.getProcessDesc(),
                                com.getProcessCdoeC(), com.getProcessDescC(),
                                com.getValueText(), com.getValueNum(),
                                com.getValueMemo(), com.getCreateName(),
                                com.getMemo(), com.getGroupSeq(),
                                com.getMinD(), com.getMaxD(), com.getMinH(), com.getMaxH(),
                                com.getMinDSign(), com.getMaxDSign(), com.getMinHSign(),
                                com.getMaxHSign() };
                        sqlIdList.add("CoreComMscStdProcess.ADD1");
                    }
                    else {
                        param = new Object[] { com.getStationCode(),
                                com.getStationDesc(), com.getProcessCdoe(),
                                com.getProcessDesc(), com.getProcessCdoeC(),
                                com.getProcessDescC(), com.getValueText(),
                                com.getValueNum(), com.getValueMemo(),
                                com.getCreateName(), com.getMemo(),
                                com.getGroupSeq(), com.getMinD(), com.getMaxD(),
                                com.getMinH(), com.getMaxH(), com.getMinDSign(),
                                com.getMaxDSign(), com.getMinHSign(), com.getMaxHSign(),
                                com.getGic(), com.getXh()};
                        sqlIdList.add("CoreComMscStdProcess.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);
            ComMscStdProcessEntity com = (ComMscStdProcessEntity) JSONObject
                    .toBean(json, ComMscStdProcessEntity.class);
            Object[] param = null;
            if (flag) {
                sqlIDlist.add("CoreComMscStdProcess.DELETE");
                param = new Object[] { com.getDeleteName(), com.getGic() };
            }
            else {
                sqlIDlist.add("CoreComMscStdProcess.RESUME");
                param = new Object[] { com.getGic() };
            }
            params.add(param);
        }
        // 从表作废或者恢复
        for (int i = 0; i < childList.size(); i++) {
            String childStr = childList.get(i).toString();
            JSONObject json = JSONObject.fromObject(childStr);
            ComMscStdProcessCEntity com = (ComMscStdProcessCEntity) JSONObject
                    .toBean(json, ComMscStdProcessCEntity.class);
            Object[] param = null;
            if (flag) {
                sqlIDlist.add("CoreComMscStdProcess.DELETE1");
                param = new Object[] { com.getDeleteName(), com.getGic(),
                        com.getXh() ,com.getGic()};
            }
            else {
                sqlIDlist.add("CoreComMscStdProcess.RESUME1");
                param = new Object[] { com.getGic(), com.getXh() };
            }
            params.add(param);
        }
        return this.setDataById(sqlIDlist, params);
    }

    /**
     * 分组
     * @param parms 参数
     * @return 数据
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doGroup(ArrayList<Object> parms) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<Object> sqlIDList = new ArrayList<Object>(); // SQL语句集合
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>(); // 参数
        if (parms.size() > 0) {
            for (int i = 0; i < parms.size(); i++) {
                ArrayList<Object> list = (ArrayList<Object>) parms.get(i);
                String pic = "";
                int seq = 0;
                ArrayList<Object> parm = new ArrayList<Object>();
                for (int j = 0; j < list.size(); j++) {
                    ArrayList<Object> list1 = (ArrayList<Object>) list.get(j);
                    parm = new ArrayList<Object>();
                    if (pic.equals("")) {
                        pic = list1.get(0).toString();
                        String str = CoreXmlSqlParsersFactory
                                .getSql("CoreComMscStdProcess.GetGroupSeq");
                        Object[] obj = new Object[] { pic };
                        try {
                            ResultSet rs = this.getDao("TgDao")
                                    .ExceuteQueryForResultSet(str, obj);
                            if (rs.next()) {
                                int indexseq = rs.getInt(1);
                                indexseq += 1;
                                seq = indexseq;
                            }
                            else {
                                seq += 1;
                            }
                        }
                        catch (SQLException e) {
                            CoreIComponent.logAdapter.filelogger.logError(e
                                    .getMessage());// 将服务端的错误信息写入日志文件
                        }
                    }
                    int index = Integer.parseInt(list1.get(1).toString());
                    parm.add(seq);
                    parm.add(pic);
                    parm.add(index);
                    sqlIDList.add(CoreXmlSqlParsersFactory
                            .getSql("CoreComMscStdProcess.SetGroupSeq"));
                    parmlist.add(parm.toArray());
                }
            }
        }
        cro = this.getDao("TgDao").ExcuteTransction(sqlIDList, parmlist);
        return cro;
    }

    /**
     * 取消分组
     * @param parms 参数
     * @return 数据
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject cancleGroup(ArrayList<Object> parms) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<Object> sqlIDList = new ArrayList<Object>(); // SQL语句集合
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>(); // 参数
        if (parms.size() > 0) {
            for (int i = 0; i < parms.size(); i++) {
                ArrayList<Object> list = (ArrayList<Object>) parms.get(i);
                sqlIDList.add(CoreXmlSqlParsersFactory
                        .getSql("CoreComMscStdProcess.CanleGroupSeq"));
                parmlist.add(list.toArray());
            }
        }
        cro = this.getDao("TgDao").ExcuteTransction(sqlIDList, parmlist);
        return cro;
    }
    
    /**
     * 通过Gic获取加工表
     * @param pic
     * @return obj
     */
    public CoreReturnObject getComGicByGic(String gic){
    	String sql = CoreXmlSqlParsersFactory.getSql("CoreComMscStdProcess.getComGicByGic");
    	sql = StringTool.ReplaceAll(sql, "#GIC#", gic);
    	return this.getData(sql);
    }


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

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