package idc.deposit.command;

import idc.model.IdcCmd;
import idc.model.IdcDAO;
import idc.model.IdcDepositNonPaymentDTO;
import idc.model.IdcNonpaymentDTO;

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

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

public class IdcDepositNonPaymentListExcelCmd implements IdcCmd
{
	private int calTime;
	IdcDAO dao;
	private int WRITING_PER_PAGE;
	
	public IdcDepositNonPaymentListExcelCmd()
	{
		dao = new IdcDAO();
		calTime = 60*60*24*1000;	//60초 곱하기 60분 곱하기 24시간 곱하기 1000(1/1000초로 나오니까 1초로 만들어준다.)
		WRITING_PER_PAGE=20;
	}
	
	//입금리스트 엑셀
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		String filter = request.getParameter("filter");
		if(filter==null)
			filter="all";
		String sc = request.getParameter("searchContent");
		if(sc==null)
			sc="";
		else if(!sc.equals(""))
			filter="all";
		int pageCnt = getPageCnt(sc, filter);
		int curPage = getCurPage(request.getParameter("curPage"));
		int firstPage = getFirstPage(pageCnt, curPage);
		int endPage = getEndPage(firstPage, pageCnt);
		ArrayList<IdcNonpaymentDTO> list = new ArrayList<IdcNonpaymentDTO>() ;
		
		//서비스 가져오기.
		idcDepositNonPaymentListCmd(curPage,list,sc, filter);

		String service_code="";
		if(!sc.equals(""))
		{
			for(int i=0;i<list.size();i++)
			{
				service_code = list.get(i).getDto().getService_code();
				//통합,분할된 db가져오기.
				ArrayList<IdcDepositNonPaymentDTO> ulist = new ArrayList<IdcDepositNonPaymentDTO>();
				ArrayList<IdcDepositNonPaymentDTO> nulist = new ArrayList<IdcDepositNonPaymentDTO>();
				
				idcDepositNonpaymentListCmd(ulist, nulist,service_code);
				list.get(i).setUlist(ulist);
				list.get(i).setNulist(nulist);
			}
		}
		
