package com.reallinkbilling.jspRedirect;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.ChallanInformationDAO;
import com.reallinkbilling.DAO.ChallanProductInfoDAO;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.utils.GetAccountListForDrCr;

public class ViewChallanJsp extends ActionSupport implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7713193858695407144L;
	
	private HttpSession session;
	private String challanDateTime;
	private String operator;
	private String paymentType;
	private String customerName;
	
	private String transportCharge;
	private String comments;
	
	private String typeOfBill;
	private String challanNumber;
	private Map<String,String> taxList = new LinkedHashMap<String,String>();
	private Map<String,String> unitList = new LinkedHashMap<String,String>();
	private Map<String,String> paymentTypeList = new  LinkedHashMap<String,String>();
	private Map<String,String> billTypeList = new  LinkedHashMap<String,String>();
	private List<ChallanProductInfoDAO> productInfoList ;
	private String defaultValue;
	private String amountPaid;
	private String returnAmount;
	
	private String challanSave;
	private String totalAmount;
	private String totalDiscount;
	private String totalAmouAfterDisount;
	
	private String removeVaules="false";
	
	private ChallanInformationDAO challanInfoDAO = null;
	
	private SessionMap<String,Object> sessionMap;
	
	private String viewBill;
	
	
	private List<String> paymentTypeList2 = new ArrayList<String>();
	private String modeOfPayment;
	private String accountId;
	private Map<String,String> accountList = new LinkedHashMap<String,String>();
	
	private Map<String,String> labourChargeTypeList = new LinkedHashMap<String,String>();
	private String labourChargeType;
	private String addLabourCharges;
	private Map<String,String> rateTypeList = new LinkedHashMap<String,String>();
	private String rateType;
	private String billDate2;
	private String dateAsStringType2;
	
	private String challanStatus;
	
	public String execute() throws IOException{
		 
		String result = "login";
		session=ServletActionContext.getRequest().getSession(false); 
		
	        if(session==null || session.getAttribute("login")==null){ 
	        	addActionMessage("Please Logout and Login again !");
	        	result = "error";
	        }  
	        else{
	        	
	        	String shopId = (String) this.getSessionMap().get("shopId");
	    		String shopCode = (String) this.getSessionMap().get("shopCode");
	    		
	        
	    			taxList = GetListResource.GetTaxList(this.getSessionMap());
	    	
	    			
	        	this.setViewBill("true");
	        	this.setChallanSave("true");
	        	unitList = GetListResource.GetUnitList();
	        	paymentTypeList.put("CASH","CASH");
	        	paymentTypeList.put("CREDIT","CREDIT");
	        	
	        	if(productInfoList == null)
	        	{
	        		productInfoList = new ArrayList<ChallanProductInfoDAO>();
	        	}
	        	
	        	if(challanInfoDAO==null)
	        	{
	        		challanInfoDAO = new ChallanInformationDAO();        		      		
	        		
	        	}
	        	
	        	
	        	paymentTypeList2.add("CASH");
	        	paymentTypeList2.add("UPI");
	        	paymentTypeList2.add("RTGS");
	        	paymentTypeList2.add("NEFT");
	        	paymentTypeList2.add("CHEQUE");
	        	
	        	HashMap<String, String> settings = (HashMap<String, String>) this.getSessionMap().get("shop_settings");
		        
	        	this.setAccountId((String) settings.get("default_account_to_collect"));
	        	this.setAccountList(GetAccountListForDrCr.getAccountList((this.getSessionMap()))); 
	        	this.getRateTypeList().put("INCLUDEGST", "WITH GST");
	        	this.getRateTypeList().put("EXCLUDEGST", "WITH-OUT GST");
	        	this.setRateType((String) settings.get("default_rate_type"));
	        	this.getLabourChargeTypeList().put("QUANTITYWISE", "BY QUANTITY");
	        	this.getLabourChargeTypeList().put("PERCENTAGEWISE", "BY PERCENTAGE");
	        	this.setAddLabourCharges((String) settings.get("add_making_charge_column"));
	        	this.setLabourChargeType("QUANTITYWISE");
	
	        	Connection connection = null;
	       		PreparedStatement preparedStatement= null;
	       		ResultSet resultSet = null;
	       		
	       		
	       		String sql = "";
	       		String db = (String) this.getSessionMap().get("db");
	       		try {
	       			
					connection = GetDBConnection.getDBConnection(db);
	       			
	       			if(this.getDateAsStringType2() == null)
	       			{
	       				this.setDateAsStringType2(this.getBillDate2());
	       			}
					
					
	       			sql = "SELECT "
	       					+ "DATE_FORMAT(challan_date, '%d-%m-%Y'),"
	       					+ "payment_type,"
	       					+ "customer_name,"
	       					+ "transportation_charges,"
	       					+ "comments,"
	       					+ "challan_total_amount,"
	       					+ "challan_amount_received,"
	       					+ "challan_amount_retrurn,"
	       					+ "challan_status "
	       					+ "FROM "
	       					+ "shop_challan_info_master "
	       					+ "WHERE "
	       					+ "shop_id = ?"
	       					+ "AND "
	       					+ "shop_code = ? "
	       					+ "AND "
	       					+ "challan_number = ? "
	       					+ "AND "
	       					+ "challan_date = STR_TO_DATE(?,'%d-%m-%Y')";
	       			
	       			
	       			
	       			preparedStatement = connection.prepareStatement(sql);
	      			preparedStatement.setString(1, shopId);
	       			preparedStatement.setString(2, shopCode);
	       			preparedStatement.setString(3, this.getChallanNumber());
	       			preparedStatement.setString(4, this.getDateAsStringType2());
	       			
	       			resultSet = preparedStatement.executeQuery();
	       			
	       			
	       			resultSet.last();
	       			int rowCount = resultSet.getRow();
	       			resultSet.beforeFirst();
	       			
	       			if(rowCount>0)
	       			{
	       				result = "success";
	       				if(resultSet.next())
	       				{
	       					this.setChallanDateTime(resultSet.getString(1));
	       					this.setPaymentType(resultSet.getString(2));
	       					this.setDefaultValue(resultSet.getString(2));
	       				
	       					this.setCustomerName(resultSet.getString(3));
	       					this.setTransportCharge(resultSet.getString(4));
	       					this.setComments(resultSet.getString(5));	       			
	       					this.setAmountPaid(resultSet.getString(7));
	       					this.setReturnAmount(""+(resultSet.getFloat(6)-resultSet.getFloat(7)));
	       					this.getChallanInfoDAO().setChallanNumber(getChallanNumber());	        	
	       	        		this.getChallanInfoDAO().setPaymentType(getPaymentType());
	       	        		this.getChallanInfoDAO().setCustomerName(getCustomerName());        		
	       		        	this.getChallanInfoDAO().setChallanSaved(true);
	       		        	this.getChallanInfoDAO().setTransportCharge(resultSet.getFloat(4));
	       		        	this.getChallanInfoDAO().setChallanInformationInserted(true);
	       		        	this.getChallanInfoDAO().setChallanDate(resultSet.getString(1));
	       					
	       		        	this.setChallanStatus(resultSet.getString(9));
	       		       	
	       		        	if(resultSet != null)
	       		        	{
	       		        		resultSet.close();
	       		        		resultSet = null;
	       		        	}
	       					if(preparedStatement != null)
	       					{
	       						preparedStatement.close();
	       						preparedStatement = null;
	       					}
	       					
	       					sql = "SELECT "
	       							+ "product_id,"
	       							+ "product_name,"
	       							+ "sales_unit,"
	       							+ "id_tax_table,"
	       							+ "sales_rate,"
	       							+ "product_quantity,"
	       							+ "discount_percentage,"
	       							+ "discount_ruppees,"
	       							+ "product_total_amount,"
	       							+ "product_total_amount_aft_discount,"
	       							+ "product_net_amount,"
	       							+ "product_igst_amount,"
	       							+ "product_cgst_amount,"
	       							+ "product_sgst_amount,"
	       							+ "making_labor_charge,"
	       							+ "product_name_in_marathi,"
	       							+ "product_quantity_2,"
	       							+ "product_batch_id,"
	       							+ "product_expiry_date "
	       							+ "FROM "
	       							+ "shop_challan_product_info_master "
	       							+ "WHERE "
	       							+ "challan_number = ? "
	       							+ "AND "
	       							+ "shop_id = ? "
	       							+ "ANd "
	       							+ "shop_code = ? ";
	       					
	       					
	       					
	       					preparedStatement = connection.prepareStatement(sql);
	       					preparedStatement.setString(1, this.getChallanNumber());
	       					preparedStatement.setString(2, shopId);
	       					preparedStatement.setString(3, shopCode);
	       					
	       					resultSet = preparedStatement.executeQuery();
	       					int serialNumber = 1;
	       					while(resultSet.next())
	       					{
	       						ChallanProductInfoDAO  challanProductInfoDAO = new ChallanProductInfoDAO();
	       						
	       						challanProductInfoDAO.setSerialNumber(""+serialNumber);
	       						challanProductInfoDAO.setProductId(resultSet.getString(1));
	       						challanProductInfoDAO.setProductName(resultSet.getString(2));
	       						challanProductInfoDAO.setSalesUnit(resultSet.getString(3));
	       						challanProductInfoDAO.setTaxId(resultSet.getString(4));
	       						challanProductInfoDAO.setSalesRate(resultSet.getFloat(5));
	       						challanProductInfoDAO.setQuantity(resultSet.getFloat(6));
	       						challanProductInfoDAO.setDiscountPecentage(resultSet.getFloat(7));
	       						challanProductInfoDAO.setDiscountRupees(resultSet.getFloat(8));
	       						challanProductInfoDAO.setAmount(resultSet.getFloat(9));
	       						challanProductInfoDAO.setAmountAfterDiscount(resultSet.getFloat(10));
	       						challanProductInfoDAO.setGrossAmount(resultSet.getFloat(11));
	       						challanProductInfoDAO.setIgst(resultSet.getFloat(12));
	       						challanProductInfoDAO.setCgst(resultSet.getFloat(13));
	       						challanProductInfoDAO.setSgst(resultSet.getFloat(14));
	       						challanProductInfoDAO.setMakingLaborCharge(resultSet.getFloat(15));
	       						challanProductInfoDAO.setProductNameMarathi(resultSet.getString(16));
	       						challanProductInfoDAO.setQuantity2(resultSet.getFloat(17));
	       						challanProductInfoDAO.setBatchId(resultSet.getString(18));
	       						challanProductInfoDAO.setExpiryDate(resultSet.getString(19));
	       						challanProductInfoDAO.setProductReturn(false);
	       						
	       						Map<String,String> taxDetails = GetListResource.GetTaxNamePercentage(resultSet.getString(4), this.getSessionMap());
	       						Float taxPercentage = 0.0F;
	       						try
	       						{
	       							taxPercentage = Float.parseFloat( taxDetails.get("TAX-PERCENTAGE"));
	       						}
	       						catch(Exception e)
	       						{
	       							taxPercentage = 0.0F;
	       						}
	       						challanProductInfoDAO.setTaxPercentage(taxPercentage);
	       						
	       			        	float totalProductDiscount = Float.parseFloat(resultSet.getString(9)) - Float.parseFloat(resultSet.getString(10));
	       						
	       			        	challanProductInfoDAO.setProductTotalDiscount(totalProductDiscount);
	       			        	
	       						this.getProductInfoList().add(challanProductInfoDAO);
	       						serialNumber++;
	       					}
	       					
	       					
	       				}
	       				
	       				
	       			}
	       			
		        	float floatTotalAmount = 0.0F;
		        	float floatTotalDiscount = 0.0F;
		        	float floatTotalAmtAfterDiscount = 0.0F;
		        	
		        	
		        	for(ChallanProductInfoDAO infoDAO : this.getProductInfoList())
		        	{
		        		floatTotalAmount  = floatTotalAmount+ infoDAO.getAmount();
		        		floatTotalAmtAfterDiscount = floatTotalAmtAfterDiscount + infoDAO.getAmountAfterDiscount();
		        		floatTotalDiscount = floatTotalDiscount + infoDAO.getProductTotalDiscount();
		        		
		        	}
		        	
		        	this.setTotalAmount(""+floatTotalAmount);	        	
		        	this.setTotalDiscount(""+floatTotalDiscount);
		        	this.setTotalAmouAfterDisount(""+floatTotalAmtAfterDiscount);
		        	
	       			this.getSessionMap().put("challanInformation", this.getChallanInfoDAO());
	       			this.getSessionMap().put("productList", this.getProductInfoList());
		        	
		        	result = "success";
	       			
	       		} catch (SQLException e) {
	       			e.printStackTrace();
	   				
	   				addActionError(e.getErrorCode()+"||"+e.getMessage()+"|| CANNOT FIND BILL INFOARMATION ! SOME ERROR !");
				
				} catch (IOException e) {
					e.printStackTrace();
					
					addActionError(e.getMessage()+"|| CANNOT FIND BILL INFOARMATION ! SOME ERROR!");
				}	
	   			finally
	   			{
	   				if(resultSet != null)
    				{
    					try {
    						resultSet.close(); resultSet = null;
    					} catch (SQLException e) {
    						
    					}
    				}
	   				if(preparedStatement != null)
	   				{
	   					try {preparedStatement.close(); preparedStatement = null;} catch (SQLException e) {}
	   				}
	   				if(connection != null)
	   				{
	   					try {connection.close(); connection = null;} catch (SQLException e) {}
	   				}
	   				
	   			}
	        	
	        }
	        
	        return result;
	}




	public HttpSession getSession() {
		return session;
	}




	public void setSession(HttpSession session) {
		this.session = session;
	}





	public String getOperator() {
		return operator;
	}




	public void setOperator(String operator) {
		this.operator = operator;
	}




	public String getPaymentType() {
		return paymentType;
	}




	public void setPaymentType(String paymentType) {
		this.paymentType = paymentType;
	}




	public String getCustomerName() {
		return customerName;
	}




	public void setCustomerName(String customerName) {
		this.customerName = customerName;
	}




	public String getTransportCharge() {
		return transportCharge;
	}




	public void setTransportCharge(String transportCharge) {
		this.transportCharge = transportCharge;
	}




	public String getComments() {
		return comments;
	}




	public void setComments(String comments) {
		this.comments = comments;
	}




	public String getChallanDateTime() {
		return challanDateTime;
	}




	public void setChallanDateTime(String challanDateTime) {
		this.challanDateTime = challanDateTime;
	}




	public String getChallanNumber() {
		return challanNumber;
	}




	public void setChallanNumber(String challanNumber) {
		this.challanNumber = challanNumber;
	}




	public List<ChallanProductInfoDAO> getProductInfoList() {
		return productInfoList;
	}




	public void setProductInfoList(List<ChallanProductInfoDAO> productInfoList) {
		this.productInfoList = productInfoList;
	}




	public String getChallanSave() {
		return challanSave;
	}




	public void setChallanSave(String challanSave) {
		this.challanSave = challanSave;
	}




	public ChallanInformationDAO getChallanInfoDAO() {
		return challanInfoDAO;
	}




	public void setChallanInfoDAO(ChallanInformationDAO challanInfoDAO) {
		this.challanInfoDAO = challanInfoDAO;
	}




	public Map<String, String> getTaxList() {
		return taxList;
	}




	public void setTaxList(Map<String, String> taxList) {
		this.taxList = taxList;
	}




	public Map<String, String> getUnitList() {
		return unitList;
	}




	public void setUnitList(Map<String, String> unitList) {
		this.unitList = unitList;
	}




	public Map<String, String> getPaymentTypeList() {
		return paymentTypeList;
	}




	public void setPaymentTypeList(Map<String, String> paymentTypeList) {
		this.paymentTypeList = paymentTypeList;
	}




	public Map<String, String> getBillTypeList() {
		return billTypeList;
	}




	public void setBillTypeList(Map<String, String> billTypeList) {
		this.billTypeList = billTypeList;
	}



	public String getDefaultValue() {
		return defaultValue;
	}




	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}




	public String getTotalAmount() {
		return totalAmount;
	}




	public void setTotalAmount(String totalAmount) {
		this.totalAmount = totalAmount;
	}




	public String getTotalDiscount() {
		return totalDiscount;
	}




	public void setTotalDiscount(String totalDiscount) {
		this.totalDiscount = totalDiscount;
	}




	public String getTotalAmouAfterDisount() {
		return totalAmouAfterDisount;
	}




	public void setTotalAmouAfterDisount(String totalAmouAfterDisount) {
		this.totalAmouAfterDisount = totalAmouAfterDisount;
	}




	public String getRemoveVaules() {
		return removeVaules;
	}




	public void setRemoveVaules(String removeVaules) {
		this.removeVaules = removeVaules;
	}


	
	public SessionMap<String, Object> getSessionMap() {
		return sessionMap;
	}

	public void setSessionMap(SessionMap<String, Object> sessionMap) {
		this.sessionMap = sessionMap;
	}


	public void setSession(Map<String, Object> map) {  
	    sessionMap=(SessionMap<String, Object>)map;  
	}




	public String getViewBill() {
		return viewBill;
	}




	public void setViewBill(String viewBill) {
		this.viewBill = viewBill;
	}





	public static long getSerialversionuid() {
		return serialVersionUID;
	}




	public String getTypeOfBill() {
		return typeOfBill;
	}




	public void setTypeOfBill(String typeOfBill) {
		this.typeOfBill = typeOfBill;
	}




	public String getAmountPaid() {
		return amountPaid;
	}




	public void setAmountPaid(String amountPaid) {
		this.amountPaid = amountPaid;
	}




	public String getReturnAmount() {
		return returnAmount;
	}




	public void setReturnAmount(String returnAmount) {
		this.returnAmount = returnAmount;
	}




	public Map<String, String> getLabourChargeTypeList() {
		return labourChargeTypeList;
	}




	public void setLabourChargeTypeList(Map<String, String> labourChargeTypeList) {
		this.labourChargeTypeList = labourChargeTypeList;
	}




	public String getLabourChargeType() {
		return labourChargeType;
	}




	public void setLabourChargeType(String labourChargeType) {
		this.labourChargeType = labourChargeType;
	}




	public String getAddLabourCharges() {
		return addLabourCharges;
	}




	public void setAddLabourCharges(String addLabourCharges) {
		this.addLabourCharges = addLabourCharges;
	}




	public Map<String, String> getRateTypeList() {
		return rateTypeList;
	}




	public void setRateTypeList(Map<String, String> rateTypeList) {
		this.rateTypeList = rateTypeList;
	}




	public String getRateType() {
		return rateType;
	}




	public void setRateType(String rateType) {
		this.rateType = rateType;
	}




	public List<String> getPaymentTypeList2() {
		return paymentTypeList2;
	}




	public void setPaymentTypeList2(List<String> paymentTypeList2) {
		this.paymentTypeList2 = paymentTypeList2;
	}




	public String getModeOfPayment() {
		return modeOfPayment;
	}




	public void setModeOfPayment(String modeOfPayment) {
		this.modeOfPayment = modeOfPayment;
	}




	public String getAccountId() {
		return accountId;
	}




	public void setAccountId(String accountId) {
		this.accountId = accountId;
	}




	public Map<String, String> getAccountList() {
		return accountList;
	}




	public void setAccountList(Map<String, String> accountList) {
		this.accountList = accountList;
	}




	public String getBillDate2() {
		return billDate2;
	}




	public void setBillDate2(String billDate2) {
		this.billDate2 = billDate2;
	}




	public String getDateAsStringType2() {
		return dateAsStringType2;
	}




	public void setDateAsStringType2(String dateAsStringType2) {
		this.dateAsStringType2 = dateAsStringType2;
	}




	public String getChallanStatus() {
		return challanStatus;
	}




	public void setChallanStatus(String challanStatus) {
		this.challanStatus = challanStatus;
	}







	
	
	
	
}

