package com.steering.pss.ydm.pipemanage;

import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;

import com.google.gson.Gson;
import com.steering.comm.DefaultWebServiceRequest;
import com.steering.comm.ServiceToCx;
import com.steering.comm.converter.CoreConverter;
import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.sale.order.orderchange.CrmBillService;
import com.steering.pss.sale.order.qualityDesign.QualityDesignTool;
import com.steering.pss.ydm.base.MeanValueCalculation;
import com.steering.pss.ydm.entity.YdmZcBillCEntity;
import com.steering.pss.ydm.entity.YdmZcBillMEntity;

import core.stlmes.server.sale.service.balance.SlmBalanceTickets;

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 net.sf.json.JSONObject;

public class CorePipeBillOfLadingClose extends DBCommon {

    /**
     * 查询提单号
     * @param params 参数集合
     * @return CoreReturnObject
     */
    public CoreReturnObject getBiltNo(ArrayList<Object> params, String[] arr,String supplyUnit) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.getBiltNo");
        sql += CoreConverter.toSqlConditionString("T.MANAGEMENT_NO", arr);
        if(supplyUnit.equals("120501")){
            sql +=" AND (T.SUPPLY_UNIT IS NULL OR T.SUPPLY_UNIT = '"+supplyUnit+"')";
        }else if(supplyUnit.equals("120504")){
            sql +=" AND T.SUPPLY_UNIT = '"+supplyUnit+"'";
        }
        sql += " GROUP BY T.BILL_NO, T.BILL_STATUS, T.LOADVEHICLE_TYPE,T.ISPRECLOSE,T.SEND_PLAN_NO, "
                + " T.PRINT_NUM,T.PRINT_FLAG,T.DELVRY_ADDR,T.ZOUT_FLAG,T.BILL_TICKET_STATUS,T.OUTSTOCK_TICKET_STATUS"
                + ",T.TRANSMNY_TICKET_STATUS,T.RECEIV_NM,T.SALE_ORG_DESC,T.SALE_ORG   ORDER BY T.BILL_NO";
        return this.getData(sql, params.toArray());
    }

    /***
     * 查询登陆人对应的销售组织
     * @param areaNo
     * @return
     */
    public CoreReturnObject getSaleorg(String areaNo) {
        return this.getDataBySqlID("CorePipeBillOfLadingClose.getSaleorg",
                new Object[] { areaNo });
    }

    /***
     * 回写打印次数，打印时间
     * @param areaNo
     * @return
     */
    public CoreReturnObject updatePintFlag(String time, String billNo) {
        return this.setDataBySqlID("CorePipeBillOfLadingClose.updatePintFlag",
                new Object[] { time, billNo });
    }

    /***
     * 查询交货行计量单位
     * @param areaNo
     * @return
     */
    public CoreReturnObject queryOrderUnit(String ordLnDlyPk) {
        return this.getDataBySqlID("CorePipeBillOfLadingClose.queryOrderUnit",
                new Object[] { ordLnDlyPk });
    }

    /***
     * 查询提单状态
     * @param areaNo
     * @return
     */
    public CoreReturnObject getBillStatus(String billNo) {
        return this.getDataBySqlID("CorePipeBillOfLadingClose.getBillStatus",
                new Object[] { billNo });
    }

    /**
     * 通过提单号查询合同信息
     * @param billNo 提单号
     * @return CoreReturnObject
     */
    public CoreReturnObject getOrderInfoByBiltNo(String billNo) {
        Object[] params = new Object[] { billNo };
        return this.getDataBySqlID(
                "CorePipeBillOfLadingClose.getOrderInfoByBiltNo", params);
    }

    /**
     * 通过提单号查询炉信息
     * @param billNo 提单号
     * @return CoreReturnObject
     */
    public CoreReturnObject getJustStoveNoInfoByBiltNo(String billNo) {
        Object[] params = new Object[] { billNo };
        return this.getDataBySqlID(
                "CorePipeBillOfLadingClose.getJustStoveNoInfoByBiltNo", params);
    }

    /**
     * 提单执行子信息
     * @param billNo 提单号
     * @return CoreReturnObject
     */
    public CoreReturnObject getQueryBillReport(ArrayList<Object> pram,
                                               String jsflag, String yearMatch, String starta, Boolean chkHk,
                                               String soage, String juNo,String supplyUnit) {
        return getQueryBillReport(pram,jsflag,yearMatch,starta,chkHk,soage,juNo,supplyUnit,null);
    }
    public CoreReturnObject getQueryBillReport(ArrayList<Object> pram,
            String jsflag, String yearMatch, String starta, Boolean chkHk,
            String soage, String juNo,String supplyUnit,String[] depts) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.QUERYBILLREPORT");
        if (!pram.get(0).equals("") && !pram.get(1).equals("")) {
            sql += "  AND T.CREATE_TIME BETWEEN TO_DATE('" + pram.get(0)
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND  TO_DATE('"
                    + pram.get(1) + "', 'YYYY-MM-DD HH24:MI:SS')";
        }
        if (!pram.get(2).equals("")) {
            sql += "  AND T.BILL_NO LIKE '%' || '" + pram.get(2) + "' || '%'";
        }
        if (!pram.get(3).equals("") && !pram.get(4).equals("")) {
            sql += "  AND T.DELETE_TIME BETWEEN TO_DATE('" + pram.get(3)
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND  TO_DATE('"
                    + pram.get(4) + "', 'YYYY-MM-DD HH24:MI:SS')";
        }
        if (!pram.get(5).equals("")) {
            sql += " AND T.ORDER_NO LIKE '%' || '" + pram.get(5) + "' || '%'";
        }
        if (jsflag.equals("")) {
            sql += "";
        }
        else if (jsflag.equals("0")) {
            sql += " AND T.REALINVOICENO IS NULL";
        }
        else {
            sql += " AND T.REALINVOICENO IS NOT NULL";
        }
        if (!soage.equals("")) {
            sql += " AND T.SALE_ORG='" + soage + "'";
        }
        if (!yearMatch.equals("")) {
            sql += " AND L.BAL_YEAR_MONTH='" + yearMatch + "'";
        }
        if (!juNo.equals("")) {
            sql += " AND C.JUDGE_STOVE_NO='" + juNo + "'";
        }
        if(supplyUnit.equals("120501"))
        {
            sql += " AND (H.SUPPLY_UNIT = '"+supplyUnit+"' OR H.SUPPLY_UNIT IS NULL)";
        }else if(supplyUnit.equals("120504")){
            sql += " AND H.SUPPLY_UNIT = '"+supplyUnit+"'";
        }
        if(depts!=null && depts.length >0){
            sql += CoreConverter.toSqlConditionString("H.CREATE_DEPT",depts);
        }
        sql += "  GROUP BY T.BILL_NO,T.ORDER_NO, T.ORDER_SEQ, H.SALE_AREA_DESC,T.DELIVERY_NO, T.PLAN_TRANS_TYPE,"
                + "C.JUDGE_STOVE_NO, C.BATCH_NO, C.GROUP_NO, C.STORAGE_NO, C.VSTEL_DESC,G.BALNCE_PRICE, "
                + "T.CREATE_NAME, T.CREATE_TIME, C.PRODUCNAME, C.STEELNAME, C.SPEC_NAME, "
                + "T.UPDATE_TIME, T.BILL_STATUS, T.LOADVEHICLE_TYPE, T.STATION_NM, T.ORD_PK,"
                + "T.ORD_LN_PK, T.ORD_LN_DLY_PK, T.SPCL_LN_NM, C.STD_NAME, C.GRADENAME, "
                + "T.RECEIV_NM, C.STD_STYLE_DESC, C.MODEL_DESC, T.ISPRECLOSE, T.SALE_ORG, "
                + "T.SALE_ORG_DESC, T.PICKUP_FLAG, L.VALIDFLAG,T.REALINVOICENO,L.BAL_YEAR_MONTH,T.ZOUT_FLAG,T.REALINVOICENO1,"
                + "T.BILL_TICKET_STATUS,T.OUTSTOCK_TICKET_STATUS,T.TRANSMNY_TICKET_STATUS) T1 ";
        if (starta.equals("0")) {// AND T.BILL_STATUS >= '4'
            sql += "  WHERE (TO_NUMBER(T1.ACT_COUNT)-TO_NUMBER(T1.BEEN_COUNT)!=0 "
                    + "OR TO_NUMBER(T1.PLAN_COUNT)-TO_NUMBER(T1.BEEN_COUNT)!=0)  ORDER BY T1.BILL_NO";
        }
        return this.getData(sql);
    }

    /**
     * 提单执行主信息
     * @param billNo 提单号
     * @return CoreReturnObject
     */
    public CoreReturnObject getQueryBillMReport(ArrayList<Object> pram,
                                                String jsflag, String yearMatch, String starta, Boolean chkHk,
                                                String soage,String supplyUnit) {
        return getQueryBillMReport(pram,jsflag,yearMatch,starta,chkHk,soage,supplyUnit,null);
    }
    public CoreReturnObject getQueryBillMReport(ArrayList<Object> pram,
            String jsflag, String yearMatch, String starta, Boolean chkHk,
            String soage,String supplyUnit,String[] depts) {

        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.QUERYBILLMREPORT");
        if (!pram.get(0).equals("") && !pram.get(1).equals("")) {
            sql += "  AND T.CREATE_TIME BETWEEN TO_DATE('" + pram.get(0)
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND  TO_DATE('"
                    + pram.get(1) + "', 'YYYY-MM-DD HH24:MI:SS')";
        }
        if (!pram.get(2).equals("")) {
            sql += "  AND T.BILL_NO LIKE '%' || '" + pram.get(2) + "' || '%'";
        }
        if (!pram.get(3).equals("") && !pram.get(4).equals("")) {
            sql += "  AND T.DELETE_TIME BETWEEN TO_DATE('" + pram.get(3)
                    + "', 'YYYY-MM-DD HH24:MI:SS') AND  TO_DATE('"
                    + pram.get(4) + "', 'YYYY-MM-DD HH24:MI:SS')";
        }
        if (jsflag.equals("")) {
            sql += "";
        }
        else if (jsflag.equals("0")) {
            sql += " AND T.REALINVOICENO IS NULL";
        }
        else {
            sql += " AND T.REALINVOICENO IS NOT NULL";
        }

        if (!soage.equals("")) {
            sql += " AND T.SALE_ORG='" + soage + "'";
        }
        if(supplyUnit.equals("120501"))
        {
            sql += " AND (O.SUPPLY_UNIT = '"+supplyUnit+"' OR O.SUPPLY_UNIT IS NULL)";
        }else if(supplyUnit.equals("120504")){
            sql += " AND O.SUPPLY_UNIT = '"+supplyUnit+"'";
        }
        if(depts!=null && depts.length >0){
            sql += CoreConverter.toSqlConditionString("o.CREATE_DEPT",depts);
        }
        sql += " GROUP BY T.BILL_NO, T.PLAN_TRANS_TYPE, T.CREATE_NAME, T.BILL_STATUS, "
                + "T.LOADVEHICLE_TYPE, T.STATION_NM, T.SPCL_LN_NM, T.RECEIV_NM, T.ISPRECLOSE, "
                + "T.SALE_ORG, T.SALE_ORG_DESC, T.PICKUP_FLAG,T.ZOUT_FLAG,"
                + "T.BILL_TICKET_STATUS,T.OUTSTOCK_TICKET_STATUS,T.TRANSMNY_TICKET_STATUS) T2, YDM_ZC_BILL_C C, "
                + "YDM_ZC_LOADVEHICLE_MAT L,SLM_ORDER_HEAD H WHERE C.BILL_NO = T2.BILL_NO AND C.MAT_NO = L.MAT_NO(+)"
                + " AND H.ORD_PK=C.ORD_PK(+) AND C.BILL_NO=L.BILL_NO(+)   AND( L.RETURN_FLAG = '0' OR L.RETURN_FLAG IS NULL) AND C.RETURN_FLAG='0'";
        if (!yearMatch.equals("")) {
            sql += " AND L.BAL_YEAR_MONTH='" + yearMatch + "'";
        }

        sql += " GROUP BY T2.BILL_NO, T2.PLAN_TRANS_TYPE,H.SALE_AREA_DESC,T2.CREATE_NAME, T2.BILL_STATUS, "
                + "T2.LOADVEHICLE_TYPE, T2.STATION_NM, T2.SPCL_LN_NM, T2.RECEIV_NM, T2.ISPRECLOSE,"
                + "T2.SALE_ORG, T2.SALE_ORG_DESC, T2.REALINVOICENO, T2.PICKUP_FLAG, T2.UPDATE_TIME,"
                + "T2.CREATE_TIME,T2.DELETE_TIME, T2.TALL_TIME, T2.LOAD_TIME,L.BAL_YEAR_MONTH,T2.ZOUT_FLAG"
                + ") T1 ";

        if (starta.equals("0")) {
            sql += "  WHERE (TO_NUMBER(T1.ACT_COUNT)-TO_NUMBER(T1.BEEN_COUNT)!=0 "
                    + "OR TO_NUMBER(T1.PLAN_COUNT)-TO_NUMBER(T1.BEEN_COUNT)!=0)  ORDER BY T1.BILL_NO";
        }
        return this.getData(sql);
    }

    /**
     * 提单关闭
     * @param billNo
     * @return
     * @throws Exception 
     */
    @SuppressWarnings( { "unchecked" })
    public CoreReturnObject BillClose(String billNo, String sendNo,
            String userNmae, ArrayList<Object> list, ArrayList<Object> pram,
            String prdCls, String loadvehicleType) throws Exception {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        PreparedStatement ps = null;
        String sql = "";
        Date nowTime = new Date();
        Gson gson = new Gson();
		Boolean interfaceState = false;
        SimpleDateFormat dfT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strNowTime = dfT.format(nowTime);
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            // 修改提单材料表长度（米/支）
            String updateBillC = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updateBillSendNum");
            PreparedStatement psUpdateBillc = con.prepareStatement(updateBillC);
            // 修改出库表长度（米/支）
            String updateOutlist = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updateOutSendNum");
            PreparedStatement psUpdateout = con.prepareStatement(updateOutlist);
            // 修改出库表长度（米/支）（坯子）
            String updateOutlistPz = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updateOutSendNumPZ");
            PreparedStatement psUpdateoutPz = con
                    .prepareStatement(updateOutlistPz);
            // 修改装车材料表实发数（米/支）
            String updateLoad = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updateLoadNum");
            PreparedStatement psUpdateLoad = con.prepareStatement(updateLoad);

            // 修改装车从表交货行对应的提单序号
            String updateLoadMat = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updateLoadMatSeq");
            PreparedStatement psUpdateLoadMat = con
                    .prepareStatement(updateLoadMat);
            String sqlMat = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updateMagment");// 修改材料表状态
            PreparedStatement psMatNo = con.prepareStatement(sqlMat);

            String updatebillM = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updatebillM");// 修改提单主表实际量
            PreparedStatement pstaupdatebillM = con
                    .prepareStatement(updatebillM);
            List<String[]> billNoInfos = CorePipeBillOfLadingClose
                    .getBiltNoInfoByBillNo(con, billNo);
            String[] arrayStr = billNoInfos.get(0); // 提单号
            int num = CorePipeBillOfLadingClose.getLoadvehicle(con, billNo);
            if (num > 0) {
                core.setV_errMsg("提单号 " + billNo + " 下有未确认的装车单,提单不能关闭!");
                return core;
            }
            if (arrayStr[2].equals("1")) {
                if (billNoInfos == null) {
                    core.setV_errMsg("提单号" + billNo + "不存在,请重新选择");
                    return core;
                }
                /*if (billNoInfos.size() > 1) {
                    core.setV_errMsg("提单号" + billNo + "数据异常,不能关闭提单!");
                    return core;
                }*/

                if (arrayStr[1].equals("0") || arrayStr[1].equals("1")) {
                    core.setV_errMsg("提单号" + billNo + "不是提单执行状态,不能关闭提单!");
                    return core;
                }
                if (Integer.parseInt(arrayStr[1]) >= 4) {
                    core.setV_errMsg("提单号" + billNo + "已提单关闭,不能重复关闭提单!");
                    return core;
                }

                // if (arrayStr[2].equals("2")) {
                // core.setV_errMsg("虚拟类型的提单号" + billNo + ",不能关闭提单!");
                // return core;
                // }
                List<YdmZcBillCEntity> billCEntitys = CorePipeBillOfLadingClose
                        .getbillCInfo(con, billNo);
                if (billCEntitys == null) {
                    core.setV_errMsg("炉号信息异常!");
                    return core;
                }
                int count = CorePipeBillOfLadingClose
                        .getTallysheet(con, billNo);
                if (count > 0) {
                    core.setV_errMsg("提单号" + billNo + "下有未装车的理货单,不能关闭!");
                    return core;
                }
                int acount = CorePipeBillOfLadingClose.getTallysheetC(con,
                        billNo);
                if (acount > 0) {
                    core.setV_errMsg("提单号" + billNo + "下还有未装完车的理货单,不能关闭");
                    return core;
                }
                // 修改材料表材料状态
                psMatNo.setObject(1, billNo);
                psMatNo.addBatch();
                psMatNo.executeBatch();
                // String sqlMatNo = CoreXmlSqlParsersFactory
                // .getSql("CorePipeBillOfLadingClose.queryYdmZcBillC1");//
                // 查询提单未理货，未装车的数据材料号
                // sqlMatNo = StringTool.ReplaceAll(sqlMatNo, "#BILL_NO#",
                // billNo);
                // ps = con.prepareStatement(sqlMatNo);
                // ResultSet rsmat = ps.executeQuery();
                // List<MatZcMInfoEntity1> matNo1 = new
                // ArrayList<MatZcMInfoEntity1>();
                // matNo1 = EntityTool.getEntitysByRs(rsmat,
                // MatZcMInfoEntity1.class);
                // rsmat.close();
                // ps.close();

                sql = CoreXmlSqlParsersFactory
                        .getSql("CorePipeBillOfLadingClose.queryYdmZcBillC");// 查询提单未理货，未装车的数据
                ps = con.prepareStatement(sql);
                ps.setObject(1, billNo);
                ResultSet rs = ps.executeQuery();
                while (rs.next()) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CorePipeBillOfLadingClose.updateYdmZcBillC");
                    ps = con.prepareStatement(sql);
                    ps.setObject(1, billNo);
                    ps.setObject(2, rs.getString(3));
                    ps.executeUpdate();
                    ps.close();

                    sql = CoreXmlSqlParsersFactory
                            .getSql("CorePipeBillOfLadingClose.updateYdmZcBillM");
                    ps = con.prepareStatement(sql);
                    ps.setObject(1, rs.getString(4));
                    ps.setObject(2, rs.getString(5));
                    ps.setObject(3, rs.getString(6));
                    ps.setObject(4, userNmae);
                    ps.setObject(5, strNowTime);
                    ps.setObject(6, billNo);
                    ps.setObject(7, rs.getString(3));
                    ps.executeUpdate();
                    ps.close();

                }
                if (!rs.next()) {
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CorePipeBillOfLadingClose.updateYdmZcBillM2");
                    ps = con.prepareStatement(sql);
                    ps.setObject(1, userNmae);
                    ps.setObject(2, strNowTime);
                    ps.setObject(3, billNo);
                    ps.executeUpdate();
                    ps.close();
                }
                rs.close();
                ps.close();

                // for (MatZcMInfoEntity1 matNos : matNo1) {

                // }
                sql = CoreXmlSqlParsersFactory
                        .getSql("CorePipeBillOfLadingClose.querySendBill");// 根据出厂计划号查询提单
                ps = con.prepareStatement(sql);
                ps.setObject(1, sendNo);
                ResultSet rs1 = ps.executeQuery();
                double planWt = 0;
                while (rs1.next()) {
                    planWt += Double.parseDouble(rs1.getString("PLAN_WT"));
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CorePipeBillOfLadingClose.updateSendC");
                    ps = con.prepareStatement(sql);
                    ps.setObject(1, rs1.getString("PLAN_WT"));
                    ps.setObject(2, userNmae);
                    ps.setObject(3, strNowTime);
                    ps.setObject(4, sendNo);
                    ps.setObject(5, rs1.getString("ORD_LN_DLY_PK"));
                    ps.executeUpdate();
                    ps.close();
                }
                rs1.close();
                ps.close();

                sql = CoreXmlSqlParsersFactory
                        .getSql("CorePipeBillOfLadingClose.updateSendM");
                ps = con.prepareStatement(sql);
                ps.setObject(1, planWt);
                ps.setObject(2, userNmae);
                ps.setObject(3, strNowTime);
                ps.setObject(4, sendNo);
                ps.executeUpdate();
                ps.close();

                // 填写的米/英尺数平均到每一支上去
                for (int i = 0; i < list.size(); i++) {
                    ArrayList<String> list1 = (ArrayList<String>) list.get(i);
                    int coun = Integer.parseInt(list1.get(1));
                    double senUnm = Double.parseDouble(list1.get(0));
                    String jutNo = list1.get(2);
                    String batchNo = list1.get(3);
                    String groupNo = list1.get(4);
                    String ordLnDylPk = list1.get(5);
                    List<String> matNo = new ArrayList<String>();
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CorePipeBillOfLadingClose.querySendNUM");// 提单关闭时通过发货量查询提单从表已发材料号
                    ps = con.prepareStatement(sql);
                    ps.setObject(1, billNo);
                    ps.setObject(2, ordLnDylPk);
                    ps.setObject(3, jutNo);
                    ps.setObject(4, batchNo);
                    ps.setObject(5, groupNo);
                    ps.setObject(6, list1.get(7));
                    ResultSet rs2 = ps.executeQuery();
                    while (rs2.next()) {
                        matNo.add(rs2.getString("MAT_NO"));
                    }
                    rs2.close();
                    ps.close();

                    if (matNo.size() == 0) {
                        continue;
                    }
                    List<double[]> lenList = MeanValueCalculation
                            .MeanCalculation(senUnm, coun);
                    List<String> len = new ArrayList<String>();
                    for (int j = 0; j < lenList.size(); j++) {
                        double[] conLen = lenList.get(j);
                        if ((int) conLen[0] >= 0) {
                            for (int z = 0; z < (int) conLen[0]; z++) {
                                len.add(String.valueOf(conLen[1]));
                            }
                        }
                    }
                    if (len.size() != matNo.size()) {
                        core.setV_errMsg("支数不匹配！");
                        return core;
                    }
                    // if (prdCls.equals("405005")) {
                    // for (int l = 0; l < matNo.size(); l++) {
                    // psUpdateBillc.setObject(1, len.get(l));
                    // psUpdateBillc.setObject(2, billNo);
                    // psUpdateBillc.setObject(3, matNo.get(l));
                    // psUpdateBillc.addBatch();
                    //
                    // psUpdateLoad.setObject(1, len.get(l));
                    // psUpdateLoad.setObject(2, billNo);
                    // psUpdateLoad.setObject(3, matNo.get(l));
                    // psUpdateLoad.addBatch();
                    //
                    // psUpdateoutPz.setObject(1, len.get(l));
                    // // psUpdateout.setObject(2, billNo);
                    // psUpdateoutPz.setObject(2, matNo.get(l));
                    // psUpdateoutPz.addBatch();
                    //
                    // }
                    // }
                    // else {
                    for (int l = 0; l < matNo.size(); l++) {
                        psUpdateBillc.setObject(1, len.get(l));
                        psUpdateBillc.setObject(2, billNo);
                        psUpdateBillc.setObject(3, matNo.get(l));
                        psUpdateBillc.addBatch();

                        psUpdateLoad.setObject(1, len.get(l));
                        psUpdateLoad.setObject(2, billNo);
                        psUpdateLoad.setObject(3, matNo.get(l));
                        psUpdateLoad.addBatch();

                       
                        psUpdateout.setObject(1, len.get(l));
                        // psUpdateout.setObject(2, billNo);
                        psUpdateout.setObject(2, matNo.get(l));
                        psUpdateout.addBatch();

                    }
                    // }

                }
                for (int z = 0; z < pram.size(); z++) {

                    ArrayList<String> pram1 = (ArrayList<String>) pram.get(z);
                    String ordLnDlyPk = pram1.get(1);
                    String billSeq = pram1.get(0);
                    
                    psUpdateLoadMat.setObject(1, billNo);
                    psUpdateLoadMat.setObject(2, billNo);
                    psUpdateLoadMat.setObject(3, billSeq);
                    psUpdateLoadMat.setObject(4, billNo);
                    psUpdateLoadMat.setObject(5, ordLnDlyPk);
                    psUpdateLoadMat.addBatch();
                }

                psUpdateLoad.executeBatch();
                psUpdateBillc.executeBatch();
                if (prdCls.equals("405005")) {
                    psUpdateoutPz.executeBatch();
                }
                else {
                    psUpdateout.executeBatch();
                }

                psUpdateLoadMat.executeBatch();
                psUpdateBillc.close();
                psUpdateLoadMat.close();

            }
            else {

                if (billNoInfos == null) {
                    core.setV_errMsg("提单号" + billNo + "不存在,请重新选择");
                    return core;
                }
                /*if (billNoInfos.size() > 1) {
                    core.setV_errMsg("提单号" + billNo + "数据异常,提单不能关闭!");
                    return core;
                }*/
                if (arrayStr[3].equals("0")) {
                    core.setV_errMsg("虚拟提单未第一次关闭,不能提单关闭!");
                    return core;
                }
                if (arrayStr[1].equals("0") || arrayStr[1].equals("1")) {
                    core.setV_errMsg("提单号" + billNo + "不是提单执行状态,不能关闭提单!");
                    return core;
                }
                if (Integer.parseInt(arrayStr[1]) >= 4) {
                    core.setV_errMsg("提单号" + billNo + "已提单关闭,不能重复关闭提单!");
                    return core;
                }
                List<YdmZcBillCEntity> billCEntitys = CorePipeBillOfLadingClose
                        .getbillCInfo(con, billNo);
                if (billCEntitys == null) {
                    core.setV_errMsg("炉号信息异常!");
                    return core;
                }
                int count = CorePipeBillOfLadingClose
                        .getTallysheet(con, billNo);
                if (count > 0) {
                    core.setV_errMsg("提单号" + billNo + "下还有未装车的理货单,不能关闭!");
                    return core;
                }
                int acount = CorePipeBillOfLadingClose
                        .getBillCTall(con, billNo);
                if (acount > 0) {
                    core.setV_errMsg("提单号" + billNo + "下还有未理货的数据,不能关闭");
                    return core;
                }
                // sql = CoreXmlSqlParsersFactory
                // .getSql("CorePipeBillOfLadingClose.updateMagment");
                // for (YdmZcBillCEntity ydmZcBillCEntity : billCEntitys) {
                // String sqlMag = EntityTool.fillSqlByEntity(sql,
                // ydmZcBillCEntity);
                // ps = con.prepareStatement(sqlMag);
                // ps.setObject(1, ydmZcBillCEntity.getGroupNo());
                // ps.executeUpdate();
                // ps.close();
                // }
                // sql = CoreXmlSqlParsersFactory
                // .getSql("CorePipeBillOfLadingClose.updateYdmZcBillC");
                // ps = con.prepareStatement(sql);
                // ps.setObject(1, billNo);
                // ps.executeUpdate();
                // ps.close();
                sql = CoreXmlSqlParsersFactory
                        .getSql("CorePipeBillOfLadingClose.updateYdmZcBillM1");
                ps = con.prepareStatement(sql);
                ps.setObject(1, userNmae);
                ps.setObject(2, strNowTime);
                ps.setObject(3, billNo);
                ps.executeUpdate();
                ps.close();

                // 填写的米/英尺数平均到每一支上去
                for (int i = 0; i < list.size(); i++) {
                    ArrayList<String> list1 = (ArrayList<String>) list.get(i);
                    int coun = Integer.parseInt(list1.get(1));
                    double senUnm = Double.parseDouble(list1.get(0));
                    String jutNo = list1.get(2);
                    String batchNo = list1.get(3);
                    String groupNo = list1.get(4);
                    String ordLnDylPk = list1.get(5);

                    List<String> matNo = new ArrayList<String>();
                    sql = CoreXmlSqlParsersFactory
                            .getSql("CorePipeBillOfLadingClose.querySendNUM");// 提单关闭时通过发货量查询提单从表已发材料号
                    ps = con.prepareStatement(sql);
                    ps.setObject(1, billNo);
                    ps.setObject(2, ordLnDylPk);
                    ps.setObject(3, jutNo);
                    ps.setObject(4, batchNo);
                    ps.setObject(5, groupNo);
                    ps.setObject(6, list1.get(7));
                    ResultSet rs2 = ps.executeQuery();
                    while (rs2.next()) {
                        matNo.add(rs2.getString("MAT_NO"));
                    }
                    rs2.close();
                    ps.close();

                    if (matNo.size() == 0) {
                        continue;
                    }
                    List<double[]> lenList = MeanValueCalculation
                            .MeanCalculation(senUnm, coun);
                    List<String> len = new ArrayList<String>();
                    for (int j = 0; j < lenList.size(); j++) {
                        double[] conLen = lenList.get(j);
                        if ((int) conLen[0] >= 0) {
                            for (int z = 0; z < (int) conLen[0]; z++) {
                                len.add(String.valueOf(conLen[1]));
                            }
                        }
                    }
                    if (len.size() != matNo.size()) {
                        core.setV_errMsg("支数不匹配！");
                        return core;
                    }
                    // if (prdCls.equals("405005")) {
                    // for (int l = 0; l < matNo.size(); l++) {
                    //
                    // psUpdateBillc.setObject(1, len.get(l));
                    // psUpdateBillc.setObject(2, billNo);
                    // psUpdateBillc.setObject(3, matNo.get(l));
                    // psUpdateBillc.addBatch();
                    //
                    // psUpdateLoad.setObject(1, len.get(l));
                    // psUpdateLoad.setObject(2, billNo);
                    // psUpdateLoad.setObject(3, matNo.get(l));
                    // psUpdateLoad.addBatch();
                    //
                    // psUpdateoutPz.setObject(1, len.get(l));
                    // // psUpdateout.setObject(2, billNo);
                    // psUpdateoutPz.setObject(2, matNo.get(l));
                    // psUpdateoutPz.addBatch();
                    // }
                    // }
                    // else {
                    for (int l = 0; l < matNo.size(); l++) {

                        psUpdateBillc.setObject(1, len.get(l));
                        psUpdateBillc.setObject(2, billNo);
                        psUpdateBillc.setObject(3, matNo.get(l));
                        psUpdateBillc.addBatch();

                        psUpdateLoad.setObject(1, len.get(l));
                        psUpdateLoad.setObject(2, billNo);
                        psUpdateLoad.setObject(3, matNo.get(l));
                        psUpdateLoad.addBatch();

                        psUpdateout.setObject(1, len.get(l));
                        // psUpdateout.setObject(2, billNo);
                        psUpdateout.setObject(2, matNo.get(l));
                        psUpdateout.addBatch();
                    }
                    // }
                }
                for (int z = 0; z < pram.size(); z++) {

                    ArrayList<String> pram1 = (ArrayList<String>) pram.get(z);
                    String ordLnDlyPk = pram1.get(1);
                    String billSeq = pram1.get(0);
                    
                    psUpdateLoadMat.setObject(1, billNo);
                    psUpdateLoadMat.setObject(2, billNo);
                    psUpdateLoadMat.setObject(3, billSeq);
                    psUpdateLoadMat.setObject(4, billNo);
                    psUpdateLoadMat.setObject(5, ordLnDlyPk);
                    psUpdateLoadMat.addBatch();
                }
                psUpdateLoad.executeBatch();
                psUpdateBillc.executeBatch();
                if (prdCls.equals("405005")) {
                    psUpdateoutPz.executeBatch();
                }
                else {
                    psUpdateout.executeBatch();
                }
                psUpdateLoadMat.executeBatch();
                psUpdateBillc.close();
                psUpdateLoadMat.close();
            }
         
            // 回写提单主表实际量
            pstaupdatebillM.setObject(1, billNo);
            pstaupdatebillM.addBatch();
            pstaupdatebillM.executeBatch();

            //crm提单同步
            String dataStuats ="";
            if(loadvehicleType.equals("实际")){
                dataStuats = "0";
            }else if(loadvehicleType.equals("虚拟")){
                dataStuats = "1";
            }
            CrmBillService crmBillService = new CrmBillService();
            if(dataStuats == "1"){
                // 未结算时添加记录
                if(!crmBillService.selectCrmBillIsPay(con, billNo)){
                    crmBillService.insertCrmBill(con,billNo,dataStuats);
                }
            } else {
                crmBillService.insertCrmBill(con,billNo,dataStuats);
            }
          //上传到产销
            /*JSONObject jsonObject = new JSONObject();
            jsonObject.put("form_code", "MESTHSO06");
            jsonObject.put("form_name", "发货计划关闭");
            jsonObject.put("form_time", arrayStr[11]);
            jsonObject.put("op_flag", "");
            jsonObject.put("msg_id", "");
            jsonObject.put("deliver_plan_num", arrayStr[0]);
            jsonObject.put("order_no", arrayStr[7]);
            jsonObject.put("order_no_main", arrayStr[8]);
            jsonObject.put("receive_customer", arrayStr[9]);
            jsonObject.put("creater", arrayStr[10]);
            jsonObject.put("createdate", arrayStr[11]);
            DefaultWebServiceRequest request = new DefaultWebServiceRequest();
            request.setServiceId("MESTHSO06");
            request.setMsgBody(jsonObject.toString());
            String result = ServiceToCx.callWebserviceASMX("http://172.54.10.24:8191/ReceiverService.asmx",request,
					"receiveMessage","");	
		   if(!result.equals("200")) {
			   core.setV_errMsg("接口信息上传失败！");
			   core.setResult(1);
			    return core;
		   }*/
            core.setV_errMsg("提单关闭成功!");
            con.commit();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            if (con != null)
                try {
                    con.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
        }
        return core;
    }

    public static List<String[]> getBiltNoInfoByBillNo(Connection con,
            String billNo) throws SQLException {
        List<String[]> list = new ArrayList<String[]>();
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.getBiltNoInfoByBillNo");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, billNo);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            String[] strArray = new String[12];
            strArray[0] = rs.getString("BILL_NO");
            strArray[1] = rs.getString("BILL_STATUS");
            strArray[2] = rs.getString("LOADVEHICLE_TYPE");
            strArray[3] = rs.getString("ISPRECLOSE");
            strArray[4] = rs.getString("BILL_TICKET_STATUS");
            strArray[5] = rs.getString("OUTSTOCK_TICKET_STATUS");
            strArray[6] = rs.getString("TRANSMNY_TICKET_STATUS");
            strArray[7] = rs.getString("ORDER_NO");
            strArray[8] = rs.getString("ORDER_SEQ");
            strArray[9] = rs.getString("CUSTOMER_NM");
            strArray[10] = rs.getString("DELETE_NAME");
            strArray[11] = rs.getString("DELETE_TIME");
            list.add(strArray);
        }
        rs.close();
        ps.close();
        if (list == null || list.size() == 0) {
            return null;
        }
        return list;
    }

    public static List<YdmZcBillCEntity> getbillCInfo(Connection con,
            String billNo) throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.getJustStoveInfoByBillNo");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, billNo);
        ResultSet rs = ps.executeQuery();
        List<YdmZcBillCEntity> list = EntityTool.getEntitysByRs(rs,
                YdmZcBillCEntity.class);
        rs.close();
        ps.close();
        if (list != null && list.size() > 0) {
            for (YdmZcBillCEntity ydmZcBillCEntity : list) {
                QualityDesignTool.nullConverNullString(ydmZcBillCEntity);
            }
            return list;
        }
        else {
            return null;
        }
    }

    /**
     * 提单划断
     * @param billNo
     * @return
     */
    public CoreReturnObject BillCut(String billNo) {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        PreparedStatement ps = null;
        String sql = "";
        SlmBalanceTickets simBalan = new SlmBalanceTickets();
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            List<String[]> billNoInfos = CorePipeBillOfLadingClose
                    .getBiltNoInfoByBillNo(con, billNo);
            if (billNoInfos == null)
                return core;
            String[] arrayStr = billNoInfos.get(0);
            if (arrayStr[2].equals("1")) {
                core.setV_errMsg("提单号" + billNo + "是实际提单,不能提单划断!");
                return core;
            }
            if (billNoInfos == null) {
                core.setV_errMsg("提单号" + billNo + "不存在,请重新选择!");
                return core;
            }
            if (billNoInfos.size() > 1) {
                core.setV_errMsg("提单号" + billNo + "数据异常,不能提单划断!");
                return core;
            }

            if (!arrayStr[1].equals("1")) {
                core.setV_errMsg("只有下发状态的提单,才能提单划断!");
                return core;
            }
            List<YdmZcBillCEntity> billCEntitys = CorePipeBillOfLadingClose
                    .getbillCInfo(con, billNo);
            if (billCEntitys == null) {
                core.setV_errMsg("炉号信息异常!");
                return core;
            }
            int count = CorePipeBillOfLadingClose.getTallysheet(con, billNo);
            if (count > 0) {
                core.setV_errMsg("提单号" + billNo + "下有未装车的理货单,不能划断!");
                return core;
            }
            // sql = CoreXmlSqlParsersFactory
            // .getSql("CorePipeBillOfLadingClose.updateMagment");
            // for (YdmZcBillCEntity ydmZcBillCEntity : billCEntitys) {
            // String sqlMag = EntityTool.fillSqlByEntity(sql,
            // ydmZcBillCEntity);
            // ps = con.prepareStatement(sqlMag);
            // ps.setObject(1, ydmZcBillCEntity.getGroupNo());
            // ps.executeUpdate();
            // ps.close();
            // }
            // sql = CoreXmlSqlParsersFactory
            // .getSql("CorePipeBillOfLadingClose.updateYdmZcBillC");
            // ps = con.prepareStatement(sql);
            // ps.setObject(1, billNo);
            // ps.executeUpdate();
            // ps.close();
            sql = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updateYdmZcBillM");
            ps = con.prepareStatement(sql);
            ps.setObject(1, billNo);
            ps.executeUpdate();
            ps.close();
            core.setV_errMsg("提单划断成功!");
            con.commit();
        }
        catch (SQLException e) {
            try {
                con.rollback();
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {
            if (con != null)
                try {
                    con.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
        }
        return core;
    }

    /**
     * 查询提单下未装车的理货单
     * @param con
     * @param billNo
     * @return
     * @throws SQLException
     */
    public static int getTallysheet(Connection con, String billNo)
            throws SQLException {
        int count = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.getTallysheet");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, billNo);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            count = rs.getInt("COUNT");
        }
        rs.close();
        ps.close();
        return count;
    }

    /**
     * 查询提单下未装完成车的理货单
     * @param con
     * @param billNo
     * @return
     * @throws SQLException
     */
    public static int getTallysheetC(Connection con, String billNo)
            throws SQLException {
        int count = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.getTallysheetC");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, billNo);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            count = rs.getInt("COUNT");
        }
        rs.close();
        ps.close();
        return count;
    }

    /**
     * 查询提单下是否有未理货的提单
     * @param con
     * @param billNo
     * @return
     * @throws SQLException
     */
    public static int getBillCTall(Connection con, String billNo)
            throws SQLException {
        int count = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.getBillCtall");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, billNo);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            count = rs.getInt("COUNT");
        }
        rs.close();
        ps.close();
        return count;
    }

    /***
     * 查询提货单下是否有未确认的装车单
     * @param con
     * @param billNo
     * @return
     */
    public static int getLoadvehicle(Connection con, String billNo) {
        int count = 0;
        String sql = CoreXmlSqlParsersFactory
                .getSql("CorePipeBillOfLadingClose.getLoadvehicle");
        PreparedStatement psta;
        try {
            psta = con.prepareStatement(sql);
            psta.setString(1, billNo);
            ResultSet rs = psta.executeQuery();
            if (rs.next()) {
                count = rs.getInt("ACOUNT");
            }
            rs.close();
            psta.close();
        }
        catch (SQLException e) {

            e.printStackTrace();
        }

        return count;
    }

    /**
     * 撤销提单关闭
     * @param billNo
     * @return
     */
    public CoreReturnObject updateBill(String billNo) {
        CoreReturnObject core = new CoreReturnObject();
        Connection con = null;
        PreparedStatement ps = null;
        String sql = "";
        Gson gson = new Gson();
		Boolean interfaceState = false;
        try {
            con = this.getDao("TgDao").getConnection();
            con.setAutoCommit(false);
            String updatebillM = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.updatebillM1");// 修改提单主表实际量
            PreparedStatement pstaupdatebillM = con
                    .prepareStatement(updatebillM);
            List<String[]> billNoInfos = CorePipeBillOfLadingClose
                    .getBiltNoInfoByBillNo(con, billNo);
            if (billNoInfos == null)
                return core;
            String[] arrayStr = billNoInfos.get(0);
            if (billNoInfos == null) {
                core.setV_errMsg("提单号" + billNo + "不存在,请重新选择!");
                return core;
            }
            if (!arrayStr[1].equals("4")) {
                core.setV_errMsg("只有关闭状态的提单,才能撤销!");
                return core;
            }
            if (!arrayStr[4].equals("0")) {
                core.setV_errMsg("货款对齐未撤销,不能进行此操作!");
                return core;
            }
            if (!arrayStr[5].equals("0")) {
                core.setV_errMsg("出库费未撤销,不能进行此操作!");
                return core;
            }
            if (!arrayStr[6].equals("0")) {
                core.setV_errMsg("运费对齐未撤销,不能进行此操作!");
                return core;
            }
            sql = CoreXmlSqlParsersFactory
                    .getSql("CorePipeBillOfLadingClose.deleteBillM");
            ps = con.prepareStatement(sql);
            ps.setObject(1, billNo);
            ps.executeUpdate();
            ps.close();

            // 回写提单主表实际量     
            pstaupdatebillM.setObject(1, billNo);
            pstaupdatebillM.addBatch();
            pstaupdatebillM.executeBatch();

            //crm同步提单关闭
            CrmBillService crmBillService = new CrmBillService();
            if(crmBillService.selectCrmBill(con,billNo,"0")){
                // 判断crm系统是否结算
                if(crmBillService.selectCrmBillIsPay(con, billNo)){
                    core.setV_errMsg("crm系统已结算，请联系crm系统撤销结算信息!");
                    return core;
                }
                crmBillService.insertCrmBill(con,billNo,"2");
            }

            core.setV_errMsg("撤销关闭提单成功!");
            con.commit();
            
            //上传到产销
            /*YdmZcBillMEntity ydmZcBillMEntity = new YdmZcBillMEntity();
            ydmZcBillMEntity.setBillNo(arrayStr[0]);
            ydmZcBillMEntity.setBillStatus("4");
            ydmZcBillMEntity.setLoadvehicleType(arrayStr[2]);
            ydmZcBillMEntity.setIspreclose(arrayStr[3]);
            String querysql = " SELECT * FROM YDM_ZC_BILL_C WHERE BILL_NO = '"+arrayStr[0]+"'";
            PreparedStatement ps2 = con.prepareStatement(querysql);
            ResultSet rs = ps2.executeQuery();
            if(rs.next()) {
            	List<YdmZcBillCEntity> billCEntities = EntityTool.getEntitysByRs(rs,YdmZcBillCEntity.class);
            	ydmZcBillMEntity.setBillMEntities(billCEntities);
            	interfaceState = ServiceToCx.HttpPostExample("",gson.toJson(ydmZcBillMEntity));
            	if(!interfaceState) {
            		core.setV_errMsg("接口数据上传失败！");
					return core;
            	}
            }*/
        }
        catch (SQLException e) {
            try {
                con.rollback();
            }
            catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {
            if (con != null)
                try {
                    con.close();
                }
                catch (SQLException e) {
                    e.printStackTrace();
                }
        }
        return core;
    }
}