		request.getSession().setAttribute("IdcNonPayMentList", list);
		request.setAttribute("searchContent",sc);
		request.setAttribute("pageCnt", pageCnt);
		request.setAttribute("curPage", curPage);
		request.setAttribute("firstPage", firstPage);
		request.setAttribute("endPage", endPage);
		request.setAttribute("filter", filter);
		if(sc!="")
			request.setAttribute("checkContent", "o");
		else
			request.setAttribute("checkContent", "x");

	}
		
	private int getCurPage(String strPage)
	{
		int curPage=1;
		
		if(strPage !=null && strPage!="")
			curPage=Integer.parseInt(strPage);
		
		return curPage;
	}
	private int getFirstPage(int pageCnt, int curPage)
	{
		int firstPage = 1;
		if(pageCnt-10>1)
			firstPage=pageCnt-10;
		
		int div =0;
		if(firstPage>=curPage)
			div = firstPage-curPage;
		firstPage-=div;
		
		return firstPage;
	}
	private int getEndPage(int firstPage, int pageCnt)
	{
		int endPage = pageCnt;
		
		int div = pageCnt-firstPage;
		if(div>10)
			endPage-=div-10;
		return endPage;
	}
	private int getPageCnt(String sc, String filter)
	{
		int pageCnt=1;
		String w = getFilter(filter);
		
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		ResultSet rs=null, rs2=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT service_code FROM clientdb as c INNER JOIN servicedb as s ";
			sql+="ON c.client_code = s.client_code ";		
			//sql+="WHERE service_nonpayment != 0 AND client_name like '%"+sc+"%'";
			sql+="WHERE client_name like '%"+sc+"%'";
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				//sql = "SELECT * FROM adddb WHERE service_code=?" + w;// AND adddb_accountStatus='incomplete' "+w;
				sql = "SELECT * FROM adddb WHERE service_code=? AND adddb_accountStatus='incomplete' "+w;
				//MK 수정
				//sql += " AND adddb_nonpayment not in ('0') ORDER BY adddb_payment_date ASC";
				sql += " AND adddb_nonpayment not in ('0') ";
				pstmt2=conn.prepareStatement(sql);
				pstmt2.setString(1, rs.getString("service_code"));
				rs2=pstmt2.executeQuery();
				if(rs2.next())
					pageCnt ++;
			}
			pageCnt = pageCnt/WRITING_PER_PAGE+1;
		}
		catch (Exception e) 
		{
			System.out.println("IdcMemberListFormCmd - pageCnt 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(rs!=null)rs.close();
				if(pstmt2!=null)pstmt2.close();
				if(rs2!=null)rs2.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcMemberListFormCmd - pageCnt  에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return pageCnt;
	}
	private int getFirstPage(int pageCnt)
	{
		int firstPage = 1;
		if(pageCnt-10>1)
			firstPage=pageCnt-10;
		return firstPage;
	}
	private String getPaymentStatus(Date payDate, int pay)
	{
		String today;

		String[] strd1,strd2;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		today = sdf.format(new java.util.Date());
		Date curDate = Date.valueOf(today);
		
		strd1 = payDate.toString().split("-");
		strd2 = curDate.toString().split("-");
		
		Calendar date1=Calendar.getInstance();
		Calendar date2=Calendar.getInstance();
		
		date1.set(Integer.parseInt(strd1[0]),Integer.parseInt(strd1[1])-1,Integer.parseInt(strd1[2]));
		date2.set(Integer.parseInt(strd2[0]),Integer.parseInt(strd2[1])-1,Integer.parseInt(strd2[2]));
		
		String result="";
		
		long bring = (date1.getTimeInMillis()-date2.getTimeInMillis())/calTime;

		if(pay==0)
		{
			result="완납";
		}
		else
		{
			switch(payDate.compareTo(curDate))
			{
			//기간 지남
			case -1: 
				result="미납 "+bring*-1+"일째";
				break;
			//당일	
			case 0 : 
				result="당일 미납";
				break;
			//기간 안됨.
			default : 
				result=bring+"일 전";
			}
		}
		return result;
	}
	//서비스 가져오기.
	private void idcDepositNonPaymentListCmd(int curPage, ArrayList<IdcNonpaymentDTO> list,String sc, String filter)
	{
//		필터 기능
		String w = getFilter(filter);
		
//		필터
		
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null, pstmt3=null, pstmt4=null;
		ResultSet rs=null, rs2=null, rs3=null, rs4=null;
		int numbering_end =  WRITING_PER_PAGE * (curPage -1);
		int numbering = 0;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT service_code FROM servicedb "; //WHERE service_nonpayment>0";
			pstmt4=conn.prepareStatement(sql);
			rs4=pstmt4.executeQuery();
			while(rs4.next())
			{
				sql="SELECT adddb_payment FROM adddb WHERE service_code=? "+w;
				//MK 수정
				//sql="SELECT * FROM adddb WHERE service_code=? "+w;
				//sql += " ORDER BY adddb_payment_date ASC";
				pstmt2=conn.prepareStatement(sql);
				pstmt2.setString(1, rs4.getString("service_code"));
				rs2 = pstmt2.executeQuery();
				if(rs2.next())
					numbering++;
			}
			numbering-=numbering_end;
			
			sql="SELECT client_name, service_line, server_code, service_ip,service_request_date, service_payment_date, service_amount, service_nonpayment, service_note, service_num, service_code, service_line ";
			sql+="FROM clientdb INNER JOIN servicedb ";
			sql+="ON clientdb.client_code = servicedb.client_code ";
			sql+="WHERE client_name like '%"+sc+"%' ";
			//sql+="WHERE servicedb.service_nonpayment != 0 AND client_name like '%"+sc+"%' ";			
			
//			System.out.println(sql);
			
			pstmt =conn.prepareStatement(sql);			
			rs = pstmt.executeQuery();
			
			while(rs.next())
			{
				IdcDepositNonPaymentDTO dto = new IdcDepositNonPaymentDTO();
				dto.setClient_name(rs.getString("client_name"));
				dto.setService_line(rs.getString("service_line"));
				
				sql = "SELECT * FROM adddb WHERE service_code=? "+w; //AND adddb_accountStatus='incomplete' "+w;
				//MK주석처리
				//sql += " ORDER BY adddb_payment_date ASC";
				System.out.println(sql);
				pstmt3 = conn.prepareStatement(sql);
				pstmt3.setString(1, rs.getString("service_code"));
				rs3=pstmt3.executeQuery();
				if(rs3.next())
				{
					IdcNonpaymentDTO udto = new IdcNonpaymentDTO();
					String temp = "";
					switch (rs.getString("service_line")){
					case "normal":
						temp = "일반";
						break;
					case "defence":
						temp = "방어";
						break;
					case "solo":
						temp = "전용";
						break;
					case "test":
						temp = "테스트";
						break;
					case "soloLine":
						temp = "전용라인";
						break;
					case "substitution":
						temp = "대체서버";
						break;
					case "vpn":
						temp = "VPN";
						break;
					case "event":
						temp = "이벤트";
						break;		
					case "office":
						temp = "자사서버";
						break;
					case "onetime":
						temp = "일회성";
						break;							
					default:
						break;
					}					
					
					
					
					dto.setTemp(temp);				
					dto.setService_num(numbering--);
					udto.setDto(dto);
					list.add(udto);
				}//if
				dto.setService_code(rs.getString("service_code"));
				dto.setServer_code(rs.getString("server_code"));
				dto.setService_ip(rs.getString("service_ip"));
				dto.setService_request_date(rs.getDate("service_request_date"));
				dto.setService_payment_date(rs.getDate("service_payment_date"));
				dto.setService_amount(rs.getInt("service_amount"));
				dto.setService_nonpayment(rs.getInt("service_nonpayment"));
				dto.setService_note(rs.getString("service_note"));
//				dto.setService_payment_status(getPaymentStatus(rs3.getDate("adddb_payment_date"),rs3.getInt("adddb_nonpayment")));
				dto.setService_payment_status(getPaymentStatus(rs.getDate("service_payment_date"),rs.getInt("service_nonpayment")));
				
			}//while
		}
		catch (Exception e) 
		{
			System.out.println("IdcDepositNonPaymentList 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(rs!=null)rs.close();
				if(rs2 != null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
				if(rs3 != null) rs3.close();
				if(pstmt3 != null) pstmt3.close();
				if(rs4 != null) rs4.close();
				if(pstmt4 != null) pstmt4.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcDepositNonPaymentList 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	/*
	 */
	//분할인거.
	private ArrayList<IdcDepositNonPaymentDTO> idcDepositNonpaymentListCmd(ArrayList<IdcDepositNonPaymentDTO> ulist, ArrayList<IdcDepositNonPaymentDTO> nulist, String sc)
	{
		String client_name="";
		Connection conn=null;
		PreparedStatement pstmt=null,pstmt2=null, pstmt3=null;
		ResultSet rs=null,rs2=null, rs3=null;

		try	
		{
			conn=dao.getConn();
			//코드명으로 이름 가져오기.
			String sql="SELECT client_name FROM servicedb, clientdb WHERE servicedb.client_code=clientdb.client_code AND service_code=?";
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, sc);
			rs2 = pstmt2.executeQuery();
			if(rs2.next())
				client_name=rs2.getString("client_name");
		
			//분할 리스트
			sql="SELECT addDB_case, service_code, addDB_amount, adddb_united, addDB_note, addDB_payment_date, addDB_nonpayment, ";
			sql+="adddb_request_date, adddb_ip  FROM adddb ";
			sql+="WHERE service_code=? AND adddb_payment_date<=Date_Add(curdate(),INTERVAL 3 DAY)";
			//sql+="WHERE addDB_nonpayment>0 AND service_code=? AND adddb_payment_date<=Date_Add(curdate(),INTERVAL 3 DAY)";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, sc);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				IdcDepositNonPaymentDTO dto = new IdcDepositNonPaymentDTO();
				dto.setClient_name(client_name);
				dto.setService_case(rs.getString("adddb_case"));
				dto.setService_request_date(rs.getDate("adddb_request_date"));
				dto.setService_payment_date(rs.getDate("adddb_payment_date"));
				dto.setService_amount(Integer.parseInt(rs.getString("adddb_amount")));
				dto.setService_nonpayment(Integer.parseInt(rs.getString("adddb_nonpayment")));
				dto.setService_payment_status(getPaymentStatus(dto.getService_payment_date(),dto.getService_nonpayment()));
				dto.setService_code(sc);
				dto.setService_ip(rs.getString("adddb_ip"));
				nulist.add(dto);
			}
			
			sql="SELECT * FROM onetimedb WHERE service_code=? AND onetime_nonpayment>0";
			pstmt3=conn.prepareStatement(sql);
			pstmt3.setString(1, sc);
			rs3 = pstmt3.executeQuery();
			while(rs3.next())
			{
				IdcDepositNonPaymentDTO dto = new IdcDepositNonPaymentDTO();
				dto.setClient_name(client_name);
				dto.setService_case(rs3.getString("onetime_case"));
				dto.setService_request_date(rs3.getDate("onetime_request_date"));
				dto.setService_payment_date(rs3.getDate("onetime_payment_date"));
				dto.setService_amount(Integer.parseInt(rs3.getString("onetime_amount")));
				dto.setService_nonpayment(Integer.parseInt(rs3.getString("onetime_nonpayment")));
				dto.setService_payment_status(getPaymentStatus(dto.getService_payment_date(),dto.getService_nonpayment()));
				dto.setService_code(sc);
				dto.setService_ip("");
				nulist.add(dto);
			}
		}
		catch (Exception e) 
		{
			System.out.println("idcDepositNonpaymentListCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(rs!=null)rs.close();
				if(pstmt2!=null)pstmt2.close();
				if(rs2!=null)rs2.close();
			}
			catch (SQLException e) 
			{
				System.out.println("idcDepositNonpaymentListCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return ulist;
	}
	
//	필터
	private String getFilter(String filter)
	{
		String w ="";
		switch(filter)
		{
		case "all" : 
			w="AND client_code not in ('C116') AND adddb_nonpayment not in ('0') ORDER BY adddb_payment_date ASC";
			break;
		case "third" : 
			w="AND client_code not in ('C116') AND adddb_nonpayment not in ('0') AND adddb_payment_date = Date_Add(curdate(),INTERVAL 3 DAY) ORDER BY adddb_payment_date ASC";
			break;
		case "second" : 
			w="AND client_code not in ('C116') AND adddb_nonpayment not in ('0') AND adddb_payment_date = Date_Add(curdate(),INTERVAL 2 DAY) ORDER BY adddb_payment_date ASC";
			break;
		case "first" : 
			w="AND client_code not in ('C116') AND adddb_nonpayment not in ('0') AND adddb_payment_date = Date_Add(curdate(),INTERVAL 1 DAY) ORDER BY adddb_payment_date ASC";
			break;
		case "today" : 
			w="AND client_code not in ('C116') AND adddb_nonpayment not in ('0') AND adddb_payment_date = curdate() ORDER BY adddb_payment_date ASC";
			break;
		case "over" : 
			w="AND client_code not in ('C116') AND adddb_nonpayment not in ('0') AND adddb_payment_date < curdate() ORDER BY adddb_payment_date ASC";
			break;
		}
		return w;
	}
}
