package com.steering.pss.qcm;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import net.sf.json.JSONObject;
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.EntityTool;
import com.steering.comm.tools.SqlBuilder;
import com.steering.comm.tools.StringTool;
import com.steering.comm.tools.TransctionTool;
import com.steering.pss.qcm.model.GenericEntity;
import com.steering.pss.qcm.model.MscBlEntity;
import com.steering.pss.qcm.model.MscEntity;
import com.steering.pss.qcm.model.PscEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignBL;

public class BLCodeManage extends DBCommon {

    public CoreReturnObject GetBLStd() {
        return this.getDataBySqlID("BLCodeManage.InitBLSTD"); // 标准描述
    }
    
    public CoreReturnObject getComBaseStdAlpha(String stdCode) {
        SqlBuilder b = new SqlBuilder("BLCodeManage.getComBaseStdAlpha");
        b.Fill(new String[]{stdCode});
        return this.getData(b.toString());
    }

    public CoreReturnObject GetBLStd_Alpha(String stdCode) {
    	String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.InitBLSTD_ALPHA");
    	sql = StringTool.ReplaceAll(sql, "#STD_CODE#", stdCode);
        return this.getData(sql); // Alpha描述
    }

    public CoreReturnObject GetBLSType() {
        return this.getDataBySqlID("BLCodeManage.InitBLSTDTYPE"); // 标准类型描述
    }

    /**
     * Title: doQuery
     * Description:  查询
     * @param includeInvalid true 有效数据 false 有效+无效数据 
     * @param parms   查询参数
     * @return 平台统一返回对象
     */
    public CoreReturnObject doQuery(Boolean includeInvalid,
            ArrayList<Object> parms) {
        String deletedFlag = includeInvalid ? "0" : "";
        String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.QUERY");
        sql = StringTool.ReplaceAll(sql, "#PRODUCNAME#", parms.get(0).toString());
        sql = StringTool.ReplaceAll(sql, "#STD_NAME#", parms.get(1).toString());
        sql = StringTool.ReplaceAll(sql, "#STEELNAME#", parms.get(2).toString());
        sql = StringTool.ReplaceAll(sql, "#STD_STYLE_DESC#", parms.get(3).toString());
        sql = StringTool.ReplaceAll(sql, "#MODEL_DESC#", parms.get(4).toString());
        sql = StringTool.ReplaceAll(sql, "#STEELCODE#", parms.get(5).toString());
        sql = sql.replace("#STEELCODE2#", parms.get(5).toString());
        sql = StringTool.ReplaceAll(sql, "#MIN_D#", parms.get(6).toString());
        sql = StringTool.ReplaceAll(sql, "#MIN_H#", parms.get(7).toString());
        sql = StringTool.ReplaceAll(sql, "#VALIDFLAG#", deletedFlag);
        sql = StringTool.ReplaceAll(sql, "#STD_CODE#", parms.get(8).toString());
        sql = StringTool.ReplaceAll(sql, "#KEY_JG#", parms.get(9).toString());
        return this.getData(sql);
    }

    /**
     * Title: doQuery1
     * Description: BLCodeManage.cs界面的查询
     * @return 平台统一返回对象
     */
    public CoreReturnObject doQuery1() {
        return this.getDataBySqlID("BLCodeManage.QUERY1");
    }
    
    /**
     * 根据接箍代码查询与其关联的备料码.
     * @return obj
     */
    public CoreReturnObject queryJgRBl(String codeJg, String custAlphaNo, String alphaCode){
        Object[] params = new Object[]{codeJg, custAlphaNo, alphaCode};
        return this.getDataBySqlID("BLCodeManage.queryJgRBl", params);
    }
    
