package com.steering.pss.ydm.pipeleavefactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import net.sf.json.JSONObject;
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.StringTool;
import com.steering.pss.ydm.entity.YdmZcDaysendplanTrainCEntity;
import com.steering.pss.ydm.entity.YdmZcDaysendplanTrainMEntity;

/**
 * 铁运出厂日计划
 * @author Administrator 2015-06-15
 */
public class FrmPipeTrainDay extends DBCommon {

    /**
     * 查询主表发货计划状态
     * @param list 参数
     * @return obj
     */
    public CoreReturnObject queryPlanState(ArrayList<String> list) {
        return this.getDataBySqlID("FrmPipeTrainDay.QueryPlanState", list
                .toArray());
    }

    /**
     * 查询铁运日计划主信息
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject queryPlanDayInfoM(ArrayList<String> list,
            String[] salgs, String staust) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmPipeTrainDay.queryPlanDayInfoM");
        if (staust != null && staust.length() != 0) {
            sql += " AND T.SEND_DAYPLAN_STATUS='" + staust + "'";
        }
        else {
            sql += "AND T.SEND_DAYPLAN_STATUS >='0'";
        }
        sql += CoreConverter.toSqlConditionString("T.MANAGEMENT_NO", salgs);
        sql += " ORDER BY T.SEND_DAYPLAN_NO DESC";
        return this.getData(sql, list.toArray());
    }

    /**
     * 查询铁运日计划子信息
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject queryPlanDayInfoC() {
        return this.getDataBySqlID("FrmPipeTrainDay.queryPlanDayInfoC");
    }

    /**
     * 自动生成发运计划号
     * @param conn c
     * @param strlist 传递参数
     * @return obj
     * @throws Exception 异常处理
     */
    public String querySendSl(Connection conn, String strlist, String strSale)
            throws Exception {
        int seq = 0;
        PreparedStatement psta = null;
        Date dt = new Date();
        SimpleDateFormat matter1 = new SimpleDateFormat("yyyy-MM-dd");
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("FrmPipeTrainDay.QuerySendSl");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1, matter1.format(dt));
        psta.setString(2, strSale);
        ResultSet rs = psta.executeQuery();
        if (rs.next()) {
            String res = rs.getString(1);
            if (res == null) {
                res = strlist + "0001";
            }
            else {
                seq = Integer.parseInt(res.substring(9, 13));
            }
        }
        rs.close();
        psta.close();
        return strlist + StringTool.formatDecimal(++seq, "0000");
    }

    /**
     * 铁运日计划保存
     * @param baseList 主表数据
     * @param childList 从表数据
     * @return 执行条数
     */
    public CoreReturnObject saveYdmSendPlan(ArrayList<Object> baseList,
            ArrayList<Object> childList) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        String sqlInster = "";
        String sqlupdate = "";
        String sqlSave = "";// 查询sql
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String strSend = "";
            for (int i = 0; i < baseList.size(); i++) {
                // 将JSON字符串转化成对象
                String baseStr = baseList.get(i).toString();
                JSONObject json = JSONObject.fromObject(baseStr);
                YdmZcDaysendplanTrainMEntity com = (YdmZcDaysendplanTrainMEntity) JSONObject
                        .toBean(json, YdmZcDaysendplanTrainMEntity.class);

                double sendMonth = 0;// 月计划剩余车皮数
                sqlSave = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeTrainDay.queryTallMatchSend");// 查询月计划剩余车皮数
                psta = connection.prepareStatement(sqlSave);
                psta.setString(1, com.getSendPlanNo());
                ResultSet rs1 = psta.executeQuery();
                if (rs1.next()) {
                    sendMonth = Double.parseDouble(rs1.getString(1));
                }
                rs1.close();
                psta.close();

                double sendDay = 0;// 日计划申请数量
                sqlSave = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeTrainDay.queryDaySendPlan");// 查询日计划申请数量
                psta = connection.prepareStatement(sqlSave);
                psta.setString(1, com.getSendPlanNo());
                ResultSet rs2 = psta.executeQuery();
                if (rs2.next()) {
                    sendDay = Double.parseDouble(rs2.getString(1));
                }
                rs2.close();
                psta.close();
                if (sendMonth < Double.parseDouble(com.getVehicleDayNum())) {
                    cro.setV_errMsg("月车皮批复数-使用数-日申请未批复数之差:" + sendMonth
                            + ",小于申请数,请重新输入！");
                    cro.setV_errCode(-1);
                    return cro;
                }

                strSend = querySendSl(connection, com.getSendDayplanNo(), com
                        .getSaleOrg());
                sqlInster = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeTrainDay.ADDSENDPLANM"); // 新增到计划主表
                psta = connection.prepareStatement(sqlInster);
                psta.setString(1, strSend);
                psta.setString(2, com.getSendPlanNo());
                psta.setString(3, com.getWagonsPlanNo());
                psta.setString(4, com.getVehicle60Num());
                psta.setString(5, com.getVehicle70Num());
                psta.setString(6, com.getVehicleDayNum());
                psta.setString(7, com.getSaleOrg());
                psta.setString(8, com.getSaleOrgDesc());
                psta.setString(9, com.getCustomerNo());
                psta.setString(10, com.getCustomerNm());
                psta.setString(11, com.getReceivNo());
                psta.setString(12, com.getReceivNm());
                psta.setString(13, com.getApplyDay());
                psta.setString(14, com.getPlanStartTime());
                psta.setString(15, com.getPlanEndTime());
                psta.setString(16, com.getPlanWt());
                psta.setString(17, com.getPlanNum());
                psta.setString(18, com.getPlanTotlLen());
                psta.setString(19, com.getStationNo());
                psta.setString(20, com.getStationNm());
                psta.setString(21, com.getSpclLnNo());
                psta.setString(22, com.getSpclLnNm());
                psta.setString(23, com.getCreateName());
                psta.setString(24, com.getDepartmentCode());
                psta.setString(25, com.getDepartmentDesc());
                psta.setString(26, com.getManagementNo());
                psta.setString(27, com.getManagementName());
                psta.executeUpdate();
                psta.close();
            }
            // 从表成分索引号与与之对应的序号
            for (int i = 0; i < childList.size(); i++) {
                // 将JSON字符串转化成对象
                String childStr = childList.get(i).toString();
                JSONObject json = JSONObject.fromObject(childStr);
                YdmZcDaysendplanTrainCEntity comc = (YdmZcDaysendplanTrainCEntity) JSONObject
                        .toBean(json, YdmZcDaysendplanTrainCEntity.class);

                double weightMonth = 0;// 月计划可编制量
                sqlSave = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeTrainDay.queryPlanDay");// 查询月计划可编辑量
                psta = connection.prepareStatement(sqlSave);
                psta.setString(1, comc.getSendPlanNo());
                psta.setString(2, comc.getOrdPk());
                psta.setString(3, comc.getOrdLnPk());
                psta.setString(4, comc.getOrdLnDlyPk());
                ResultSet rs1 = psta.executeQuery();
                if (rs1.next()) {
                    weightMonth = Double.parseDouble(rs1.getString(1));
                }
                rs1.close();
                psta.close();

                if (weightMonth < Double.parseDouble(comc.getPlanWt())) {
                    cro.setV_errMsg("合同号为:" + comc.getOrderNo() + "、合同行号为:"
                            + comc.getOrderSeq() + "、交货行为:"
                            + comc.getDeliveryNo() + "该记录,可编制量为:" + weightMonth
                            + "吨,编制量大于可编制量,请重新输入！");
                    cro.setV_errCode(-1);
                    return cro;
                }

                sqlInster = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeTrainDay.ADDSENDPLANC"); // 新增到计划子表
                psta = connection.prepareStatement(sqlInster);
                psta.setString(1, strSend);
                psta.setString(2, comc.getSendPlanNo());
                psta.setString(3, comc.getOrderNo());
                psta.setString(4, comc.getOrderSeq());
                psta.setString(5, comc.getDeliveryNo());
                psta.setString(6, comc.getMaterialNo());
                psta.setString(7, comc.getMaterialName());
                psta.setString(8, comc.getProduccode());
                psta.setString(9, comc.getProducname());
                psta.setString(10, comc.getPrdCls());
                psta.setString(11, comc.getPsc());
                psta.setString(12, comc.getPscDesc());
                psta.setString(13, comc.getSpecCode());
                psta.setString(14, comc.getSpecName());
                psta.setString(15, comc.getLenNo());
                psta.setString(16, comc.getLenDesc());
                psta.setString(17, comc.getPlanWt());
                psta.setString(18, comc.getPlanNum());
                psta.setString(19, comc.getPlanTotlLen());
                psta.setString(20, comc.getCreateName());
                psta.setString(21, comc.getCreateTime());
                psta.setString(22, comc.getOrdPk());
                psta.setString(23, comc.getOrdLnPk());
                psta.setString(24, comc.getOrdLnDlyPk());
                psta.executeUpdate();
                psta.close();

                double weight = 0;
                sqlSave = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeTrainDay.queryTallDayPlanM");// 查询计划号向下是否还有可编制量
                psta = connection.prepareStatement(sqlSave);
                psta.setString(1, comc.getSendPlanNo());
                ResultSet rs = psta.executeQuery();
                if (rs.next()) {
                    weight = Double.parseDouble(rs.getString(1));
                }
                rs.close();
                psta.close();

                if (weight > 0) {
                    sqlupdate = "UPDATE YDM_ZC_SENDPLAN_M SET  SEND_PLAN_STATUS='2',UPDATE_NAME='"
                            + comc.getUpdateName()
                            + "',UPDATE_TIME=TO_DATE('"
                            + comc.getCreateTime()
                            + "','YYYY-MM-DD HH24:MI:SS')  WHERE SEND_PLAN_NO='"
                            + comc.getSendPlanNo() + "' "; // 修改计划主表状态(执行)
                }
                else {
                    sqlupdate = "UPDATE YDM_ZC_SENDPLAN_M SET  SEND_PLAN_STATUS='3',UPDATE_NAME='"
                            + comc.getUpdateName()
                            + "',UPDATE_TIME=TO_DATE('"
                            + comc.getCreateTime()
                            + "','YYYY-MM-DD HH24:MI:SS')  WHERE SEND_PLAN_NO='"
                            + comc.getSendPlanNo() + "'"; // 修改计划主表状态（关闭）
                }
                Statement sta = connection.createStatement();
                sta.executeUpdate(sqlupdate);
                sta.close();
            }

            cro.setResult(1);
            connection.commit();
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            cro.setV_errMsg(e.getMessage());
            cro.setV_errCode(-1);
            if (connection != null) {
                try {
                    connection.rollback(); // 回滚事务
                }
                catch (Exception e2) {
                }
            }
        }
        finally {
            try {
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                }
            }
            catch (Exception e2) {
            }
        }
        return cro;
    }

    /**
     * 废除出厂计划
     * @param pram 主表数据
     * @param list 从表数据
     * @return 返回条数
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject deltePlanSend(ArrayList<Object> pram1,
            ArrayList<Object> list1) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        String sqlSave = "";
        String sqlupdate = "";
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            for (int i = 0; i < list1.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) list1.get(i);
                // 修改子表有效标志
                // sqllist.add(CoreXmlSqlParsersFactory
                // .getSql("FrmPipeTrainDay.UdatePlan"));
                // parmlist.add(list.get(i).toArray());
                //                
                sqlupdate = "UPDATE YDM_ZC_DAYSENDPLAN_TRAIN_C SET VALIDFLAG = '0',UPDATE_NAME = '"
                        + list.get(5)
                        + "',"
                        + " UPDATE_TIME = TO_DATE('"
                        + list.get(6)
                        + "','YYYY-MM-DD HH24:MI:SS') WHERE SEND_DAYPLAN_NO = '"
                        + list.get(0)
                        + "' AND SEND_PLAN_NO =  '"
                        + list.get(1)
                        + "' AND ORDER_NO =  '"
                        + list.get(2)
                        + "' AND ORDER_SEQ =  '"
                        + list.get(3)
                        + "' AND DELIVERY_NO =  '"
                        + list.get(4)
                        + "'AND VALIDFLAG='1'";
                Statement sta = connection.createStatement();
                sta.executeUpdate(sqlupdate);
                sta.close();

                double weight = 0;
                sqlSave = CoreXmlSqlParsersFactory
                        .getSql("FrmPipeTrainDay.queryTallDayPlanC");// 查询计划号向下是否还有可编制量
                psta = connection.prepareStatement(sqlSave);
                psta.setObject(1, list.get(1));
                ResultSet rs = psta.executeQuery();
                if (rs.next()) {
                    weight = Double.parseDouble(rs.getString(1));
                }
                rs.close();
                psta.close();

                if (weight > 0) {
                    sqlupdate = "UPDATE YDM_ZC_SENDPLAN_M SET SEND_PLAN_STATUS='2',UPDATE_NAME='"
                            + list.get(5)
                            + "',UPDATE_TIME=TO_DATE('"
                            + list.get(6)
                            + "','YYYY-MM-DD HH24:MI:SS')  WHERE SEND_PLAN_NO='"
                            + list.get(1) + "' "; // 修改计划主表状态(执行)
                }
                else {
                    sqlupdate = "UPDATE YDM_ZC_SENDPLAN_M SET SEND_PLAN_STATUS='1',UPDATE_NAME='"
                            + list.get(5)
                            + "',UPDATE_TIME=TO_DATE('"
                            + list.get(6)
                            + "','YYYY-MM-DD HH24:MI:SS')  WHERE SEND_PLAN_NO='"
                            + list.get(1) + "'"; // 修改计划主表状态（下发）
                }
                sta = connection.createStatement();
                sta.executeUpdate(sqlupdate);
                sta.close();
            }
            for (int z = 0; z < pram1.size(); z++) {
                ArrayList<String> pram = (ArrayList<String>) pram1.get(z);
                // 修改主表有效标志
                // sqllist.add(CoreXmlSqlParsersFactory
                // .getSql("FrmPipeTrainDay.UdateSendPlan"));
                // parmlist.add(pram.toArray());

                sqlupdate = "UPDATE YDM_ZC_DAYSENDPLAN_TRAIN_M SET VALIDFLAG = '0', UPDATE_NAME = '"
                        + pram.get(0)
                        + "', UPDATE_TIME = TO_DATE('"
                        + pram.get(1)
                        + "','YYYY-MM-DD HH24:MI:SS')"
                        + "WHERE SEND_DAYPLAN_NO = '"
                        + pram.get(2)
                        + "' AND SEND_PLAN_NO='"
                        + pram.get(3)
                        + "' AND VALIDFLAG = '1'";
                Statement sta = connection.createStatement();
                sta.executeUpdate(sqlupdate);
                sta.close();
            }
            cro.setResult(1);
            connection.commit();
        }
        catch (Exception 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 list 查询参数
     * @return obj
     */
    public CoreReturnObject querySendPlanM(ArrayList<String> list,
            String[] salgs) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmPipeTrainDay.QuerySENDPLANM");
        sql += CoreConverter.toSqlConditionString("T.MANAGEMENT_NO", salgs);
        sql += " ORDER BY T.SEND_PLAN_NO DESC";
        return this.getData(sql, list.toArray());
    }

    /**
     * 根据主表查询出厂计划子表信息
     * @return obj
     */
    public CoreReturnObject querySendPlanC() {
        return this.getDataBySqlID("FrmPipeTrainDay.QuerySENDPLANC");
    }

    /**
     * 查询月计划子表数据
     * @param list 参数
     * @return
     */
    public CoreReturnObject querySendC(ArrayList<String> list) {
        return this
                .getDataBySqlID("FrmPipeTrainDay.QuerySendC", list.toArray());
    }

    /**
     * 下发计划
     * @param list 下发数据
     * @return obj
     */
    public CoreReturnObject queryPlanIssued(ArrayList<ArrayList<String>> list) {
        // sql语句
        ArrayList<String> sqllist = new ArrayList<String>();
        // 字段集合
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        for (int z = 0; z < list.size(); z++) {
            // 修改主表有效标志
            sqllist.add(CoreXmlSqlParsersFactory
                    .getSql("FrmPipeTrainDay.QueryPlanIssued"));
            parmlist.add(list.get(z).toArray());
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqllist, parmlist);
    }

    /**
     * 查询发运日计划表请车数量
     * @param list 下发数据
     * @return obj
     */
    public CoreReturnObject queryDaySendPlan(String list) {
        return this.getDataBySqlID("FrmPipeTrainDay.queryDaySendPlan",
                new Object[] { list });
    }

    /**
     * 查询库存可编制量
     * @param list 参数
     * @return obj
     */
    public CoreReturnObject queryPlanDay(ArrayList<String> list) {
        return this.getDataBySqlID("FrmPipeTrainDay.queryPlanDay", list
                .toArray());
    }

}
