package com.steering.pss.plnsaleord.planStove;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

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.pss.plnsaleord.planStove.entity.MatGpTrackEntity;
import com.steering.pss.plnsaleord.steelMarkingPlan.FrmSteelMakingPlanChange;
import com.steering.pss.plnsaleord.stove.entity.MatGpMEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnZyDzCEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnZyDzMEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnZyZgCEntity;
import com.steering.pss.plnsaleord.stove.entity.PlnZyZgMEntity;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;

public class FrmPlanStoveC extends DBCommon {
    private static double Pi = 3.1415926; // 圆周率

    /**
     * 查询锻造炉计划
     * @return
     */
    public CoreReturnObject queryPlanStoveC(String proPlanId, String gxPlanNo) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmPlanStoveC.queryPlanStoveC");
        return this.getData(sql, new Object[] { proPlanId, gxPlanNo });
    }

    /**
     * 通过炉计划号查询实际炉计划
     * @throws SQLException
     */
    public static List<PlnZyDzCEntity> getQureyZyDzC(Connection con,
            String heatPlanNo, String heatPlanNoSeq) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmPlanStoveC.getPlanZyDzC");
        if (!heatPlanNoSeq.equals("")) {
            sql += " AND T.HEAT_PLAN_SQE='" + heatPlanNoSeq + "'";
        }
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, heatPlanNo);
        ResultSet rs = ps.executeQuery();
        List<PlnZyDzCEntity> list = EntityTool.getEntitysByRs(rs,
                PlnZyDzCEntity.class);
        ps.close();
        rs.close();
        if (list == null || list.size() == 0) {
            return null;
        }
        else {
            for (PlnZyDzCEntity listL : list) {
                QualityDesignTool.nullConverNullString(listL);
            }
            return list;
        }
    }

    /**
     * 通过炉计划号查询虚拟炉计划
     * @throws SQLException
     */
    public static List<PlnZyDzMEntity> getQureyZyDzM(Connection con,
            String heatPlanNo) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmPlanStoveC.getPlanZyDzM");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, heatPlanNo);
        ResultSet rs = ps.executeQuery();
        List<PlnZyDzMEntity> list = EntityTool.getEntitysByRs(rs,
                PlnZyDzMEntity.class);
        ps.close();
        rs.close();
        if (list == null || list.size() == 0) {
            return null;
        }
        else {
            for (PlnZyDzMEntity listL : list) {
                QualityDesignTool.nullConverNullString(listL);
            }
            return list;
        }
    }

    /**
     * 锻造炉计划下发
     * @param jslist
     * @param userName 操作人
     * @throws ParseException
     */
    public CoreReturnObject doFurnacePlan(ArrayList<ArrayList<String>> jslist,
            String userName, String flag) throws ParseException {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            PreparedStatement ps = null;
            // ResultSet rs = null;
            // 获取数据库当前时间
            String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
            // 循环虚拟炉计划信息
            for (int i = 0; i < jslist.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) jslist.get(i);
                String heatPlanNo = list.get(0);
                // String heatPlanNoSeq = list.get(1);
                String planstatus = "";
                // 查询炉计划信息
                List<PlnZyDzMEntity> listDzM = getQureyZyDzM(conn, heatPlanNo);
                if (listDzM == null) {
                    cro.setV_errMsg("锻造炉计划已发生变化,请重新查询!");
                    return cro;
                }
                // List<PlnZyDzCEntity> listC = getQureyZyDzC(conn, heatPlanNo);
                for (PlnZyDzMEntity plnDzM : listDzM) {
                    if (flag.equals("1")) {// 撤销下发
                        planstatus = "00";
                        if (plnDzM.getSubcontractFlag().equals("1")) {
                            cro.setV_errMsg("选择的锻造炉计划已委外,不能撤销下发!");
                            return cro;
                        }
                        if (!plnDzM.getPlanstatus().equals("10")) {
                            cro.setV_errMsg("选择的锻造炉计划不是下发状态,不能撤销下发!");
                            return cro;
                        }
                    }
                    else {
                        planstatus = "10";
                        if (!plnDzM.getPlanstatus().equals("00")) {
                            cro.setV_errMsg("选择的锻造炉计划状态不是计划状态,不能下发!");
                            return cro;
                        }
                    }
                    // 修改轧管虚拟炉计划
                    String deleteZgM = "UPDATE PLN_ZY_DZ_M T SET T.PLANSTATUS=?,T.DOWNMAN=?,T.DOWNTIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS') WHERE T.HEAT_PLAN_NO=?";
                    ps = conn.prepareStatement(deleteZgM);
                    ps.setObject(1, planstatus);
                    ps.setObject(2, userName);
                    ps.setObject(3, dateTime);
                    ps.setObject(4, heatPlanNo);
                    ps.executeUpdate();
                    ps.close();
                }
            }
            if (flag.equals("1")) {
                cro.setV_errMsg("撤销成功!");
            }
            else {
                cro.setV_errMsg("下发成功!");
            }
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                if (conn != null) {
                    conn.rollback();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }

    /**
     * 查询坯子库存信息
     * @param con
     * @param judgeStoveNo 判定炉号
     * @throws SQLException
     */
    public static List<MatGpMEntity> getQureyMatGpCx(Connection con,
            String judgeStoveNo, double actLen, double fixLen, int cutNumGp,
            int takeCount, String proPlanId, String gxPlanNo)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmPlanStoveC.QueryMatGpCx");

        sql += " AND T.PRO_PLAN_ID_ZG='" + proPlanId + "' ";
        sql += " AND T.GX_PLAN_NO_ZG='" + gxPlanNo + "' ";
        sql += " ORDER BY T.MAT_NO ASC) WHERE ROWNUM <= ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, judgeStoveNo);
        ps.setObject(2, actLen);
        ps.setObject(3, fixLen);
        ps.setObject(4, cutNumGp);
        ps.setObject(5, takeCount);
        ResultSet rs = ps.executeQuery();
        List<MatGpMEntity> list = EntityTool.getEntitysByRs(rs,
                MatGpMEntity.class);
        ps.close();
        rs.close();
        if (list == null || list.size() == 0) {
            return null;
        }
        else {
            for (MatGpMEntity listL : list) {
                QualityDesignTool.nullConverNullString(listL);
            }
            return list;
        }
    }

    /**
     *锻造炉计划撤销
     * @param jslist
     * @param userName 操作人
     * @throws ParseException
     */
    public CoreReturnObject doDeleteZGC(ArrayList<ArrayList<String>> jslist,
            String userName) throws ParseException {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);
            PreparedStatement ps = null;
            ResultSet rs = null;
            // 获取数据库当前时间
            String dateTime = FrmSteelMakingPlanChange.getSystemTime(conn);
            Date now = new Date();

            // 循环虚拟炉计划信息
            for (int i = 0; i < jslist.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) jslist.get(i);
                String heatPlanNo = list.get(0);
                String heatPlanNoSeq = list.get(1);

                int seq = 1;
                int plnNum = 0;
                double plnWt = 0;
                String proPlanId = "";
                String gxPlanNo = "";
                String ifMatchOdd = "";
                List<PlnZyDzMEntity> listDzM = getQureyZyDzM(conn, heatPlanNo);
                if (listDzM == null) {
                    cro.setV_errMsg("锻造炉计划已发生变化,请重新查询!");
                    return cro;
                }

                for (PlnZyDzMEntity plnzgM : listDzM) {

                    // if (!plnzgM.getPlanstatus().equals("00")) {
                    // cro.setV_errMsg("锻造炉计划状态不是计划状态!,请确认!");
                    // return cro;
                    // }
                    if (heatPlanNoSeq.equals("")) {// 只有虚拟炉计划
                        plnNum = Integer.parseInt(plnzgM.getPlnInsingleNum());// 单倍支数
                        plnWt = Double.parseDouble(plnzgM.getPlnInsingleWt());
                        proPlanId = plnzgM.getProPlanId();
                        gxPlanNo = plnzgM.getGxPlanNo();
                        ifMatchOdd = plnzgM.getIfMatchOdd();
                        if (!plnzgM.getPlanstatus().equals("00")) {
                            cro.setV_errMsg("锻造炉计划状态不是计划状态!,请确认!");
                            return cro;
                        }
                        // 删除锻造虚拟炉计划
                        String deleteZgM = "DELETE PLN_ZY_DZ_M WHERE HEAT_PLAN_NO = ?";
                        ps = conn.prepareStatement(deleteZgM);
                        ps.setObject(1, heatPlanNo);
                        ps.executeUpdate();
                        ps.close();
                    }
                    else {
                        List<PlnZyDzCEntity> listC = getQureyZyDzC(conn,
                                heatPlanNo, heatPlanNoSeq);
                        int cutNumCount = 0;
                        for (PlnZyDzCEntity plnDzC : listC) {
                            if (plnDzC == null) {
                                cro.setV_errMsg("锻造炉计划数据已发生改变,请刷新!");
                                return cro;
                            }
                            ifMatchOdd = plnzgM.getIfMatchOdd();
                            proPlanId = plnDzC.getProPlanId();
                            gxPlanNo = plnDzC.getGxPlanNo();
                            int num = Integer.parseInt(plnDzC
                                    .getPlanIndoubleNum());
                            plnWt += Double.parseDouble(plnDzC
                                    .getPlanIndoubleWt());
                            plnNum += Integer.parseInt(plnDzC
                                    .getPlanIndoubleNum());
                            cutNumCount += num
                                    * Integer.parseInt(plnDzC.getCutNumGp());
                            // 删除锻造实际炉计划
                            String deleteZgC = "DELETE PLN_ZY_DZ_C WHERE HEAT_PLAN_NO = ? AND HEAT_PLAN_SQE=?";
                            ps = conn.prepareStatement(deleteZgC);
                            ps.setObject(1, heatPlanNo);
                            ps.setObject(2, heatPlanNoSeq);
                            ps.executeUpdate();
                            ps.close();

                            double fixLenTake = Double.parseDouble(plnDzC
                                    .getLenGpSingle());
                            double actLenTake = Double.parseDouble(plnDzC
                                    .getLengthM());

                            int cutNum = Integer.parseInt(plnDzC.getCutNumGp());

                            List<MatGpMEntity> matGpMlist = getQureyMatGpCx(
                                    conn, plnDzC.getJudgeStoveNo(), actLenTake,
                                    fixLenTake, cutNum, num, proPlanId,
                                    gxPlanNo);
                            if (matGpMlist == null) {
                                cro.setV_errMsg("管坯物料已发生改变,请刷新!");
                                return cro;
                            }
                            SimpleDateFormat dateFormat = new SimpleDateFormat(
                                    "yyyyMMddHHmmss");
                            DecimalFormat df = new DecimalFormat("0000000000");
                            for (MatGpMEntity matGpM : matGpMlist) {
                                if (!matGpM.getMatStatus().equals("80150103")) {
                                    cro.setV_errMsg("判定炉号为:"
                                            + matGpM.getJudgeStoveNo()
                                            + ",不是材料已编计划状态,不能删除炉计划!");
                                    return cro;
                                }
                                // 修改库坯料库存
                                String sqlUpdateZgS = "UPDATE MAT_GP_M T SET T.HANGING_FLAG=?,T.MAT_STATUS=?,"
                                        + " T.UPDATE_NAME=?,"
                                        + " T.UPDATE_TIME=TO_DATE(?,'YYYY-MM-DD HH24:MI:SS'),"
                                        + " T.LK_FLAG='0',T.PRO_PLAN_ID_ZG = '',T.GX_PLAN_NO_ZG  = '', T.ORDER_NO= '',T.ORDER_SEQ= '',"
                                        + " T.ORDER_SEQ_NO = '',T.ORD_PK= '',T.ORD_LN_PK= '', T.ORD_LN_DLY_PK  = '' WHERE T.MAT_NO=?";
                                // T.PRO_PLAN_ID_ZG=?,T.GX_PLAN_NO_ZG=?,
                                ps = conn.prepareStatement(sqlUpdateZgS);
                                ps.setObject(1, "0");
                                ps.setObject(2, "80150102");
                                ps.setObject(3, userName);
                                ps.setObject(4, dateTime);
                                ps.setObject(5, matGpM.getMatNo());
                                ps.executeUpdate();
                                ps.close();

                                String resumeSeq = dateFormat.format(now)
                                        + df.format(seq);
                                // 生成利库日志
                                MatGpTrackEntity matGpTrack = new MatGpTrackEntity();
                                matGpTrack.setResumeSeq(resumeSeq);
                                matGpTrack.setEventId("900101");
                                matGpTrack.setEventDesc("锻造脱单");
                                matGpTrack
                                        .setFormName("com.steering.pss.plnsaleord.planStove.FrmRollTubeLibraryZg");
                                matGpTrack.setCallFuncCoding("doDeleteZGC");
                                matGpTrack
                                        .setKeyvalue1("List<MatGpMEntity> matGpMlist");
                                matGpTrack.setKeyvalue1Desc("物料主表关键字实体类集合");
                                matGpTrack.setKeyvalue2("String userName");
                                matGpTrack.setKeyvalue2Desc2("操作人");
                                matGpTrack.setKeyvalue3("doDeleteZGC");
                                matGpTrack.setKeyvalue3Desc3("删除炉计划");
                                matGpTrack.setMatNo(matGpM.getMatNo());
                                matGpTrack.setProductFlag(matGpM
                                        .getProductFlag());
                                matGpTrack.setMatStatus(matGpM.getMatStatus());
                                matGpTrack.setStoveNo(matGpM.getStoveNo());
                                matGpTrack.setFlagStoveNo(matGpM
                                        .getFlagStoveNo());
                                matGpTrack.setJudgeStoveNo(matGpM
                                        .getJudgeStoveNo());
                                matGpTrack.setGroudNo(matGpM.getGroudNo());
                                matGpTrack.setCastNo(matGpM.getCastNo());
                                matGpTrack.setCcmid(matGpM.getCcmid());
                                matGpTrack.setGradecode(matGpM.getGradecode());
                                matGpTrack.setGradename(matGpM.getGradename());
                                matGpTrack.setStdCode(matGpM.getStdCode());
                                matGpTrack.setStdName(matGpM.getStdName());
                                matGpTrack.setActDimater(matGpM.getDimater().replace(
                                        "t", ""));
                                matGpTrack.setActHeight(matGpM.getHeight());
                                matGpTrack
                                        .setActLen(String.valueOf(actLenTake));
                                matGpTrack.setActFixLen(String
                                        .valueOf(fixLenTake));
                                matGpTrack.setActFixNum(matGpM.getFixNum());
                                matGpTrack.setActCount("1");
                                matGpTrack.setActWeight(matGpM.getActWeight());
                                matGpTrack.setActTheoryWeight(matGpM
                                        .getActTheoryWeight());
                                matGpTrack.setOldOrdPk(matGpM.getOrdPk());
                                matGpTrack.setOldOrdLnPk(matGpM.getOrdLnPk());
                                matGpTrack.setOldOrdLnDlyPk(matGpM
                                        .getOrdLnDlyPk());
                                matGpTrack.setOldOrderNo(matGpM.getOrderNo());
                                matGpTrack.setOldOrderSeq(matGpM.getOrderSeq());
                                matGpTrack.setOldOrderSeqNo(matGpM
                                        .getOrderSeqNo());
                                matGpTrack.setMemo("");
                                matGpTrack.setCreateName(userName);
                                matGpTrack.setCreateTime(dateTime);
                                matGpTrack.setOldJudgeStoveNo(matGpM
                                        .getJudgeStoveNo());
                                matGpTrack.setOldGroudNo(matGpM.getGroudNo());
                                matGpTrack.setOldGradecode(matGpM
                                        .getGradecode());
                                matGpTrack.setOldGradename(matGpM
                                        .getGradename());
                                matGpTrack.setOldStdCode(matGpM.getStdCode());
                                matGpTrack.setOldStdName(matGpM.getStdName());
                                matGpTrack.setOldStoveNo(matGpM.getStoveNo());
                                seq++;
                                String sqlAddTrack = EntityTool
                                        .fillSqlByEntity(
                                                CoreXmlSqlParsersFactory
                                                        .getSql("FrmPlanMaterialSelection.addMatGpTrack"),
                                                matGpTrack);
                                ps = conn.prepareStatement(sqlAddTrack);
                                ps.executeUpdate();
                                ps.close();
                            }
                        }
                        int countM = 0;
                        // 查询是否实际炉计划全部删除
                        String sqlM = "SELECT COUNT(*) COUNT FROM PLN_ZY_DZ_C T WHERE T.HEAT_PLAN_NO = ?";
                        ps = conn.prepareStatement(sqlM);
                        ps.setObject(1, heatPlanNo);
                        rs = ps.executeQuery();
                        if (rs.next()) {
                            countM = rs.getInt("COUNT");
                        }
                        rs.close();
                        ps.close();

                        if (countM == 0) {
                            // 删除轧管虚拟炉计划
                            String deleteZgM = "DELETE PLN_ZY_DZ_M WHERE HEAT_PLAN_NO = ?";
                            ps = conn.prepareStatement(deleteZgM);
                            ps.setObject(1, heatPlanNo);
                            ps.executeUpdate();
                            ps.close();
                        }
                        else {
                            // 修改虚拟炉计划量
                            String sqlUpdate = CoreXmlSqlParsersFactory
                                    .getSql("FrmPlanSteelMakMod.updatePlnDzM");
                            ps = conn.prepareStatement(sqlUpdate);
                            ps.setObject(1, heatPlanNo);
                            ps.setObject(2, heatPlanNo);
                            ps.executeUpdate();
                            ps.close();
                        }
                    }
                }
                // 利库记录修改铸造利库量
                if (ifMatchOdd.equals("2")) {
                    double wt = 0;
                    int num = 0;
                    // 查询锻造订单对应铸造订单
                    String sqlCast = CoreXmlSqlParsersFactory
                            .getSql("FrmPlanStoveC.getOrderZz");
                    ps = conn.prepareStatement(sqlCast);
                    ps.setObject(1, proPlanId);
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        int numlk = 0;
                        double wtLk = 0;
                        wt = rs.getDouble("PLAN_WT_SOLD");
                        num = rs.getInt("PLAN_NUM_SOLD");
                        if (plnNum > num) {
                            numlk = num;
                            wtLk = wt;
                        }
                        else {
                            numlk = plnNum;
                            wtLk = plnWt;
                        }
                        // 修改铸造订单利库量
                        String updateZz = "UPDATE PLN_ORDER_CAST_S T SET T.PLAN_WT_SOLD=NVL(T.PLAN_WT_SOLD,0)-?,"
                                + "T.PLAN_NUM_SOLD=NVL(T.PLAN_NUM_SOLD,0)-? WHERE T.PRO_PLAN_ID=? AND T.GX_PLAN_NO=?";
                        PreparedStatement ps1 = conn.prepareStatement(updateZz);
                        ps1.setObject(1, wtLk);
                        ps1.setObject(2, numlk);
                        ps1.setObject(3, rs.getString("PRO_PLAN_ID"));
                        ps1.setObject(4, rs.getString("GX_PLAN_NO"));
                        ps1.executeUpdate();
                        ps1.close();
                        plnNum = plnNum - numlk;
                        plnWt = plnWt - wtLk;
                    }
                    rs.close();
                    ps.close();
                }
            }
            cro.setV_errMsg("删除成功!");
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return cro;
    }
}
