package com.steering.pss.ydm.pipeleavefactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
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.YdmZcSendplanCEntity;
import com.steering.pss.ydm.entity.YdmZcSendplanMEntity;

/**
 * 汽运出厂计划
 * @author Administrator TJG 2015-06-10
 */
public class CorePipeLeaveFactory extends DBCommon {

    /**
     * 查询客户信息
     * @return obj
     */
    public CoreReturnObject getCustomer() {
        return this.getDataBySqlID("CorePipeLeaveFactory.GetCustomer");
    }

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

    /**
     * 查询可发资源主信息
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject queryOrderInfo(ArrayList<Object> list,
            String[] salgs) {
        if (list.size() < 3) {
            return null;
        }
        String custName = list.get(0).toString();
        String beginTime = list.get(1).toString();
        String endTime = list.get(2).toString();
        String orderNo = list.get(3).toString();
        Object[] params = new Object[] { custName, custName, custName,
                beginTime, endTime, orderNo };
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeLeaveFactory.queryOrderInfo");
        sql += CoreConverter.toSqlConditionString("T1.CREATE_DEPT", salgs);
        sql += " ORDER BY T1.CUSTOMER_NM,T1.RECEIV_NM, T1.CREATE_DEPT";
        return this.getData(sql, params);
    }

    /**
     * 查询可发资源子信息
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject queryChildOrderInfo(ArrayList<Object> params) {
        return this.getDataBySqlID("CorePipeLeaveFactory.QueryChild",
                params.toArray());
    }

    /**
     * 自动生成发运计划号
     * @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;
        String sqlLovsqe = CoreXmlSqlParsersFactory
                .getSql("CorePipeLeaveFactory.QuerySendSl");
        psta = conn.prepareStatement(sqlLovsqe);
        psta.setString(1, 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 sqlquery = "";
        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);
                YdmZcSendplanMEntity com = (YdmZcSendplanMEntity) JSONObject
                        .toBean(json, YdmZcSendplanMEntity.class);
                strSend = querySendSl(connection, com.getSendPlanNo(),
                        com.getSaleOrg());
                sqlInster = CoreXmlSqlParsersFactory
                        .getSql("CorePipeLeaveFactory.ADDSENDPLANM"); // 新增到计划主表
                psta = connection.prepareStatement(sqlInster);
                psta.setString(1, strSend);
                psta.setString(2, com.getSaleOrg());
                psta.setString(3, com.getSaleOrgDesc());
                psta.setString(4, com.getCustomerNo());
                psta.setString(5, com.getCustomerNm());
                psta.setString(6, com.getReceivNo());
                psta.setString(7, com.getReceivNm());
                psta.setString(8, "110501");
                psta.setString(9, com.getPlanYearMonth());
                psta.setString(10, com.getPlanStartTime());
                psta.setString(11, com.getPlanEndTime());
                psta.setString(12, com.getPlanWt());
                psta.setString(13, com.getPlanNum());
                psta.setString(14, com.getPlanTotlLen());
                psta.setString(15, com.getCreateName());
                psta.setString(16, com.getDepartmentCode());
                psta.setString(17, com.getDepartmentDesc());
                psta.setString(18, com.getManagementNo());
                psta.setString(19, 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);
                YdmZcSendplanCEntity comc = (YdmZcSendplanCEntity) JSONObject
                        .toBean(json, YdmZcSendplanCEntity.class);

                double weightMonth = 0;// 可编制量
                double delvrMonth = 0;// 交货量
                double maxDelvr = 0;// 上限值
                double maxdelvrMonth = 0;// 交货量上限值
                double beenwt = 0;// 已编制量
                sqlquery = CoreXmlSqlParsersFactory
                        .getSql("CorePipeLeaveFactory.QueryMatPlan");// 查询可编辑量
                psta = connection.prepareStatement(sqlquery);
                psta.setString(1, comc.getOrdPk());
                psta.setString(2, comc.getOrdLnPk());
                psta.setString(3, comc.getOrdLnDlyPk());
                ResultSet rs1 = psta.executeQuery();
                if (rs1.next()) {
                    weightMonth = Double.parseDouble(rs1.getString(1));
                    delvrMonth = Double.parseDouble(rs1.getString(2));
                    maxDelvr = Double.parseDouble(rs1.getString(3));
                    beenwt = Double.parseDouble(rs1.getString(4));
                }
                rs1.close();
                psta.close();
                maxdelvrMonth = delvrMonth + delvrMonth * (maxDelvr / 100);
                // 计划量不能大于可编制量
                if (weightMonth < Double.parseDouble(comc.getPlanWt())) {
                    cro.setV_errMsg("合同号为:" + comc.getOrderNo() + "、合同行号为:"
                            + comc.getOrderSeq() + "、交货行为:"
                            + comc.getDeliveryNo() + "该记录,可编制量为:" + weightMonth
                            + "吨,计划量大于可编制量,请重新输入！");
                    cro.setV_errCode(-1);
                    return cro;
                }
                // 计划量不能大于交货量上限
                // if (maxdelvrMonth < Double.parseDouble(comc.getPlanWt())) {
                // cro.setV_errMsg("合同号为:" + comc.getOrderNo() + "、合同行号为:"
                // + comc.getOrderSeq() + "、交货行为:"
                // + comc.getDeliveryNo() + "该记录,交货量上限为:"
                // + maxdelvrMonth + "吨,计划量大于交货量上限,请重新输入！");
                // cro.setV_errCode(-1);
                // return cro;
                // }
                // 计划量不能大于交货量量上限-已编制量
                // if (maxdelvrMonth - beenwt < Double.parseDouble(comc
                // / .getPlanWt())) {
                // cro.setV_errMsg("合同号为:" + comc.getOrderNo() + "、合同行号为:"
                // + comc.getOrderSeq() + "、交货行为:"
                // + comc.getDeliveryNo()
                // + "该记录,计划量大于交货量上限与已编制量之差,请重新输入！");
                // cro.setV_errCode(-1);
                // return cro;
                // }

                sqlInster = CoreXmlSqlParsersFactory
                        .getSql("CorePipeLeaveFactory.ADDSENDPLANC"); // 新增到计划子表
                psta = connection.prepareStatement(sqlInster);
                psta.setString(1, strSend);
                psta.setString(2, comc.getOrderNo());
                psta.setString(3, comc.getOrderSeq());
                psta.setString(4, comc.getDeliveryNo());
                psta.setString(5, comc.getProduccode());
                psta.setString(6, comc.getProducname());
                psta.setString(7, comc.getPrdCls());
                psta.setString(8, comc.getPsc());
                psta.setString(9, comc.getPscDesc());
                psta.setString(10, comc.getSpecCode());
                psta.setString(11, comc.getSpecName());
                psta.setString(12, comc.getLenNo());
                psta.setString(13, comc.getLenDesc());
                psta.setString(14, comc.getPlanWt());
                psta.setString(15, comc.getPlanNum());
                psta.setString(16, comc.getPlanTotlLen());
                psta.setString(17, comc.getCreateName());
                psta.setString(18, comc.getOrdPk());
                psta.setString(19, comc.getOrdLnPk());
                psta.setString(20, comc.getOrdLnDlyPk());
                psta.setString(21, comc.getDelvryBdate());
                psta.setString(22, comc.getDelvryEdate());
                psta.executeUpdate();
                psta.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 返回条数
     */
    public CoreReturnObject deltePlanSend(ArrayList<String> pram,
            ArrayList<ArrayList<String>> list) {
        // sql语句
        ArrayList<String> sqllist = new ArrayList<String>();
        // 字段集合
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();

        for (int i = 0; i < list.size(); i++) {
            // 修改子表有效标志
            sqllist.add(CoreXmlSqlParsersFactory
                    .getSql("CorePipeLeaveFactory.UdatePlan"));
            parmlist.add(list.get(i).toArray());
        }
        // 修改主表有效标志
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CorePipeLeaveFactory.UdateSendPlan"));
        parmlist.add(pram.toArray());
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqllist, parmlist);
    }

    /**
     * 废除出厂计划子表数据更新主表计划支、重量、长度
     * @param pram 子表数据
     * @param list 主表数据
     * @return 返回条数
     */
    public CoreReturnObject deltePlanChild(ArrayList<String> pram,
            ArrayList<String> list) {
        // sql语句
        ArrayList<String> sqllist = new ArrayList<String>();
        // 字段集合
        ArrayList<Object[]> parmlist = new ArrayList<Object[]>();
        // 删除子表信息
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CorePipeLeaveFactory.DeltePlanSend"));
        parmlist.add(pram.toArray());
        // 更新主表信息（支、吨、米）
        sqllist.add(CoreXmlSqlParsersFactory
                .getSql("CorePipeLeaveFactory.UdateSendPlanChild"));
        parmlist.add(list.toArray());
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqllist, parmlist);
    }

    /**
     * 查询出厂计划主表信息
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject querySendPlanM(ArrayList<Object> list,
            String[] salgPermissions) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeLeaveFactory.QuerySENDPLANM");
        sql += CoreConverter.toSqlConditionString("T.MANAGEMENT_NO",
                salgPermissions);
        sql += "   ORDER BY T.SEND_PLAN_NO DESC";
        return this.getData(sql, list.toArray());
    }

    /**
     * 根据主表查询出厂计划子表信息
     * @return obj
     */
    public CoreReturnObject querySendPlanC(String sendPlanNo) {
        Object[] param = new Object[] { sendPlanNo };
        return this
                .getDataBySqlID("CorePipeLeaveFactory.QuerySENDPLANC", param);
    }

    /**
     * 下发计划
     * @param list 下发数据
     * @return obj
     */
    public CoreReturnObject queryPlanIssued(ArrayList<String> list) {
        return this.setDataBySqlID("CorePipeLeaveFactory.QueryPlanIssued",
                list.toArray());
    }

    // 2015-08-20
    public CoreReturnObject getCustomerBySalg(String[] salgs) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeLeaveFactory.getCustomerBySalg");
        sql += CoreConverter.toSqlConditionString("T2.SALE_ORG", salgs);
        sql += "   ORDER BY T1.CUSTOMER_NM";
        return this.getData(sql);
    }
    
    /**
     * 废除出厂计划
     * @param pram 主表数据
     * @param list 从表数据
     * @return 返回条数
     */
    public CoreReturnObject doDown(ArrayList<String> param, String userName) {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeTrainMonth.getSendPlanStatus");
            String sqlUm = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeTrainMonth.doDown");
            for (String sendPlanNo : param) {
                ps = con.prepareStatement(sql);
                ps.setObject(1, sendPlanNo);
                rs = ps.executeQuery();
                String status = "";
                if (rs.next()) {
                    status = rs.getString("SEND_PLAN_STATUS");
                }
                rs.close();
                ps.close();
                if (!status.equals("0")) {
                    core.setV_errMsg("不是编辑的计划号,不能下发!");
                    return core;
                }
                ps = con.prepareStatement(sqlUm);
                ps.setObject(1, sendPlanNo);
                ps.execute();
                ps.close();
            }
            core.setV_errMsg("下发计划成功!");
            con.commit();
        }
        catch (SQLException e) {

            e.printStackTrace();
        }
        finally {
            try {
                if (con != null)
                    con.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return core;
    }
    
    /**
     * 废除出厂计划
     * @param pram 主表数据
     * @param list 从表数据
     * @return 返回条数
     */
    public CoreReturnObject deltePlanSend(ArrayList<String> param,
            String userName) {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            con.setAutoCommit(false);
            String sql = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeTrainMonth.getSendPlanStatus");
            String sqlUm = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeTrainMonth.UdatePlan");
            String sqlDc = CoreXmlSqlParsersFactory
                    .getSql("FrmPipeTrainMonth.UdateSendPlan");
            for (String sendPlanNo : param) {
                ps = con.prepareStatement(sql);
                ps.setObject(1, sendPlanNo);
                rs = ps.executeQuery();
                String status = "";
                if (rs.next()) {
                    status = rs.getString("SEND_PLAN_STATUS");
                }
                rs.close();
                ps.close();
                if (!(status.equals("0") || status.equals("1"))) {
                    core.setV_errMsg("不是编辑/下发的计划号,不能撤销!");
                    return core;
                }
                ps = con.prepareStatement(sqlDc);
                ps.setObject(1, sendPlanNo);
                ps.execute();
                ps.close();
                ps = con.prepareStatement(sqlUm);
                ps.setObject(1, sendPlanNo);
                ps.execute();
                ps.close();
            }
            core.setV_errMsg("撤销计划成功!");
            con.commit();
        }
        catch (SQLException e) {

            e.printStackTrace();
        }
        finally {
            try {
                if (con != null)
                    con.close();
            }
            catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return core;
    }
}
