package com.steering.mes.mcp.CollarLibrary;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
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 java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.SA08.CoreXmlSqlParsersFactory;
import CoreFS.SC01.CoreConstantData;

import com.steering.comm.converter.CoreConverter;
import com.steering.comm.converter.EntityTool;
import com.steering.comm.converter.QualityDesignTool;
import com.steering.comm.db.DBCommon;
import com.steering.mes.mcp.entity.ComMscJgEntity;
import com.steering.mes.mcp.entity.CouplingMatDealEntity;
import com.steering.mes.mcp.entity.JgPurchasePlanEntity;
import com.steering.mes.mcp.entity.JgPurchasePlanQueryParams;

/**
 * 接箍盘库入库
 * @author TJG 2016/04/27
 * @version v1.0
 */
public class FrmCollarInventory extends DBCommon {

    /**
     * 查询盘库入库实绩
     * @param list 传递参数
     * @return 平台统一返回对象
     */
    public CoreReturnObject queryOutPerfo(ArrayList<String> list, String[] arr) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmCollarInventory.queryOutPerfo");
        if (!list.get(0).equals("")) {
            sql += " AND STORAGE_NO ='" + list.get(0) + "'";
        }
        else {
            sql += CoreConverter.toSqlConditionString("STORAGE_NO", arr);
        }
        // sql += "  AND KEP_NO LIKE '%' || '" + list.get(1) + "' || '%' ";
        if (!list.get(2).equals("")) {
            sql += " AND judge_stove_no LIKE '%' || '" + list.get(2)
                    + "' || '%'";
        }
        if(list.get(3).equals(""))
        {
        	sql += "";
        }else{
        sql += " AND DECODE('" + list.get(3)
                + "', NULL, to_date('2019-01-01'), create_time) BETWEEN DECODE('" + list.get(4)
                + "', NULL, to_date('2019-01-01'), to_date('" + list.get(5)
                + "', 'YYYY-MM-DD HH24:MI:SS'))";
        sql += " AND DECODE('" + list.get(6) + "', NULL, to_date('2019-01-01'), to_date('"
                + list.get(7) + "', 'YYYY-MM-DD HH24:MI:SS')) ";
        }
        sql += " AND DEAL_TYPE_CODE ='800702'";
        sql += " AND HAND_FLAG ='1' ORDER BY CREATE_TIME desc";
        return this.getData(sql);
    }

    /**
     * 查询接箍基础信息
     * @param con
     * @param sendPlanNo
     * @return
     * @throws SQLException
     */
    public static ComMscJgEntity getSendPlanCInfo(Connection con, String planNo)
            throws SQLException {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmCollarInventory.QUERYMatButterResult");
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1, planNo);
        ResultSet rs = ps.executeQuery();
        List<ComMscJgEntity> sendPlanCEntitys = EntityTool.getEntitysByRs(rs,
                ComMscJgEntity.class);
        rs.close();
        ps.close();
        if (sendPlanCEntitys == null || sendPlanCEntitys.size() == 0) {
            return null;
        }
        else {
            for (ComMscJgEntity sendPlanCEntity : sendPlanCEntitys) {
                QualityDesignTool.nullConverNullString(sendPlanCEntity);
            }
            return sendPlanCEntitys.get(0);
        }
    }

    /**
     * 查询接箍基础信息（所有）
     * @param list 传递参数
     * @return 平台统一返回对象
     */
    public CoreReturnObject getPsc() {
        String sql = CoreXmlSqlParsersFactory
                .getSql("FrmCollarInventory.getPscJg");
        return this.getData(sql);
    }

    /**
     * 查询材料类别/材料状态
     * @param list 传递参数
     * @return 平台统一返回对象
     */
    public CoreReturnObject queryProductFlag(String sortCode) {
        String sql ="SELECT T.BASECODE,T.BASENAME FROM COM_BASE_INFO T WHERE T.VALIDFLAG='1'";
      if(sortCode.equals("8014")){
    	  sql+=" AND T.SORTCODE='8014' AND T.BASECODE <>'801403'";
      }else{
    	  sql+=" AND T.SORTCODE='"+sortCode+"'";
      }
      
        return this.getData(sql);
    }
    /**
     * 新增
     * @param list 传递参数
     * @return 平台统一返回对象
     */
    public CoreReturnObject addOutLibResult(String mscJgStr,
            String bc, String bz) {
    	 CouplingMatDealEntity mscJg = EntityTool.getEntityByJSONStr(mscJgStr,
    			 CouplingMatDealEntity.class);
        QualityDesignTool.nullConverNullString(mscJg);
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        PreparedStatement psta = null;
        ResultSet rs = null;
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String sqlAddDeal = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.AddDealResult");// 新增交易信息
            // PreparedStatement patAddDeal = connection
            // .prepareStatement(sqlAddDeal);
            String sqlAddButter = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.AddButterResult");// 新增位置表
            PreparedStatement patAddButter = connection
                    .prepareStatement(sqlAddButter);
            String sqlupdateButter = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.AddMatJgResult");// 新增材料表
            PreparedStatement patupdateButter = connection
                    .prepareStatement(sqlupdateButter);
            // Date now = new Date();
            // SimpleDateFormat dateFormat = new SimpleDateFormat(
            // "yyyy-MM-dd HH:mm:ss");
            // String systime = dateFormat.format(now);
           

            String matNoMaX = "";
            // 查询最大物料编号
            String sql = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.getMaxMatNo");
            psta = connection.prepareStatement(sql);
            psta.setObject(1, mscJg.getJudgeStoveNo());
            psta.setObject(2, mscJg.getJudgeStoveNo());
            rs = psta.executeQuery();
            if (rs.next()) {
                matNoMaX = rs.getString("MAT_NO");
            }
            rs.close();
            psta.close();
            
            String blCode = "";
            // 查询备料码
             sql = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.getBlCode");
            psta = connection.prepareStatement(sql);
            psta.setObject(1, mscJg.getJudgeStoveNo());
            rs = psta.executeQuery();
            if (rs.next()) {
            	blCode = rs.getString("BL_CODE");
            }
            rs.close();
            psta.close();
            if(!"".equals(blCode) && blCode != null && !mscJg.getCodeJgBl().equals("")){
            	if(!blCode.equals(mscJg.getCodeJgBl())){
            		cro.setV_errMsg(mscJg.getJudgeStoveNo() + "的备料码信息为：" + blCode);
                	return cro;
            	}
            }
            // 获取接箍基础信息
            ComMscJgEntity pln = getSendPlanCInfo(connection, mscJg.getCodeJg());
            QualityDesignTool.nullConverNullString(pln);
            
            if(pln==null){
            	cro.setV_errMsg("为找到接箍基础信息!");
            	return cro;
            }
            String storageAtte = "";
            String storageAtteName = "";
            String storageType = "";
            String storageTypeName = "";
            String sqlloading = CoreXmlSqlParsersFactory
                    .getSql("FrmInLibrary.queryStorageType");
            psta = connection.prepareStatement(sqlloading);
            psta.setObject(1, mscJg.getStorageNo());
            rs = psta.executeQuery();
            if (rs.next()) {
                storageAtte = rs.getString("STORAGE_ATTR");
                storageAtteName = rs.getString("STORAGE_ATTR_NAME");
                storageType = rs.getString("STORAGE_TYPE_NO");
                storageTypeName = rs.getString("STORAGE_TYPE_NAME");
            }
            rs.close();
            psta.close();
            // 获取交易单号
            String dealOrde = FrmCollarOutBound.doAddDealOrde("IB", "800702",
                    connection);
            if(mscJg.getDeterResults().equals("40740703")){
            	mscJg.setDeterStatus("0");
            }else{
            	mscJg.setDeterStatus("2");
            }
         // 车丝合同信息
            sql = CoreXmlSqlParsersFactory
                   .getSql("FrmCollarInventory.getCSOrderInfo");
           psta = connection.prepareStatement(sql);
           psta.setObject(1, mscJg.getOrderNo());
           rs = psta.executeQuery();
           if (rs.next()) {
        	   mscJg.setOrderNo(rs.getString("ORDER_NO"));
        	   mscJg.setOrderSeq(rs.getString("ORDER_SEQ"));
        	   mscJg.setDeliveryNo(rs.getString("ORDER_SEQ"));
        	   mscJg.setOrdPk(rs.getString("ORD_PK"));
        	   mscJg.setOrdLnPk(rs.getString("ORD_LN_PK"));
        	   mscJg.setOrdLnDlyPk(rs.getString("ORD_LN_DLY_PK"));
           }
           else{
           	cro.setV_errMsg("未找到车丝合同"+mscJg.getOrderNo()+"信息!");
           	return cro;
           }
           rs.close();
           psta.close();
           
            // 盘库入库实绩
            mscJg.setSourceCode("");
            mscJg.setSourceName("");
            mscJg.setMatNo(matNoMaX);
            mscJg.setMinD(pln.getMinD());
            mscJg.setMinH(pln.getMinH());
            mscJg.setSteelcode(pln.getSteelcodeJg());
            mscJg.setSteelname(pln.getSteelcodeJgDesc());
            mscJg.setModelCode(pln.getModelCode());
            mscJg.setModelDesc(pln.getModelDesc());
            mscJg.setOutdiameter(pln.getDiameterJg());
            mscJg.setWallthick(pln.getHeightJg());
            mscJg.setSpecJg(pln.getSpecJg());
            mscJg.setSpecJgDesc(pln.getSpecJgDesc());
            mscJg.setStyleJg(pln.getStyleJg());
            mscJg.setDiameter(pln.getDiameter());
            mscJg.setCheckJVal(pln.getCheckJVal());
            mscJg.setAimlength(pln.getLengthJg());
            mscJg.setSingleweight(pln.getWeightJg());
            mscJg.setStorageAttr(storageAtte);
            mscJg.setStorageAttrName(storageAtteName);
            mscJg.setStorageTypeNo(storageType);
            mscJg.setStorageTypeName(storageTypeName);
            mscJg.setDealOrde(dealOrde);
            String sqlDocStr = EntityTool.fillSqlByEntity(sqlAddDeal, mscJg);
            psta = connection.prepareStatement(sqlDocStr);
            psta.executeUpdate();
            psta.close();

            // 新增材料表
            patupdateButter.setObject(1, matNoMaX);
            patupdateButter.setObject(2, mscJg.getPlineCode());
            patupdateButter.setObject(3, mscJg.getPlineName());
            patupdateButter.setObject(4, mscJg.getJudgeStoveNo());
            patupdateButter.setObject(5, mscJg.getBatchNo());
            patupdateButter.setObject(6, mscJg.getBlWlId());
            patupdateButter.setObject(7, mscJg.getBlWlDesc());
            patupdateButter.setObject(8, pln.getMinD());
            patupdateButter.setObject(9, pln.getMinH());
            patupdateButter.setObject(10, mscJg.getCodeJg());
            patupdateButter.setObject(11, mscJg.getGradecode());
            patupdateButter.setObject(12, mscJg.getGradename());
            patupdateButter.setObject(13, pln.getSteelcodeJg());
            patupdateButter.setObject(14, pln.getSteelcodeJgDesc());
            patupdateButter.setObject(15, pln.getModelCode());
            patupdateButter.setObject(16, pln.getModelDesc());
            patupdateButter.setObject(17, pln.getDiameterJg());
            patupdateButter.setObject(18, pln.getHeightJg());
            patupdateButter.setObject(19, pln.getSpecJg());
            patupdateButter.setObject(20, pln.getSpecJgDesc());
            patupdateButter.setObject(21, pln.getStyleJg());
            patupdateButter.setObject(22, pln.getDiameter());
            patupdateButter.setObject(23, pln.getCheckJVal());
            patupdateButter.setObject(24, pln.getLengthJg());
            patupdateButter.setObject(25, pln.getWeightJg());
            patupdateButter.setObject(26, mscJg.getDealNum());
            patupdateButter.setObject(27, mscJg.getDealWt());
            patupdateButter.setObject(28, bc);
            patupdateButter.setObject(29, bz);
            patupdateButter.setObject(30, mscJg.getCreateName());
            patupdateButter.setObject(31, mscJg.getCreateName());
            patupdateButter.setObject(32, mscJg.getMemo());
            patupdateButter.setObject(33, mscJg.getDeterStatus());
            patupdateButter.setObject(34, mscJg.getDeterResults());
            patupdateButter.setObject(35, mscJg.getDeterResults());
            patupdateButter.setObject(36, mscJg.getWoId());
            patupdateButter.setObject(37, mscJg.getStoveNo());
            patupdateButter.setObject(38, mscJg.getCodeJgBl());
            patupdateButter.addBatch();
         
            // 新增位置表
            patAddButter.setObject(1, mscJg.getKepNo());
            patAddButter.setObject(2, matNoMaX);
            patAddButter.setObject(3, mscJg.getDealNum());
            patAddButter.setObject(4, mscJg.getDealWt());
            patAddButter.setObject(5, mscJg.getStorageNo());
            patAddButter.setObject(6, mscJg.getStorageNo() + "10101");
            patAddButter.setObject(7, storageAtte);
            patAddButter.setObject(8, storageAtteName);
            patAddButter.setObject(9, storageType);
            patAddButter.setObject(10, storageTypeName);
            patAddButter.setObject(11, "");
            patAddButter.setObject(12, "");
            patAddButter.setObject(13, "");
            patAddButter.setObject(14, mscJg.getCreateName());
            patAddButter.setObject(15, mscJg.getProductFlag());// 材料类别
            patAddButter.setObject(16, mscJg.getMatStatus());// 材料状态
            patAddButter.setObject(17, "0001");
            patAddButter.addBatch();

            patupdateButter.executeBatch();
            patAddButter.executeBatch();
            
            patupdateButter.close();
            patAddButter.close();

            cro.setV_errMsg("盘库入库成功！");
            connection.commit();
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            cro.setV_errMsg(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;
    }

    /**
	 * 查询物料码
	 */
	public CoreReturnObject queryMaterial(String plineCode,String codeJg) {
	    String sql = "SELECT T.OUT_MATERIAL_NO,T.OUT_MATERIAL_DESC FROM SLM_BASE_MATERIAL_H_PL T WHERE 1=1";
	    if(!plineCode.equals("")){
	    	sql+=" AND  T.PLINE_CODE='"+plineCode+"'";
	    }
	    if(!codeJg.equals("")){
	    	sql+="AND T.OUT_MATERIAL_NO='"+codeJg+"'";
	    }
	    return this.getData(sql);
	}

	/**
     * 撤销盘库入库实绩记录
     * @param list 传递参数
     * @return obj
     */
    public CoreReturnObject deleteOutLibResult(ArrayList<ArrayList<String>> list) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = this.getDao(CoreConstantData.sysbeanstr)
                .getConnection();
        // PreparedStatement psta = null;
        try {
            connection.setAutoCommit(false); // 取消自动提交事务
            String sqlAddDeal = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.deleteDealResult");// 删除交易信息
            PreparedStatement patAddDeal = connection
                    .prepareStatement(sqlAddDeal);
            String sqlAddButter = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.deleteButterResult");// 删除位置表
            PreparedStatement patAddButter = connection
                    .prepareStatement(sqlAddButter);
            String sqlupdateButter = CoreXmlSqlParsersFactory
                    .getSql("FrmCollarInventory.deleteMatResult");// 删除材料表
            PreparedStatement patupdateButter = connection
                    .prepareStatement(sqlupdateButter);

            for (int i = 0; i < list.size(); i++) {
                ArrayList<String> pram = (ArrayList<String>) list.get(i);
                String matNo = pram.get(0);
                // String kenNo = pram.get(1);
                // String storage = pram.get(2);
                // String name = pram.get(3);
                String dealNo = pram.get(4);

                // 删除交易信息
                patAddDeal.setObject(1, dealNo);
                patAddDeal.addBatch();

                // 删除位置表
                patAddButter.setObject(1, matNo);
                patAddButter.addBatch();

                // 删除材料表
                patupdateButter.setObject(1, matNo);
                patupdateButter.addBatch();

            }
            patAddDeal.executeBatch();
            patAddButter.executeBatch();
            patupdateButter.executeBatch();
            
            patAddDeal.close();
            patAddButter.close();
            patupdateButter.close();
            
            cro.setV_errMsg("撤销成功！");
            connection.commit();

        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            cro.setV_errMsg(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;
    }
    
    /*************************************接箍采购流程****************************************/
    
    /***
	 * 查询钢种基础信息
	 * 
	 * @return
	 */
	public CoreReturnObject getGrade() {
		return this.getDataBySqlID("JgPurchasePlan.getGrade");
	}
	/***
	 * 查询规格基础信息
	 * 
	 * @return
	 */
	public CoreReturnObject getSpec() {
		return this.getDataBySqlID("JgPurchasePlan.getSpec");
	}

	/***
	 * 查询扣型基础信息
	 * 
	 * @return
	 */
	public CoreReturnObject getModel() {
		return this.getDataBySqlID("JgPurchasePlan.getModel");
	}

	/***
	 * 查询外径壁厚
	 * 
	 * @param parm
	 * @return
	 */
	public CoreReturnObject getDimHeig(ArrayList<String> parm) {
		return this.getDataBySqlID("JgPurchasePlan.getDimHeig", parm.toArray());
	}
	
    /**
     * 查询接箍采购计划
     * @param conditionJson 查询条件JSON字符串
     * @return 平台统一返回对象
     */
    public CoreReturnObject queryPurchasePlan(String conditionJson) {
        CoreReturnObject cro = new CoreReturnObject();
        try {
            // 使用查询参数类
            JgPurchasePlanQueryParams condition = EntityTool.getEntityByJSONStr(conditionJson, JgPurchasePlanQueryParams.class);
            QualityDesignTool.nullConverNullString(condition);
            
            // 构建查询SQL - Oracle语法
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.append("SELECT * FROM JG_PURCHASE_PLAN WHERE 1=1 ");
            
            // 计划号查询
            if (condition.getPlanno() != null && !condition.getPlanno().isEmpty()) {
                sqlBuilder.append(" AND PLANNO LIKE '%").append(condition.getPlanno()).append("%' ");
            }
            
            // 状态查询
            if (condition.getStatus() != null&& !condition.getStatus().isEmpty()) {
                sqlBuilder.append(" AND STATUS = ").append(condition.getStatus()).append(" ");
            }
            
            // 合同号查询
            if (condition.getContractNo() != null && !condition.getContractNo().isEmpty()) {
                sqlBuilder.append(" AND CONTRACT_NO LIKE '%").append(condition.getContractNo()).append("%' ");
            }
            
            // 钢级查询
            if (condition.getSgSign() != null && !condition.getSgSign().isEmpty()) {
                sqlBuilder.append(" AND SG_SIGN LIKE '%").append(condition.getSgSign()).append("%' ");
            }
            
            // 规格查询
            if (condition.getSpec() != null && !condition.getSpec().isEmpty()) {
                sqlBuilder.append(" AND SPEC LIKE '%").append(condition.getSpec()).append("%' ");
            }
            
            // 扣型查询
            if (condition.getBuckleType() != null && !condition.getBuckleType().isEmpty()) {
                sqlBuilder.append(" AND BUCKLE_TYPE LIKE '%").append(condition.getBuckleType()).append("%' ");
            }
            
            // 标准查询
            if (condition.getSgStd() != null && !condition.getSgStd().isEmpty()) {
                sqlBuilder.append(" AND SG_STD LIKE '%").append(condition.getSgStd()).append("%' ");
            }
            
            // Oracle日期范围查询
            if (condition.getCreateTimeStart() != null && !condition.getCreateTimeStart().isEmpty()) {
                sqlBuilder.append(" AND CREATE_TIME >= TO_DATE('")
                         .append(condition.getCreateTimeStart())
                         .append(" 00:00:00', 'YYYY-MM-DD HH24:MI:SS') ");
            }
            if (condition.getCreateTimeEnd() != null && !condition.getCreateTimeEnd().isEmpty()) {
                sqlBuilder.append(" AND CREATE_TIME <= TO_DATE('")
                         .append(condition.getCreateTimeEnd())
                         .append(" 23:59:59', 'YYYY-MM-DD HH24:MI:SS') ");
            }            
            // 排序
            sqlBuilder.append(" ORDER BY CREATE_TIME DESC ");
            
            // 直接返回拼接好的SQL
            return this.getData(sqlBuilder.toString());
            
        } catch (Exception e) {
            System.out.println(e.getMessage());
            cro.setV_errMsg("查询失败：" + e.getMessage());
            return cro;
        }
    }
    /**
     * 新增接箍采购计划
     * @param planJson 采购计划JSON字符串
     * @return 平台统一返回对象
     */
    public CoreReturnObject addPurchasePlan(String planJson) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = null;
        PreparedStatement psta = null;
        ResultSet rs = null;
        try {
            // 尝试解析JSON
            JgPurchasePlanEntity plan = EntityTool.getEntityByJSONStr(planJson, JgPurchasePlanEntity.class);
            if (plan == null) {
                cro.setV_errMsg("实体类转换失败：plan为null");
                return cro;
            }
            QualityDesignTool.nullConverNullString(plan);
            connection = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            connection.setAutoCommit(false);
            
            // 生成主键ID
            String id = UUID.randomUUID().toString().replace("-", "");
            plan.setId(id);
            plan.setStatus("0"); // 默认状态为0（计划）
            
            // 生成计划号（格式：JGXQ250918001）
            String planNo = generatePlanNo(connection);
            plan.setPlanno(planNo);

            // ========== 新增：调用接口 MESTHJGXQ01 ==========
            JSONObject jsonObject = new JSONObject();
            // 动态获取参数值，空值转为空字符串
            jsonObject.put("LENGTH", plan.getLength() != null ? plan.getLength() : "");
            jsonObject.put("QUANTITY", plan.getQuantity() != null ? plan.getQuantity() : "");
            jsonObject.put("SG_SIGN", plan.getSgSign() != null ? plan.getSgSign() : "");
            jsonObject.put("SG_SIGN_CODE", plan.getSgSignCode() != null ? plan.getSgSignCode() : "");
            jsonObject.put("SG_STD", plan.getSgStd() != null ? plan.getSgStd() : "");
            jsonObject.put("SG_STD_CODE", plan.getSgStdCode() != null ? plan.getSgStdCode() : "");
            jsonObject.put("PLANNO", planNo); // 使用生成的计划号
            jsonObject.put("BUCKLE_TYPE_CODE", plan.getBuckleTypeCode() != null ? plan.getBuckleTypeCode() : "");
            jsonObject.put("BUCKLE_TYPE", plan.getBuckleType() != null ? plan.getBuckleType() : "");
            jsonObject.put("SPEC", plan.getSpec() != null ? plan.getSpec() : "");
            jsonObject.put("FLAG", "I");
            
            JSONArray respos = new JSONArray();
            respos.add(jsonObject);
            JSONObject object = new JSONObject();
            object.put("messageBody", respos.toString());
            object.put("messageCode", "MESTHJGXQ01");
            String res = postJsonParams("http://172.54.10.24:8091/api/Jgimes/sendMessage", object.toString());
            String operResult = null;

            try {
                // 解析返回的JSON
            	JSONObject responseJson = (JSONObject) JSONSerializer.toJSON(res);
                boolean result = responseJson.getBoolean("result");
                String message = responseJson.getString("message");
                
                if (result) {
                    operResult = "成功:" + message;
                } else {
                    operResult = "失败:" + message;
                    cro.setV_errMsg("调用接口MESTHJGXQ01失败：" + message);
                    connection.rollback();
                    return cro;
                }
            } catch (Exception e) {
                // JSON解析失败，说明返回格式异常
                operResult = "失败:接口返回格式异常 - " + res;
                cro.setV_errMsg("调用接口MESTHJGXQ01失败：返回格式异常");
                connection.rollback();
                return cro;
            }

            // 记录接口调用日志
            this.saveDbLog(connection, "MESTHJGXQ01_I", jsonObject.toString(), planNo, operResult);
            // ========== 接口调用结束 ==========

            // 插入数据
            String insertSql = CoreXmlSqlParsersFactory.getSql("JgPurchasePlan.AddPurchasePlan");
            String sqlStr = EntityTool.fillSqlByEntity(insertSql, plan);
            psta = connection.prepareStatement(sqlStr);
            int result1 = psta.executeUpdate();
            if (result1 > 0) {
                cro.setV_errMsg("新增成功！");
                connection.commit();
            } else {
                cro.setV_errMsg("新增失败！");
                connection.rollback();
            }
            
        } catch (Exception e) {
            System.out.println("发生异常: " + e.getMessage());
            e.printStackTrace(); // 打印完整堆栈信息
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (Exception e2) {
                    System.out.println("回滚异常: " + e2.getMessage());
                }
            }
        } finally {
            try {
                if (rs != null) rs.close();
                if (psta != null) psta.close();
                if (connection != null) connection.close();
            } catch (Exception e2) {
                System.out.println("资源释放异常: " + e2.getMessage());
            }
        }
        return cro;
    }
    /**
   	 * 插入接口日志表
   	 */
   	public static String InsertCxToMesLog = 
   			" insert into cx_to_mes_log "
   			+ "  (SOCKET_NAME,SOCKET_PARMER,SOCKET_TIME,KEY,OPERATE_RESULT) "
   			+ " values (?,?,sysdate,?,?)";
    /**
     * 存储数据操作日志
     * @param connection 数据库连接
     * @param name 接口名称
     * @param params 参数
     * @param key 关键标识
     * @param result 操作结果
     * @throws Exception
     */
    private void saveDbLog(Connection connection, String name, String params, String key, String result) throws Exception {
        PreparedStatement psta = null;
        try {
            psta = connection.prepareStatement(InsertCxToMesLog);
            psta.setString(1, name);
            psta.setString(2, params);
            psta.setString(3, key);
            psta.setString(4, result);
            psta.executeUpdate();
        } finally {
            if (psta != null) {
                psta.close();
            }
        }
    }

    /**
     * 生成计划号（格式：JGXQ250918001）
     * JGXQ + 年月日后两位 + 3位序列号
     */
    private String generatePlanNo(Connection connection) throws SQLException {
        PreparedStatement psta = null;
        ResultSet rs = null;
        
        try {
            // 获取当前日期的后6位（年月日）
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
            String datePart = sdf.format(new Date());
            
            // 查询当天的最大序列号
            String querySql = "SELECT MAX(PLANNO) FROM JG_PURCHASE_PLAN WHERE PLANNO LIKE ?";
            psta = connection.prepareStatement(querySql);
            psta.setString(1, "JGXQ" + datePart + "%");
            rs = psta.executeQuery();
            
            int sequence = 1; // 默认从001开始
            
            if (rs.next()) {
                String maxPlanNo = rs.getString(1);
                if (maxPlanNo != null && maxPlanNo.length() >= 12) {
                    // 提取最后3位序列号
                    String seqStr = maxPlanNo.substring(9, 12);
                    try {
                        sequence = Integer.parseInt(seqStr) + 1;
                    } catch (NumberFormatException e) {
                        sequence = 1;
                    }
                }
            }
            
            // 格式化序列号为3位，不足补0
            String sequencePart = String.format("%03d", sequence);
            
            return "JGXQ" + datePart + sequencePart;
            
        } finally {
            if (rs != null) rs.close();
            if (psta != null) psta.close();
        }
    }
        
    /**
     * 删除接箍采购计划（批量删除）
     * @param idList 主键ID列表
     * @return 平台统一返回对象
     */
    public CoreReturnObject deletePurchasePlan(ArrayList<String> idList) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection connection = null;
        PreparedStatement checkPsta = null;
        PreparedStatement selectPsta = null;
        PreparedStatement deletePsta = null;
        ResultSet rs = null;
        
        if (idList == null || idList.isEmpty()) {
            cro.setV_errMsg("参数不能为空！");
            return cro;
        }
        try {
            connection = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            connection.setAutoCommit(false);
            
            // 检查所有ID是否可以删除（只有状态为0的计划状态可以删除）
            String checkSql = "SELECT ID, STATUS FROM JG_PURCHASE_PLAN WHERE ID = ?";
            checkPsta = connection.prepareStatement(checkSql);
            for (String id : idList) {
                checkPsta.setString(1, id);
                rs = checkPsta.executeQuery();
                
                if (rs.next()) {
                    int status = rs.getInt("STATUS");
                    if (status != 0) {
                        cro.setV_errMsg("ID为 " + id + " 的数据状态不为0，无法删除！只有计划状态的数据可以删除！");
                        connection.rollback();
                        return cro;
                    }
                } else {
                    cro.setV_errMsg("ID为 " + id + " 的数据不存在！");
                    connection.rollback();
                    return cro;
                }
                rs.close();
            }
            
            // 查询要删除的数据详情，用于调用接口
            String selectSql = "SELECT LENGTH, QUANTITY, SG_SIGN, SG_SIGN_CODE, SG_STD, SG_STD_CODE, PLANNO, BUCKLE_TYPE_CODE, BUCKLE_TYPE, SPEC FROM JG_PURCHASE_PLAN WHERE ID = ?";
            selectPsta = connection.prepareStatement(selectSql);
            
            // 批量删除数据
            String deleteSql = "DELETE FROM JG_PURCHASE_PLAN WHERE ID = ?";
            deletePsta = connection.prepareStatement(deleteSql);
            
            int totalDeleted = 0;
            boolean allInterfaceSuccess = true;
            String failedId = null;
            
            for (String id : idList) {
                // 查询数据详情
                selectPsta.setString(1, id);
                rs = selectPsta.executeQuery();
                
                if (rs.next()) {
                    // 构造接口参数
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("LENGTH", rs.getString("LENGTH") != null ? rs.getString("LENGTH") : "");
                    jsonObject.put("QUANTITY", rs.getString("QUANTITY") != null ? rs.getString("QUANTITY") : "");
                    jsonObject.put("SG_SIGN", rs.getString("SG_SIGN") != null ? rs.getString("SG_SIGN") : "");
                    jsonObject.put("SG_SIGN_CODE", rs.getString("SG_SIGN_CODE") != null ? rs.getString("SG_SIGN_CODE") : "");
                    jsonObject.put("SG_STD", rs.getString("SG_STD") != null ? rs.getString("SG_STD") : "");
                    jsonObject.put("SG_STD_CODE", rs.getString("SG_STD_CODE") != null ? rs.getString("SG_STD_CODE") : "");
                    jsonObject.put("PLANNO", rs.getString("PLANNO") != null ? rs.getString("PLANNO") : "");
                    jsonObject.put("BUCKLE_TYPE_CODE", rs.getString("BUCKLE_TYPE_CODE") != null ? rs.getString("BUCKLE_TYPE_CODE") : "");
                    jsonObject.put("BUCKLE_TYPE", rs.getString("BUCKLE_TYPE") != null ? rs.getString("BUCKLE_TYPE") : "");
                    jsonObject.put("SPEC", rs.getString("SPEC") != null ? rs.getString("SPEC") : "");
                    jsonObject.put("FLAG", "D");  // 删除标识

                    JSONArray respos = new JSONArray();
                    respos.add(jsonObject);
                    JSONObject object = new JSONObject();
                    object.put("messageBody", respos.toString());
                    object.put("messageCode", "MESTHJGXQ01");
                    String res = postJsonParams("http://172.54.10.24:8091/api/Jgimes/sendMessage", object.toString());
                    String operResult = null;

                    try {
                        // 解析返回的JSON
                    	 JSONObject responseJson = (JSONObject) JSONSerializer.toJSON(res);
                        boolean result = responseJson.getBoolean("result");
                        String message = responseJson.getString("message");
                        
                        if (result) {
                            operResult = "成功:" + message;
                            // 记录接口调用日志
                            this.saveDbLog(connection, "MESTHJGXQ01_D", respos.toString(), rs.getString("PLANNO"), operResult);
                            
                            // 接口调用成功，添加到批量删除
                            deletePsta.setString(1, id);
                            deletePsta.addBatch();
                            totalDeleted++;
                        } else {
                            operResult = "失败:" + message;
                            allInterfaceSuccess = false;
                            failedId = id;
                            // 记录接口调用日志
                            this.saveDbLog(connection, "MESTHJGXQ01_D", respos.toString(), rs.getString("PLANNO"), operResult);
                            cro.setV_errMsg("调用接口MESTHJGXQ01失败：" + message);
                            break; // 接口调用失败，中断循环
                        }
                    } catch (Exception e) {
                        // JSON解析失败，说明返回格式异常
                        operResult = "失败:接口返回格式异常 - " + res;
                        allInterfaceSuccess = false;
                        failedId = id;
                        this.saveDbLog(connection, "MESTHJGXQ01_D", respos.toString(), rs.getString("PLANNO"), operResult);
                        cro.setV_errMsg("调用接口MESTHJGXQ01失败：返回格式异常");
                        break;
                    }
                }
                rs.close();
            }
            
            if (!allInterfaceSuccess) {
                cro.setV_errMsg("ID为 " + failedId + " 的数据调用删除接口失败，所有数据删除操作已取消！");
                connection.rollback();
                return cro;
            }
            
            // 执行批量删除
            deletePsta.executeBatch();
            cro.setV_errMsg("成功删除 " + totalDeleted + " 条数据！");
            connection.commit();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            cro.setV_errMsg("删除失败：" + e.getMessage());
            if (connection != null) {
                try {
                    connection.rollback();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        } finally {
            try {
                if (rs != null) rs.close();
                if (checkPsta != null) checkPsta.close();
                if (selectPsta != null) selectPsta.close();
                if (deletePsta != null) deletePsta.close();
                if (connection != null) connection.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        
        return cro;
    }
    
    public static String postJsonParams(String requestUrl, String params) {
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(requestUrl);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setConnectTimeout(5000); // 规定20秒内必须响应
            connection.setRequestProperty("Accept", "/"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("serviceId", "MESTHJGXQ01"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();
            if (connection != null) {
                InputStream inputStream = null;
                //根据responseCode来获取输入流，此处错误响应码的响应体内容也要获取（看服务端的返回结果形式决定）
                if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
                    inputStream = connection.getInputStream();
                } else {
                    inputStream = connection.getErrorStream();
                }
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append("\r\n");
                }
                br.close();
            }
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    
    
    /*************************************接箍采购流程****************************************/
    
}
