package com.steering.pss.qcm;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import CoreFS.SA01.CoreIComponent;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.SqlBuilder;

/**
 * @author WHB 2015-1-16 水压系数基础管理
 */
public class CoreWaterRatio extends DBCommon {

    /**
     * 获取标准
     * @param stdCode 标准代码
     * @return 平台统一返回对象
     */
    public CoreReturnObject GetStd(String stdCode) {
        Object[] parms = new Object[] { stdCode, stdCode, stdCode };
        return this.getDataBySqlID("CoreWaterRatio.GetStd", parms);
    }

    public CoreReturnObject getStdStyle() {

        return this.getDataBySqlID("CoreWaterRatio.GetStdStyle");
    }

    /**
     * 获得水压系数对应的钢级
     * @param id 水压系数ID
     * @return 平台统一返回对象
     */
    public CoreReturnObject GetSteel(String id) {
        Object[] obj = new Object[] { id, id, id, id };
        return this.getDataBySqlID("CoreWaterRatio.GetSteel", obj);
    }

    /**
     * 新增一条水压系数时获取钢级
     * @param StdName 标准代码
     * @return 平台统一返回对象
     */
    public CoreReturnObject getSteelNew(String stdCode) {
        Object[] obj = new Object[] { stdCode };
        return this.getDataBySqlID("CoreWaterRatio.GetSteelNew", obj);
    }

    /**
     * 获取扣型
     * @param id 水压系数
     * @return 平台统一返回对象
     */
    public CoreReturnObject getModel(String id) {
        Object[] obj = new Object[] { id, id, id };
        return this.getDataBySqlID("CoreWaterRatio.GetModel", obj);
    }

    /**
     * 查询
     * @param stdCode 标准代码
     * @return 平台统一返回对象
     */
    public CoreReturnObject doQuery(String stdCode, String stdStyleCode,
            Boolean valid, String stdCodeNk) {
        String flag = valid ? "0" : "";
        Object[] parms = new Object[] { stdCode, stdCode, stdCode, flag,
        		stdStyleCode, stdStyleCode, stdCodeNk, stdCodeNk };
        return this.getDataBySqlID("CoreWaterRatio.Query", parms);
    }

