package idc.business.command;

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

import utility.StringToDate;
import idc.model.*;

import java.sql.*;
import java.sql.Date;
import java.util.*;

public class IdcBusinessListCmd implements IdcCmd{
	
	IdcDAO dao = new IdcDAO();

	public void execute(HttpServletRequest request, HttpServletResponse response) {
		
		//날짜 받아오기		
		StringToDate st = new StringToDate();
		String str_date = request.getParameter("date");
		Date date;
		if(str_date == "" || str_date == null){
			date = null;
		}else{
			date = st.stringToDate(str_date);
		}
	
		//전달사항용으로 받아올 것들
		String[] filter = request.getParameterValues("filter");
		request.setAttribute("filter", filter);
		filter = setFilter(filter);
		
		//세션에서 아이디 기준으로 근무 시간 불러오기
		IdcMemberDBDTO d1to = (IdcMemberDBDTO)request.getSession().getAttribute("member");
		String id = d1to.getId();
		String name = d1to.getName();
		String part = d1to.getPart();
		String location = d1to.getLocation();
				
		//서버보유현황
		ArrayList<IdcHaveListDBDTO> list = null;
		list = idcClientAllServerList();				
		
		request.setAttribute("IdcHaveList", list);
		request.setAttribute("IdcHaveListSize", list.size());
						
		//전달사항
		ArrayList<IdcDeliveryDTO> delivery_list = null;
		delivery_list = getDeliveryDTO(filter, date);		
		request.setAttribute("delivery_list", delivery_list);
		
		//금일 완료된 업무 불러오기
		ArrayList<IdcWorkDTO> endWork_list = null;		
		endWork_list = getEndWorkDTO(date);		
		request.setAttribute("endWork_list", endWork_list);
		
		//금일 진행중인 업무
		ArrayList<IdcWorkDTO> ongoingWork_list = null;		
		ongoingWork_list = getGoingWorkDTO(date);		
		request.setAttribute("ongoingWork_list", ongoingWork_list);
		
		//업무일지 멤버자료
		IdcBusinessMemberDTO memberDTO;
		
		//세션에서 로그인한 아이디 받아옴
		memberDTO = getMemberDTO( id,  location,  name,  part, date);		
		request.setAttribute("memberDTO", memberDTO);
		
		//금일 변동 사항 리스트 받아오기
		ArrayList<IdcTodayChangeDTO> change_list = null;
		change_list = getChangeDTO(date);
		request.setAttribute("change_list", change_list);
						
	}
	//필터 설정
	private String[] setFilter(String[] filter){
		String[] result = {"", "", "", "", "", ""};
		if(filter!=null){
			for(int i=0;i<filter.length;i++){
				if(filter[i]!=null)
					result[i]=filter[i];
			}
		}		
		return result;
	}
	
