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;

import utility.StringToDate;

public class IdcWeeklyNonpaymentCmd implements IdcCmd
{
	private int calTime;
	IdcDAO dao;
	private int WRITING_PER_PAGE;
	private long total_nonpayment =0l;
	
	public IdcWeeklyNonpaymentCmd()
	{
		dao = new IdcDAO();
		calTime = 60*60*24*1000;	//60초 곱하기 60분 곱하기 24시간 곱하기 1000(1/1000초로 나오니까 1초로 만들어준다.)
		WRITING_PER_PAGE=10;
	}
	
	//주간 미납리스트 
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response){
				
		//날짜 받아오기		
		StringToDate st = new StringToDate();
		String str_first = request.getParameter("first_date");
		Date first_date;
		if(str_first == "" || str_first == null){
			first_date = null;
		}else{
			first_date = st.stringToDate(str_first);
		}
				
		String str_last = request.getParameter("last_date");
		Date last_date;
		if(str_last == "" || str_last == null){
			last_date = null;
		}else{
			last_date = st.stringToDate(str_last);
		}
				
		request.setAttribute("first_date",first_date);
		request.setAttribute("last_date",last_date);		
		
		String filter = request.getParameter("filter");				
		
		if(filter==null){
			filter="";
		}		
		String sc = request.getParameter("searchContent");
		if(sc==null){
			sc="";
		}else if(!sc.equals("")){
			//filter="all";
		}
			
		System.out.println("filter : " + filter);	
		System.out.println("searchContent : " + sc);			
				
		int pageCnt = getPageCnt(sc, filter, first_date, last_date);
		int curPage = getCurPage(request.getParameter("curPage"));
		int firstPage = getFirstPage(pageCnt, curPage);
		int endPage = getEndPage(firstPage, pageCnt);
			
		//서비스 가져오기.
		ArrayList<IdcDepositNonPaymentDTO>list =  idcDepositNonPaymentListCmd(curPage, sc, filter, first_date, last_date);		
		
		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");

		request.setAttribute("total_nonpayment", total_nonpayment);
		
	}
		
	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, Date first_date, Date last_date)
	{
		int pageCnt=1;
		String w = getFilter(filter, sc);
		
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		ResultSet rs=null, rs2=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT COUNT(*) AS num FROM clientdb as c INNER JOIN servicedb as s ";			
			sql+="ON c.client_code = s.client_code ";		
			sql+="WHERE service_nonpayment != 0 "+w;
									
			if(first_date != null && last_date != null){
				sql+=" AND service_payment_date between ? and ?";			
				pstmt =conn.prepareStatement(sql);
				pstmt.setDate(1, first_date);
				pstmt.setDate(2, last_date);
			}else{
				pstmt =conn.prepareStatement(sql);
			}
						
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				int num = rs.getInt("num");
				//pageCnt = rs.getInt("num")/WRITING_PER_PAGE+1;
				
				if(num%WRITING_PER_PAGE == 0){
					pageCnt = num/WRITING_PER_PAGE;
				}else{
					pageCnt = num/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 ArrayList<IdcDepositNonPaymentDTO> idcDepositNonPaymentListCmd(
			int curPage, String sc, String filter, Date first_date, Date last_date){
//		필터 기능
		String w = getFilter(filter, sc);				
		ArrayList<IdcDepositNonPaymentDTO> list = new ArrayList<IdcDepositNonPaymentDTO>();		
		
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null, pstmt3=null, pstmt4=null, pstmt5=null;
		ResultSet rs=null, rs2=null, rs3=null, rs4=null, rs5=null;
		int numbering_end =  WRITING_PER_PAGE * (curPage -1);
		int numbering = 0;
		try	
		{
			conn=dao.getConn();
			//String sql="SELECT COUNT(*) AS num FROM servicedb WHERE service_nonpayment>0 " + w ;
			String sql="SELECT COUNT(*) AS num FROM servicedb WHERE service_nonpayment>0 ";
			
			if(first_date != null && last_date != null){				
				sql+="AND service_payment_date between ? and ?";	
				pstmt4=conn.prepareStatement(sql);
				pstmt4.setDate(1, first_date);
				pstmt4.setDate(2, last_date);
				
			}else{
				pstmt4=conn.prepareStatement(sql);
			}
						
			rs4=pstmt4.executeQuery();
			
			if(rs4.next()){
				numbering = rs4.getInt("num") - numbering_end;
			}						
			
			sql="SELECT client_name, service_line, server_code, service_request_date, service_payment_date, ";
			sql+="service_amount, service_nonpayment, service_note, service_num, service_code, service_ip, c.client_code ";
			sql+="FROM clientdb as c INNER JOIN servicedb as s ";
			sql+="ON c.client_code = s.client_code ";
			sql+="WHERE s.service_nonpayment != 0 "+w;			
			
			//System.out.println("first_Date " + first_date);
			//System.out.println("last_Date " + last_date);
												
			if(first_date != null && last_date != null){				
				sql+="AND service_payment_date between ? and ?";
				sql+=" ORDER BY client_name asc, service_payment_date asc ";
				sql+="LIMIT ?,?";
				pstmt=conn.prepareStatement(sql);				
				pstmt.setDate(1, first_date);
				pstmt.setDate(2, last_date);												
				pstmt.setInt(3, numbering_end);
				pstmt.setInt(4, WRITING_PER_PAGE);
				System.out.println(pstmt.toString());
			}else{
				sql+=" ORDER BY client_name asc, service_payment_date asc ";
				sql+="LIMIT ?,?";				
				pstmt=conn.prepareStatement(sql);
				pstmt.setInt(1, numbering_end);
				pstmt.setInt(2, WRITING_PER_PAGE);
				System.out.println(pstmt.toString());
			}
			
			//System.out.println(pstmt.toString());
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				
				IdcDepositNonPaymentDTO dto = new IdcDepositNonPaymentDTO();
				String client_name = rs.getString("client_name");
				String client_code = rs.getString("client_code");
				
				System.out.println("client_name : " + client_name);
				System.out.println("client_code : " + client_code);
				
				dto.setClient_name(client_name);
				dto.setService_line(rs.getString("service_line"));
				
				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;
				default:
					break;
				}
				
				dto.setTemp(temp);				
				dto.setServer_code(rs.getString("server_code"));
				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")));
				if(rs.getInt("service_nonpayment") > 0){
					dto.setService_payment_status("미납");
				}else{
					dto.setService_payment_status("완납");
				}				
				dto.setService_num(numbering--);
				dto.setService_code(rs.getString("service_code"));
				dto.setService_ip(rs.getString("service_ip"));
				
				//전체합계
				total_nonpayment += (long)rs.getInt("service_nonpayment");
				
				//고객명 전체의 미납금 구하기				
				String sql2="select sum(service_nonpayment) as sum from serviceDB where client_code='"+client_code+"' ";
				pstmt5=conn.prepareStatement(sql2);			
				//System.out.println("pstmt5" + pstmt5.toString());
				rs5=pstmt5.executeQuery();				
				//filter == client_name//sc<--고객명
				if(rs5.next()){
					dto.setClient_nonpayment(rs5.getInt("sum"));
				}
				
				list.add(dto);
			}						
		}
		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();
				if(rs5 != null) rs5.close();
				if(pstmt5 != null) pstmt5.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcDepositNonPaymentList 에서의 sqlexception");
				e.printStackTrace();
			}
		}		
		return list;
	}		
	
	private String getFilter(String filter, String sc)
	{
		String w = "";
		if(filter==null)
			filter="";
		switch(filter)
		{
		case "client_name":
			//w=" client_code='"+IdcGetClientNameCode.getClientCode(sc)+"' ";			
			w = " AND s.client_code = any(Select client_code from clientDB where client_name like '%"+sc+"%')";
			break;
		case "server_code":
			w=" AND server_code like '%"+sc+"%' ";
			break;
		case "service_sw":
			w=" AND service_sw like '%"+sc+"%' ";
			break;
		case "service_ip":
			w=" AND service_ip like '%"+sc+"%' ";
			break;
		default :
			w="";
		}
//		System.out.println("w" + w);
		return w;
	}

}
