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.SqlBuilder;
import com.steering.comm.tools.StringTool;
import com.steering.pss.qcm.model.SpecCObject;
import com.steering.pss.qcm.model.SpecObject;
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/11/09
 * @version v1.0
 */
public class CoreTolerances extends DBCommon {
    /**
     * 公差标准索引表 查询
     * @param params 查询条件
     * @param style 类型
     * @param cic 公差索引号
     * @return 数据集
     */
    public CoreReturnObject getCoreTolerances(ArrayList<String> params,
            String style, String cic, String msc, String codeJg,
            String producCode, String steelcodeNk, String processCode, String modelCode){
        String sql;
        if(style.equals("1")){
        	sql = CoreXmlSqlParsersFactory.getSql("CoreTolerancesStandard.QUERYG");
        }else{
        	sql = CoreXmlSqlParsersFactory.getSql("CoreTolerancesStandard.QUERYN");
        }
        sql = StringTool.ReplaceAll(sql, "#STD_NAME#", 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#", params.get(3));
        sql = StringTool.ReplaceAll(sql, "#SIC#", 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#", producCode);
        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 valid 有效标识
     * @return 数据集
     */
    public CoreReturnObject getCoreTolerancesC(String customInfo, String valid, String stdCode,
            String msc, String codeJg, String producCode, String steelcodeNk, String processCode, String modelCode) {
    	String sql = "";
    	if(customInfo.equals("1")){
    		sql = CoreXmlSqlParsersFactory.getSql("CoreTolerancesStandard.QUERYGC");
    	}else{
    		sql = CoreXmlSqlParsersFactory.getSql("CoreTolerancesStandard.QUERYOTHERC");
    	}
    	sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", valid);
    	sql = StringTool.ReplaceAll(sql, "#STD_CODE#", stdCode);
    	sql = StringTool.ReplaceAll(sql, "#MSC#", msc);
    	sql = StringTool.ReplaceAll(sql, "#CODE_JG#", codeJg);
    	sql = StringTool.ReplaceAll(sql, "#PRODUCCODE_NK#", producCode);
    	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);
    }
    
    public CoreReturnObject getPurchaseAgreementSic(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreTolerancesStandard.getPurchaseAgreementSic");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }
    
    public CoreReturnObject getPurchaseAgreementSpec(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreTolerancesStandard.getPurchaseAgreementSpec");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }

    /**
     * 删除或者恢复
     * @param baseList 主表项
     * @param childList 从表项
     * @param flag true 删除 false 恢复
     * @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);
            SpecObject com = (SpecObject) JSONObject.toBean(json,
                    SpecObject.class);
            Object[] param = null;
            // 删除
            if (flag) {
                param = new Object[] { com.getDeleteName(), com.getSic() };
                sqlIdList.add("CoreTolerancesStandard.DELETE");
            }
            else {
                param = new Object[] { "", com.getSic() };
                sqlIdList.add("CoreTolerancesStandard.RESUME");
            }
            params.add(param);
        }
        for (int i = 0; i < childList.size(); i++) {
            String chlidStr = childList.get(i).toString();
            JSONObject json = JSONObject.fromObject(chlidStr);
            SpecCObject comC = (SpecCObject) JSONObject.toBean(json,
                    SpecCObject.class);
            Object[] param = null;
            if (flag) {
                param = new Object[] { comC.getDeleteName(), comC.getSic(),
                        comC.getIndexSeq(), comC.getSic() };
                sqlIdList.add("CoreTolerancesStandard.DELETE1");
            }
            else {
                param = new Object[] { "", comC.getSic(), comC.getIndexSeq() };
                sqlIdList.add("CoreTolerancesStandard.RESUME1");
            }
            params.add(param);
        }
        return this.setDataById(sqlIdList, params);
    }

    /**
     * 公差标准 保存
     * @param baseList 主表数据
     * @param childList 从表数据
     * @param style 内控或者国标
     * @return 执行行数
     */
    public CoreReturnObject saveCoreTolerances(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[]>();
            // 主表增加页面主键与存入数据库主键 SIC
            HashMap<String, String> sicH = new HashMap<String, String>();
            try {
                // 查询主表最大主键数字部分
                // 交付标准
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CoreTolerancesStandard.QUERYMAXG");
                // 内控标准
                if (style.equals("N") || style.equals("L")) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreTolerancesStandard.QUERYMAXN");
                }
                if (style.equals("K")) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreTolerancesStandard.QUERYMAXK");
                }
                if (style.equals("S")) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreTolerancesStandard.QUERYMAXS");
                }
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                //ResultSet rs = this.getDao("TgDao").ExceuteQueryForResultSet(sql);
                int sicPart = 0;
                if (rs.next()) {
                    sicPart = Integer.parseInt(rs.getString(1));
                }
                rs.close();
                ps.close();
                // 主表参数
                for (int i = 0; i < baseList.size(); i++) {
                    String baseStr = baseList.get(i).toString();
                    JSONObject json = JSONObject.fromObject(baseStr);
                    SpecObject com = (SpecObject) JSONObject.toBean(json,
                            SpecObject.class);
                    Object[] param = null;
                    // 根据创建时间是否为空来判断是新增还是修改(空为新增)
                    if (com.getValidflag().equals("")) {
                        // 生成10位字符串的公差索引号 组成：SIC + 类型 + 6位数字
                        DecimalFormat df = new DecimalFormat("000000");
                        String stdStyle = style;
                        String sic = "SIC" + stdStyle + df.format(sicPart + 1);
                        param = new Object[] { sic, com.getPsc(), com.getMsc(),
                                com.getStdStyle(), com.getStdCode(),
                                com.getStdName(), com.getProcessCode(),
                                com.getProcessDesc(), com.getModelCode(),
                                com.getModelDesc(), com.getStdMemo(),
                                com.getProducHead(), com.getCodeJg(),
                                com.getCreateName(), com.getSpecialPath(),
                                com.getSteelcodeNk(), com.getSteelnameNk(),
                                com.getModelCodeNk(), com.getModelDescNk(),
                                com.getProduccodeNk(), com.getProducnameNk()};
                        sqlIdList.add("CoreTolerancesStandard.ADD");
                        params.add(param);
                        sicPart += 1;
                        sicH.put(com.getSic(), sic);
                        // 修改
                    }
                    else {
                        param = new Object[] { com.getSic(), com.getPsc(),
                                com.getMsc(), com.getStdStyle(), com.getStdCode(),
                                com.getStdName(), com.getProcessCode(),
                                com.getProcessDesc(), com.getModelCode(),
                                com.getModelDesc(), com.getStdMemo(),
                                com.getProducHead(), com.getCodeJg(),
                                com.getUpdateName(), com.getSpecialPath(),
                                com.getSteelcodeNk(), com.getSteelnameNk(),
                                com.getModelCodeNk(), com.getModelDescNk(),
                                com.getProduccodeNk(), com.getProducnameNk(),
                                com.getSic() };
                        sqlIdList.add("CoreTolerancesStandard.UPDATE");
                        params.add(param);
                    }
                }
                // 从表存储各SIC下的序号
                HashMap<String, Integer> sicHashC = new HashMap<String, Integer>();
                int indexSeq = 1;
                for (int i = 0; i < childList.size(); i++) {
                    String chlidStr = childList.get(i).toString();
                    JSONObject json = JSONObject.fromObject(chlidStr);
                    SpecCObject comC = (SpecCObject) JSONObject.toBean(json,
                            SpecCObject.class);
                    Object[] param = null;
                    if (comC.getValidflag().equals("")) {
                        // 如果生成的SIC与界面上不符，换成生成的SIC
                        String sicC = "";
                        if (sicH.containsKey(comC.getSic())) {
                            sicC = sicH.get(comC.getSic());
                        }
                        else {
                            sicC = comC.getSic();
                        }
                        if (!sicHashC.containsKey(sicC)) {
                            // 查询最大序号
                            String sqlC = CoreXmlSqlParsersFactory
                                    .getSql("CoreTolerancesStandard.QUERYMAX1");
                            Object[] obj = new Object[] { sicC };
                            PreparedStatement psC = con.prepareStatement(sqlC);
                            psC.setObject(1, sicC);
                            ResultSet rsC = psC.executeQuery();
//                            ResultSet rsC = this.getDao("TgDao")
//                                    .ExceuteQueryForResultSet(sqlC, obj);
                            if (rsC.next()) {
                                indexSeq = rsC.getInt(1) + 1;
                            }
                            rsC.close();
                            psC.close();
                            sicHashC.put(sicC, indexSeq);
                        }
                        param = new Object[] { sicC, sicHashC.get(sicC),
                                comC.getBiasCode(), comC.getBiasName(),
                                comC.getLv(), comC.getBiasCodeZ(),
                                comC.getBiasNameZ(), comC.getZminSign(),
                                comC.getZmin(), comC.getZmaxSign(), comC.getZmax(),
                                comC.getBiasCodeC(), comC.getBiasNameC(),
                                comC.getCminSign(), comC.getCmin(),
                                comC.getCmaxSign(), comC.getCmax(),
                                comC.getBiasCodeS(), comC.getBiasNameS(),
                                comC.getSminSign(), comC.getSmin(),
                                comC.getSmaxSign(), comC.getSmax(),
                                comC.getIsCheck(), comC.getStdMinVal(),
                                comC.getStdMaxVal(), comC.getStdMinIn(),
                                comC.getStdMaxIn(), comC.getStdMinPercent(),
                                comC.getStdMaxPercent(), comC.getStdMinFormula(),
                                comC.getStdMaxFormula(), comC.getStdMinFormulaV(),
                                comC.getStdMaxFormulaV(), comC.getStdMemo(),
                                comC.getCreateName(), comC.getGroupSeq() };
                        sqlIdList.add("CoreTolerancesStandard.ADD1");
                        params.add(param);
                        sicHashC.put(sicC, sicHashC.get(sicC) + 1);
                    }
                    else {
                        param = new Object[] { comC.getSic(), comC.getIndexSeq(),
                                comC.getBiasCode(), comC.getBiasName(),
                                comC.getLv(), comC.getBiasCodeZ(),
                                comC.getBiasNameZ(), comC.getZminSign(),
                                comC.getZmin(), comC.getZmaxSign(), comC.getZmax(),
                                comC.getBiasCodeC(), comC.getBiasNameC(),
                                comC.getCminSign(), comC.getCmin(),
                                comC.getCmaxSign(), comC.getCmax(),
                                comC.getBiasCodeS(), comC.getBiasNameS(),
                                comC.getSminSign(), comC.getSmin(),
                                comC.getSmaxSign(), comC.getSmax(),
                                comC.getIsCheck(), comC.getStdMinVal(),
                                comC.getStdMaxVal(), comC.getStdMinIn(),
                                comC.getStdMaxIn(), comC.getStdMinPercent(),
                                comC.getStdMaxPercent(), comC.getStdMinFormula(),
                                comC.getStdMaxFormula(), comC.getStdMinFormulaV(),
                                comC.getStdMaxFormulaV(), comC.getStdMemo(),
                                comC.getUpdateName(), comC.getGroupSeq(), comC.getSic(),
                                comC.getIndexSeq()};
                        sqlIdList.add("CoreTolerancesStandard.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 list
     * @return
     */
    public CoreReturnObject group(ArrayList<ArrayList<String>> list,
            Boolean isGroup) {
        ArrayList<String> sqllist = new ArrayList<String>();
        String sqlGroup = CoreXmlSqlParsersFactory
                .getSql("CoreTolerancesStandard.group");
        String sqlCancelGroup = CoreXmlSqlParsersFactory
                .getSql("CoreTolerancesStandard.cancelGroup");
        for (int i = 0; i < list.size(); i++) {
            ArrayList<String> listSub = list.get(i);
            String sql2 = "";
            if (isGroup) {
                sql2 = sqlGroup;
            }
            else {
                sql2 = sqlCancelGroup;
            }
            sql2 = StringTool.ReplaceAll(sql2, "#SIC#", listSub.get(0));
            sql2 = sql2.replaceAll("#INDEX_SEQS#", listSub.get(1));
            sqllist.add(sql2);
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqllist);
    }

    /**
     * 通过Sic获取公差表
     * @param pic
     * @return obj
     */
    public CoreReturnObject getComSicBySic(String sic) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreTolerancesStandard.getComSicBySic");
        sql = StringTool.ReplaceAll(sql, "#SIC#", sic);
        return this.getData(sql);
    }

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

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