	//서버보유현황 페이지 읽어오기
	public ArrayList<IdcHaveListDBDTO> idcClientAllServerList(){
		ArrayList<IdcHaveListDBDTO> names=new ArrayList<IdcHaveListDBDTO>();
		
		Connection conn=null;
		PreparedStatement pstmt=null,pstmt2=null;
		ResultSet rs = null, rs2=null;
		
		try{
			conn = dao.getConn();
			String sql = "SELECT * FROM havelist ";
			pstmt = conn.prepareStatement(sql);			
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				IdcHaveListDBDTO dto = new IdcHaveListDBDTO();
				dto.setClient_name(rs.getString("client_name"));
				dto.setDefence_c(rs.getInt("defence_c"));
				dto.setDefence_t(rs.getInt("defence_t"));
				dto.setNormal_c(rs.getInt("normal_c"));
				dto.setNormal_t(rs.getInt("normal_t"));
				dto.setSolo_c(rs.getInt("solo_c"));
				dto.setSolo_t(rs.getInt("solo_t"));
				dto.setSub_c(rs.getInt("substitution_c"));
				dto.setSub_t(rs.getInt("substitution_t"));
				dto.setTest_c(rs.getInt("test_c"));
				dto.setTest_t(rs.getInt("test_t"));
				dto.setTest_total(rs.getInt("test_total"));
				dto.setTotal_c(rs.getInt("total_c"));
				dto.setTotal_t(rs.getInt("total_t"));
				dto.setTotal_total(rs.getInt("total_total"));
				
				names.add(dto);
			}
			
			sql="SELECT  sum(normal_t) as normal_t, sum(normal_c) as normal_c, sum(defence_t) as defence_t, sum(defence_c) as defence_c, ";
			sql+="sum(solo_t) as solo_t, sum(solo_c) as solo_c, sum(substitution_t) as substitution_t, sum(substitution_c) as substitution_c, sum(total_t) as total_t, sum(total_c) as total_c, ";
			sql+="sum(total_total) as total_total, sum(test_t) as test_t, sum(test_c) as test_c, sum(test_total) as test_total ";
			sql+=" FROM havelist";
			
			pstmt2 = conn.prepareStatement(sql);
			rs2 = pstmt2.executeQuery();
			
			if(rs2.next()){
				IdcHaveListDBDTO dto = new IdcHaveListDBDTO();
				dto.setClient_name("최종합계");
				dto.setDefence_c(rs2.getInt("defence_c"));
				dto.setDefence_t(rs2.getInt("defence_t"));
				dto.setNormal_c(rs2.getInt("normal_c"));
				dto.setNormal_t(rs2.getInt("normal_t"));
				dto.setSolo_c(rs2.getInt("solo_c"));
				dto.setSolo_t(rs2.getInt("solo_t"));
				dto.setSub_c(rs2.getInt("substitution_c"));
				dto.setSub_t(rs2.getInt("substitution_t"));
				dto.setTest_c(rs2.getInt("test_c"));
				dto.setTest_t(rs2.getInt("test_t"));
				dto.setTest_total(rs2.getInt("test_total"));
				dto.setTotal_c(rs2.getInt("total_c"));
				dto.setTotal_t(rs2.getInt("total_t"));
				dto.setTotal_total(rs2.getInt("total_total"));				
				names.add(dto);
			}
		}catch (Exception e){
			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) 
			{
				e.printStackTrace();
			}
		}
		return names;
	}

	//전달 사항 읽어오기	
	public ArrayList<IdcDeliveryDTO> getDeliveryDTO(String[] filter, Date date){
		ArrayList<IdcDeliveryDTO> delivery_list = new ArrayList<IdcDeliveryDTO>();
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		
		try {
			conn = dao.getConn();
			String sql = "SELECT delivery_num, delivery_sort, client_name, delivery_content, delivery_check_date, delivery_end_date, ";
			sql += "delivery_status, delivery_manager FROM deliveryDB ";
			sql += "WHERE ";
			sql+="(delivery_sort like '%"+filter[0]+"%' AND client_name like '%"+filter[1]+"%' AND delivery_check_date like '%"+filter[2]+"%' ";
			sql+="AND delivery_end_date like '%"+filter[3]+"%' ";
			sql+="AND delivery_manager like '%"+filter[5]+"%')";
			
			if(!filter[4].equals("")){
				sql+="AND delivery_status ='"+filter[4]+"' ORDER BY delivery_num DESC limit 0,10";
			}else{
				sql+="AND delivery_status !='end' ";
			}	
			
			if(date != null){
				sql += "AND delivery_check_date >=? ";
				sql += " ORDER BY delivery_num DESC";
				pstmt = conn.prepareStatement(sql);
				pstmt.setDate(1, date);
			}else{
				sql += " ORDER BY delivery_num DESC";
				pstmt = conn.prepareStatement(sql);
			}
						
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				String delivery_sort = rs.getString("delivery_sort");
				String delivery_temp = "";
				switch (delivery_sort){
				case "all":
					delivery_temp = "전체";
					break;
				case "group":
					delivery_temp = "그룹";
					break;
				case "each":
					delivery_temp = "개별";
					break;
				}
				
				int num=rs.getInt("delivery_num");
				String client_name = rs.getString("client_name");
				String delivery_content = rs.getString("delivery_content");
				Date delivery_check_date = rs.getDate("delivery_check_date"); 
				Date delivery_end_date = rs.getDate("delivery_end_date");
				String delivery_status = rs.getString("delivery_status");				
				String delivery_temp1 = delivery_status;				
				String delivery_manager = rs.getString("delivery_manager");
				
				IdcDeliveryDTO writing = new IdcDeliveryDTO();				
				writing.setNum(num);
				writing.setDelivery_sort(delivery_sort);
				writing.setClient_name(client_name);
				writing.setDelivery_content(delivery_content);
				writing.setDelivery_check_date(delivery_check_date);
				writing.setDelivery_end_date(delivery_end_date);
				writing.setDelivery_status(delivery_status);
				writing.setDelivery_manager(delivery_manager);
				writing.setDelivery_temp(delivery_temp);
				writing.setDelivery_temp1(delivery_temp1);
				
				delivery_list.add(writing);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return delivery_list;
	}
	
	//금일 완료된 업무 불러오기	
	public ArrayList<IdcWorkDTO> getEndWorkDTO(Date date){
		ArrayList<IdcWorkDTO> work_list = new ArrayList<IdcWorkDTO>();
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		
		try {
			conn = dao.getConn();
			//오늘 완료된 업무
			String sql = "";
			
			if(date == null){
				sql="SELECT * FROM workdb ";			
				sql+=" WHERE work_finish_date=curdate() ORDER BY work_num DESC";
				pstmt = conn.prepareStatement(sql);
			}else{
				sql="SELECT * FROM workdb ";			
				sql+=" WHERE work_finish_date=? ORDER BY work_num DESC";
				pstmt = conn.prepareStatement(sql);
				pstmt.setDate(1, date);
			}
			
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				String work_sort = rs.getString("work_sort");
				String temp1 = "";
				switch (work_sort){
				case "new":
					temp1 = "신규";
					break;
				case "cancel":
					temp1 = "해지";
					break;
				case "test":
					temp1 = "테스트";
					break;
				case "substitution":
					temp1 = "대체";
					break;
				case "lineChange":
					temp1 = "회선변경";
					break;
				case "block":
					temp1 = "차단";
					break;
				case "defence":
					temp1 = "방어";
					break;
				case "disorder":
					temp1 = "장애";
					break;
				case "accounting":
					temp1 = "과금";
					break;
				case "request":
					temp1 = "요청";
					break;
				case "addService":
					temp1 = "부가서비스";
					break;
				}
				
				String client_name = rs.getString("client_name");
				String work_content = rs.getString("work_content");
				Date work_check_date = rs.getDate("work_check_date"); 
				Date work_end_date = rs.getDate("work_end_date");
				String work_status = rs.getString("work_status");
				String work_manager = rs.getString("work_manager");
				
				IdcWorkDTO writing = new IdcWorkDTO();
				writing.setWork_sort(work_sort);
				writing.setClient_name(client_name);
				writing.setWork_content(work_content);
				writing.setWork_check_date(work_check_date);
				writing.setWork_end_date(work_end_date);
				writing.setWork_status(work_status);
				writing.setWork_manager(work_manager);
				writing.setTemp1(temp1);
				writing.setNum(rs.getInt("work_num"));
				work_list.add(writing);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return work_list;
	}
	
	//	현재 진행중인 업무 불러오기
	private ArrayList<IdcWorkDTO> getGoingWorkDTO(Date date){
		ArrayList<IdcWorkDTO> list = new ArrayList<IdcWorkDTO>();
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql = "";
			
			if(date == null){
				sql="SELECT * FROM workdb WHERE work_status!='end' ORDER BY work_num DESC";
				pstmt =conn.prepareStatement(sql);
			}else{
				sql="SELECT * FROM workdb ";
				sql += " WHERE work_status!='end' OR work_finish_date >= ? ";
				sql += "ORDER BY work_num DESC";				
				pstmt =conn.prepareStatement(sql);
				pstmt.setDate(1, date);
			}			
						
			rs = pstmt.executeQuery();
			
			while(rs.next()){
				IdcWorkDTO dto = new IdcWorkDTO();
				
				dto.setClient_name(rs.getString("client_name"));
				dto.setNum(rs.getInt("work_num"));
				dto.setWork_check_date(rs.getDate("work_check_date"));
				dto.setWork_content(rs.getString("work_content"));
				dto.setWork_end_date(rs.getDate("work_end_date"));
				dto.setWork_sort(rs.getString("work_sort"));
				dto.setTemp1(getSort(dto.getWork_sort()));
				dto.setWork_status(rs.getString("work_status"));
				dto.setWork_manager(rs.getString("work_manager"));
				list.add(dto);
			}
		}catch (Exception e){
			System.out.println("IdcBusinessListCmd 에서의 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("IdcBusinessListCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return list;
	}
	
	//멤버관련 자료 
	private IdcBusinessMemberDTO getMemberDTO(String id, String location, String name, String part, Date date){
		IdcBusinessMemberDTO writing = new IdcBusinessMemberDTO();
		
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt1 = null, pstmt2 = null;
		ResultSet rs = null, rs1 = null, rs2 = null;
		String sql;
		
		try {
			conn = dao.getConn();

			sql = "SELECT count(work_num) AS num FROM workDB ";
			sql += "WHERE work_status='end' and work_manager=? ";					
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, name);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				String count_end = rs.getInt("num")+"";				
				writing.setCount_end(count_end);		
			}
			
			sql = "SELECT count(work_num) AS num FROM workDB ";
			sql += "WHERE work_status!='end' and work_manager=? ";
			
			pstmt1 = conn.prepareStatement(sql);
			pstmt1.setString(1, name);
			rs1 = pstmt1.executeQuery();
			
			if(rs1.next()){
				String count_ongoing = rs1.getInt("num")+"";				
				writing.setCount_ongoing(count_ongoing);		
			}
			
			if(date == null){
				sql = "select curdate() as date";							
				pstmt2 = conn.prepareStatement(sql);			
				rs2 = pstmt2.executeQuery();
				
				if(rs2.next()){
					Date curDate = rs2.getDate("date");
					writing.setCurDate(curDate);					
				}
				
			}else{
				writing.setCurDate(date);
			}

			writing.setName(name);
			writing.setLocation(location);
			writing.setPart(part);

		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(rs1 != null) rs1.close();
				if(pstmt1 != null) pstmt1.close();
				if(rs2 != null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return writing;
	}
	
	private String getSort(String temp){
		String temp1="";
		switch (temp){
		case "new":
			temp1 = "신규";
			break;
		case "cancel":
			temp1 = "해지";
			break;
		case "test":
			temp1 = "테스트";
			break;
		case "substitution":
			temp1 = "대체";
			break;
		case "lineChange":
			temp1 = "회선변경";
			break;
		case "block":
			temp1 = "차단";
			break;
		case "defence":
			temp1 = "방어";
			break;
		case "disorder":
			temp1 = "장애";
			break;
		case "accounting":
			temp1 = "과금";
			break;
		case "request":
			temp1 = "요청";
			break;
		case "addService":
			temp1 = "부가서비스";
			break;
		}
		return temp1;
	}

	private ArrayList<IdcTodayChangeDTO> getChangeDTO(Date date){
		ArrayList<IdcTodayChangeDTO> work_list = new ArrayList<IdcTodayChangeDTO>();
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs = null;
		
		try {
			conn = dao.getConn();
			String sql = "";
								
			if(date == null ){
				sql = "SELECT  client_name, new_t, new_c, del_t, del_c, newCancel_t, newCancel_c, delCancel_t, delCancel_c, ";
				sql += "test_t, test_c, endTest_t, endTest_c, change_date FROM changeDB ";
				sql += " WHERE change_date >= NOW() - INTERVAL 1 DAY ORDER BY num DESC ";
				
				pstmt = conn.prepareStatement(sql);
			}else{
				sql = "SELECT  client_name, new_t, new_c, del_t, del_c, newCancel_t, newCancel_c, delCancel_t, delCancel_c, ";
				sql += "test_t, test_c, endTest_t, endTest_c, change_date FROM changeDB ";
				sql += " WHERE change_date <= DATE(?) and change_date >= SUBDATE(?, 1) ORDER BY num DESC; ";
								
				pstmt = conn.prepareStatement(sql);
				pstmt.setDate(1, date);
				pstmt.setDate(2, date);				
			}
												
			rs = pstmt.executeQuery();
			
			//총합계
			int total_new_t = 0;
			int total_new_c = 0;
			int total_del_t = 0;
			int total_del_c = 0;
			int total_newCancel_t = 0;
			int total_newCancel_c = 0;
			int total_delCancel_t = 0;
			int total_delCancel_c = 0;
			//int total_test_t = 0;
			//int total_test_c = 0;
			int total_endTest_t = 0;
			int total_endTest_c = 0;
			int total_total_tokyo = 0;
			int total_total_chiba = 0;
			
			while(rs.next()){				
				String client_name = rs.getString("client_name");
				int new_t = rs.getInt("new_t");
				int new_c = rs.getInt("new_c");
				int del_t = rs.getInt("del_t");
				int del_c = rs.getInt("del_c");
				int newCancel_t = rs.getInt("newCancel_t");
				int newCancel_c = rs.getInt("newCancel_c");
				int delCancel_t = rs.getInt("delCancel_t");
				int delCancel_c = rs.getInt("delCancel_c");
				int test_t = rs.getInt("test_t");
				int test_c = rs.getInt("test_c");
				int endTest_t = rs.getInt("endTest_t");
				int endTest_c = rs.getInt("endTest_c");
				Date change_date = rs.getDate("change_date");
				
				int total_tokyo = new_t + del_t + newCancel_t + delCancel_t + test_t + endTest_t;
				int total_chiba = new_c + del_c + newCancel_c + delCancel_c + test_c + endTest_c;
								
				IdcTodayChangeDTO writing = new IdcTodayChangeDTO();
				writing.setClient_name(client_name);
				writing.setNew_t(new_t);
				writing.setNew_c(new_c);
				writing.setDel_t(del_t);
				writing.setDel_c(del_c);
				writing.setNewCancel_t(newCancel_t);
				writing.setNewCancel_c(newCancel_c);
				writing.setDelCancel_t(delCancel_t);
				writing.setDelCancel_c(delCancel_c);
				writing.setTest_t(endTest_t);
				writing.setTest_c(endTest_c);
				writing.setEndTest_t(endTest_t);
				writing.setEndTest_c(endTest_c);
				writing.setChange_date(change_date);
				writing.setTotal_tokyo(total_tokyo);
				writing.setTotal_chiba(total_chiba);
				work_list.add(writing);
				
				 total_new_t += new_t;
				 total_new_c += new_c;
				 total_del_t += del_t;
				 total_del_c += del_c;
				 total_newCancel_t += newCancel_t;
				 total_newCancel_c += newCancel_c;
				 total_delCancel_t += delCancel_t;
				 total_delCancel_c += delCancel_c;
				 //total_test_t += test_t;
				 //total_test_c += test_c;
				 total_endTest_t += endTest_t;
				 total_endTest_c += endTest_c;
				 total_total_tokyo += total_tokyo;
				 total_total_chiba += total_chiba;
			}
						
			IdcTodayChangeDTO writing = new IdcTodayChangeDTO();
			writing.setClient_name("총 합계");
			writing.setNew_t(total_new_t);
			writing.setNew_c(total_new_c);
			writing.setDel_t(total_del_t);
			writing.setDel_c(total_del_c);
			writing.setNewCancel_t(total_newCancel_t);
			writing.setNewCancel_c(total_newCancel_c);
			writing.setDelCancel_t(total_delCancel_t);
			writing.setDelCancel_c(total_delCancel_c);
			writing.setTest_t(total_endTest_t);
			writing.setTest_c(total_endTest_c);
			writing.setEndTest_t(total_endTest_t);
			writing.setEndTest_c(total_endTest_c);
			writing.setTotal_tokyo(total_total_tokyo);
			writing.setTotal_chiba(total_total_chiba);
			work_list.add(writing);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return work_list;
	}

}
