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.PressWaterCObject;
import com.steering.pss.qcm.model.PressWaterObject;
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.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 水压标准管理类
 * @author Administrator PDY 2014-12-30
 */
public class CoreWaterStand extends DBCommon {

    /**
     * 查询
     * @param params 查询条件
     * @param style 交付标准或者内控标准
     * @return 数据集
     */
    public CoreReturnObject getCoreWaterStand(ArrayList<String> params, String style, String msc,
    		String codeJg, String produccodeNk, String steelcodeNk, String processCode, String modelCode) {
        String sql;
        if(style.equals("G")){
        	sql = CoreXmlSqlParsersFactory.getSql("CoreWaterPressureStand.QUERYG");
        }else if(style.equals("N")){
        	sql = CoreXmlSqlParsersFactory.getSql("CoreWaterPressureStand.QUERYN");
        }else{
        	sql = CoreXmlSqlParsersFactory.getSql("CoreWaterPressureStand.QUERYK");
        }
        sql = StringTool.ReplaceAll(sql, "#STD_NAME#", params.get(0));
        sql = StringTool.ReplaceAll(sql, "#STD_NAME_NK#", params.get(0));
        sql = StringTool.ReplaceAll(sql, "#PSC_DESC#", 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, "#WIC#", params.get(4));
        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_CDOE#", processCode);
        sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
        
        return this.getData(sql);
    }

    /**
     * 从表查询
     * @param valid 是否无效
     * @param style 交付标准或者内控标准
     * @return 数据集
     */
    public CoreReturnObject getCoreWaterStandC(String valid, String stdCode, String style,
    		String msc, String codeJg, String produccodeNk, String steelcodeNk,
    		String processCode, String modelCode) {
        String sql;
        if(style.equals("G")){
        	sql = CoreXmlSqlParsersFactory.getSql("CoreWaterPressureStand.QUERYGC");
        }else if(style.equals("N")){
        	sql = CoreXmlSqlParsersFactory.getSql("CoreWaterPressureStand.QUERYNC");
        }else{
        	sql = CoreXmlSqlParsersFactory.getSql("CoreWaterPressureStand.QUERYKC");
        }
    	sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", valid);
    	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_CDOE#", processCode);
    	sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
    	
    	return this.getData(sql);
    }
    
