package idc.service.command;

import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.ArrayList;

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

import utility.IdcGetClientNameCode;
import idc.model.*;

public class IdcServiceListCmd implements IdcCmd{
	
	IdcDAO dao = new IdcDAO();		
	private int WRITING_PER_PAGE = 20;
	
	//서비스 리스트 및 고객 리스트 불러오기
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		String scs = request.getParameter("searchContextService"); if(scs==null) scs="";
		String scc = request.getParameter("searchContextClient"); if(scc==null) scc="";
		String filter = request.getParameter("filter");
		if(scs.equals(""))
			filter=null;
		
		try
		{
			scs = new String(scs.getBytes("utf-8"),"utf-8");
			
		} 
		catch (UnsupportedEncodingException e)
		{

			e.printStackTrace();
		}
		
		int s_pageCnt = getPageCnt("servicedb",scs, filter );
		int s_curPage = getCurPage(request.getParameter("s_curPage"));
		int s_firstPage = getFirstPage(s_pageCnt, s_curPage);
		int s_endPage = getEndPage(s_firstPage, s_pageCnt);
				
		int c_pageCnt = getPageCnt("clientdb",scc,"");
		int c_curPage = getCurPage(request.getParameter("c_curPage"));
		int c_firstPage = getFirstPage(c_pageCnt, c_curPage);
		int c_endPage = getEndPage(c_firstPage, c_pageCnt);
		
		
		//들어올때 클라이언트 코드나 기타 등등 받아옴
		String idcTargetNum = request.getParameter("IdcTargetNum");
		request.setAttribute("IdcTargetNum", idcTargetNum);
		
		//서비스 전체 리스트
		ArrayList<IDCserviceListDTO>all;		

		all = getAllserviceList(Integer.toString(s_curPage), scs, filter);		
		request.setAttribute("all", all);
		
		//고객 리스트
		ArrayList<IdcClientDBDTO>clientList;
		
		clientList = idcClientDBList(Integer.toString(c_curPage), scc);
		request.setAttribute("clientList", clientList);
		
		//뿌려주는 리스트 결정하는 변수
		String view_state = request.getParameter("view_state");
		//System.out.println("view_state " + view_state);
		
		if(view_state == null) view_state = "serviceList";																  	
		request.setAttribute("view_state", view_state);

		if(filter==null)
			filter="mk_all";
		request.setAttribute("filter", filter);
		
		request.setAttribute("s_pageCnt", s_pageCnt);
		request.setAttribute("s_curPage", s_curPage);
		request.setAttribute("s_firstPage", s_firstPage);
		request.setAttribute("s_endPage", s_endPage);
		request.setAttribute("searchContextService", scs);

