package com.steering.mes.mcp.heatTreatment;

import CoreFS.SA06.CoreReturnObject;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;
import com.steering.comm.converter.QualityDesignTool;
import com.steering.comm.db.DBCommon;
import com.steering.common.EntityTool;
import com.steering.mes.mcp.collarMaterial.MeanValueCalculation;
import com.steering.mes.mcp.entity.VrpMatZcMEntity;

public class FrmHttApply extends DBCommon {

    /**
     * 查询炉计划
     * @param list
     * @param startTim
     * @param endTim
     * @return
     */
    public CoreReturnObject doQueryLibrary(String jubNo, String start,
            String end) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmHttApply.doQueryLibrary");
        if (!start.equals("")) {
            sql += " AND T.CREATE_TIME >=TO_DATE('"
                    + start
                    + "', 'YYYY-MM-DD HH24:MI:SS')AND T.CREATE_TIME <=TO_DATE('"
                    + end + "', 'YYYY-MM-DD HH24:MI:SS') ";
        }
        if (!jubNo.equals("")) {
            sql += " AND T.JUDGE_STOVE_NO || '&' LIKE '%' || '" + jubNo
                    + "' || '%'";
        }
        sql += " GROUP BY  T.ORDER_NO,T.ORDER_SEQ,T.DELIVERY_NO,T.JUDGE_STOVE_NO,"
                + "T.BATCH_NO,T.GRADECODE, T.GRADENAME,T.OUTWL_ID,T.OUTWL_DESC, "
                + "T1.PRODUCCODE,T1.PRODUCNAME,T1.STD_CODE,T1.STD_NAME, T1.STEELCODE,T1.STEELNAME,"
                + "T1.SPEC_CODE,T1.SPEC_NAME,T1.MODEL_CODE,T1.MODEL_DESC,T1.LENGTHMIN,T1.LENGTHMAX, "
                + "T1.STD_STYLE_DESC,T.CREATE_NAME,TO_CHAR(T.CREATE_TIME,'YYYY-MM-DD'),T.ISENDGX,T.CRAFT_FILE_NO,"
                + " T.ZY_BATCH_ID,TH.BATCH_GROUD_NO) T3";
        sql += "  ORDER BY T3.JUDGE_STOVE_NO, T3.ZG_BATCH_NO ASC ";
        return this.getData(sql);
    }

    /**
     * 查询炉批信息
     * @param list
     * @param startTim
     * @param endTim
     * @return
     */
    public CoreReturnObject doQueryMatZcM(String heatPlanNo, String batchNo,
            String groupNo, String value) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmHttApply.doQueryMatZcM");

        if (value.equals("0")) {
            sql = sql.replace("#HTT_JUGDE_APPLY_CODE#",
                    " AND T1.HTT_JUGDE_APPLY_CODE IS NULL");
        }
        else if (value.equals("1")) {
            sql = sql.replace("#HTT_JUGDE_APPLY_CODE#",
                    " AND T1.HTT_JUGDE_APPLY_CODE IS NOT NULL");
        }
        else {
            sql = sql.replace("#HTT_JUGDE_APPLY_CODE#", "");
        }
        return this.getData(sql, new Object[] { heatPlanNo, batchNo });
    }

   

    /**
     * 材料类别
     * @return
     */
    public CoreReturnObject getProductflag(String storaCode) {
        return this.getDataBySqlID("FrmHttApply.getProductflag",
                new Object[] { storaCode });
    }

    /***
     * 获取材料表实体类
     * @param con
     * @param heatNo
     * @return
     * @throws SQLException
     */
    public static VrpMatZcMEntity getVrpMatNo(Connection con, String judNo,
            String batchNo, String groupNo) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmHttApply.doQueryVrpMatNo");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, judNo);
        ps.setObject(2, batchNo);
        ps.setObject(3, groupNo);
        ResultSet rs = ps.executeQuery();
        List<VrpMatZcMEntity> sendPlanCEntitys = EntityTool.getEntitysByRs(rs,
                VrpMatZcMEntity.class);
        rs.close();
        ps.close();
        if (sendPlanCEntitys == null || sendPlanCEntitys.size() == 0) {
            return null;
        }
        else {
            for (VrpMatZcMEntity sendPlanCEntity : sendPlanCEntitys) {
                QualityDesignTool.nullConverNullString(sendPlanCEntity);
            }
            return sendPlanCEntitys.get(0);
        }
    }

    /***
     * 申请判定
     * @param parm
     * @return
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doApplyDec(ArrayList<Object> parm, String herdNo) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String systime = dateFormat.format(now);
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        String jugdeApplyNo = "";// 判定单号
        int prossWtCount = 0;
        String prnFlag = "";// 是否需过磅
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String updateSql = CoreXmlSqlParsersFactory
                    .getSql("FrmHttApply.doDecision");// 修改材料表判定单号
            PreparedStatement updatePsta = connection
                    .prepareStatement(updateSql);
            String updateProt = CoreXmlSqlParsersFactory
                    .getSql("FrmHttApply.doUpdateProt");// 修改管号队列判定单号
            PreparedStatement pstaProt = connection
                    .prepareStatement(updateProt);
            String insertJugeApplySql = CoreXmlSqlParsersFactory
                    .getSql("FrmHttApply.insertJugeApply");// 插入判定表
            PreparedStatement insertJugeApplyPsta = connection
                    .prepareStatement(insertJugeApplySql);

            for (int i = 0; i < parm.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) parm.get(i);
                String juduNo = list.get(0);
                String batchNo = list.get(1);
                String groupNo = list.get(2);
                String name = list.get(3);
                String bc = list.get(4);
                String bz = list.get(5);
                String plineCode = list.get(6);
                String produFlag = list.get(7);
                String deid = list.get(8);
                String dename = list.get(9);
                String ismgx = list.get(10);
                String scpch = list.get(11);
                String gywjh = list.get(12);
                // VrpMatZcMEntity vrpMat = getVrpMatNo(connection, juduNo,
                // batchNo, groupNo);
                // List<VrpMatZcMEntity> mat = new ArrayList<VrpMatZcMEntity>();
                // sql = CoreXmlSqlParsersFactory
                // .getSql("FrmHttApply.doQueryVrpMatNo");// 查询材料表信息
                // psta = connection.prepareStatement(sql);
                // psta.setObject(1, juduNo);
                // psta.setObject(2, batchNo);
                // psta.setObject(3, groupNo);
                // rs = psta.executeQuery();
                // mat = EntityTool.getEntitysByRs(rs, VrpMatZcMEntity.class);
                // rs.close();
                // psta.close();

                sql = CoreXmlSqlParsersFactory
                        .getSql("FrmHttApply.jugdeApplyNo");// 生成判定单号
                psta = connection.prepareStatement(sql);
                psta.setObject(1, plineCode);
                psta.setObject(2, "F");
                psta.setObject(3, plineCode);
                psta.setObject(4, "F");
                rs = psta.executeQuery();
                if (rs.next()) {
                    jugdeApplyNo = rs.getString("JUGDE_APPLY_CODE");
                }
                rs.close();
                psta.close();
                // for (VrpMatZcMEntity vrpMatNo : mat) {
                // 修改材料表申请判定单号
                updatePsta.setObject(1, jugdeApplyNo);
                updatePsta.setObject(2, systime);
                updatePsta.setObject(3, juduNo);
                updatePsta.setObject(4, batchNo);
                updatePsta.setObject(5, groupNo);
                updatePsta.addBatch();
                // }

                insertJugeApplyPsta.setString(1, juduNo);
                insertJugeApplyPsta.setString(2, batchNo);
                insertJugeApplyPsta.setString(3, groupNo);
                insertJugeApplyPsta.setString(4, plineCode);
                insertJugeApplyPsta.setString(5, juduNo);
                insertJugeApplyPsta.setString(6, batchNo);
                insertJugeApplyPsta.setString(7, groupNo);
                insertJugeApplyPsta.setString(8, plineCode);
                insertJugeApplyPsta.setString(9, jugdeApplyNo);
                insertJugeApplyPsta.setString(10, name);
                insertJugeApplyPsta.setString(11, systime);
                insertJugeApplyPsta.setString(12, scpch);// 生产批次号
                insertJugeApplyPsta.setString(13, gywjh);// 工艺文件号
                insertJugeApplyPsta.setString(14, deid);
                insertJugeApplyPsta.setString(15, dename);
                insertJugeApplyPsta.setString(16, ismgx);
                insertJugeApplyPsta.addBatch();

//                sql = CoreXmlSqlParsersFactory
//                        .getSql("FrmInOnlineStore.doQueryMilPlanPrt");
//                psta = connection.prepareStatement(sql);
//                psta.setString(1, juduNo);
//                rs = psta.executeQuery();
//                if (rs.next()) {
//                    prnFlag = rs.getString("PRT_FLAG");
//                }
//                rs.close();
//                psta.close();
//                if (prnFlag.equals("1")) {
//                    sql = CoreXmlSqlParsersFactory
//                            .getSql("FrmInOnlineStore.SelectPorssWt");
//                    psta = connection.prepareStatement(sql);
//                    psta.setString(1, juduNo);
//                    rs = psta.executeQuery();
//                    if (rs.next()) {
//                        prossWtCount = Integer.parseInt(rs.getString("ACOUNT"));
//                    }
//                    rs.close();
//                    psta.close();
//                    if (prossWtCount > 0) {
//                        cro.setV_errMsg("此炉需回报过磅重量才能进行申请判定!");
//                        return cro;
//                    }
//                }

            }
            insertJugeApplyPsta.executeBatch();
            updatePsta.executeBatch();

            pstaProt.setObject(1, jugdeApplyNo);
            pstaProt.setObject(2, "1");
            pstaProt.setObject(3, herdNo);
            pstaProt.addBatch();
            pstaProt.executeBatch();
            cro.setV_errMsg("申请判定成功!");
            connection.commit();
        }
        catch (SQLException e) {
            System.out.println(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
    }

    /***
     * 撤销申请判定
     * @param parm
     * @return
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject DoUndoApply(ArrayList<Object> parm, String herdNo) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String sql = "";
            PreparedStatement psta = null;
            ResultSet rs = null;
            String acount = "";
            String updateMatZcSql = CoreXmlSqlParsersFactory
                    .getSql("FrmHttApply.cancelDoDecision");
            PreparedStatement updateMatZcPsta = connection
                    .prepareStatement(updateMatZcSql);
            String updateProt = CoreXmlSqlParsersFactory
                    .getSql("FrmHttApply.doUpdateProt");// 修改管号队列判定单号
            PreparedStatement pstaProt = connection
                    .prepareStatement(updateProt);
            for (int i = 0; i < parm.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) parm.get(i);
                String juduNo = list.get(0);
                String batchNo = list.get(1);
                String groupNo = list.get(2);
                // String name = list.get(3);
                // String plineCode = list.get(4);
                // String produFlag = list.get(5);
                String vrpApplyCode = list.get(6);// 申请判定单号

                if (vrpApplyCode.equals("")) {
                    cro.setV_errMsg("炉号'" + juduNo + "'未进行申请判定,不能进行撤销!");
                    return cro;
                }
                sql = CoreXmlSqlParsersFactory
                        .getSql("cancelDoDecision.doQuery");// 查询是否已判定
                psta = connection.prepareStatement(sql);
                psta.setString(1, vrpApplyCode);
                psta.setString(2, juduNo);
                psta.setString(3, batchNo);
                psta.setString(4, groupNo);
                rs = psta.executeQuery();
                if (rs.next()) {
                    acount = rs.getString("ACOUNT");
                }
                rs.close();
                psta.close();
                if (Integer.parseInt(acount) > 0) {
                    cro.setV_errMsg("炉号'" + juduNo + "'已有进行质量判定的材料,无法撤销申请!");
                    return cro;
                }

                sql = CoreXmlSqlParsersFactory
                        .getSql("cancelDoDecision.ReciveZB");// 查询是否已接收
                psta = connection.prepareStatement(sql);
                psta.setString(1, vrpApplyCode);
                psta.setString(2, juduNo);
                psta.setString(3, batchNo);
                psta.setString(4, groupNo);
                rs = psta.executeQuery();
                if (rs.next()) {
                    acount = rs.getString("ACOUNT");
                }
                rs.close();
                psta.close();
                if (Integer.parseInt(acount) > 0) {
                    cro.setV_errMsg("炉号'" + juduNo + "'已有正在进行质量判定,无法撤销申请!");
                    return cro;
                }

                updateMatZcPsta.setString(1, vrpApplyCode);
                updateMatZcPsta.setString(2, juduNo);
                updateMatZcPsta.setString(3, batchNo);
                updateMatZcPsta.setString(4, groupNo);
                updateMatZcPsta.setString(5, vrpApplyCode);
                updateMatZcPsta.setString(6, juduNo);
                updateMatZcPsta.setString(7, batchNo);
                updateMatZcPsta.setString(8, groupNo);
                updateMatZcPsta.addBatch();
            }
            updateMatZcPsta.executeBatch();

            pstaProt.setObject(1, "");
            pstaProt.setObject(2, "0");
            pstaProt.setObject(3, herdNo);
            pstaProt.addBatch();
            pstaProt.executeBatch();

            cro.setV_errMsg("撤销申请判定成功!");
            connection.commit();
        }
        catch (SQLException e) {
            System.out.println(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
    }

    /***
     * 查询是否有未送判的数据
     * @param jugeNo
     * @return
     */
    public CoreReturnObject doQueryApplyCodeNull(String jugeNo, String batchNo,
            String groupNo) {
        return this.getDataBySqlID("FrmHttApply.doQueryApplyCodeNull",
                new Object[] { jugeNo, batchNo });
    }

    /***
     * 回报过磅重量
     * @return
     */
    public CoreReturnObject doReturnWt(ArrayList<String> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sql = "";
        PreparedStatement psta = null;
        ResultSet rs = null;
        int acount = 0;
        int k = 0;
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String updateProssWtSql = CoreXmlSqlParsersFactory
                    .getSql("FrmHttApply.updatePossWt");// 修改材料表过磅重量
            PreparedStatement updateProssPsta = connection
                    .prepareStatement(updateProssWtSql);
            String updateVrpIn = CoreXmlSqlParsersFactory
                    .getSql("FrmHttApply.updateVrpInfo");// 修改公共实绩表过磅重量
            PreparedStatement updateVrpInPast = connection
                    .prepareStatement(updateVrpIn);

            String hePlanNo = list.get(0);
            String pgroWt = list.get(1);
            String juduNo = list.get(2);
            String batchNo = list.get(3);
            String groupNo = list.get(4);

            sql = CoreXmlSqlParsersFactory.getSql("FrmHttApply.selectCount");
            psta = connection.prepareStatement(sql);
            psta.setObject(1, juduNo);
            psta.setObject(2, batchNo);
            psta.setObject(3, groupNo);
            rs = psta.executeQuery();
            if (rs.next()) {
                acount = Integer.parseInt(rs.getString("ACOUNT"));
            }
            rs.close();
            psta.close();
            if (acount == 0) {
                cro.setV_errMsg("该炉计划信息已无炉信息!");
                return cro;
            }

            ArrayList<String> matNoList = new ArrayList<String>();
            // 查询材料号
            sql = CoreXmlSqlParsersFactory.getSql("FrmHttApply.selectMatNo");
            psta = connection.prepareStatement(sql);
            psta.setObject(1, juduNo);
            psta.setObject(2, batchNo);
            psta.setObject(3, groupNo);
            rs = psta.executeQuery();
            while (rs.next()) {
                matNoList.add(rs.getString("MAT_NO"));
            }
            rs.close();
            psta.close();
            List<double[]> list1 = MeanValueCalculation.MeanCalculation(Double
                    .parseDouble(pgroWt), acount);
            for (int j = 0; j < list1.size(); j++) {
                double[] conW = list1.get(j);
                if ((int) conW[0] >= 0) {
                    for (int z = 0; z < (int) conW[0]; z++) {
                        // 修改材料表过磅重量
                        updateProssPsta.setString(1, String.valueOf(conW[1]));
                        updateProssPsta.setString(2, matNoList.get(k));
                        updateProssPsta.setString(3, juduNo);
                        updateProssPsta.addBatch();
                        k++;
                    }
                }
            }
//            sql = CoreXmlSqlParsersFactory.getSql("FrmHttApply.selectMatNo");
//            psta = connection.prepareStatement(sql);
//            psta.setObject(1, juduNo);
//            psta.setObject(2, batchNo);
//            psta.setObject(3, groupNo);
//            rs = psta.executeQuery();
//            while (rs.next()) {
//                matNoList.add(rs.getString("MAT_NO"));
//            }
//            rs.close();
//            psta.close();
            // List<double[]> list2 =
            // MeanValueCalculation.MeanCalculation(Double
            // .parseDouble(pgroWt), acount);
            // for (int i = 0; i < list2.size(); i++) {
            // double[] conW = list2.get(i);
            // if ((int) conW[0] >= 0) {
            // for (int b = 0; b < (int) conW[0]; b++) {
            // updateVrpInPast.setObject(1, pgroWt);
            // updateVrpInPast.setObject(2, hePlanNo);
            // }
            // }
            // }
            updateVrpInPast.setObject(1, pgroWt);
            updateVrpInPast.setObject(2, hePlanNo);
            updateVrpInPast.addBatch();
            updateVrpInPast.executeBatch();
            updateProssPsta.executeBatch();

            cro.setV_errMsg("回报过磅重量成功!");
            connection.commit();
        }
        catch (SQLException e) {
            System.out.println(e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
    }
}