    /**
     * 冶金规范中的备料查询
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject queryWithMsc(ArrayList<String> list){
        return this.getDataBySqlID("BLCodeManage.QueryWithMsc", list.toArray());
    }

    /**
     * Title: doAdd
     * Description: 新增备料码
     * @return 平台统一返回对象
     */
    public CoreReturnObject doAdd(String strJSONBl, String strJSONPsc) {
    	TransctionTool transction = new TransctionTool();
    	CoreReturnObject cro = new CoreReturnObject();
    	try{
	    	JSONObject objBl = JSONObject.fromObject(strJSONBl);
	    	MscBlEntity mscBlEntity = (MscBlEntity)JSONObject.toBean(objBl, MscBlEntity.class);
	    	
	    	JSONObject objPsc = JSONObject.fromObject(strJSONPsc);
	    	PscEntity pscEntity = (PscEntity)JSONObject.toBean(objPsc, PscEntity.class);
	    	boolean result = false;
    	
	    	Connection con = transction.getCon();
	    	
	        String blcode = "";
	        String str = CoreXmlSqlParsersFactory.getSql("BLCodeManage.GetBLCode"); //取得最大编号的SQL语句
	        try {//自动生成BL码
	            ResultSet rs = this.getDao("TgDao").ExceuteQueryForResultSet(str);
	            if (rs.next()) {//取得最大编号
	                blcode = rs.getString(1).toString().substring(2, 7); //Java的substring两个参数都是索引，且返回第二个参数-1的字符
	                long code = Long.parseLong(blcode);
	                if (code == 99999) {
	                    cro = cro.SetErrInfo("备料编码已经达到最大，请清理数据库");
	                    return cro;
	                }
	                else {//编号加1再加上BL前缀。
	                    code += 1;
	                    blcode = "0000" + String.valueOf(code);
	                    blcode = blcode.substring(blcode.length()-5,blcode.length() );
	                    blcode = "BL" + blcode;
	                }
	            }
	            else {//如果数据库没有值，则第一个添加的序号为BL00001
	                blcode = "BL00001";
	            }
	            mscBlEntity.setPscBl(blcode);
	        }
	        catch (SQLException e) {
	            // TODO Auto-generated catch block
	            CoreIComponent.logAdapter.filelogger.logError(e.getMessage());// 将服务端的错误信息写入日志文件
	        }
	        String slqGetPsc = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getPsc");
	        slqGetPsc = EntityTool.fillSqlByEntity(slqGetPsc, mscBlEntity);
	        ArrayList<PscEntity> listPsc = EntityTool.getEntitysBySqlNoClsCon(slqGetPsc, con, PscEntity.class);
	        if(listPsc.size() > 0){
	        	pscEntity.setPsc(listPsc.get(0).getPsc());
	        	pscEntity.setPscDesc(listPsc.get(0).getPscDesc());
	        }else{
	        	String slqGetMaxPsc = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getMaxPsc");
	        	ArrayList<GenericEntity> listMaxPsc = EntityTool.getEntitysBySqlNoClsCon(slqGetMaxPsc, con, GenericEntity.class);
	        	pscEntity.setPsc(listMaxPsc.get(0).getMaxValue());
	        	String pscDesc = getPscDesc(mscBlEntity);
	        	pscEntity.setPscDesc(pscDesc);
	        }
	        
	        String sqlInsertBl = CoreXmlSqlParsersFactory.getSql("BLCodeManage.ADD");
	        sqlInsertBl = EntityTool.fillSqlByEntity(sqlInsertBl, mscBlEntity);
	        sqlInsertBl = EntityTool.fillSqlByEntity(sqlInsertBl, pscEntity);
	        result = transction.ExcuteTransction(sqlInsertBl);
	        if(result == false){
	        	return transction.rollBack();
	        }
	        
	        cro = insertMscByPscBl(pscEntity, mscBlEntity, transction);
	        if(cro.getV_errCode() == -1){
	        	return cro;
	        }
	        
	        cro = transction.commit();
	        
	      //质量设计备料码
	        QualityDesignBL qualityDesignBL = new QualityDesignBL();
	        qualityDesignBL.qualityDesignBL(mscBlEntity.getPscBl(), mscBlEntity.getCreateName());
	        return cro;
	        
    	}catch(Exception ex){
    		cro = transction.rollBack();
			cro.setV_errMsg(ex.getMessage());
			return cro;
    	}
    }
    
    /**
     * 获取产品描述（品名+标准类别+钢级+标准名称）
     * @param mscBlEntity
     * @return
     */
    private String getPscDesc(MscBlEntity mscBlEntity){
    	String pscDesc = mscBlEntity.getProducname();
    	if(pscDesc.equals("")){
    		pscDesc += mscBlEntity.getStdStyleDesc();
    	}else{
    		if(!mscBlEntity.getStdStyleDesc().equals("")){
    			pscDesc += "," + mscBlEntity.getStdStyleDesc();
    		}
    	}
    	if(pscDesc.equals("")){
    		pscDesc += mscBlEntity.getSteelname();
    	}else{
    		if(!mscBlEntity.getSteelname().equals("")){
    			if(mscBlEntity.getStdStyleDesc().equals("")){
    				pscDesc += "," +  mscBlEntity.getSteelname();
    			}else{
    				pscDesc += " " + mscBlEntity.getSteelname();
    			}
    		}
    	}
    	if(pscDesc.equals("")){
    		pscDesc += mscBlEntity.getStdName();
    	}else{
    		if(!mscBlEntity.getStdName().equals("")){
    			pscDesc += "," + mscBlEntity.getStdName();
    		}
    	}
    	return pscDesc;
    }

