package com.steering.pss.ydm.pipeleavefactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
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.pss.ydm.entity.YdmZcAskDayEntity;

/**
 * 铁运出厂日计划运号审批
 * @author Administrator 2015-06-23
 */
public class FrmShipmentDayApp extends DBCommon {

    /**
     * 查询铁运运号
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject doQuery(ArrayList<String> list, String[] salgs) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmShipmentDayApp.doQuery");
        sql += CoreConverter.toSqlConditionString("T.MANAGEMENT_NO", salgs);
        sql += "   ORDER BY T.CREATE_TIME,T.ASK_DAY_NO DESC";
        return this.getData(sql, list.toArray());

    }

    /**
     * 查询铁运运号
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject doQueryBilM(ArrayList<String> list, String[] salgs) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmShipmentDayApp.doQueryBilM");
        sql += CoreConverter.toSqlConditionString("T.MANAGEMENT_NO", salgs);
        sql += " GROUP BY T.BILL_NO,T.STATION_NO, T.STATION_NM,T.SPCL_LN_NO,T.SPCL_LN_NM,T.RECEIV_NO,T.RECEIV_NM ORDER BY BILL_NO ASC";
        return this.getData(sql, list.toArray());

    }

    /**
     * 查询批复状态
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject doQueryFalg(ArrayList<String> list) {
        return this.getDataBySqlID("FrmShipmentDayApp.doQueryFalg", list
                .toArray());
    }

    /**
     * 查询是否存在记录
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject doQueryDayAsk(ArrayList<String> list) {
        return this.getDataBySqlID("FrmShipmentDayApp.doQueryDayAsk", list
                .toArray());
    }

    /**
     * 查询日请车批车号
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject doQueryAskDay(String day) {
        return this.getDataBySqlID("FrmShipmentDayApp.doQueryAskDay",
                new Object[] { day });
    }

    /**
     * 查询月请车信息
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject doQueryAskMonth(ArrayList<String> list) {
        return this.getDataBySqlID("FrmShipmentDayApp.doQueryAskMonth", list
                .toArray());
    }

    /**
     * 查询日请车审批状态信息
     * @param list 查询参数
     * @return obj
     */
    public CoreReturnObject doQueryFalgAsk(ArrayList<String> list) {
        return this.getDataBySqlID("FrmShipmentDayApp.doQueryFalgAsk", list
                .toArray());
    }