    public CoreReturnObject getPurchaseAgreementWic(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreWaterPressureStand.getPurchaseAgreementWic");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }
    
    public CoreReturnObject getPurchaseAgreementWater(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("CoreWaterPressureStand.getPurchaseAgreementWater");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }

    /**
     * 保存
     * @param baseData 主表数据
     * @param childData 从表数据
     * @param style 交付标准或者内控标准
     * @return 執行條數
     */
    public CoreReturnObject saveCoreWaterStand(ArrayList<Object> baseData,
            ArrayList<Object> childData, 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> wicH = new HashMap<String, String>();
            try {
                // 查询主表最大主键数字部分
                // 交付标准
                String sql = CoreXmlSqlParsersFactory
                        .getSql("CoreWaterPressureStand.QUERYMAXG");
                // 内控标准
                if (style.equals("N") || style.equals("L")) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreWaterPressureStand.QUERYMAXN");
                }

                if (style.equals("K")) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CoreWaterPressureStand.QUERYMAXK");
                }
            	PreparedStatement ps = con.prepareStatement(sql);
            	ResultSet rs = ps.executeQuery();
                //ResultSet rs = this.getDao("TgDao").ExceuteQueryForResultSet(sql);
                int wicPart = 0;
                if (rs.next()) {
                    wicPart = Integer.parseInt(rs.getString(1));
                }
                rs.close();
                ps.close();
                // 主表参数
                for (int i = 0; i < baseData.size(); i++) {
                    String baseStr = baseData.get(i).toString();
                    JSONObject json = JSONObject.fromObject(baseStr);
                    PressWaterObject com = (PressWaterObject) JSONObject
                            .toBean(json, PressWaterObject.class);
                    Object[] param = null;
                    // 根据创建时间是否为空来判断是新增还是修改(空为新增)
                    if (com.getValidflag().equals("")) {
                        // 生成10位字符串的公差索引号 组成：SIC + 类型 + 6位数字
                        DecimalFormat df = new DecimalFormat("000000");
                        String stdStyle = style;

                        String wic = "WIC" + stdStyle + df.format(wicPart + 1);
                        param = new Object[] { wic, com.getPsc(), com.getMsc(),
                                com.getStdstyle(), com.getProcessCdoe(),
                                com.getProcessDesc(), com.getStdCodeNk(),
                                com.getStdNameNk(), com.getMinD(), com.getMaxD(),
                                com.getMinH(), com.getMaxH(), com.getSpecJg(),
                                com.getSpecJgDesc(), 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("CoreWaterPressureStand.ADD");
                        params.add(param);
                        wicPart += 1;
                        wicH.put(com.getWic(), wic);
                        // 修改
                    }
                    else {
                        param = new Object[] { com.getWic(), com.getPsc(),
                                com.getMsc(), com.getStdstyle(),
                                com.getProcessCdoe(), com.getProcessDesc(),
                                com.getStdCodeNk(), com.getStdNameNk(),
                                com.getMinD(), com.getMaxD(), com.getMinH(),
                                com.getMaxH(), com.getSpecJg(),
                                com.getSpecJgDesc(), 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.getWic() };
                        sqlIdList.add("CoreWaterPressureStand.UPDATE");
                        params.add(param);
                    }
                }
                // 从表存储各WIC下的序号
                HashMap<String, Integer> wicHashC = new HashMap<String, Integer>();
                int xh = 1;
                for (int i = 0; i < childData.size(); i++) {
                    String chlidStr = childData.get(i).toString();
                    JSONObject json = JSONObject.fromObject(chlidStr);
                    PressWaterCObject comC = (PressWaterCObject) JSONObject
                            .toBean(json, PressWaterCObject.class);
                    Object[] param = null;
                    if (comC.getValidflag().equals("")) {
                        // 如果生成的SIC与界面上不符，换成生成的SIC
                        String wicC = "";
                        if (wicH.containsKey(comC.getWic())) {
                            wicC = wicH.get(comC.getWic());
                        }
                        else {
                            wicC = comC.getWic();
                        }
                        if (!wicHashC.containsKey(wicC)) {
                            // 查询最大序号
                            String sqlC = CoreXmlSqlParsersFactory
                                    .getSql("CoreWaterPressureStand.QUERYMAXC");
                            Object[] obj = new Object[] { wicC };
                            PreparedStatement psC = con.prepareStatement(sqlC);
                            psC.setObject(1, wicC);
                        	ResultSet rsC = psC.executeQuery();
//                            ResultSet rsC = this.getDao("TgDao")
//                                    .ExceuteQueryForResultSet(sqlC, obj);
                            if (rsC.next()) {
                                xh = rsC.getInt(1) + 1;
                            }
                            rsC.close();
                            psC.close();
                            wicHashC.put(wicC, xh);
                        }
                        param = new Object[] { wicC, wicHashC.get(wicC),
                                comC.getPressureY(), comC.getPressure(),
                                comC.getFormula(), comC.getSaveTime(),
                                comC.getCreateName(), comC.getMemo(),
                                comC.getMaxval(), comC.getMinval(),
                                comC.getRoundRule(), comC.getOutputStyle(),
                                comC.getZbsOutputStyle(), comC.getPressureBar()};
                        sqlIdList.add("CoreWaterPressureStand.ADDC");
                        params.add(param);
                        wicHashC.put(wicC, wicHashC.get(wicC) + 1);
                    }
                    else {
                        param = new Object[] { comC.getWic(), comC.getXh(),
                                comC.getPressureY(), comC.getPressure(),
                                comC.getFormula(), comC.getSaveTime(),
                                comC.getUpdateName(), comC.getMemo(),
                                comC.getMaxval(), comC.getMinval(), 
                                comC.getRoundRule(), comC.getOutputStyle(),
                                comC.getZbsOutputStyle(), comC.getPressureBar(),
                                comC.getWic(), comC.getXh()};
                        sqlIdList.add("CoreWaterPressureStand.UPDATEC");
                        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++) {
            String baseStr = baseList.get(i).toString();
            JSONObject json = JSONObject.fromObject(baseStr);
            PressWaterObject comM = (PressWaterObject) JSONObject.toBean(
                    json, PressWaterObject.class);
            Object[] param = null;
            if (flag) {
                param = new Object[] { comM.getDeleteName(), comM.getWic() };
                sqlIDlist.add("CoreWaterPressureStand.DELETE");
            }
            else {
                param = new Object[] { comM.getWic() };
                sqlIDlist.add("CoreWaterPressureStand.RESUME");
            }
            params.add(param);
        }
        for (int i = 0; i < childList.size(); i++) {
            String childStr = childList.get(i).toString();
            JSONObject json = JSONObject.fromObject(childStr);
            PressWaterCObject comMC = (PressWaterCObject) JSONObject
                    .toBean(json, PressWaterCObject.class);
            Object[] param = null;
            if (flag) {
                param = new Object[] { comMC.getDeleteName(), comMC.getWic(),
                        comMC.getXh(),comMC.getWic() };
                sqlIDlist.add("CoreWaterPressureStand.DELETEC");
            }
            else {
                param = new Object[] { comMC.getWic(), comMC.getXh() };
                sqlIDlist.add("CoreWaterPressureStand.RESUMEC");
            }
            params.add(param);
        }
        return this.setDataById(sqlIDlist, params);

    }

    /**
     * 水压公式
     * @param min 最小值
     * @param max 最大值
     * @param stdname 标准名称
     * @param steelcode 钢种
     * @return 数据
     */
    public CoreReturnObject getWaterRatio(String min, String max,
            String stdname, String steelcode) {
        Object[] obj = new Object[] { min, max, stdname, steelcode };
        return this.getDataBySqlID("CoreWaterPressureStand.GetRatio", obj);
    }
    
    /**
     * 通过Wic获取水压表
     * @param wic
     * @return obj
     */
    public CoreReturnObject getComWicByWic(String wic){
    	String sql = CoreXmlSqlParsersFactory.getSql("CoreWaterPressureStand.getComWicByWic");
    	sql = StringTool.ReplaceAll(sql, "#WIC#", wic);
    	return this.getData(sql);
    }
    
    /**
     * 水压圆整。
     * @param value 公制压力
     * @param roundRule 圆整规则代码
     * @return
     */
    public CoreReturnObject waterRound(Double value, String roundRule){
    	CoreReturnObject cro = new CoreReturnObject();
    	double mpa = 0.0;
    	double psi = 0.0;
		NumberFormat nfFormat = NumberFormat.getInstance();  
        nfFormat.setMaximumFractionDigits(0);
        nfFormat.setGroupingUsed(false);
        double a= Double.parseDouble(nfFormat.format(16.5));
    	if(roundRule.equals("409401")){//0.5Mpa/100psi
    		mpa = RoundGBT81702008.round3_4_1(value);
    		psi = RoundGBT81702008.roundPsi(value, 100);
    	}else if(roundRule.equals("409402")){//0.1Mpa/10psi
    		mpa = RoundGBT81702008.round3_4_3(value);
    		psi = RoundGBT81702008.roundPsi(mpa, 10);
    	}else if(roundRule.equals("409403")){//<7Mpa/1000psi:0.5Mpa/50psi;>=7Mpa/1000psi:1Mpa/100psi
    		if(value < 7){
    			mpa = RoundGBT81702008.round3_4_1(value);
    			psi = RoundGBT81702008.roundPsi(value, 50);
    		}else{
    			mpa = RoundGBT81702008.round3_2(value, 0);
    			psi = RoundGBT81702008.roundPsi(value, 100);
    		}
    	} else if(roundRule.equals("409404")){//(0.1Mpa/10psi)+10psi
            mpa = RoundGBT81702008.round3_4_3(value);
            psi = RoundGBT81702008.roundPsi(mpa, 10);
            psi = psi + 10;
        } else if(roundRule.equals("409406")){//<10Mpa:0.5Mpa;>=10Mpa:1Mpa
            if(value < 10){
                mpa = RoundGBT81702008.round3_4_1(value);
            }else{
                mpa = RoundGBT81702008.round3_2(value, 0);
            }
        } else if(roundRule.equals("409407")){//＜7MPa/1000psi:(0.5MPa/50psi)+50psi;＞=7MPa/1000psi:(1MPa/100psi)+100psi
            if(value < 7){
                mpa = RoundGBT81702008.round3_4_1(value);
                psi = RoundGBT81702008.roundPsi(value, 50);
                psi = psi + 50;
            }else{
                mpa = RoundGBT81702008.round3_2(value, 0);
                psi = RoundGBT81702008.roundPsi(value, 100);
                psi = psi + 100;
            }
        } else{
    		//没圆整规则就不圆整。
    		mpa = RoundGBT81702008.round3_2(value, 0);
            //psi = mpa * 145;
    		//psi = RoundGBT81702008.round3_2(value / 0.006895, 0);
    		psi = RoundGBT81702008.round3_2(value * 145.0377439, 0);
    	}
    	
    	double[] values = new double[2];
    	values[0] = mpa;
    	values[1] = psi;
    	cro.setResult(values);
    	return cro;
    }
    
//    /**
//     * 水压公制圆整
//     * @param value 公制压力
//     * @return
//     */
//    private double roundMpa(double value, int mpa){
//    	value = value * mpa;
//    	value = RoundGBT81702008.Round3_4_1(value);
//    	value = value / mpa;
//    	return value;
//    }

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

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