    /**
     * Title: doUpdate
     * Description: 修改数据
     * @return   平台统一返回对象
     */
    public CoreReturnObject doUpdate(String strJSONBl, String strJSONPsc) {
    	TransctionTool transction = new TransctionTool();
    	try{
	    	JSONObject objBl = JSONObject.fromObject(strJSONBl);
	    	MscBlEntity mscBlEntity = (MscBlEntity)JSONObject.toBean(objBl, MscBlEntity.class);
	    	
	    	JSONObject objPsc = JSONObject.fromObject(strJSONPsc);
	    	PscEntity pscEntity = (PscEntity)JSONObject.toBean(objPsc, PscEntity.class);
	    	
	    	boolean result = false;
    	
	    	Connection con = transction.getCon();
	    	String slqGetPsc = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getPsc");
	        slqGetPsc = EntityTool.fillSqlByEntity(slqGetPsc, mscBlEntity);
	        ArrayList<PscEntity> listPsc = EntityTool.getEntitysBySqlNoClsCon(slqGetPsc, con, PscEntity.class);
	        if(listPsc.size() > 0){
	        	pscEntity.setPsc(listPsc.get(0).getPsc());
	        	pscEntity.setPscDesc(listPsc.get(0).getPscDesc());
	        }else{
	        	String slqGetMaxPsc = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getMaxPsc");
	        	ArrayList<GenericEntity> listMaxPsc = EntityTool.getEntitysBySqlNoClsCon(slqGetMaxPsc, con, GenericEntity.class);
	        	pscEntity.setPsc(listMaxPsc.get(0).getMaxValue());
	        	String pscDesc = getPscDesc(mscBlEntity);
	        	pscEntity.setPscDesc(pscDesc);
	        }
	        
	        String sqlInsertBl = CoreXmlSqlParsersFactory.getSql("BLCodeManage.UPDATE");
	        sqlInsertBl = EntityTool.fillSqlByEntity(sqlInsertBl, mscBlEntity);
	        sqlInsertBl = EntityTool.fillSqlByEntity(sqlInsertBl, pscEntity);
	        result = transction.ExcuteTransction(sqlInsertBl);
	        if(result == false){
	        	return transction.rollBack();
	        }
	        
	        CoreReturnObject cro = insertMscByPscBl(pscEntity, mscBlEntity, transction);
	        if(cro.getV_errCode() == -1){
	        	return cro;
	        }
	        
	      //质量设计备料码
	        QualityDesignBL qualityDesignBL = new QualityDesignBL();
	        qualityDesignBL.qualityDesignBL(mscBlEntity.getPscBl(), mscBlEntity.getUpdateName());
	        
	        return transction.commit();
    	}catch(Exception ex){
    		CoreReturnObject cro = transction.rollBack();
			cro.setV_errMsg(ex.getMessage());
			return cro;
    	}
    }
    
