package core.stlmes.server.sale.dao;

import CoreFS.SA06.CoreReturnObject;
import core.stlmes.server.sale.po.SlmBalanceDetailAllBean;
import core.stlmes.server.sale.po.SlmBalanceInfoBean;
import core.stlmes.server.sale.util.Convert;
import org.apache.commons.lang.time.DateUtils;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class SlmBalanceDetailAllDao extends BaseService
{

	private final String STATUS_CD_NOACCEPT = "0";
	private final String STATUS_CD_ACCEPT = "1";

	private List<SlmBalanceDetailAllBean> query(String sqlCondition)
			throws SQLException
	{
		List<SlmBalanceDetailAllBean> list = null;
		String sqlStr = QUERY_DETAIL_SQL;
		sqlStr = sqlStr + sqlCondition;
		java.sql.ResultSet set = null;
		set = super.executeForResult(sqlStr);
		list = SlmBalanceDetailAllBean.convertResultSetToBeanList(set);
		set.close();
		return list;
	}

	private SlmBalanceInfoDao slmBalanceInfoDao = null;
	private String QUERY_DETAIL_SQL = "";

	public SlmBalanceDetailAllDao()
	{
		slmBalanceInfoDao = new SlmBalanceInfoDao();
		QUERY_DETAIL_SQL = SqlCollection.getSlmBalanceDetailAll();

	}

	public boolean isAskPlanIdExists(String askPlanId)
			throws java.sql.SQLException
	{

		String sqlStr = "select 1 from slm_balancedetail_all where 1 = 1 and askplan_id = ?  and rownum = 1 ";
		java.sql.ResultSet set = null;
		sqlStr = super.getPreparedSQL(sqlStr, new Object[]
		{ askPlanId });
		set = super.executeForResult(sqlStr);
		while (set.next())
		{
			return true;
		}

		return false;
	}

	public List<SlmBalanceDetailAllBean> getSlmBalanceDetailAllByAskPlanId(
			String askPlanId) throws java.sql.SQLException
	{
		String sqlCondition = super.GetSqlConditionByStringValue("ASKPLAN_ID",
				askPlanId);

		return this.query(sqlCondition);

	}

	public List<SlmBalanceDetailAllBean> getSlmBalanceDetailAllByProdId(
			String PRD_ID) throws java.sql.SQLException
	{
		String sqlCondition = super.GetSqlConditionByStringValue("PRD_ID",
				PRD_ID);

		return this.query(sqlCondition);

	}

	public List<SlmBalanceDetailAllBean> getNoAcceptSlmBalanceDetailAllByAskPlanId(
			String askPlanId) throws java.sql.SQLException
	{
		String sqlCondition = super.GetSqlConditionByStringValue("ASKPLAN_ID",
				askPlanId);
		sqlCondition += super.GetSqlConditionByStringValue("STATUS_CD",
				STATUS_CD_NOACCEPT);
		return this.query(sqlCondition);

	}

	public List<SlmBalanceDetailAllBean> getNoAcceptSlmBalanceDetailAllByAskPlanId(
			java.sql.Connection conn, String askPlanId)
			throws java.sql.SQLException
	{
		String sqlCondition = super.GetSqlConditionByStringValue("ASKPLAN_ID",
				askPlanId);
		sqlCondition += super.GetSqlConditionByStringValue("STATUS_CD",
				STATUS_CD_NOACCEPT);
		String sqlStr = QUERY_DETAIL_SQL;
		sqlStr = sqlStr + sqlCondition;
		java.sql.Statement st = conn.createStatement();
		java.sql.ResultSet set = st.executeQuery(sqlStr);
		List<SlmBalanceDetailAllBean> list = null;
		list = SlmBalanceDetailAllBean.convertResultSetToBeanList(set);
		set.close();

		return list;

	}

	public List<SlmBalanceDetailAllBean> getAcceptSlmBalanceDetailAllByAskPlanId(
			String askPlanId) throws java.sql.SQLException
	{
		String sqlCondition = super.GetSqlConditionByStringValue("ASKPLAN_ID",
				askPlanId);
		sqlCondition += super.GetSqlConditionByStringValue("STATUS_CD",
				STATUS_CD_ACCEPT);
		return this.query(sqlCondition);

	}

	public CoreReturnObject updateDetailStatusToAccept(String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = "  update SLM_BALANCEDETAIL_ALL set  "
				+ "  STATUS_CD = '1'  where ASKPLAN_ID = ? ";
		sql = super.getPreparedSQL(sql, new Object[]
		{ askPlanId });
		cro = super.ExcuteNonQueryIgnoreTrans(sql);
		return cro;

	}

	public CoreReturnObject updateDetailStatusToAccept(
			java.sql.Connection conn, String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = "  update SLM_BALANCEDETAIL_ALL set  "
				+ "  STATUS_CD = '1'  where ASKPLAN_ID = ? ";
		sql = super.getPreparedSQL(sql, new Object[]
		{ askPlanId });
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
		return cro;

	}

	public CoreReturnObject deleteByAskPlanId(String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = "  delete from  SLM_BALANCEDETAIL_ALL   "
				+ "     where ASKPLAN_ID = ? ";
		sql = super.getPreparedSQL(sql, new Object[]
		{ askPlanId });
		cro = super.ExcuteNonQueryIgnoreTrans(sql);
		return cro;

	}

	public String deleteByAskPlanIdSql(String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = "  delete from  SLM_BALANCEDETAIL_ALL   "
				+ "     where ASKPLAN_ID = ? ";
		sql = super.getPreparedSQL(sql, new Object[]
		{ askPlanId });
		// cro = super.ExcuteNonQueryIgnoreTrans(sql);
		return sql;

	}

	public CoreReturnObject insert(SlmBalanceDetailAllBean bean)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();

		String sql = SqlCollection.getSlmBalanceDetailInsert(bean);
		cro = super.ExcuteNonQueryIgnoreTrans(sql);
		return cro;

	}

	public CoreReturnObject insert(java.sql.Connection con,
			SlmBalanceDetailAllBean bean) throws java.sql.SQLException,
			java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();

		String sql = SqlCollection.getSlmBalanceDetailInsert(bean);
		PreparedStatement ps = con.prepareStatement(sql);
		ps.executeUpdate();
		ps.close();
		return cro;

	}

	public CoreReturnObject updateAcceptStatusToAccept(String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = " update ydm_zc_bill_m  set BILL_STATUS = '4' where BILL_NO = ?  and  BILL_STATUS = '3'";
		sql = super.getPreparedSQL(sql, new Object[]
		{ askPlanId });
		super.ExcuteNonQueryIgnoreTrans(sql);
		return cro;

	}

	public CoreReturnObject updateAcceptStatusToUnAccept(String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = " update ydm_zc_bill_m  set BILL_STATUS = '3' where BILL_NO = ?  and BILL_STATUS = '4' ";
		sql = super.getPreparedSQL(sql, new Object[]
		{ askPlanId });
		super.ExcuteNonQueryIgnoreTrans(sql);
		return cro;

	}

	public CoreReturnObject updatePreCloseToClose(String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = " update Slm_Balancedetail_All set ISPRECLOSE = '0'  where ASKPLAN_ID =  ? and ISPRECLOSE = '1' ";

		Object[] param = new Object[]
		{ askPlanId };
		sql = super.getPreparedSQL(sql, param);
		cro = super.ExcuteNonQueryIgnoreTrans(sql);
		return cro;
	}

	public CoreReturnObject updateSendNum(String ord_no, String ord_seq,
			String ord_ln_dly, String askplan_id, String askplan_id_seq,
			String spetkey, String steelcodekey, String batchNo, String sendNum)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		String sql = " update Slm_Balancedetail_All a set send_num = ?"
				+ "  where 1=1 and rownum = 1 and a.ord_no||a.ord_seq||a.ord_ln_dly||a.askplan_id||a.askplan_id_seq||a.spetkey||steelcodekey||a.batch_no = ? ";

		Object[] param = new Object[]
		{
				sendNum,
				ord_no + ord_seq + ord_ln_dly + askplan_id + askplan_id_seq
						+ spetkey + steelcodekey + batchNo };
		sql = super.getPreparedSQL(sql, param);
		cro = super.ExcuteNonQueryIgnoreTrans(sql);
		return cro;
	}

	public List<SlmBalanceInfoBean> getSelBalanceInfo(String askPlanId)
			throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		List<SlmBalanceDetailAllBean> list = getNoAcceptSlmBalanceDetailAllByAskPlanId(askPlanId);
		List<SlmBalanceInfoBean> listBalance = new ArrayList<SlmBalanceInfoBean>();
		java.util.Hashtable hsKey = new java.util.Hashtable();
		java.util.Hashtable hsWgt = new java.util.Hashtable();
		java.util.Hashtable hsQty = new java.util.Hashtable();
		java.util.Hashtable hsSendNum = new java.util.Hashtable();
		if (list == null) return null;
		double qty = 0;
		double wgt = 0;
		double sendNum = 0;
		String insertKey = "";
		java.lang.StringBuilder sb = null;
		for (SlmBalanceDetailAllBean bean : list)
		{
			sb = new StringBuilder();
			insertKey = sb.append(bean.getOrd_no()).append(bean.getOrd_seq())
					.append(bean.getOrd_ln_dly()).append(bean.getAskplan_id())
					.append(bean.getAskplan_id_seq()).append(bean.getSpetkey())
					.append(bean.getSteelcodekey()).toString();
			if (hsQty.containsKey(insertKey))
			{
				qty = core.stlmes.server.sale.util.Convert.getDouble(hsQty.get(
						insertKey).toString());

				hsQty.remove(insertKey);
			}
			else
				qty = 0;

			if (hsWgt.containsKey(insertKey))
			{
				wgt = core.stlmes.server.sale.util.Convert.getDouble(hsWgt.get(
						insertKey).toString());
				hsWgt.remove(insertKey);

			}
			else
				wgt = 0;

			if (hsSendNum.containsKey(insertKey))
			{
				sendNum = core.stlmes.server.sale.util.Convert
						.getDouble(hsSendNum.get(insertKey).toString());
				hsSendNum.remove(insertKey);

			}
			else
				sendNum = 0;

			hsQty.put(insertKey, qty + bean.getPrd_qty());
			hsWgt.put(insertKey, wgt + bean.getAct_wgt());

			hsSendNum.put(insertKey, sendNum + bean.getSend_num());
			if (!hsKey.containsKey(insertKey))
			{
				hsKey.put(insertKey, bean);
			}

		}
		listBalance = getSlmbalanceInfoBeanByDeail(hsKey, hsWgt, hsQty,
				hsSendNum);
		return listBalance;

	}

	public List<SlmBalanceInfoBean> getSelBalanceInfo(java.sql.Connection conn,
			String askPlanId) throws java.sql.SQLException,java.lang.Exception
	{
		CoreReturnObject cro = new CoreReturnObject();
		List<SlmBalanceDetailAllBean> list = getNoAcceptSlmBalanceDetailAllByAskPlanId(
				conn, askPlanId);
		List<SlmBalanceInfoBean> listBalance = new ArrayList<SlmBalanceInfoBean>();
		java.util.Hashtable hsKey = new java.util.Hashtable();
		java.util.Hashtable hsWgt = new java.util.Hashtable();
		java.util.Hashtable hsQty = new java.util.Hashtable();

		java.util.Hashtable hsSendNum = new java.util.Hashtable();

		if (list == null) return null;
		double qty = 0;
		double wgt = 0;
		double sendNum = 0;

		String insertKey = "";
		java.lang.StringBuilder sb = null;
		for (SlmBalanceDetailAllBean bean : list)
		{
			qty = 0;
			wgt = 0;
			sendNum = 0;
			sb = new StringBuilder();
			insertKey = sb.append(bean.getOrd_no()).append(bean.getOrd_seq())
					.append(bean.getOrd_ln_dly()).append(bean.getAskplan_id())
					.append(bean.getAskplan_id_seq()).append(bean.getSpetkey())
					.append(bean.getSteelcodekey()).toString();
			if (hsQty.containsKey(insertKey))
			{
				qty = core.stlmes.server.sale.util.Convert.getDouble(hsQty.get(
						insertKey).toString());

				hsQty.remove(insertKey);
			}
			else
				qty = 0;

			if (hsWgt.containsKey(insertKey))
			{
				wgt = core.stlmes.server.sale.util.Convert.getDouble(hsWgt.get(
						insertKey).toString());
				hsWgt.remove(insertKey);

			}
			else
				wgt = 0;

			if (hsSendNum.containsKey(insertKey))
			{
				sendNum = core.stlmes.server.sale.util.Convert
						.getDouble(hsSendNum.get(insertKey).toString());
				hsSendNum.remove(insertKey);

			}
			else
				sendNum = 0;

			hsQty.put(insertKey, qty + bean.getPrd_qty());
			hsWgt.put(insertKey, wgt + bean.getAct_wgt());

			hsSendNum.put(insertKey, sendNum + bean.getSend_num());

			if (!hsKey.containsKey(insertKey))
			{
				hsKey.put(insertKey, bean);
			}

		}
		listBalance = getSlmbalanceInfoBeanByDeail(hsKey, hsWgt, hsQty,
				hsSendNum);
		return listBalance;

	}

	private List<SlmBalanceInfoBean> getSlmbalanceInfoBeanByDeail(
			java.util.Hashtable hsKey, java.util.Hashtable hsWgt,
			java.util.Hashtable hsQty, java.util.Hashtable hsSendNum)
	{
		List<SlmBalanceInfoBean> listBalance = new ArrayList<SlmBalanceInfoBean>();
		SlmBalanceInfoBean bal = null;
		SimpleDateFormat tempDate = new SimpleDateFormat("yyyyMM");
        Calendar cal_1=Calendar.getInstance();//获取当前日期
        cal_1.set(Calendar.DAY_OF_MONTH,26);//设置为26号
        cal_1.set(Calendar.HOUR, 21);
        cal_1.set(Calendar.MINUTE,0);
        cal_1.set(Calendar.SECOND,0);
        String time = tempDate.format(new Date());
        if(new Date().getTime() > cal_1.getTime().getTime()){ // 当前时间大于指定时间
            time = tempDate.format(DateUtils.addMonths(new Date(), 1));
        }

		java.util.Iterator<String> it = hsKey.keySet().iterator();
		while (it.hasNext())
		{
			bal = new SlmBalanceInfoBean();
			String key = it.next();
			SlmBalanceDetailAllBean va = ( SlmBalanceDetailAllBean)hsKey
					.get(key);
			bal.setOrd_no(va.getOrd_no());
			bal.setOrd_seq(va.getOrd_seq());
			bal.setOrd_ln_dly(va.getOrd_ln_dly());
			bal.setAskplan_id(va.getAskplan_id());
			bal.setAskplan_id_seq(va.getAskplan_id_seq());
			bal.setSteelcodekey(va.getSteelcodekey());
			bal.setSteelcode(va.getSteelcode());
			bal.setSpetkey(va.getSpetkey());
			bal.setSpet(va.getPspetkey());
			bal.setPly(va.getOrd_thk());
			bal.setWidth(va.getOrd_wth());
			bal.setLength(va.getOrd_len());
			bal.setPrd_ply(va.getPrd_thk());
			bal.setPrd_widht(va.getPrd_wth());
			bal.setPrd_length(va.getPrd_len());
			bal.setListnumber(va.getListnumber());
			bal.setQuantity(Convert.getDouble(hsQty.get(key).toString()));
			bal.setWeight(Convert.getDouble(hsWgt.get(key).toString()));
			bal.setSend_num(Convert.getDouble(hsSendNum.get(key).toString()));
			bal.setPrice(va.getPrice());
			bal.setBaseprice(va.getOrd_price());

			double mny = super.getMoneyByOrderUnit(va.getPrice().toString(), va
					.getOrder_unit(), Convert.getDouble(hsWgt.get(key)
					.toString()), Convert.getDouble(hsQty.get(key).toString()),
					0);
			bal.setMoney(mny);
			// bal.setMoney(va.getPrice()
			// * Convert.getDouble(hsWgt.get(key).toString()));

			bal.setBalancestatus("0");
			bal.setProdline(va.getProdline());

			bal.setBuyercode(va.getBuyercode());

			bal.setBuyerName(va.getBuyername());
			bal.setInceptcorpcode(va.getRecv_unit());
			bal.setStationcode(va.getStationname());
			bal.setBaseprice(va.getOrd_price());
			bal.setClearflag("0");
			// bal.setCategory(va.getCategoryname());
			bal.setCategory(va.getPd_name());
			bal.setIsout(va.getIsout());
			bal.setForecorpcode(va.getForecorpname());
			bal.setIslockprice(va.getIslockprice());
			bal.setIswatercarriage(va.getIswatercarrage());
			bal.setDockcode(va.getDockname());
			bal.setAreacode(va.getAreacode());
			// bal.setSendbegindate(va.getSendbegindate());
			bal.setFixsize(va.getFixsize_desc());
			bal.setIsinvoicenolocked("0");
			bal.setPlandate(va.getPlandate());
			bal.setTicketstatus("0");
			bal.setBalancestatus_org("0");

			bal.setFst_drawee_unit(va.getFst_drawee_unit());
			bal.setTrans_type(va.getTrans_type());
			bal.setTrans_type_name(va.getTrans_type_name());

			bal.setOrd_pk(va.getOrd_pk());
			bal.setOrd_ln_pk(va.getOrd_ln_pk());
			bal.setOrd_ln_dly_pk(va.getOrd_ln_dly_pk());
			bal.setCreate_dept(va.getCreate_dept());

			bal.setCustomer_no(va.getCustomer_no());
			bal.setCustomer_nm(va.getCustomer_nm());
			bal.setSale_area_no(va.getSale_area_no());
			bal.setSale_area_desc(va.getSale_area_desc());
			bal.setOrder_unit(va.getOrder_unit());

			bal.setSpec_abbsymname(va.getSpec_abbsymname());
			bal.setModel_desc(va.getModel_desc());

			bal.setStd_style(va.getStd_style());
			bal.setStd_style_desc(va.getStd_style_desc());
			String isPreClose = (va.getIspreclose().equals("0") ) ? "否" : "是";

			bal.setIspreclose(isPreClose);
			bal.setContain_tax(va.getContain_tax());
			bal.setPactindex(va.getCategoryname());

			bal.setInvoice_month(time);
			bal.setInvoice_sts("0");

			listBalance.add(bal);

		}
		return listBalance;

	}

}
