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.DectionCObject;
import com.steering.pss.qcm.model.DectionObject;
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;

/**
 * 探伤要求管理类
 * @author Administrator pdy 2014/12/27
 * @version v1.1
 */
public class CoreDetection extends DBCommon {

    /**
     * 探伤主表 查询
     * @param params 查询条件
     * @param style  交付标准或者内控
     * @param dic    探伤索引号
     * @return       数据集
     */
    public CoreReturnObject getCoreDetection(ArrayList<String> params,
            String style,String dic, String msc, String codeJg, String produccode, 
            String steelcodeNk, String stdCodeSNK, String stdStyleSNk, String isNkEdite,
            String processCode, String modelCode) {
        String sql;
        if(style.equals("1")){
        	sql = CoreXmlSqlParsersFactory.getSql("ComMSCStdDetection.QUERYG");
        }else{
        	sql = CoreXmlSqlParsersFactory.getSql("ComMSCStdDetection.QUERYN");
        }
        sql = StringTool.ReplaceAll(sql, "#STD_NAME#", params.get(0));
        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, "#DIC#", dic);
        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#", produccode);
        sql = StringTool.ReplaceAll(sql, "#STEELCODE_NK#", steelcodeNk);
        sql = StringTool.ReplaceAll(sql, "#STD_CODE_S_NK#", stdCodeSNK);
        sql = StringTool.ReplaceAll(sql, "#STD_STYLE_S_NK#", stdStyleSNk);
        sql = StringTool.ReplaceAll(sql, "#IS_NK_EDITE#", isNkEdite);
        sql = StringTool.ReplaceAll(sql, "#PROCESS_CODE#", processCode);
        sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
        