    /**
     * 修改车皮运号，批复数
     * @param list 参数
     * @return obj
     */
    public CoreReturnObject doUpdate(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("FrmShipmentDayApp.doUpdate"));
            parmlist.add(list.get(i).toArray());
        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqllist, parmlist);
    }

    /**
     * 审批
     * @param list 参数
     * @return obj
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doApp(ArrayList<Object> list1) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        Statement sta = null;
        String sqlupdate = "";
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            for (int i = 0; i < list1.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) list1.get(i);
                sqlupdate = "UPDATE YDM_ZC_ASK_MONTH SET ACT_MONTH_NUM = TO_NUMBER(NVL(ACT_MONTH_NUM, 0)) + TO_NUMBER('"
                        + list.get(3)
                        + "')"
                        + "WHERE STATION_NO = '"
                        + list.get(4)
                        + "' AND DECODE(SPCL_LN_NO,'','N',SPCL_LN_NO) = '"
                        + list.get(5)
                        + "'  AND RECEIV_NO = '"
                        + list.get(6)
                        + "' AND ASK_MONTH_NO = '" + list.get(7) + "'";
                sta = connection.createStatement();
                sta.executeUpdate(sqlupdate);
                sta.close();

                sqlupdate = "UPDATE YDM_ZC_ASK_DAY SET APP_FLAG  = '1',APP_NAME  = '"
                        + list.get(0)
                        + "',APP_TIME  = TO_DATE('"
                        + list.get(1)
                        + "','YYYY-MM-DD HH24:MI:SS')"
                        + "WHERE ASK_DAY_PK='"
                        + list.get(2) + "'";
                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
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject doDeleteApp(ArrayList<Object> list1) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        String sqlupdate = "";
        Statement sta = null;
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            for (int i = 0; i < list1.size(); i++) {
                ArrayList<String> list = (ArrayList<String>) list1.get(i);

                sqlupdate = "UPDATE YDM_ZC_ASK_MONTH SET ACT_MONTH_NUM = TO_NUMBER(NVL(ACT_MONTH_NUM, 0)) - TO_NUMBER('"
                        + list.get(3)
                        + "')"
                        + "WHERE STATION_NO = '"
                        + list.get(4)
                        + "' AND DECODE(SPCL_LN_NO,'','N',SPCL_LN_NO) = '"
                        + list.get(5)
                        + "'  AND RECEIV_NO = '"
                        + list.get(6)
                        + "' AND ASK_MONTH_NO = '" + list.get(7) + "'";
                sta = connection.createStatement();
                sta.executeUpdate(sqlupdate);
                sta.close();
                sqlupdate = "UPDATE YDM_ZC_ASK_DAY SET APP_FLAG  = '0',APP_NAME  = '"
                        + list.get(0)
                        + "',APP_TIME  = TO_DATE('"
                        + list.get(1)
                        + "','YYYY-MM-DD HH24:MI:SS')"
                        + "WHERE ASK_DAY_PK='"
                        + list.get(2) + "'";
                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 doAdd(ArrayList<Object> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        String sqlInster = "";
        String sqlquery = "";
        String sqlupdate = "";
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            for (int i = 0; i < list.size(); i++) {
                double sendCount = 0;
                String askDay = "";
                // String appFlag = "";

                // 将JSON字符串转化成对象
                String baseStr = list.get(i).toString();
                JSONObject json = JSONObject.fromObject(baseStr);
                YdmZcAskDayEntity com = (YdmZcAskDayEntity) JSONObject.toBean(
                        json, YdmZcAskDayEntity.class);

                String spclNo = "N";
                if (!com.getSpclLnNo().equals("")) {
                    spclNo = com.getSpclLnNo();
                }
                double batchMonth = 0;
//                double actMonth = 0;
                double verDay = 0;
                double batchDay = 0;
                sqlquery = CoreXmlSqlParsersFactory
                        .getSql("FrmShipmentDayApp.queryAskMonth"); // 查询到月度请车批车表
                psta = connection.prepareStatement(sqlquery);
                psta.setString(1, com.getSendPlanNo());
                ResultSet rs = psta.executeQuery();
                while (rs.next()) {
                    // sendCount = Double.parseDouble(rs.getString(4));
                    batchMonth = Double.parseDouble(rs.getString(2));
//                    actMonth = Double.parseDouble(rs.getString(3));

                    if (rs.getString("APP_FLAG") != null
                            && !rs.getString("APP_FLAG").equals("")) {
                        if (!rs.getString("APP_FLAG").equals("0")) {
                            batchDay += Double.parseDouble(rs.getString(5));
                        }
                        else {
                            verDay += Double.parseDouble(rs.getString(4));
                        }
                    }
                    else {
                        verDay += Double.parseDouble(rs.getString(4));
                    }

                }
                rs.close();
                psta.close();
                sendCount = batchMonth - batchDay - verDay;// 日可请车数
                if (sendCount < Double.parseDouble(com.getVehicleDayNum())) {
                    cro.setV_errMsg("日请车数不能大于月批复数,请重新输入日请车数！");
                    cro.setV_errCode(-1);
                    return cro;
                }
                sqlquery = CoreXmlSqlParsersFactory
                        .getSql("FrmShipmentDayApp.doQueryFalg"); // 查询到日请车批车表
                psta = connection.prepareStatement(sqlquery);
                psta.setString(1, com.getAskDayNo());
                psta.setString(2, com.getAskMonthNo());
                psta.setString(3, com.getBillNo());
                psta.setString(4, com.getStationNo());
                psta.setString(5, spclNo);
                psta.setString(6, com.getReceivNo());
                rs = psta.executeQuery();
                if (rs.next()) {
                    askDay = rs.getString(3);
                }
                rs.close();
                psta.close();

                if (askDay.equals(com.getAskDayNo())) {
                    sqlupdate = "UPDATE YDM_ZC_ASK_DAY SET VEHICLE_DAY_NUM = TO_NUMBER(VEHICLE_DAY_NUM)+TO_NUMBER('"
                            + com.getVehicleDayNum()
                            + "')  WHERE ASK_DAY_NO = '"
                            + com.getAskDayNo()
                            + "' AND ASK_MONTH_NO = '"
                            + com.getAskMonthNo()
                            + "'AND BILL_NO = '"
                            + com.getBillNo()
                            + "' AND STATION_NO='"
                            + com.getStationNo()
                            + "' AND DECODE(SPCL_LN_NO,'','N',SPCL_LN_NO)='"
                            + spclNo
                            + "' AND RECEIV_NO='"
                            + com.getReceivNo()
                            + "'";
                    Statement sta = connection.createStatement();
                    sta.executeUpdate(sqlupdate);
                    sta.close();
                    cro.setV_errMsg("修改请车成功！");
                }
                else {
                    sqlInster = CoreXmlSqlParsersFactory
                            .getSql("FrmShipmentDayApp.AddAskDay"); // 新增日请车批车表
                    psta = connection.prepareStatement(sqlInster);
                    psta.setString(1, com.getAskDayNo());
                    psta.setString(2, com.getAskMonthNo());
                    psta.setString(3, com.getWagonsPlanNo());
                    psta.setString(4, com.getBillNo());
                    psta.setString(5, com.getVehicleDayNum());
                    psta.setString(6, com.getWagonsFlag());
                    psta.setString(7, com.getStationNo());
                    psta.setString(8, com.getStationNm());
                    psta.setString(9, com.getSpclLnNo());
                    psta.setString(10, com.getSpclLnNm());
                    psta.setString(11, com.getReceivNo());
                    psta.setString(12, com.getReceivNm());
                    psta.setString(13, com.getPurName());
                    psta.setString(14, com.getPurTime());
                    psta.setString(15, com.getDepartmentCode());
                    psta.setString(16, com.getDepartmentDesc());
                    psta.setString(17, com.getManagementNo());
                    psta.setString(18, com.getManagementName());
                    psta.setString(19, com.getCreateName());
                    psta.setString(20, com.getCreateTime());
                    psta.setString(21, com.getMemo());
                    psta.executeUpdate();
                    psta.close();
                    cro.setV_errMsg("新增请车成功！");
                }
            }
            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 list 参数
     * @return obj
     */
    public CoreReturnObject doDelete(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("FrmShipmentDayApp.doDelete"));
            parmlist.add(new Object[] { list.get(i).get(0) });

            // sqllist.add(CoreXmlSqlParsersFactory
            // .getSql("FrmShipmentDayApp.updateAskMonth"));
            // parmlist
            // .add(new Object[] { list.get(i).get(1), list.get(i).get(2),
            // list.get(i).get(3), list.get(i).get(4),
            // list.get(i).get(5) });

        }
        return this.getDao(CoreConstantData.sysbeanstr).ExcuteTransction(
                sqllist, parmlist);
    }
}
