/**
 * 
 */
package com.ampiere.web.struts.button;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.apache.ecs.AlignType;
import org.compiere.model.MInOut;
import org.compiere.model.MInOutLine;
import org.compiere.model.MInvoice;
import org.compiere.model.MInvoiceLine;
import org.compiere.model.MOrder;
import org.compiere.model.MOrderLine;
import org.compiere.util.Ctx;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.KeyNamePair;
import org.compiere.util.Msg;

import com.ampiere.dto.CodeValue;
import com.ampiere.search.ColBean;

/**
 * @author Shinjirito
 */
public class CreateFromInvoiceForm extends CreateFromBaseForm {
	private static final long serialVersionUID = 8907414101343633246L;

	/**
	 *	Static Setup - set field value
	 */
	public void statInit(Ctx ctx) {
		super.statInit(ctx);
		setTitle(Msg.getElement(ctx, "C_Invoice_ID", false) + " .. " + Msg.translate(ctx, "CreateFrom"));

		initBPartner(getBpartnerID(), true, ctx);
	}

	/**
	 *  Init Details - load receipts not invoiced
	 *  @param C_BPartner_ID BPartner
	 */
	protected void initBPDetails(int C_BPartner_ID, Ctx ctx)
	{
		log.config("C_BPartner_ID" + C_BPartner_ID);

		//  load Shipments (Receipts) - Completed, Closed
		shipmentList = new ArrayList<CodeValue>();

		//	None
		CodeValue pp = new CodeValue("0", "");
		shipmentList.add(pp);

		//	Display
		StringBuffer display = new StringBuffer("s.DocumentNo||' - '||")
			.append(DB.TO_CHAR("s.MovementDate", DisplayType.Date, Env.getAD_Language(ctx)));
		//
		StringBuffer sql = new StringBuffer("SELECT s.M_InOut_ID,").append(display)
			.append(" FROM M_InOut s "
			+ "WHERE s.C_BPartner_ID=? AND s.IsSOTrx='N' AND s.DocStatus IN ('CL','CO')"
			+ " AND s.M_InOut_ID IN "
				+ "(SELECT sl.M_InOut_ID FROM M_InOutLine sl"
				+ " LEFT OUTER JOIN M_MatchInv mi ON (sl.M_InOutLine_ID=mi.M_InOutLine_ID) "
				+ "GROUP BY sl.M_InOut_ID,mi.M_InOutLine_ID,sl.MovementQty "
				+ "HAVING (sl.MovementQty<>SUM(mi.Qty) AND mi.M_InOutLine_ID IS NOT NULL)"
				+ " OR mi.M_InOutLine_ID IS NULL) "
			+ "ORDER BY s.MovementDate");
		try
		{
			PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
			pstmt.setInt(1, C_BPartner_ID);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next())
			{
				pp = new CodeValue(rs.getString(1), rs.getString(2));
				shipmentList.add(pp);
			}
			rs.close();
			pstmt.close();
		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, sql.toString(), e);
		}
		shipmentSelected = "0";
	}   //  initDetails

	/**
	 *  Load Data - Shipment not invoiced
	 *  @param M_InOut_ID InOut
	 */
	public List loadShipment (int M_InOut_ID, Ctx ctx, int maxRecNo)
	{
		log.config("M_InOut_ID=" + M_InOut_ID);
/*
		m_inout = new MInOut(ctx, M_InOut_ID, null);
		p_order = null;
		if (m_inout.getC_Order_ID() != 0)
			p_order = new MOrder (ctx, m_inout.getC_Order_ID(), null);
*/

		//
		StringBuffer sql = new StringBuffer("SELECT "	//	QtyEntered
			+ "l.MovementQty-SUM(NVL(mi.Qty,0)),l.QtyEntered/l.MovementQty,"
			+ " l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"			//  3..4
			+ " l.M_Product_ID,p.Name, l.M_InOutLine_ID,l.Line,"        //  5..8
			+ " l.C_OrderLine_ID ");                             		//  9
		if (Env.isBaseLanguage(ctx, "C_UOM"))
		{
			sql.append("FROM C_UOM uom, M_InOutLine l, M_Product p, M_MatchInv mi ");
			sql.append("WHERE l.C_UOM_ID=uom.C_UOM_ID");
		}
		else
		{
			sql.append("FROM C_UOM_Trl uom, M_InOutLine l, M_Product p, M_MatchInv mi ");
			sql.append("WHERE l.C_UOM_ID=uom.C_UOM_ID AND uom.AD_Language='").append(Env.getAD_Language(ctx)).append("'");
		}
		sql.append(" AND l.M_Product_ID=p.M_Product_ID")
			.append(" AND l.M_InOutLine_ID=mi.M_InOutLine_ID(+)")
			.append("AND l.M_InOut_ID=? ")					//  #1
			.append("GROUP BY l.MovementQty,l.QtyEntered/l.MovementQty,"
				+ "l.C_UOM_ID,COALESCE(uom.UOMSymbol,uom.Name),"
				+ "l.M_Product_ID,p.Name, l.M_InOutLine_ID,l.Line,l.C_OrderLine_ID ")
			.append("ORDER BY l.Line");

		ArrayList<ColBean> resultList = new ArrayList<ColBean>();
		try
		{
			PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
			pstmt.setInt(1, M_InOut_ID);
			ResultSet rs = pstmt.executeQuery();
			int lineCount = 0;
			while (rs.next())
			{
				ColBean colBean = new ColBean();
				colBean.setColId(Integer.toString(lineCount));
				int beanOffset = 0;

				if (++lineCount > maxRecNo) {
					break;
				}

				// 0-Selection
				colBean.setColData(beanOffset, "false");
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "Select"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.CENTER + ";");
				beanOffset++;

				// 1-Qty
				BigDecimal qtyOrdered = rs.getBigDecimal(1);
				BigDecimal multiplier = rs.getBigDecimal(2);
				BigDecimal qtyEntered = qtyOrdered.multiply(multiplier);
				colBean.setColData(beanOffset, qtyEntered);
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "Quantity"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.RIGHT + ";");
				beanOffset++;

				// 2-UOM
				KeyNamePair pp = new KeyNamePair(rs.getInt(3), rs.getString(4).trim());
				colBean.setColData(beanOffset, pp);
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "C_UOM_ID"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				// 3-Product
				pp = new KeyNamePair(rs.getInt(5), rs.getString(6));
				colBean.setColData(beanOffset, pp);
				colBean.setColTitle(beanOffset, Msg.translate(ctx, "M_Product_ID"));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				// 4-OrderLine
				int C_OrderLine_ID = rs.getInt(9);
				if (rs.wasNull())
					colBean.setColData(beanOffset, null);
				else
					colBean.setColData(beanOffset, new KeyNamePair(C_OrderLine_ID, "."));
				colBean.setColTitle(beanOffset, Msg.getElement(ctx, "C_Order_ID", false));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				// 5-Ship
				pp = new KeyNamePair(rs.getInt(7), rs.getString(8));
				colBean.setColData(beanOffset, pp);
				colBean.setColTitle(beanOffset, Msg.getElement(ctx, "M_InOut_ID", false));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				// 6-Invoice
				colBean.setColData(beanOffset, null);
				colBean.setColTitle(beanOffset, Msg.getElement(ctx, "C_Invoice_ID", false));
				colBean.setStyle(beanOffset, "text-align: " + AlignType.LEFT + ";");
				beanOffset++;

				resultList.add(colBean);
			}
			rs.close();
			pstmt.close();
		}
		catch (SQLException e)
		{
			log.log(Level.SEVERE, sql.toString(), e);
		}

		return resultList;
	}   // loadShipment

	/**
	 *  Save - Create Invoice Lines
	 *  @return true if saved
	 */
	public boolean save(Ctx ctx, int C_Invoice_ID, List resultList)
	{
		log.config("");

		if (selectedIndex == null || selectedIndex.length() <= 0) {
			return false;
		}
		String ppp[] = selectedIndex.split("\\,");
		if (ppp == null || ppp.length <= 0) {
			return false;
		}

		MInOut m_inout = null;
		MOrder p_order = null;
		int M_InOut_ID = Integer.parseInt(shipmentSelected);
		if (M_InOut_ID != 0) {
			m_inout = new MInOut(ctx, M_InOut_ID, null);
			if (m_inout.getC_Order_ID() != 0) {
				p_order = new MOrder(ctx, m_inout.getC_Order_ID(), null);
			}
		} else {
			int C_Order_ID = Integer.parseInt(orderSelected);
			if (C_Order_ID != 0) {
				p_order = new MOrder (ctx, C_Order_ID, null);
			}
		}

		// Invoice
		MInvoice invoice = new MInvoice (ctx, C_Invoice_ID, null);
		log.config(invoice.toString());

		if (p_order != null)
		{
			invoice.setOrder(p_order);	//	overwrite header values
			invoice.save();
		}

		if (m_inout != null && m_inout.getM_InOut_ID() != 0 
			&& m_inout.getC_Invoice_ID() == 0)	//	only first time
		{
			m_inout.setC_Invoice_ID(C_Invoice_ID);
			m_inout.save();
		}


		// Lines
		for (int i = 0; i < ppp.length; i++)
		{
			int idx = Integer.parseInt(ppp[i]);
			ColBean colBean = (ColBean)resultList.get(idx);
			if (colBean != null)
			{
				//  variable values
				BigDecimal QtyEntered = (BigDecimal)colBean.getColData(1);//  1-Qty
				KeyNamePair pp = (KeyNamePair)colBean.getColData(2);   //  2-UOM
				int C_UOM_ID = pp.getKey();
				//
				pp = (KeyNamePair)colBean.getColData(3);               //  3-Product
				int M_Product_ID = 0;
				if (pp != null)
					M_Product_ID = pp.getKey();

				//
				int C_OrderLine_ID = 0;
				pp = (KeyNamePair)colBean.getColData(4);               //  4-OrderLine
				if (pp != null)
					C_OrderLine_ID = pp.getKey();
				int M_InOutLine_ID = 0;
				pp = (KeyNamePair)colBean.getColData(5);               //  5-Shipment
				if (pp != null)
					M_InOutLine_ID = pp.getKey();
				//
				log.fine("Line QtyEntered=" + QtyEntered
					+ ", Product_ID=" + M_Product_ID 
					+ ", OrderLine_ID=" + C_OrderLine_ID + ", InOutLine_ID=" + M_InOutLine_ID);

				MInvoiceLine invoiceLine = new MInvoiceLine (invoice);
				invoiceLine.setM_Product_ID(M_Product_ID, C_UOM_ID);	//	Line UOM
				invoiceLine.setQty(QtyEntered);							//	Invoiced/Entered

				//  Info
				MOrderLine orderLine = null;
				if (C_OrderLine_ID != 0)
					orderLine = new MOrderLine (ctx, C_OrderLine_ID, null);
				MInOutLine inoutLine = null;
				if (M_InOutLine_ID != 0)
				{
					inoutLine = new MInOutLine (ctx, M_InOutLine_ID, null);
					if (orderLine == null && inoutLine.getC_OrderLine_ID() != 0)
					{
						C_OrderLine_ID = inoutLine.getC_OrderLine_ID();
						orderLine = new MOrderLine (ctx, C_OrderLine_ID, null);
					}
				}
				else
				{
					MInOutLine[] lines = MInOutLine.getOfOrderLine(ctx, 
						C_OrderLine_ID, null, null);
					log.fine ("Receipt Lines with OrderLine = #" + lines.length);
					if (lines.length > 0)
					{
						for (int j = 0; j < lines.length; j++)
						{
							MInOutLine line = lines[j];
							if (line.getQtyEntered().compareTo(QtyEntered) == 0)
							{
								inoutLine = line;
								M_InOutLine_ID = inoutLine.getM_InOutLine_ID();
								break;
							}
						}
						if (inoutLine == null)
						{
							inoutLine = lines[0];	//	first as default
							M_InOutLine_ID = inoutLine.getM_InOutLine_ID();
						}
					}
				}	//	get Ship info

				//	Shipment Info
				if (inoutLine != null)
				{
					invoiceLine.setShipLine(inoutLine);		//	overwrites
					if (inoutLine.getQtyEntered().compareTo(inoutLine.getMovementQty()) != 0)
						invoiceLine.setQtyInvoiced(QtyEntered
							.multiply(inoutLine.getMovementQty())
							.divide(inoutLine.getQtyEntered(), 12, BigDecimal.ROUND_HALF_UP));
				}
				else
					log.fine("No Receipt Line");
					
				//	Order Info
				if (orderLine != null)
				{
					invoiceLine.setOrderLine(orderLine);	//	overwrites
					if (orderLine.getQtyEntered().compareTo(orderLine.getQtyOrdered()) != 0)
						invoiceLine.setQtyInvoiced(QtyEntered
							.multiply(orderLine.getQtyOrdered())
							.divide(orderLine.getQtyEntered(), 12, BigDecimal.ROUND_HALF_UP));
				}
				else
				{
					log.fine("No Order Line");
					invoiceLine.setPrice();
					invoiceLine.setTax();
				}
				if (!invoiceLine.save())
					log.log(Level.SEVERE, "Line NOT created #" + i);
			}   //   if selected
		}   //  for all rows

		return true;
	}   // saveInvoice
}
