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 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-15 Modify By WHB 2014-12-28
 */
public class ComMaterial extends DBCommon {

    /**
     * 主表 材质标准索引号
     * @return 最大材质标准索引号
     */
    public CoreReturnObject getAddCondition() {

        return this.getDataBySqlID("ComMaterialStandard.GetAddCondition");
    }
 
    public CoreReturnObject getMaxPic() {

        return this.getDataBySqlID("ComMaterialStandard.MAXPIC");
    }

    public CoreReturnObject getMultStd() {

        return this.getDataBySqlID("ComMaterialStandard.GetMultStd");
    }
    /**
     * 产品规范码
     * @return 产品规范码
     */
    public CoreReturnObject getPSC() {

        return this.getDataBySqlID("ComMaterialStandard.GetPSC");
    }

    /**
     * 从表 最大序号
     * @param pic 材质标准索引号
     * @return 返回CoreReturnObject
     */
    public CoreReturnObject getMaxIndexSeq(String pic) {
        Object[] params = new Object[] { pic };
        return this.getDataBySqlID("ComMaterialStandard.MAXINDEX", params);
    }

    /**
     * 主表查询
     * @param flag 是否有效
     * @param style 类型
     * @param pic 材质索引号
     * @return 材质数据集
     */
    public CoreReturnObject getComMaterial(ArrayList<String> list, String style,
    		ArrayList<String> listGrade, String producCode, String steelcodeNk,
    		String processCode, String modelCode) {
        String sql;
        if(style.equals("1")){
        	sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.QUERYG");
        }else if(style.equals("2")){
        	sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.QUERYN");
        }else{
    		sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.QUERYK");
        }
        sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", list.get(0));
        sql = StringTool.ReplaceAll(sql, "#STD_CODE_NK#", list.get(1));
        sql = StringTool.ReplaceAll(sql, "#PIC#", list.get(2));
        
        if(style.equals("2")){
        	sql = StringTool.ReplaceAll(sql, "#MSC2#", "");
        }else{
        	sql = StringTool.ReplaceAll(sql, "#MSC2#", list.get(3));
        }
        
        sql = StringTool.ReplaceAll(sql, "#CODE_JG#", list.get(4));
        sql = StringTool.ReplaceAll(sql, "#PRODUCCODE#", producCode);
        sql = StringTool.ReplaceAll(sql, "#STEELCODE_NK#", steelcodeNk);
        sql = StringTool.ReplaceAll(sql, "#PROCESS_CDOE#", processCode);
        sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);

        String sqlWhere = "";
        if(listGrade.size() > 0){
        	sqlWhere = "AND (1 <> 1 ";
            for(String str : listGrade){
            	sqlWhere += " OR NVL(INSTR(P.GRADECODE, '"+ str +"'), 1) > 0";
            }
            sqlWhere += ")";
        }
        
        sql = sql.replaceAll("#WHERE#", sqlWhere);
        
