package com.steering.pss.plnsaleord.processOrder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

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

import com.steering.comm.db.DBCommon;
import com.steering.comm.tools.EntityTool;
import com.steering.pss.plnsaleord.processOrder.entity.MscPlineChangeEntity;
import com.steering.pss.plnsaleord.processOrder.entity.PlnSaleordProcEntity;

/**
 * 制程变更
 * 
 * @author Administrator
 * 
 */
public class CoreMscPlineChange extends DBCommon {

	/**
	 * 查询合同排产
	 * 
	 * @param ordLnDlyPk
	 *            交货行主键
	 * @return
	 */
	public CoreReturnObject querySaleOrdProc(String ordLnDlyPk) {
		Object[] params = new Object[] { ordLnDlyPk };
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreMscPlineChange.querySaleOrdProc");
		return this.getData(sql, params);
	}

	/**
	 * 查询制程
	 * 
	 * @param ordLnDlyPk
	 * @return
	 */
	public CoreReturnObject queryPline(String ordLnDlyPk) {
		Object[] params = new Object[] { ordLnDlyPk };
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreMscPlineChange.queryPline");
		return this.getData(sql, params);
	}

	/**
	 * 查询钢种
	 * 
	 * @param designKey
	 * @param mscPline
	 * @return
	 */
	public CoreReturnObject queryGrade(String designKey, String mscPline) {
		Object[] params = new Object[] { designKey, mscPline };
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreMscPlineChange.queryGrade");
		return this.getData(sql, params);
	}

	/**
	 * 查询工序
	 * 
	 * @param designKey
	 * @param mscPline
	 * @return
	 */
	public CoreReturnObject queryOperation(String designKey, String mscPline) {
		Object[] params = new Object[] { designKey, mscPline };
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreMscPlineChange.queryOperation");
		return this.getData(sql, params);
	}

	/**
	 * 查询工序点
	 * 
	 * @param designKey
	 * @param mscPline
	 * @return
	 */
	public CoreReturnObject queryOperationPoint(String designKey,
			String mscPline) {
		Object[] params = new Object[] { designKey, mscPline };
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreMscPlineChange.queryOperationPoint");
		return this.getData(sql, params);
	}

	/**
	 * 查询BOM
	 * 
	 * @param materialNo
	 *            物料编码
	 * @param msc
	 *            冶金规范码
	 * @param mscPline
	 *            制程
     * @param wholeBacklog
     *            全程途径码
	 * @return CoreReturnObject
	 */
    public CoreReturnObject queryBom(String materialNo, String msc,
            String mscPline, String wholeBacklog) {
        String sql = CoreXmlSqlParsersFactory
                .getSql("CoreMscPlineChange.queryBom");
        Object[] params = new Object[] { materialNo, msc, mscPline, wholeBacklog };
        return this.getData(sql, params);
    }

	/**
	 * 查询轧管产线
	 * 
	 * @param designKey
	 *            工艺主键
	 * @param dInMaterialNo
	 *            轧管投入物料
	 * @param dOutMaterialNo
	 *            轧管产出物料
	 * @return
	 */
	public CoreReturnObject queryLine(String designKey, String mscPline,
			String dInMaterialNo, String dOutMaterialNo) {
		String sql = CoreXmlSqlParsersFactory
				.getSql("CoreMscPlineChange.queryLine");
		Object[] params = new Object[] { designKey, mscPline, dInMaterialNo,
				dOutMaterialNo };
		return this.getData(sql, params);
	}

	// 制程变更
	/**
	 * 新增合同排产制程分解表
	 * 
	 * @param con
	 * @param procEntity
	 *            排产制程分解实体类
	 * @throws SQLException
	 */
	public static void addPlnSaleordProc(Connection con,
			PlnSaleordProcEntity procEntity) throws SQLException {
		String sql = CoreXmlSqlParsersFactory.getSql("");
		sql = EntityTool.fillSqlByEntity(sql, procEntity);
		PreparedStatement ps = con.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 查询合同排产制程分解表
	 * 
	 * @param con
	 * @param ordLnDlyPk
	 *            交货行主键
	 * @param plndivideId
	 *            排产流水号
	 * @return PlnSaleordProcEntity
	 * @throws SQLException
	 */
	public static PlnSaleordProcEntity queryPlnSaleordProc(Connection con,
			String ordLnDlyPk, String plndivideId) throws SQLException {
		String sql = CoreXmlSqlParsersFactory.getSql("");
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, ordLnDlyPk);
		ps.setObject(2, plndivideId);
		ResultSet rs = ps.executeQuery();
		List<PlnSaleordProcEntity> list = EntityTool.getEntitysByRs(rs,
				PlnSaleordProcEntity.class);
		rs.close();
		ps.close();
		if (list == null || list.size() == 0) {
			return null;
		} else {
			return list.get(0);
		}
	}