    /**
     * 通过产品和BL生成MSC
     * @param pscEntity
     * @param mscBlEntity
     * @param transction
     * @return
     */
    private CoreReturnObject insertMscByPscBl(PscEntity pscEntity, MscBlEntity mscBlEntity, TransctionTool transction){
    	boolean result = false;
    	Connection con = transction.getCon();
    	String sqlGetComPsc = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getComPsc");
        sqlGetComPsc = EntityTool.fillSqlByEntity(sqlGetComPsc, pscEntity);
        ArrayList<PscEntity> listPscEntity = EntityTool.getEntitysBySqlNoClsCon(sqlGetComPsc, con, PscEntity.class);
        String useCode = listPscEntity.get(0).getStdCode() + "000";
        String useDesc = "/";
        //MSC0
        String sqlGetStdMscByPsc = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getStdMscByPsc");
        sqlGetStdMscByPsc = StringTool.ReplaceAll(sqlGetStdMscByPsc, "#PSC#", pscEntity.getPsc());
        ArrayList<MscEntity> listStdMsc = EntityTool.getEntitysBySqlNoClsCon(sqlGetStdMscByPsc, con, MscEntity.class);
        if(listStdMsc.size() == 0){
	        CoreProductManage cpm = new CoreProductManage();
	        MscEntity mscEntity = new MscEntity();
	        mscEntity.setUseCode(useCode);
	        mscEntity.setUseDesc(useDesc);
	        listPscEntity.get(0).setCreateName(mscBlEntity.getCreateName());
	        String sqlInsertMsc = cpm.getInsertMscSql(listPscEntity.get(0), mscEntity, "BL");
	        result = transction.ExcuteTransction(sqlInsertMsc);
	        if(result == false){
	        	return transction.rollBack();
	        }
        }
        
        //MSCn
        sqlGetStdMscByPsc = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getStdMscByPsc");
        sqlGetStdMscByPsc = StringTool.ReplaceAll(sqlGetStdMscByPsc, "#PSC#", pscEntity.getPsc());
        listStdMsc = EntityTool.getEntitysBySqlNoClsCon(sqlGetStdMscByPsc, con, MscEntity.class);
        String sqlGetMscByPscUseCode = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getMscByPscUseCode");
        sqlGetMscByPscUseCode = StringTool.ReplaceAll(sqlGetMscByPscUseCode, "#PSC#", pscEntity.getPsc());
        sqlGetMscByPscUseCode = StringTool.ReplaceAll(sqlGetMscByPscUseCode, "#USE_CODE#", mscBlEntity.getUseCode());
        ArrayList<GenericEntity> listMsc = EntityTool.getEntitysBySqlNoClsCon(sqlGetMscByPscUseCode, con, GenericEntity.class);
        if(listMsc.size() == 0){
	        CoreProductManage cpm = new CoreProductManage();
	        MscEntity mscEntity = new MscEntity();
	        mscEntity.setUseCode(mscBlEntity.getUseCode());
	        mscEntity.setUseDesc(mscBlEntity.getUseDesc());
	        mscEntity.setMscSeq(listStdMsc.get(0).getMsc());
	        mscEntity.setMscDescSeq(listStdMsc.get(0).getMscDesc());
	        listPscEntity.get(0).setCreateName(mscBlEntity.getCreateName());
	        String sqlInsertMsc = cpm.getInsertMscSql(listPscEntity.get(0), mscEntity, "BL");
	        result = transction.ExcuteTransction(sqlInsertMsc);
	        if(result == false){
	        	return transction.rollBack();
	        }
        }
        CoreReturnObject cro = new CoreReturnObject();
        cro.setV_errCode(0);
        return cro;
    }

    /**
     * Title: doDeleteOrResume
     * Description:  恢复或删除
     * @param code 备料码
     * @param deletename   删除人
     * @param flag  true 删除  false 恢复
     * @return  平台统一返回对象
     */
    public CoreReturnObject doDeleteOrResume(String code, String deletename,
            Boolean flag) {
        if (flag) {
            Object[] params = new Object[] { deletename, code };
            return this.setDataBySqlID("BLCodeManage.DELETE", params);
        }
        else {
            Object[] params = new Object[] { code };
            return this.setDataBySqlID("BLCodeManage.RESUME", params);
        }
    }
    
    public CoreReturnObject isCompleteMsc(String blCode, String alpha){
        Object[] params = new Object[]{blCode, blCode, blCode, blCode, 
                blCode, blCode, blCode, alpha, alpha, alpha, blCode,
                blCode, blCode, blCode, alpha, alpha, alpha, blCode,
                blCode, blCode, blCode, alpha, alpha, alpha, blCode,
                blCode, blCode, blCode, alpha, alpha, alpha, blCode,
                blCode, blCode, blCode, alpha, alpha, alpha, blCode};
        return this.getDataBySqlID("BLCodeManage.isCompleteMsc", params);
    }
    