        return this.getData(sql);
    }

    public CoreReturnObject getComMaterialTemplate(String pic) {
        String sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.QUERYGTEMPLATE");
        sql = StringTool.ReplaceAll(sql, "#PIC#", pic);
        return this.getData(sql);
    }

    public CoreReturnObject getComMaterialTemplateC(String pic,String userName) {
        String sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.QUERYGTEMPLATEC");
        sql = StringTool.ReplaceAll(sql, "#PIC#", pic);
        sql += " WHERE CREATE_NAME = '" + userName + "'";
        return this.getData(sql);
    }


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

    public CoreReturnObject getComMaterialNKC(String msc) {
        String sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.getComMaterialNKC");
//        sql = StringTool.ReplaceAll(sql, "#PIC#", pic);
        sql = StringTool.ReplaceAll(sql, "#MSC#", msc);
        return this.getData(sql);
    }

    /**
     * 从表 查询
     * @param params 查询条件
     * @return 数据集
     */
    public CoreReturnObject getComMaterialC(String customInfo, ArrayList<String> params, ArrayList<String> listSteel,
    		String producCode, String steelcodeNk, String processCode, String modelCode) {
    	String sql = "";
    	if(customInfo.equals("1")){
    		sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.QUERYGC");
    	}else{
    		sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.QUERYOTHERC");
    	}
    	sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", params.get(0));
    	sql = StringTool.ReplaceAll(sql, "#STD_CODE_NK#", params.get(1));
    	if(!customInfo.equals("1")){
        	sql = StringTool.ReplaceAll(sql, "#MSC#", "");
        }else{
        	sql = StringTool.ReplaceAll(sql, "#MSC#", params.get(2));
        }
    	
    	sql = StringTool.ReplaceAll(sql, "#CODE_JG#", params.get(3));
    	sql = StringTool.ReplaceAll(sql, "#PRODUCCODE#", producCode);
    	sql = StringTool.ReplaceAll(sql, "#STEELCODE_NK#", steelcodeNk);
    	sql = StringTool.ReplaceAll(sql, "#PROCESS_CDOE#", processCode);
    	sql = StringTool.ReplaceAll(sql, "#MODEL_CODE_NK#", modelCode);
    	
    	String sqlWhere = "";
        if(listSteel.size() > 0){
        	sqlWhere = "AND (1 <> 1 ";
            for(String str : listSteel){
            	sqlWhere += " OR NVL(INSTR(B.GRADECODE, '"+ str +"'), 1) > 0";
            }
            sqlWhere += ")";
        }
        sql = sql.replaceAll("#WHERE#", sqlWhere);
    	
        return this.getData(sql);
    }
    
    public CoreReturnObject getPurchaseAgreementPic(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("ComMaterialStandard.getPurchaseAgreementPic");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }
    
    public CoreReturnObject getPurchaseAgreementPhy(String stdCodeNk){
    	SqlBuilder b = new SqlBuilder("ComMaterialStandard.getPurchaseAgreementPhy");
    	b.Fill(new String[]{stdCodeNk});
    	return this.getData(b.toString());
    }

    public CoreReturnObject SaveTemplate(ArrayList<ArrayList<Object>> addChild) {
        ArrayList<String> sqlList = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        for (int i = 0; i < addChild.size(); i++) {
            sqlList.add(CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.SaveTemplate"));
            ArrayList<Object> clist = (ArrayList<Object>) addChild.get(i);
            clist.remove(0);
            params.add(clist.toArray());
        }

        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqlList, params);
    }

    public CoreReturnObject DeleteTemplate(ArrayList<Object> ids) {
        ArrayList<String> sqlList = new ArrayList<String>();
        for (int i = 0; i < ids.size(); i++) {
            String sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.DeleteTemplate");
            sql = StringTool.ReplaceAll(sql, "#ID#", ids.get(i).toString());
            sqlList.add(sql);
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqlList);
    }

    /**
     * 材质标准 保存
     * @param addBase 主表增加项
     * @param updateBase 主表修改项
     * @param addChild 从表增加项
     * @param updateChild 从表修改项
     * @return 增加或者修改数据
     */
    public CoreReturnObject saveComMaterial(
            ArrayList<ArrayList<Object>> addBase,
            ArrayList<ArrayList<Object>> updateBase,
            ArrayList<ArrayList<Object>> addChild,
            ArrayList<ArrayList<Object>> updateChild, String acceptBid) {
    	Connection con = null;
    	try{
    		con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            ArrayList<String> sqlList = new ArrayList<String>();
            ArrayList<Object[]> params = new ArrayList<Object[]>();
            HashMap<String, String> map = new HashMap<String, String>();
            HashMap<String, String> mapid = new HashMap<String, String>();
            ArrayList<String> pics = new ArrayList<String>();
            for (int i = 0; i < addBase.size(); i++) {
                sqlList.add(CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.ADD"));
                String strSql = CoreXmlSqlParsersFactory
                        .getSql("ComMaterialStandard.MAXPIC1");
                ArrayList<Object> list = (ArrayList<Object>) addBase.get(i);
                String pic = "";
                map.put(list.get(0).toString(), pic);
                String style = list.get(2).toString();
                String style1 = "";
                if (style.equals("G") || style.equals("X")) {
                    style = "G"; // G、X国标协议采用统一的PICG编码格式
                    style1 = "X";
                }else if (style.equals("N")) { // K Alpha采用PICK N
                    // 内控采用PICN
                	if(acceptBid.equals("1")){
                		style = "N";
                    	style1 = "L";
                	}else{
                		style = "L";
                    	style1 = "N";
                	}
                	
    			}else if (style.equals("K")) { // K Alpha采用PICK N
                	style = "K";                                          // 内控采用PICN
                    style1 = "K";
                }
                Object[] obj = new Object[] { style, style1 };
                if (!mapid.containsKey(style)) {
                    mapid.put(style, pic);
                }

                try {
                    long stdCodePart = 0;
                    PreparedStatement st = con.prepareStatement(strSql);
                    st.setObject(1, style);
                    st.setObject(2, style1);
                    ResultSet rs = st.executeQuery();
//                    ResultSet rs = db.ExceuteQueryForResultSet(
//                            strSql, obj); // 取得对应标准类型的最大编码
                    if (rs.next()) {
                        String picp = rs.getString(1);
                        pic = mapid.get(style);
                        if (picp.compareTo(pic) < 0) {
                            stdCodePart = Integer.parseInt(pic.substring(4, 10));
                            DecimalFormat df = new DecimalFormat("000000");
                            String stdCode = "PIC" + style
                                    + df.format(stdCodePart + 1);
                            pic = stdCode;
                            map.put(list.get(0).toString(), pic);
                            mapid.put(style, pic);
                            list.set(0, stdCode);

                        }
                        else {
                            stdCodePart = Integer.parseInt(picp);
                            DecimalFormat df = new DecimalFormat("000000");
                            String stdCode = "PIC" + style
                                    + df.format(stdCodePart + 1);
                            pic = stdCode;
                            map.put(list.get(0).toString(), pic);
                            mapid.put(style, pic);
                            list.set(0, stdCode);

                        }
                    }
                    else {
                        if (mapid.get(style).equals("")) {
                            DecimalFormat df = new DecimalFormat("000000");
                            String stdCode = "PIC" + style + df.format(1);
                            map.put(list.get(0).toString(), stdCode);
                            mapid.put(style, stdCode);
                            list.set(0, stdCode);

                        }
                        else {
                            String p = mapid.get(style);
                            stdCodePart = Integer.parseInt(p.substring(4, 10));
                            DecimalFormat df = new DecimalFormat("000000");
                            String stdCode = "PIC" + style
                                    + df.format(stdCodePart + 1);
                            map.put(list.get(0).toString(), stdCode);
                            mapid.put(style, stdCode);
                            list.set(0, stdCode);

                        }
                    }
                    rs.close();
                    st.close();
                }
                catch (SQLException e) {
                    CoreIComponent.logAdapter.filelogger.logError(e.getMessage());// 将服务端的错误信息写入日志文件
                }
                params.add(list.toArray());
                
            }
            for (int i = 0; i < updateBase.size(); i++) {
            	sqlList.add(CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.UPDATE"));
                params.add(updateBase.get(i).toArray());

            }
            HashMap<String, Integer> mapc = new HashMap<String, Integer>();
            int index = 0; // 序号
            for (int i = 0; i < addChild.size(); i++) {
            	sqlList.add(CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.ADD1"));
                ArrayList<Object> clist = (ArrayList<Object>) addChild.get(i);
                String piccs = clist.get(0).toString(); // 未改之前的产品规范码
                String piccd = ""; // 改之后的产品规范码
                if (map.containsKey(piccs)) {
                    piccd = map.get(piccs);
                }
                else {
                    piccd = piccs;
                }
                if (!mapc.containsKey(piccd)) {
                    mapc.put(piccd, 0); // 产品规范码对应序号
                }
                String str = CoreXmlSqlParsersFactory
                        .getSql("ComMaterialStandard.MAXINDEX");
                Object[] obj = new Object[] { piccd };
                try {
                	PreparedStatement st = con.prepareStatement(str);
                	st.setObject(1, piccd);
                    ResultSet rs = st.executeQuery();
//                    ResultSet rs = db.ExceuteQueryForResultSet(
//                            str, obj);
                    if (rs.next()) {
                        int indexseq = rs.getInt(1);
                        if (indexseq > mapc.get(piccd)) {
                            indexseq += 1;
                            index = indexseq;
                            mapc.put(piccd, index);
                            clist.set(0, piccd);
                            clist.set(1, index);
                        }
                        else {
                            index = mapc.get(piccd);
                            index += 1;
                            mapc.put(piccd, index);
                            clist.set(0, piccd);
                            clist.set(1, index);
                        }
                    }
                    else { // 数据库不存在序号
                        index = mapc.get(piccd);
                        index += 1;
                        mapc.put(piccd, index);
                        clist.set(0, piccd);
                        clist.set(1, index);
                    }
                    rs.close();
                    st.close();
                }
                catch (SQLException e) {
                    CoreIComponent.logAdapter.filelogger.logError(e.getMessage());// 将服务端的错误信息写入日志文件
                }

                if(!pics.contains(clist.get(0))){
                	pics.add(clist.get(0).toString());
                }
                params.add(clist.toArray());
            }
            
            for (int i = 0; i < updateChild.size(); i++) {
                ArrayList <Object> list = (ArrayList<Object>)updateChild.get(i);
                sqlList.add(CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.UPDATE1"));
                if(!pics.contains(list.get(0))){
                	pics.add(list.get(0).toString());
                }
                params.add(list.toArray());
            }
            
            //处理试样组序号
            for(String pic : pics){
            	SqlBuilder b = new SqlBuilder("ComMaterialStandard.setPhyMinSeq");
            	b.Fill(new String[]{ pic });
            	sqlList.add(b.toString());
            	params.add(null);
            }
            
            
            return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqlList, params);
    	}catch(Exception ex){
    		String s = ex.getMessage();
    		return new CoreReturnObject();
    	}
    	finally{
    		if(con != null){
    			try {
					con.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    	}
    }

    /**
     * 材质标准管理
     * @param listBase 主表项
     * @param listChild 从表项
     * @param flag 标识
     * @return 删除或者恢复
     */
    public CoreReturnObject deleteComMaterial(ArrayList<ArrayList<Object>> listBase,
            ArrayList<ArrayList<Object>> listChild, Boolean flag) {
        ArrayList<String> sqlIDlist = new ArrayList<String>();
        ArrayList<Object[]> params = new ArrayList<Object[]>();
        for (int i = 0; i < listBase.size(); i++) {
            if (flag) {
                sqlIDlist.add("ComMaterialStandard.DELETE");
                sqlIDlist.add("ComMaterialStandard.DELETE2"); // 删除主表记录下的从表记录
                params.add(listBase.get(i).toArray());
                params.add(listBase.get(i).toArray());
            }
            else {
                sqlIDlist.add("ComMaterialStandard.RESUME");
                params.add(listBase.get(i).toArray());
            }
        }
        for (int i = 0; i < listChild.size(); i++) {
            if (flag) {
                sqlIDlist.add("ComMaterialStandard.DELETE1");
                ArrayList<Object> list = (ArrayList<Object>)listChild.get(i);
                list.add(list.get(2));
                params.add(list.toArray());
            }

            else {
                sqlIDlist.add("ComMaterialStandard.RESUME1");
                params.add(listChild.get(i).toArray());
            }

        }
        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("ComMaterialStandard.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("ComMaterialStandard.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("ComMaterialStandard.CancelGroupSeq"));
                parmlist.add(list.toArray());
            }
        }
        cro = this.getDao("TgDao").ExcuteTransction(sqlIDList, parmlist);
        return cro;
    }
    
    /**
     * 通过Pic获取理化表
     * @param pic
     * @return obj
     */
    public CoreReturnObject getComPicByPic(String pic){
    	String sql = CoreXmlSqlParsersFactory.getSql("ComMaterialStandard.getComPicByPic");
    	sql = StringTool.ReplaceAll(sql, "#PIC#", pic);
    	return this.getData(sql);
    }
    
    /**
     * 获取试样组序号
     * @param pic
     * @param phyCodeMin
     * @param itemCodeF
     * @param itemCodeW
     * @param itemCodeS
     * @return
     */
    public CoreReturnObject getPhyMinSeq(String pic, String phyCodeMin, String itemCodeF,
    		String itemCodeW, String itemCodeS){
    	SqlBuilder b = new SqlBuilder("ComMaterialStandard.getPhyMinSeq");
    	b.Fill(new String[]{ pic, phyCodeMin, itemCodeF, itemCodeW, itemCodeS });
    	
    	return this.getData(b.toString());
    }
}
