package idc.json.command;

import idc.model.IdcCmd;
import idc.model.IdcDAO;
import idc.model.IdcPaymentListDTO;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

public class IdcGetPaymentListJSONCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcGetPaymentListJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//입금리스트 가져오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		JSONArray list = new JSONArray();
		String sc = request.getParameter("service_code");
		String from = request.getParameter("from");
		if(from!=null && from.equals(""))
			from=null;
		getList(list, sc, from);
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		
		try
		{
			response.getWriter().write(list.toString());
		}
		catch (IOException e)
		{
			System.out.println("IdcGetPaymentListJSONCmd - SEND 오류");
			e.printStackTrace();
		}
	}
	
	private void getList(JSONArray list, String sc, String d)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		
		String day = " AND date_format(payment_date,'%y-%m') = date_format(?,'%y-%m') ";
		if(d==null)
			day = " AND date_format(payment_date,'%y-%m') = date_format(curdate(),'%y-%m') ";
		try	
		{
			conn=dao.getConn();
			//String sql="SELECT * FROM paymentList WHERE service_code='"+sc+"' " + day;
			String sql="SELECT * FROM paymentList WHERE service_code='"+sc+"' ";
			sql+="ORDER BY num DESC ";
			pstmt =conn.prepareStatement(sql);
			if(d!=null)
				pstmt.setDate(1, Date.valueOf(d));
			rs = pstmt.executeQuery();
			System.out.println(sql);
			while(rs.next())
			{
				IdcPaymentListDTO dto = new IdcPaymentListDTO();
				dto.set_case(rs.getString("_case"));
				dto.setCode(rs.getString("service_code"));
				dto.setDate(rs.getDate("payment_date"));
				dto.setName(rs.getString("client_name"));
				dto.setPayment(rs.getString("payment"));
				dto.setAdddb_code(rs.getString("adddb_code"));
				dto.nullDate();
				
				list.add(dto);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetPaymentListJSONCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(rs!=null)rs.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcGetPaymentListJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
