    /**
     * 保存
     * @param listAdd 水压系数新增
     * @param listUpdate 水压系数修改
     * @param listSteel 关联的钢级
     * @param listModel 关联的扣型
     * @return 平台统一返回对象
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doSave(ArrayList<Object> listAdd,
            ArrayList<Object> listUpdate, ArrayList<Object> listSteel,
            ArrayList<Object> listModel) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<String> sqlIDlist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        int index = 0;
        int oldId = 0;
        HashMap<Integer, Integer> has = new HashMap<Integer, Integer>();
        for (int i = 0; i < listAdd.size(); i++) {

            ArrayList<Object> lista = (ArrayList<Object>) listAdd.get(i);
            oldId = Integer.parseInt(lista.get(0).toString());

            String isref = CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.IsRefrenced");
            Object[] refobj = new Object[] { lista.get(1), lista.get(12) };
            try {
                ResultSet rsref = this.getDao(CoreConstantData.sysbeanstr)
                        .ExceuteQueryForResultSet(isref, refobj);
                if (rsref.next()) {
                    cro.setV_errMsg("FALSE####");
                    return cro;
                }
            }
            catch (SQLException e1) {
                CoreIComponent.logAdapter.filelogger.logError(e1.getMessage());// 将服务端的错误信息写入日志文件
            }

//            String isReapt = CoreXmlSqlParsersFactory
//                    .getSql("CoreWaterRatio.IsReapt");
//            Object[] objReapt = new Object[] { lista.get(1), lista.get(12),
//                    lista.get(3), lista.get(4), lista.get(5), lista.get(6),
//                    lista.get(7), lista.get(11) };
//
//            try {
//                ResultSet rsReapt = this.getDao(CoreConstantData.sysbeanstr)
//                        .ExceuteQueryForResultSet(isReapt, objReapt);
//
//                if (rsReapt.next()) {
//                    cro.setV_errMsg("FALSE#Reapt");
//                    cro.setResult(rsReapt.getString(1));
//                    return cro;
//                }
//            }
//            catch (SQLException e2) {
//                CoreIComponent.logAdapter.filelogger.logError(e2.getMessage());// 将服务端的错误信息写入日志文件
//            }

            String strsql = CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.GetMaxId");
            try {
                ResultSet rs = this.getDao(CoreConstantData.sysbeanstr)
                        .ExceuteQueryForResultSet(strsql);
                if (rs.next()) {
                    int id = rs.getInt(1);
                    if (id < index) {
                        index += 1;
                        lista.add(index);
                    }
                    else {
                        id += 1;
                        index = id;
                        lista.set(0, index);
                    }
                }
                else {
                    index += 1;
                    lista.set(0, index);
                }
            }
            catch (SQLException e) {
                CoreIComponent.logAdapter.filelogger.logError(e.getMessage());// 将服务端的错误信息写入日志文件
            }
            params.add(lista.toArray());
            sqlIDlist
                    .add(CoreXmlSqlParsersFactory.getSql("CoreWaterRatio.Add"));
            has.put(oldId, index);
        }

        for (int i = 0; i < listUpdate.size(); i++) {
            ArrayList<Object> list = new ArrayList<Object>();
            list = (ArrayList<Object>) listUpdate.get(i);

            String isref = CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.IsRefrenced");
            Object[] refobj = new Object[] { list.get(1), list.get(12) };
            try {
                ResultSet rsref = this.getDao(CoreConstantData.sysbeanstr)
                        .ExceuteQueryForResultSet(isref, refobj);
                if (rsref.next()) {
                    cro.setV_errMsg("FALSE####");
                    return cro;
                }
            }
            catch (SQLException e1) {
                CoreIComponent.logAdapter.filelogger.logError(e1.getMessage());// 将服务端的错误信息写入日志文件
            }

//            String isReapt = CoreXmlSqlParsersFactory
//                    .getSql("CoreWaterRatio.IsReaptUpdate");
//            Object[] objReapt = new Object[] { list.get(1), list.get(12),
//                    list.get(3), list.get(4), list.get(5), list.get(6),
//                    list.get(7), list.get(11), list.get(0) };
//
//            try {
//                ResultSet rsReapt = this.getDao(CoreConstantData.sysbeanstr)
//                        .ExceuteQueryForResultSet(isReapt, objReapt);
//                if (rsReapt.next()) {
//                    cro.setV_errMsg("FALSE#Reapt");
//                    cro.setResult(rsReapt.getString(1));
//                    return cro;
//                }
//            }
//            catch (SQLException e2) {
//                CoreIComponent.logAdapter.filelogger.logError(e2.getMessage());// 将服务端的错误信息写入日志文件
//            }

            list.add(list.get(0).toString());
            params.add(list.toArray());
            sqlIDlist.add(CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.Update"));
        }

        if (listSteel.size() > 0) {// 必有一个钢级选择
            ArrayList<Object> list = (ArrayList<Object>) listSteel.get(0);
            String raId = list.get(0).toString();
            if (has.containsKey(Integer.parseInt(raId))) {
                raId = String.valueOf(has.get(Integer.parseInt(raId)));
            }// 删除新生成ID对应的钢级，以免删错
            sqlIDlist.add(CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.DeleteRatioSteel"));
            Object[] obj = new Object[] { raId };
            params.add(obj);
        }
        for (int i = 0; i < listSteel.size(); i++) {
            ArrayList<Object> list = new ArrayList<Object>();
            list = (ArrayList<Object>) listSteel.get(i);
            sqlIDlist.add(CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.AddRatio_Steel"));
            if (has.containsKey(Integer.parseInt(list.get(0).toString()))) {
                list.set(0, has.get(Integer.parseInt(list.get(0).toString())));
            }
            params.add(list.toArray());
        }

        if (listModel.size() > 0) { // 必有一个扣型选择
            ArrayList<Object> list = (ArrayList<Object>) listModel.get(0);
            String raId = list.get(0).toString();
            if (has.containsKey(Integer.parseInt(raId))) {
                raId = String.valueOf(has.get(Integer.parseInt(raId)));
            }// 删除新生成ID对应的扣型，以免删错
            sqlIDlist.add(CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.DeleteRatioModel"));
            Object[] obj = new Object[] { raId };
            params.add(obj);
        }

        for (int i = 0; i < listModel.size(); i++) {
            ArrayList<Object> list = new ArrayList<Object>();
            list = (ArrayList<Object>) listModel.get(i);
            sqlIDlist.add(CoreXmlSqlParsersFactory
                    .getSql("CoreWaterRatio.AddRatio_Model"));
            if (has.containsKey(Integer.parseInt(list.get(0).toString()))) {
                list.set(0, has.get(Integer.parseInt(list.get(0).toString())));
            }
            params.add(list.toArray());
        }
        cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqlIDlist, params);
        return cro;
    }

    /**
     * 作废或恢复
     * @param parm 水压系数
     * @param flag 作废 或者恢复
     * @return 平台统一返回对象
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doDelete(ArrayList<Object> parm, Boolean flag) {
        CoreReturnObject cro = new CoreReturnObject();
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        if (flag) {// 删除主表，先删除其关联的所有记录
            for (int i = 0; i < parm.size(); i++) {
                // 先判断是否被引用

                ArrayList<Object> list = (ArrayList<Object>) parm.get(i);
                String id = list.get(1).toString();
//                String sql = CoreXmlSqlParsersFactory
//                        .getSql("CoreWaterRatio.IsReaptDelete");
//                try {
//                    ResultSet rs = this.getDao(CoreConstantData.sysbeanstr)
//                            .ExceuteQueryForResultSet(sql,
//                                    new Object[] { id, id });
//                    if(rs.next()){
//                        cro.setV_errMsg("DeleteFALSE##"); // 删除已引用。
//                        return cro;
//                    }
//                }
//                catch (SQLException e) {
//                    e.printStackTrace();
//                }
                
                params.add(new Object[] { id });
                params.add(new Object[] { id });
                params.add(list.toArray());
                sqllist.add(CoreXmlSqlParsersFactory
                        .getSql("CoreWaterRatio.DeleteRatioSteel"));
                sqllist.add(CoreXmlSqlParsersFactory
                        .getSql("CoreWaterRatio.DeleteRatioModel"));
                sqllist.add(CoreXmlSqlParsersFactory
                        .getSql("CoreWaterRatio.DELETE"));

            }
        }
        else {
            for (int i = 0; i < parm.size(); i++) {
                ArrayList<Object> list = (ArrayList<Object>) parm.get(i);

                Object[] Rsobj = list.toArray();

//                String sql = CoreXmlSqlParsersFactory
//                        .getSql("CoreWaterRatio.IsReaptResume");
//
//                try {
//                    ResultSet rss = this.getDao(CoreConstantData.sysbeanstr)
//                            .ExceuteQueryForResultSet(sql, Rsobj);
//                    if (rss.next()) {
//                        cro.setV_errMsg("ResumeFALSE##"); // 恢复发现重复。
//                        cro.setResult(rss.getString(1));
//                        return cro;
//                    }
//                }
//                catch (SQLException e) {
//                    CoreIComponent.logAdapter.filelogger.logError(e
//                            .getMessage());// 将服务端的错误信息写入日志文件
//                }
                Object[] obj = new Object[] { list.get(8) };
                params.add(obj);
                sqllist.add(CoreXmlSqlParsersFactory
                        .getSql("CoreWaterRatio.Resume"));
            }
        }
        cro = this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqllist, params);
        return cro;
    }
    
    /**
     * 获取设定的水压系数
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject getSetRatio(String ordLnPk){
    	SqlBuilder b = new SqlBuilder("CoreWaterRatio.getSetRatio");
    	b.Fill(new String[]{ ordLnPk });
    	return this.getData(b.toString());
    }
    
    /**
     * 设定水压系数
     * @param ordLnPk
     * @param ratioId
     * @return
     */
    public CoreReturnObject setRatio(String ordLnPk, String ratioId){
    	ArrayList<String> sqllist = new ArrayList<String>();
    	SqlBuilder  b = new SqlBuilder("CoreWaterRatio.deleteCraftRatio");
    	b.Fill(new String[]{ ordLnPk });
    	sqllist.add(b.toString());
    	b = new SqlBuilder("CoreWaterRatio.insertCraftRatio");
    	b.Fill(new String[]{ ordLnPk, ratioId });
    	sqllist.add(b.toString());
    	
    	return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist);
    }
    
    /**
     * 获取匹配的水压系数主键
     * @param ordLnPk
     * @return
     */
    public CoreReturnObject getMatchRatioId(String ordLnPk){
    	SqlBuilder b = new SqlBuilder("CoreWaterRatio.getMatchRatioId");
    	b.Fill(new String[]{ ordLnPk });
    	return this.getData(b.toString());
    }
    
    /**
     * 查询条件获取匹配的水压系数主键
     * @param stdName
     * @param dimater
     * @param stdStyleDesc
     * @param modelDesc
     * @param steelName
     * @return
     */
    public CoreReturnObject getMatchRatioIdFrm(String stdName, String dimater,
    		String stdStyleDesc, String modelDesc, String steelName){
    	SqlBuilder b = new SqlBuilder("CoreWaterRatio.getMatchRatioIdFrm");
    	b.Fill(new String[]{ stdName, dimater, stdStyleDesc, modelDesc, steelName });
    	
    	return this.getData(b.toString());
    }
    
    /**
     * 是否存在重复的数据
     * @param stdCode
     * @param stdStyle
     * @param minSign
     * @param min
     * @param maxSign
     * @param max
     * @param ratioStd
     * @param maxPress
     * @param steels
     * @param models
     * @param ratioId
     * @return
     */
    public CoreReturnObject existsWaterRatio(String stdCode, String stdStyle, String minSign,
    		String min, String maxSign, String max, String ratioStd, String maxPress,
    		String[] steels, String[] models, String ratioId,String stdCodeNk){
    	String strSteels = "'1'";
    	for(String steel : steels){
    		strSteels += ",'" + steel + "'";
    	}
    	//strSteels = strSteels.substring(1, strSteels.length() - 1);
    	
    	String strModels = "'1'";
    	for(String model : models){
    		strModels += ",'" + model + "'";
    	}
    	//strModels = strModels.substring(1, strModels.length() - 1);
    	
    	SqlBuilder b = new SqlBuilder("CoreWaterRatio.existsWaterRatio");
    	b.Fill(new String[]{ stdCode, stdStyle, minSign, min, maxSign, max, ratioStd,
    			maxPress, ratioId, stdCodeNk});
    	String sql = b.toString();
    	sql = sql.replaceAll("#STEELCODE#", strSteels);
    	sql = sql.replaceAll("#MODEL_CODE#", strModels);
    	return this.getData(sql);
    }
    
    /**
     * 复制标准对应的水压系数
     * @param stdCode
     * @return
     */
    public CoreReturnObject copyRatioByStd(String stdCode, String stdCodeNew, String stdNameNew){
    	SqlBuilder b = new SqlBuilder("CoreWaterRatio.copyRatioByStd");
    	b.Fill(new String[]{ stdCode, stdCodeNew, stdNameNew });
    	
    	return this.setData(b.toString());
    }
}