	/**
	 * 修改原始变更行的数据
	 * 
	 * @param con
	 * @param processCode
	 *            变更工序
	 * @param ordLnDlyPk
	 *            交货行主键
	 * @param plndivideId
	 *            排产流水号
	 * @param planGroupId
	 *            排产联动组号
	 * @param planWgt
	 *            工序完成量
	 * @throws SQLException
	 */
	public static void updateProcessData(Connection con, String processCode,
			String ordLnDlyPk, String plndivideId, String planGroupId,
			String planWgt) throws SQLException {
		String sql = "";
		if (processCode.equals("B")) {

		} else if (processCode.equals("C")) {
			sql = "update pln_order_dz t set t.orderweight = ?, t.orderstatus = '9' where t.ord_ln_dly_pk=? and t.pln_divide_id=? and t.plan_group_id=?";
		} else if (processCode.equals("D")) {
			sql = "update pln_order_zg t set t.orderweight = ?, t.orderstatus = '9' where t.ord_ln_dly_pk=? and t.pln_divide_id=? and t.plan_group_id=?";
		} else if (processCode.equals("E")) {
			sql = "update pln_order_dbk t set t.orderweight = ?, t.orderstatus = '9' where t.ord_ln_dly_pk=? and t.pln_divide_id=? and t.plan_group_id=?";
		} else if (processCode.equals("F")) {
			sql = "update pln_order_rcl t set t.orderweight = ?, t.orderstatus = '9' where t.ord_ln_dly_pk=? and t.pln_divide_id=? and t.plan_group_id=?";
		} else {
			sql = "update pln_order_jgx t set t.orderweight = ?, t.orderstatus = '9' where t.ord_ln_dly_pk=? and t.pln_divide_id=? and t.plan_group_id=?";
		}
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, planWgt);
		ps.setObject(2, ordLnDlyPk);
		ps.setObject(3, plndivideId);
		ps.setObject(4, planGroupId);
		ps.executeUpdate();
		ps.close();
	}

	/**
	 * 制程变更
	 * 
	 * @param processCode
	 *            当前变更工序
	 * @param planGroupId
	 *            排产联动组号
	 * @param initPlanWgt
	 *            初始工序分配量
	 * @param planWgtSum
	 *            变更前总排产量
	 * @param originalProcEntity
	 *            原始排产类
	 * @param newProcEntitys
	 *            新增排产类集合
	 * @param changeEntiys
	 *            新增传递数据集合
	 * @return CoreReturnObject
	 */
	public CoreReturnObject mscPlineChange(String processCode,
			String planGroupId, String initPlanWgt, String planWgtSum,
			PlnSaleordProcEntity originalProcEntity,
			List<PlnSaleordProcEntity> newProcEntitys,
			List<MscPlineChangeEntity> changeEntiys) {
		CoreReturnObject core = new CoreReturnObject();
		Connection con = null;
		try {
			con = this.getDao(CoreConstantData.sysbeanstr).getConnection();
			con.setAutoCommit(false);
			// 比较界面与数据库的原始排产记录是否发生变化
			PlnSaleordProcEntity proEntity = CoreMscPlineChange
					.queryPlnSaleordProc(con,
							originalProcEntity.getOrdLnDlyPk(),
							originalProcEntity.getPlnDivideId());
			if (proEntity == null) {
				core.setV_errMsg("合同号:" + originalProcEntity.getOrderNo() + "/"
						+ originalProcEntity.getOrderSeq() + "交货行号:"
						+ originalProcEntity.getDeliveryNo() + "排产流水号:"
						+ originalProcEntity.getPlnDivideId() + "数据异常,请重新获取数据!");
				return core;
			}
			if (!originalProcEntity.getPlanWtD().equals(planWgtSum)) {
				core.setV_errMsg("合同号:" + originalProcEntity.getOrderNo() + "/"
						+ originalProcEntity.getOrderSeq() + "交货行号:"
						+ originalProcEntity.getDeliveryNo() + "排产流水号:"
						+ originalProcEntity.getPlnDivideId()
						+ "数据已经发生变化,请重新获取数据!");
				return core;
			}
			// 修改原始排产信息
			// 交货行主键
			String ordLnDlyPk = originalProcEntity.getOrdLnDlyPk();
			// 排产流水号
			String plndivideId = originalProcEntity.getPlnDivideId();
			// 全程途径码
			String mscPline = originalProcEntity.getProcessSeq();
			// 制程经过的工序
			String[] processes = mscPline.substring(
					mscPline.indexOf(processCode)).split("-");
			// 当前变更工序
			CoreMscPlineChange.updateProcessData(con, processCode, ordLnDlyPk,
					plndivideId, planGroupId, initPlanWgt);
			String planWgt = initPlanWgt;
			String getRate = "1";
			CoreProcessOrder CoreProcessOrder = new CoreProcessOrder();
			for (String process : processes) {
				CoreReturnObject coreR = CoreProcessOrder.getGetRate(process,
						ordLnDlyPk, plndivideId, planGroupId);
				// 成材率
				getRate = coreR.getV_errMsg();
				// 工序排产量
				planWgt = String.valueOf(Double.parseDouble(planWgt)
						* Double.parseDouble(getRate));
				CoreMscPlineChange.updateProcessData(con, process, ordLnDlyPk,
						plndivideId, planGroupId, planWgt);
			}
			// 查询最大排产流水号
			// 保存新增排产记录
			for (PlnSaleordProcEntity newProcEntity : newProcEntitys) {
				newProcEntity.setPlanstatus("2");
			}
			con.commit();
		}
        catch (SQLException sqle) {
            try {
                con.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		return core;
	}
	
    /**
     * 查询排产行工艺制程物料产线
     * @param ordLnDlyPk
     * @param plnDivideId
     * @return
     */
    public CoreReturnObject queryProcCraftIndex(String ordLnDlyPk,
            String plnDivideId) {
        CoreReturnObject cro = new CoreReturnObject();
        cro = this.getDataBySqlID("CoreMscPlineChange.queryProcCraftIndex",
                new Object[] { ordLnDlyPk, plnDivideId });
        return cro;
    }
    
    /**
     * 查询
     * @param planGroupId
     * @param processCode
     * @param changeEntity
     * @return
     */
    public CoreReturnObject getIsUseNewCraft(String planGroupId,
            String processCode, MscPlineChangeEntity changeEntity) {
        CoreReturnObject cro = new CoreReturnObject();
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = this.getDao(CoreConstantData.sysbeanstr).getConnection();
            conn.setAutoCommit(false);

            boolean fl = false;
            String oldBom = "";// 原记录Bom号
            String newBom = changeEntity.getBom();
            /*String sqlgetB = "SELECT T.NEXT_GX FROM PLN_REQINF_GP T WHERE T.PLAN_GROUP_ID = ?";
            String sqlgetC = "SELECT T.NEXT_GX, T.BOM, T.ORDERSTATUS FROM PLN_ORDER_DZ T WHERE T.PLAN_GROUP_ID = ?";*/
            String sqlgetD = "SELECT T.NEXT_GX, T.BOM, T.ORDERSTATUS FROM PLN_ORDER_ZG T WHERE T.PLAN_GROUP_ID = ?";
            String sqlgetE = "SELECT T.NEXT_GX, T.BOM, T.ORDERSTATUS FROM PLN_ORDER_DBK T WHERE T.PLAN_GROUP_ID = ?";
            String sqlgetF = "SELECT T.NEXT_GX, T.BOM, T.ORDERSTATUS FROM PLN_ORDER_RCL T WHERE T.PLAN_GROUP_ID = ?";
            String sqlgetG = "SELECT T.BOM, T.ORDERSTATUS FROM PLN_ORDER_JGX T WHERE T.PLAN_GROUP_ID = ?";
            String sql = "";
            /*if (processCode.equals("B")) {
                sql = sqlgetB;
            }
            else if (processCode.equals("C")) {
                sql = sqlgetC;
            }
            else*/ 
            if (processCode.equals("D")) {
                sql = sqlgetD;
            }
            else if (processCode.equals("E")) {
                sql = sqlgetE;
            }
            else if (processCode.equals("F")) {
                sql = sqlgetF;
            }
            else {
                cro.setResult(fl);
                return cro;
            }
            ps = conn.prepareStatement(sql);
            ps.setObject(1, planGroupId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                if (rs.getString("NEXT_GX") != null) {
                    // if (processCode.equals("C")) {
                    // sql = sqlgetC;
                    // }
                    // else
                    if (processCode.equals("D")) {
                        sql = sqlgetD;
                    }
                    else if (processCode.equals("E")) {
                        sql = sqlgetE;
                    }
                    else if (processCode.equals("F")) {
                        sql = sqlgetF;
                    }
                    else if (processCode.equals("G")) {
                        sql = sqlgetG;
                    }
                    PreparedStatement psta = conn.prepareStatement(sql);
                    psta.setObject(1, planGroupId);
                    ResultSet reSet = psta.executeQuery();
                    if (reSet.next()) {
                        if (reSet.getString("ORDERSTATUS") != null
                                && reSet.getString("ORDERSTATUS").trim()
                                        .equals("1")) {
                            oldBom = reSet.getString("BOM");
                        }
                    }
                    psta.close();
                    reSet.close();
                }
            }
            rs.close();
            ps.close();

            if (!oldBom.equals("")) {
                sql = CoreXmlSqlParsersFactory
                        .getSql("CoreMscPlineChange.queryBomMaterialNo");
                PreparedStatement ps1 = conn.prepareStatement(sql);
                ps1.setObject(1, oldBom);
                ResultSet rs1 = ps1.executeQuery();
                
                String oldMaterialNo = "";
                String newMaterialNo = "";
                PreparedStatement ps2 = conn.prepareStatement(sql);
                ps2.setObject(1, newBom);
                ResultSet rs2 = ps2.executeQuery();
                if (rs1.next() && rs2.next()) {
                    if (processCode.equals("B")) {
                        if (rs1.getString("B_OUT_MATERIAL_NO") != null
                                && rs2.getString("B_OUT_MATERIAL_NO") != null) {
                            oldMaterialNo = rs1.getString("B_OUT_MATERIAL_NO");
                            newMaterialNo = rs2.getString("B_OUT_MATERIAL_NO");
                            if (oldMaterialNo.equals(newMaterialNo)) {
                                fl = true;
                            }
                        }
                    }
                    else if (processCode.equals("C")) {
                        if (rs1.getString("C_OUT_MATERIAL_NO") != null
                                && rs2.getString("C_OUT_MATERIAL_NO") != null) {
                            oldMaterialNo = rs1.getString("C_OUT_MATERIAL_NO");
                            newMaterialNo = rs2.getString("C_OUT_MATERIAL_NO");
                            if (oldMaterialNo.equals(newMaterialNo)) {
                                fl = true;
                            }
                        }
                    }
                    else if (processCode.equals("D")) {
                        if (rs1.getString("D_OUT_MATERIAL_NO") != null
                                && rs2.getString("D_OUT_MATERIAL_NO") != null) {
                            oldMaterialNo = rs1.getString("D_OUT_MATERIAL_NO");
                            newMaterialNo = rs2.getString("D_OUT_MATERIAL_NO");
                            if (oldMaterialNo.equals(newMaterialNo)) {
                                fl = true;
                            }
                        }
                    }
                    else if (processCode.equals("E")) {
                        if (rs1.getString("E_OUT_MATERIAL_NO") != null
                                && rs2.getString("E_OUT_MATERIAL_NO") != null) {
                            oldMaterialNo = rs1.getString("E_OUT_MATERIAL_NO");
                            newMaterialNo = rs2.getString("E_OUT_MATERIAL_NO");
                            if (oldMaterialNo.equals(newMaterialNo)) {
                                fl = true;
                            }
                        }
                    }
                    else if (processCode.equals("F")) {
                        if (rs1.getString("F_OUT_MATERIAL_NO") != null
                                && rs2.getString("F_OUT_MATERIAL_NO") != null) {
                            oldMaterialNo = rs1.getString("F_OUT_MATERIAL_NO");
                            newMaterialNo = rs2.getString("F_OUT_MATERIAL_NO");
                            if (oldMaterialNo.equals(newMaterialNo)) {
                                fl = true;
                            }
                        }
                    }
                }
            }
            cro.setResult(fl);
            conn.commit();
        }
        catch (SQLException sqle) {
            try {
                conn.rollback();
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            cro.setV_errCode(-1);
            cro.setV_errMsg(sqle.getMessage());
            return cro;
        }
        finally {
            try {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return cro;
    }
}