		request.setAttribute("c_pageCnt", c_pageCnt);
		request.setAttribute("c_curPage", c_curPage);
		request.setAttribute("c_firstPage", c_firstPage);
		request.setAttribute("c_endPage", c_endPage);
		request.setAttribute("searchContextClient", scc);

	}
	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 getCurPage(String strPage)
	{
		int curPage=1;
		
		if(strPage !=null && strPage!="")
			curPage=Integer.parseInt(strPage);
		
		return curPage;
	}
	
	private int getPageCnt(String db, String sc, String filter)
	{
		int pageCnt=1;
		
		String where=null;
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String s = IdcGetClientNameCode.getClientCode(sc);
		String w = getFilter(filter, sc);
		
		
		if(db.equals("servicedb"))
		{
			if(null != s)
				sc = s;
			where =" WHERE "+w;
		}
		else
		{
			where = " WHERE client_code = any(Select client_code from clientDB where client_name like '%"+sc+"%')";
		}
		
		try	
		{
			conn=dao.getConn();
			String sql="SELECT COUNT(*) as a FROM "+db;
			sql = sql.concat(where);
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
		
			if(rs.next()){
				int num = rs.getInt("a");				
				if(num%WRITING_PER_PAGE == 0){
					pageCnt = num/WRITING_PER_PAGE;
				}else{
					pageCnt = num/WRITING_PER_PAGE + 1;
				}
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcServiceListCmd - pageCnt 에서의 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("IdcMemberListFormCmd - pageCnt  에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return pageCnt;
	}
	
	//전체서비스리스트 가져오기
	
	private ArrayList<IDCserviceListDTO> getAllserviceList(String curPage, String sc, String filter){
		System.out.println("scs " + sc);
		
		ArrayList<IDCserviceListDTO>list = new ArrayList<IDCserviceListDTO>();
		String w = getFilter(filter, sc);
		
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null, pstmt3=null;
		ResultSet rs = null,rs2=null, rs3=null;
		int numbering_end = WRITING_PER_PAGE * (Integer.parseInt(curPage) - 1);
		int numbering = 0;
		try {
			conn = dao.getConn();
			String sql = "SELECT COUNT(*) as a FROM servicedb WHERE "+w;
			pstmt2 = conn.prepareStatement(sql);
			rs2 = pstmt2.executeQuery();
			if(rs2.next())
				numbering = rs2.getInt("a")-numbering_end;
			
			//sql = "SELECT service_num, service_status, servicedb.service_code, servicedb.client_code, service_line, server_code, service_sw, service_os, service_ip, ";
			sql = "SELECT service_num, service_status, service_code, client_code, service_line, server_code, service_sw, service_os, service_ip, ";
			sql +=" service_request_date, service_payment_date, service_amount, service_nonpayment, service_note, service_manager, service_open_date,  service_defence, service_cost ";			
			//sql +=" , addDB_code FROM serviceDB INNER JOIN adddb";
			sql +=" FROM serviceDB";
			sql +=" WHERE "+w;
			sql += " ORDER BY service_num desc LIMIT ?, ?";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, numbering_end);
			pstmt.setInt(2, WRITING_PER_PAGE);
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				int service_num =numbering--;
				String service_status = rs.getString("service_status");
				String service_code = rs.getString("service_code");
				String client_code = rs.getString("client_code");
				String service_line = rs.getString("service_line");
				String server_code = rs.getString("server_code");
				String service_sw = rs.getString("service_sw");
				String service_os = rs.getString("service_os");
				String service_ip = rs.getString("service_ip");				
				Date service_request_date = rs.getDate("service_request_date");
				Date service_payment_date = rs.getDate("service_payment_date");
				Date service_open_date = rs.getDate("service_open_date");
				String service_amount = rs.getString("service_amount");
				String service_nonpayment = rs.getString("service_nonpayment");
				String service_note = rs.getString("service_note");
				String service_manager = rs.getString("service_manager");
				String service_defence = rs.getString("service_defence");
				String service_cost = rs.getString("service_cost");
				
				String client_name = "";
				sql = "SELECT client_name FROM clientDB WHERE client_code=?";
				pstmt3 = conn.prepareStatement(sql);
				pstmt3.setString(1, client_code);
				rs3 = pstmt3.executeQuery();
				if(rs3.next()){
					client_name = rs3.getString("client_name");
				}
								
				IDCserviceListDTO writing = new IDCserviceListDTO();
				
				writing.setService_num(service_num);
				writing.setService_status(service_status);
				writing.setService_code(service_code);
				writing.setClient_code(client_code);							
				
				String temp = "";
				switch (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;
				}
				
				writing.setService_line(service_line);
				writing.setServer_code(server_code);
				writing.setService_sw(service_sw);
				writing.setService_os(service_os);
				writing.setService_ip(service_ip);				
				writing.setService_request_date(service_request_date);
				writing.setService_payment_date(service_payment_date);
				writing.setService_amount(service_amount);
				writing.setService_nonpayment(service_nonpayment);
				writing.setService_note(service_note);
				writing.setService_manager(service_manager);
				writing.setClient_name(client_name);
				writing.setService_open_date(service_open_date);
				writing.setService_defence(service_defence);
				writing.setTemp(temp);
				writing.setService_cost(service_cost);
								
				list.add(writing);					
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs3 != null) rs.close();
				if(pstmt3 != null) rs.close();
				if(rs != null) rs.close();
				if(pstmt != null) rs.close();
				if(rs2 != null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return list;
	}
	
	
	//고객리스트 가져오기
	public ArrayList<IdcClientDBDTO> idcClientDBList(String curPage, String sc)
	 {
		ArrayList<IdcClientDBDTO> list = new ArrayList<IdcClientDBDTO>();
	 	Connection conn = null;
	 	PreparedStatement pstmt = null, pstmt2 = null;
	 	ResultSet rs = null, rs2 = null;
	 	int numbering_end =WRITING_PER_PAGE*(Integer.parseInt(curPage)-1) ;
	 	int numbering=0;
	 	try
	 	{
	 		conn = dao.getConn();
	 		
	 		String sql = "SELECT COUNT(*) as a FROM clientdb";
	 		pstmt2 = conn.prepareStatement(sql);
	 		rs2 = pstmt2.executeQuery();
	 		if(rs2.next())
	 			numbering = rs2.getInt("a")-numbering_end;
	 		
	 		sql = "SELECT Client_Num, client_code, client_name, client_reseller, client_phone1, client_phone2,";
	 		sql+="client_email1, client_email2, client_receive_date, client_renew_date, ";
	 		sql+="client_note FROM clientdb ";
	 		sql+="WHERE client_name like '%"+sc+"%' ";
	 		sql+="ORDER BY client_num desc LIMIT ?,? ";
	 		
	 		pstmt = conn.prepareStatement(sql);
	 		pstmt.setInt(1,numbering_end);
	 		pstmt.setInt(2,WRITING_PER_PAGE);

	 		rs = pstmt.executeQuery();
	 		while(rs.next())
	 		{
	 			int client_num = numbering--;
	 			String client_code = rs.getString("client_code");
	 			String client_name = rs.getString("client_name");
	 			String client_reseller = rs.getString("client_reseller");
	 			String client_phone1 = rs.getString("client_phone1");
	 			String client_phone2 = rs.getString("client_phone2");
	 			String client_email1 = rs.getString("client_email1");
	 			String client_email2 = rs.getString("client_email2");
	 			Date client_receive_date = rs.getDate("client_receive_date");
	 			Date client_renew_date = rs.getDate("client_renew_date");
	 			String client_note = rs.getString("client_note");
	 			
	 			IdcClientDBDTO writing = new IdcClientDBDTO();
	 			
	 			writing.setClient_num(client_num);
	 			writing.setClient_code(client_code);
	 			writing.setClient_name(client_name);
	 			writing.setClient_reseller(client_reseller);
	 			writing.setClient_phone1(client_phone1);
	 			writing.setClient_phone2(client_phone2);
	 			writing.setClient_email1(client_email1);
	 			writing.setClient_email2(client_email2);
	 			writing.setClient_receive_date(client_receive_date);
	 			writing.setClient_renew_date(client_renew_date);	 			
	 			writing.setClient_note(client_note);
	 			
	 			list.add(writing);
	 		}
	 	}
	 	catch(Exception e)
	 	{
	 		e.printStackTrace();
	 	}
	 	finally
	 	{
	 		try
	 		{
	 			if(rs!=null)rs.close();
	 			if(pstmt!=null)pstmt.close();
	 			if(rs2 != null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
	 			if(conn!=null)conn.close();
	 		}
	 		catch(SQLException e)
	 		{
	 			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 = any(Select client_code from clientDB where client_name like '%"+sc+"%')";
			break;
		case "server_code":
			w=" server_code like '%"+sc+"%' ";
			break;
		case "service_sw":
			w=" service_sw like '%"+sc+"%' ";
			break;
		case "service_ip":
			w = "service_code = any(SELECT service_code FROM ipdb WHERE ip_address like '%"+sc+"%')" ;
			break;
		case "mk_all":
			//w = "service_code = any(SELECT service_code FROM ipdb WHERE ip_address like '%"+sc+"%') or client_code = any(Select client_code from clientDB where client_name like '%"+sc+"%') or server_code like '%"+sc+"%'  or service_sw like '%"+sc+"%' or addDB_code like '%"+sc+"%'" ;
			w = "service_code = any(SELECT service_code FROM ipdb WHERE ip_address like '%"+sc+"%') or client_code = any(Select client_code from clientDB where client_name like '%"+sc+"%') or server_code like '%"+sc+"%'  or service_sw like '%"+sc+"%' or service_code = any(Select service_code from adddb where addDB_code like '%"+sc+"%')" ;
			//2016/11/22일 : 검색에서 필드 추가 (service_note)
			w = "service_code = any(SELECT service_code FROM ipdb WHERE ip_address like '%"+sc+"%') or client_code = any(Select client_code from clientDB where client_name like '%"+sc+"%') or server_code like '%"+sc+"%'  or service_sw like '%"+sc+"%' or service_note like '%"+sc+"%' or service_code = any(Select service_code from adddb where addDB_code like '%"+sc+"%')" ;
			//w = "client_code = any(Select client_code from clientDB where client_name like '%"+sc+"%') or server_code like '%"+sc+"%'  or service_sw like '%"+sc+"%' or service_note like '%"+sc+"%' or service_code = any(Select service_code from adddb where addDB_code like '%"+sc+"%')" ;
			break;
		default :
			w="service_code like '%%' ";
		}
		return w;
	}		
	
}