        return this.getData(sql);
    }

    /**
     * 探伤保存
     * @param baseList 主表
     * @param childList 从表
     * @param style 类型
     * @return 条数
     */
    public CoreReturnObject saveCoreDetection(ArrayList<Object> baseList,
            ArrayList<Object> childList, String style) {
    	Connection con = null;
    	try{
    		con = this.getDao(CoreConstantData.sysbeanstr).getConnection();

    		String sql = CoreXmlSqlParsersFactory
                    .getSql("ComMSCStdDetection.GETMAXDICG");
            if (style.equals("N") || style.equals("L")) {
                sql = CoreXmlSqlParsersFactory
                        .getSql("ComMSCStdDetection.GETMAXDICN");
            }
            if (style.equals("K")) {
                sql = CoreXmlSqlParsersFactory
                        .getSql("ComMSCStdDetection.GETMAXDICK");
            }
            if (style.equals("S")) {
                sql = CoreXmlSqlParsersFactory
                        .getSql("ComMSCStdDetection.GETMAXDICS");
            }
            HashMap<String, String> hmS = new HashMap<String, String>();
            try {
                // 主表查询最大序号
            	PreparedStatement ps = con.prepareStatement(sql);
            	ResultSet rs = ps.executeQuery();
                //ResultSet rs = this.getDao("TgDao").ExceuteQueryForResultSet(sql);
                int dicPart = 0;
                if (rs.next()) {
                    dicPart = Integer.parseInt(rs.getString(1));
                }
                rs.close();
                ps.close();

                ArrayList<String> sqlIDlist = new ArrayList<String>();
                ArrayList<Object[]> params = new ArrayList<Object[]>();
                for (int i = 0; i < baseList.size(); i++) {
                    String baseStr = baseList.get(i).toString();
                    JSONObject json = JSONObject.fromObject(baseStr);
                    DectionObject comM = (DectionObject) JSONObject
                            .toBean(json, DectionObject.class);
                    Object[] param = null;
                    // 主表 增加
                    if (comM.getValidflag().equals("")) {
                        // 转化成"DICN000001"类型的字符串
                        DecimalFormat df = new DecimalFormat("000000");
                        String stdStyle = style;
                        String dic = "DIC" + stdStyle + df.format(dicPart + 1);
                        param = new Object[] { dic, comM.getPsc(), comM.getMsc(),
                                comM.getStdStyle(), comM.getProcessCode(),
                                comM.getProcessDesc(), comM.getStdCodeNk(),
                                comM.getStdNameNk(), comM.getModelCode(),
                                comM.getModelDesc(), comM.getCreateName(),
                                comM.getMemo(), comM.getProducHead(),
                                comM.getCodeJg(),
                                comM.getSteelcodeNk(), comM.getSteelnameNk(),
                                comM.getModelCodeNk(), comM.getModelDescNk(),
                                comM.getProduccodeNk(), comM.getProducnameNk(),
                                comM.getStdCodeSNk(), comM.getStdNameSNk(),
                                comM.getStdStyleSNk(), comM.getStdStyleDescSNk()};
                        sqlIDlist.add("ComMSCStdDetection.ADD");
                        params.add(param);
                        dicPart += 1;
                        hmS.put(comM.getDic(), dic);
                    }
                    else {
                        // 主表 修改
                        param = new Object[] { comM.getDic(), comM.getPsc(),
                                comM.getMsc(), comM.getStdStyle(),
                                comM.getProcessCode(), comM.getProcessDesc(),
                                comM.getStdCodeNk(), comM.getStdNameNk(),
                                comM.getModelCode(), comM.getModelDesc(),
                                comM.getUpdateName(), comM.getMemo(),
                                comM.getProducHead(), comM.getCodeJg(),
                                comM.getSteelcodeNk(), comM.getSteelnameNk(),
                                comM.getModelCodeNk(), comM.getModelDescNk(),
                                comM.getProduccodeNk(), comM.getProducnameNk(),
                                comM.getStdCodeSNk(), comM.getStdNameSNk(),
                                comM.getStdStyleSNk(), comM.getStdStyleDescSNk(),
                                comM.getDic() };
                        sqlIDlist.add("ComMSCStdDetection.UPDATE");
                        params.add(param);
                    }
                }
                // 从表
                HashMap<String, Integer> hm = new HashMap<String, Integer>();
                int xh = 1;
                for (int i = 0; i < childList.size(); i++) {
                    String childStr = childList.get(i).toString();
                    JSONObject json = JSONObject.fromObject(childStr);
                    DectionCObject comMC = (DectionCObject) JSONObject
                            .toBean(json, DectionCObject.class);
                    Object[] param = null;
                    // 根据是否存在创建时间来判断是否新增还是修改
                    if (comMC.getValidflag().equals("")) {
                        // 定位
                        String dicC = "";
                        if (hmS.containsKey(comMC.getDic())) {
                            dicC = hmS.get(comMC.getDic());
                        }
                        else {
                            dicC = comMC.getDic();
                        }
                        if (!hm.containsKey(dicC)) {
                            // 查询最大序号
                            String sqlC = CoreXmlSqlParsersFactory
                                    .getSql("ComMSCStdDetection.GETMAXXH");
                            Object[] obj = new Object[] { dicC };
                            PreparedStatement psC = con.prepareStatement(sqlC);
                            psC.setObject(1, dicC);
                        	ResultSet rsC = psC.executeQuery();
//                            ResultSet rsC = this.getDao("TgDao")
//                                    .ExceuteQueryForResultSet(sqlC, obj);
                            if (rsC.next()) {
                                xh = rsC.getInt(1) + 1;
                            }
                            rsC.close();
                            psC.close();
                            hm.put(dicC, xh);
                        }
                        param = new Object[] { dicC, hm.get(dicC),
                                comMC.getPhyCode(), comMC.getPhyName(),
                                comMC.getPositionCode(), comMC.getPositionDesc(),
                                comMC.getStdDesc(), comMC.getLvCode(),
                                comMC.getLvDesc(), comMC.getCoverage(),
                                comMC.getGroovePos(), comMC.getGrooveDir(),
                                comMC.getCreateName(), comMC.getMemo(),
                                comMC.getRate(),comMC.getRatedesc(),comMC.getRateval(),
                                comMC.getMinD(), comMC.getMaxD(), comMC.getMinH(),
                                comMC.getMaxH(), comMC.getGroupSeq() };
                        sqlIDlist.add("ComMSCStdDetection.ADD1");
                        params.add(param);
                        hm.put(dicC, hm.get(dicC) + 1);
                    }
                    else {
                        param = new Object[] { comMC.getDic(),
                                Integer.parseInt(comMC.getXh()),
                                comMC.getPhyCode(), comMC.getPhyName(),
                                comMC.getPositionCode(), comMC.getPositionDesc(),
                                comMC.getStdDesc(), comMC.getLvCode(),
                                comMC.getLvDesc(), comMC.getCoverage(),
                                comMC.getGroovePos(), comMC.getGrooveDir(),
                                comMC.getUpdateName(), comMC.getMemo(),
                                comMC.getRate(),comMC.getRatedesc(),comMC.getRateval(),
                                comMC.getMinD(), comMC.getMaxD(), comMC.getMinH(),
                                comMC.getMaxH(), comMC.getGroupSeq(),
                                comMC.getDic(), comMC.getXh()};
                        sqlIDlist.add("ComMSCStdDetection.UPDATE1");
                        params.add(param);
                    }
                }
                return this.setDataById(sqlIDlist, params);
            }
            catch (SQLException e) {
            	
            }
            return null;
    	}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();
				}
    		}
    	}
    }
    
    public CoreReturnObject getPurchaseAgreementDic(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("ComMSCStdDetection.getPurchaseAgreementDic");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }
    
    public CoreReturnObject getPurchaseAgreementDetec(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("ComMSCStdDetection.getPurchaseAgreementDetec");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }

    /**
     * 探伤要求从表 查询
     * @param flag 是否有效
     * @return 数据集
     */
    public CoreReturnObject getCoreDetectionC(String customInfo, String flag, String stdCode, String msc,
    		String codeJg, String produccodeNk, String steelcodeNk, String processCode, String modelCode) {
    	String sql = "";
    	if(customInfo.equals("1")){
    		sql = CoreXmlSqlParsersFactory.getSql("ComMSCStdDetection.QUERYGC");
    	}else{
    		sql = CoreXmlSqlParsersFactory.getSql("ComMSCStdDetection.QUERYOTHERC");
    		
    	}
    	sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", flag);
    	sql = StringTool.ReplaceAll(sql, "#STD_CODE_NK#", stdCode);
    	sql = StringTool.ReplaceAll(sql, "#MSC#", msc);
    	sql = StringTool.ReplaceAll(sql, "#CODE_JG#", codeJg);
    	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);
        
    	return this.getData(sql);
    }

    /**
     * 探伤要求从表 查询最大序号
     * @param dic 探伤索引号
     * @return 数据集
     */
    public CoreReturnObject getMaxXH(String dic) {
        Object[] params = new Object[] { dic };
        return this.getDataBySqlID("ComMSCStdDetection.GETMAXXH", params);
    }

    /**
     * 作废或者恢复
     * @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++) {
            String baseStr = baseList.get(i).toString();
            JSONObject json = JSONObject.fromObject(baseStr);
            DectionObject comM = (DectionObject) JSONObject
                    .toBean(json, DectionObject.class);
            Object[] param = null;
            if (flag) {
                param = new Object[] { comM.getDeleteName(), comM.getDic() };
                sqlIDlist.add("ComMSCStdDetection.DELETE");
            }
            else {
                param = new Object[] { comM.getDic() };
                sqlIDlist.add("ComMSCStdDetection.RESUME");
            }
            params.add(param);
        }
        for (int i = 0; i < childList.size(); i++) {
            String childStr = childList.get(i).toString();
            JSONObject json = JSONObject.fromObject(childStr);
            DectionCObject comMC = (DectionCObject) JSONObject
                    .toBean(json, DectionCObject.class);
            Object[] param = null;
            if (flag) {
                param = new Object[] { comMC.getDeleteName(), comMC.getDic(),
                        comMC.getXh() ,comMC.getDic()};
                sqlIDlist.add("ComMSCStdDetection.DELETE1");
            }
            else {
                param = new Object[] { comMC.getDic(), comMC.getXh() };
                sqlIDlist.add("ComMSCStdDetection.RESUME1");
            }
            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("ComMSCStdDetection.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) {
                            // TODO Auto-generated catch block
                            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("ComMSCStdDetection.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("ComMSCStdDetection.CancelGroupSeq"));
                parmlist.add(list.toArray());
            }
        }
        cro = this.getDao("TgDao").ExcuteTransction(sqlIDList, parmlist);
        return cro;
    }
    
    /**
     * 通过Dic获取探伤表
     * @param pic
     * @return obj
     */
    public CoreReturnObject getComDicByDic(String dic){
    	String sql = CoreXmlSqlParsersFactory.getSql("ComMSCStdDetection.getComDicByDic");
    	sql = StringTool.ReplaceAll(sql, "#DIC#", dic);
    	return this.getData(sql);
    }
    
    /**
     * 通过检验项获取工序点
     * @param phyCode
     * @return
     */
    public CoreReturnObject getStationByPhyCode(String phyCode){
    	String sql = CoreXmlSqlParsersFactory.getSql("ComMSCStdDetection.getStationByPhyCode");
    	sql = StringTool.ReplaceAll(sql, "#PHY_CODE#", phyCode);
    	return this.getData(sql);
    }

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

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