    public CoreReturnObject group(ArrayList<ArrayList<String>> list){
        ArrayList<String> sqllist = new ArrayList<String>();
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        for (ArrayList<String> arrayList : list) {
            sqllist.add(CoreXmlSqlParsersFactory.getSql("BLCodeManage.Group"));
            parmlist.add(arrayList.toArray());
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(sqllist, parmlist);
    }
    
    /**
     * 备料码是否存在
     * @return
     */
    public CoreReturnObject isExistBl(ArrayList<String> list){
        return this.getDataBySqlID("BLCodeManage.isExistBl", list.toArray());
    }
    
    /**
     * 新增备料码记录到产品表中
     * @param list
     * @return obj
     */
    public CoreReturnObject insertBlToPsc(ArrayList<String> list){
    	String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.insertBlToPsc");
    	sql = sql.replaceFirst(":PRODUCCODE:", list.get(0));
    	sql = sql.replaceFirst(":PRODUCNAME:", list.get(1));
    	sql = sql.replaceFirst(":STD_CODE:", list.get(2));
    	sql = sql.replaceFirst(":STD_NAME:", list.get(3));
    	sql = sql.replaceFirst(":STEELCODE:", list.get(4));
    	sql = sql.replaceFirst(":STEELNAME:", list.get(5));
    	sql = sql.replaceFirst(":STD_STYLE:", list.get(6));
    	sql = sql.replaceFirst(":STD_STYLE_DESC:", list.get(7));
    	sql = sql.replaceFirst(":DEPARTMENT_CODE:", list.get(8));
    	sql = sql.replaceFirst(":DEPARTMENT_DESC:", list.get(9));
    	sql = sql.replaceFirst(":UNIT_CODE:", list.get(10));
    	sql = sql.replaceFirst(":UNIT_DESC:", list.get(11));
    	sql = sql.replaceFirst(":CREATE_NAME:", list.get(12));
        return this.setData(sql);
    }
    
    /**
     * 查询产品规范码。
     * @param list 参数(品名、标准、钢级、标准类别)
     * @return obj
     */
    public CoreReturnObject queryPscCode(ArrayList<String> list) {
    	String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.queryPscCode");
    	sql = StringTool.ReplaceAll(sql, "#PRODUCCODE#", list.get(0));
    	sql = StringTool.ReplaceAll(sql, "#STD_CODE#", list.get(1));
    	sql = StringTool.ReplaceAll(sql, "#STEELCODE#", list.get(2));
    	sql = StringTool.ReplaceAll(sql, "#STD_STYLE#", list.get(3));
    	
        return this.getData(sql);
    }
    
    /**
     * 是否被引用。
     * @param blCode
     * @return
     */
    public CoreReturnObject queryIsRef(String blCode){
    	String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.queryIsRef");
    	sql = StringTool.ReplaceAll(sql, "#BL_CODE#", blCode);
    	
    	return this.getData(sql);
    }
    
    /**
     * 查询备料表
     * @param blCode
     * @return
     */
    public CoreReturnObject queryMscBlByPk(String blCode){
    	String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.queryMscBlByPk");
    	sql = StringTool.ReplaceAll(sql, "#PSC_BL#", blCode);
    	return this.getData(sql);
    }
    
    /**
     * 修改评审状态
     * @param state
     * @param blCode
     * @return
     */
    public CoreReturnObject updateReviewStateByPk(String state, String blCode){
    	String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.updateReviewStateByPk");
    	sql = StringTool.ReplaceAll(sql, "#REVIEW_STATUS#", state);
    	sql = StringTool.ReplaceAll(sql, "#PSC_BL#", blCode);
    	sql = StringTool.ReplaceAll(sql, "#DESGIN_KEY#", "");
    	return this.setData(sql);
    }
    
    /**
     * 查询备料管是否被引用
     * @param blCode
     * @return
     */
    public CoreReturnObject getIsRef(String blCode){
    	String sql = CoreXmlSqlParsersFactory.getSql("BLCodeManage.getRefCnt");
    	sql = StringTool.ReplaceAll(sql, "#CODE_JG#", blCode);
    	sql = StringTool.ReplaceAll(sql, "#PSC_BL#", blCode);
    	return this.getData(sql);
    }
    
    /**
     * 通过备料码获取对应的PSC
     * @param blCode
     * @return
     */
    public CoreReturnObject getPscByBl(String blCode){
    	SqlBuilder b = new SqlBuilder("BLCodeManage.getPscByBl");
    	b.Fill(new String[]{blCode});
    	return this.getData(b.toString());
    }
    
    /**
     * 获取被使用的合同
     * @param blCode
     * @return
     */
    public CoreReturnObject getUseOrder(String blCode){
    	SqlBuilder b = new SqlBuilder("BLCodeManage.getUseOrder");
    	b.Fill(new String[]{blCode});
    	
    	return this.getData(b.toString());
    }
}
