package idc.service.command;

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

import java.sql.*;

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

public class IdcServiceAddHandleCmd implements IdcCmd{

	IdcDAO dao = new IdcDAO();
	
	//부가서비스 추가처리
	public void execute(HttpServletRequest request, HttpServletResponse response) 
	{
		//checkToken 값이 다르면 true반환.
		if(dao.checkToken(request))
		{
			request.setAttribute("reError", dao.reError);
			return;
		}
		else
		{
			//토큰이 같아서 등록성공이 될 경우 토큰을 삭제해 준다.
			request.getSession().removeAttribute("token");
		}
				
		String client_code = request.getParameter("client_code");
		String service_code = request.getParameter("service_code");
		String server_code = request.getParameter("server_code");		
		String addDB_amount = request.getParameter("account1");
		String addDB_payment = request.getParameter("account2");		
		String accountStatus = request.getParameter("accountStatus");						
		String addDB_case = request.getParameter("addDB_case");		
		String addDB_ip = request.getParameter("addDB_ip");
		String str_request_date = request.getParameter("request_date");
		String str_cancel_date = request.getParameter("cancel_date");
		String result = request.getParameter("result");
		String united = request.getParameter("united");
		String addDB_note = request.getParameter("addDB_note");
		String addDB_code = request.getParameter("addDB_code");
		String addDB_comment = request.getParameter("addDB_comment");
		String str_payment_date = request.getParameter("payment_date");
		String service_defence = request.getParameter("service_defence");
		
		//처리자
		//String addDB_manager = "test";
		IdcMemberDBDTO mdto = (IdcMemberDBDTO)request.getSession().getAttribute("member");
		String addDB_manager = mdto.getId();
				
		Date request_date;
		StringToDate st = new StringToDate();
		if(str_request_date == ""){
			request_date = null;
		}else{
			request_date = st.stringToDate(str_request_date);
		}
				
		Date cancel_date;
		if(str_cancel_date == ""){
			cancel_date = null;
		}else{
			cancel_date = st.stringToDate(str_cancel_date);
		}
		Date payment_date;
		if(str_payment_date == ""){
			payment_date = getPayment_date(service_code);
		}else{
			payment_date = st.stringToDate(str_payment_date);
		}
		
		if(addDB_case == "defence" || addDB_case.equals("defence"))
		{						
			updateDefence( client_code,  service_code,  server_code,  addDB_case,  addDB_ip, 
					 request_date,  cancel_date,  addDB_amount,  accountStatus,  united,  addDB_note,
					 addDB_code,  addDB_comment,  payment_date,  addDB_manager,  service_defence,
					 addDB_payment);
							
			//Histroy에 등록(IdcSetHistory)는 static 클래스이다.
			IdcSetHistory.setHistory(service_code, server_code, addDB_case+" 수정", addDB_ip, addDB_code,"",client_code);
//			adddb service쪽 금액 업데이트.
		}
		else if(addDB_case =="ip" || addDB_case.equals("ip"))
		{
			insertAddDB(client_code, service_code, server_code, addDB_case,  addDB_ip, request_date, cancel_date, 
					result, accountStatus, united, addDB_note, addDB_code, addDB_comment, payment_date, addDB_manager, addDB_amount, addDB_payment);
			
			//ipDB에 addDB에 추가된ip 반영
			updateIp("ip_sub", client_code, service_code, addDB_ip);
			
			//Histroy에 등록(IdcSetHistory)는 static 클래스이다.
			IdcSetHistory.setHistory(service_code, server_code, addDB_case+" 추가", addDB_ip, addDB_code,"",client_code);
		}
		else if(addDB_case == "cs" || addDB_case.equals("cs"))
		{
			
		}
	}
	
	//부가서비스 등록
	public void insertAddDB(String client_code, String service_code, String server_code, String addDB_case, String addDB_ip, 
			Date request_date, Date cancel_date, String result, String accountStatus, String addDB_united, String addDB_note,
			String addDB_code, String addDB_comment, Date payment_date, String addDB_manager, String addDB_amount, String addDB_payment){
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null, pstmt3=null, pstmt4=null;
		ResultSet rs = null,rs2=null;
		String sql;
		int adddb_num=0;
		int addDB_nonpayment = Integer.parseInt(addDB_amount) - Integer.parseInt(addDB_payment);
		
		//String addDB_amount = result;
		try {
			conn = dao.getConn();
			sql="SELECT max(adddb_num) as a FROM adddb";
			pstmt2=conn.prepareStatement(sql);
			rs2=pstmt2.executeQuery();
			if(rs2.next())
				adddb_num = rs2.getInt("a")+1;
			sql = "INSERT INTO addDB (addDB_case, service_code, addDB_request_date, addDB_cancel_date, addDB_amount, "
					+ "addDB_note, addDB_united, addDB_accountStatus, addDB_ip, addDB_code, "
					+ "addDB_comment, addDB_payment_date, client_code, addDB_handle_date, "
					+ "addDB_manager, adddb_nonpayment, adddb_payment, adddb_num, ";
			sql+="adddb_original_date) ";
			sql += "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, curdate(), ?, ?, ?,?,?)";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, addDB_case);
			pstmt.setString(2, service_code);
			pstmt.setDate(3, request_date);
			pstmt.setDate(4, cancel_date);
			pstmt.setString(5, addDB_amount);
			pstmt.setString(6, addDB_note);
			pstmt.setString(7, addDB_united);
			pstmt.setString(8, accountStatus);
			pstmt.setString(9, addDB_ip);
			pstmt.setString(10, addDB_code);
			pstmt.setString(11, addDB_comment);
			pstmt.setDate(12, payment_date);
			pstmt.setString(13, client_code);
			pstmt.setString(14, addDB_manager);			
			pstmt.setString(15, addDB_nonpayment+"");		
			pstmt.setString(16, addDB_payment);			
			pstmt.setInt(17, adddb_num);
			pstmt.setDate(18, payment_date);
			pstmt.executeUpdate();		
			
				sql = "UPDATE amountDB SET "; 
				sql+="amount_ip=amount_ip+?, service_amount=service_amount+? WHERE service_code=?";
				pstmt3 = conn.prepareStatement(sql);
				pstmt3.setString(1, addDB_amount);
				pstmt3.setString(2, addDB_amount);
				pstmt3.setString(3, service_code);
				pstmt3.executeUpdate();		
							
				sql = "UPDATE serviceDB SET ";
				sql+="service_amount=service_amount+?, service_nonpayment= service_nonpayment+? WHERE service_code=?";
				pstmt4 = conn.prepareStatement(sql);
				pstmt4.setString(1, addDB_amount);
				pstmt4.setString(2, Integer.toString(addDB_nonpayment));
				pstmt4.setString(3, service_code);
				pstmt4.executeUpdate();
				
		} catch (Exception e) {
			e.printStackTrace();

		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(pstmt2 != null) pstmt2.close();
				if(pstmt3 != null) pstmt3.close();
				if(pstmt4 != null) pstmt4.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
						
	}
	
	//추가 아이피 업데이트
	public void updateIp(String ip_case2, String client_code, String service_code, String ip_address){
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null;
		ResultSet rs = null,rs2=null;
		String sql = "";
		String client_name = "";
		
		try {
			conn = dao.getConn();
			
			sql = "SELECT client_name FROM clientDB WHERE client_code=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, client_code);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				client_name = rs.getString("client_name");
			}												
			
			sql = "UPDATE ipDB SET ip_case2=?, ip_user=?, ip_able='0', service_code=? WHERE ip_address=?";
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, ip_case2);
			pstmt2.setString(2, client_name);
			pstmt2.setString(3, service_code);
			pstmt2.setString(4, ip_address);

			pstmt2.executeUpdate();
			
		} 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();
			}
		}
	}
	//방어서비스 일때 업데이트
		public void updateDefence(String client_code, String service_code, String server_code, String addDB_case, String addDB_ip, 
				Date request_date, Date cancel_date, String addDB_amount, String accountStatus, String addDB_united, String addDB_note,
				String addDB_code, String addDB_comment, Date payment_date, String addDB_manager, String service_defence,
				String addDB_payment
				)
		{
			Connection conn=null;
			PreparedStatement pstmt=null, pstmt2=null, pstmt3=null, pstmt4=null, pstmt5=null, pstmt6=null, pstmt7=null, pstmt8=null,
									   pstmt9=null, pstmt10=null, pstmt11=null;
			ResultSet rs=null, rs2=null, rs3=null, rs6=null, rs8=null, rs11=null;
			boolean addDefence=true;
			
			//defence, service를 제외한 모든 가격
			//int sub_payment =0, sub_amount=0;
			try	
			{
				conn=dao.getConn();
				//디펜스 있나없나 체크
				String sql = "SELECT adddb_num FROM adddb WHERE service_code=? AND adddb_case='defence'";
				pstmt6=conn.prepareStatement(sql);
				pstmt6.setString(1, service_code);
				rs6 = pstmt6.executeQuery();
				if(rs6.next())
					addDefence=false;
				//디펜스 없을경우 새로 추가.
				if(addDefence)
				{
					sql="INSERT INTO adddb (addDB_case, service_code, adddb_request_date, adddb_amount, adddb_accountStatus, ";
					sql+="adddb_payment_date, adddb_ip, client_code, adddb_manager, adddb_nonpayment, adddb_payment, adddb_united, ";
					sql+="adddb_handle_date, adddb_original_date, adddb_code) ";
					sql+="values(?,?,curdate(),?,?,?,?,?,?,?,?,?,curdate(),?,?)";
					pstmt7 =conn.prepareStatement(sql);
					pstmt7.setString(1, "defence");
					pstmt7.setString(2, service_code);
					pstmt7.setString(3, addDB_amount);
					pstmt7.setString(4, "incomplete");
					pstmt7.setDate(5, payment_date);
					pstmt7.setString(6, null);
					pstmt7.setString(7, client_code);
					pstmt7.setString(8, null);
					pstmt7.setString(9, Integer.toString(Integer.parseInt(addDB_amount)-Integer.parseInt(addDB_payment)));
					pstmt7.setString(10, addDB_payment);
					pstmt7.setString(11, "o");
					pstmt7.setDate(12, payment_date);
					pstmt7.setString(13, addDB_code);
					pstmt7.executeUpdate();
					
					//서버 위치 받아오기.
					String location="", service_line="";
					sql="SELECT server_location, service_line FROM servicedb as sev, serverdb as ser ";
					sql+="WHERE sev.service_code=? AND sev.server_code = ser.server_code";
					pstmt4 = conn.prepareStatement(sql);
					pstmt4.setString(1, service_code);
					rs8 = pstmt4.executeQuery();
					if(rs8.next())
					{
						location = rs8.getString("server_location");
						service_line = rs8.getString("service_line");
					}
					if(location.equals("tokyo"))
						location="_t";
					else
						location="_c";
					int myreseller=0;
					sql="SELECT amount_reseller FROM amountdb WHERE service_code=?";
					pstmt11 = conn.prepareStatement(sql);
					pstmt11.setString(1, service_code);
					rs11 = pstmt11.executeQuery();
					if(rs11.next())
						myreseller = rs11.getInt("amount_reseller");
					
					
					String before=service_line+location;
					String defence="defence"+location;
					sql="UPDATE havelist SET "+before+"="+before+"-1, "+defence+"="+defence+"+1 ";
					if(myreseller>0)	
						sql+="WHERE client_code='"+client_code+"' ";
					else
						sql+="WHERE client_code='IDCJP' ";
					pstmt9 = conn.prepareStatement(sql);
					pstmt9.executeUpdate();
				}
				
				int amo=0, pay=0;
				sql="SELECT * FROM adddb WHERE service_code=? AND adddb_case='defence'";
				pstmt2 = conn.prepareStatement(sql);
				pstmt2.setString(1, service_code);
				rs2 = pstmt2.executeQuery();
				if(rs2.next())
				{
					amo=rs2.getInt("adddb_amount");
					pay=rs2.getInt("adddb_payment");
				}
				
//				amountdb 업데이트
				sql="UPDATE amountdb SET amount_defence=?, service_amount=service_amount - ? + ?  WHERE service_code=?";
				pstmt3 = conn.prepareStatement(sql);
				pstmt3.setString(1, addDB_amount);
				pstmt3.setString(2,Integer.toString(amo));
				pstmt3.setString(3,addDB_amount);
				pstmt3.setString(4, service_code);
				pstmt3.executeUpdate();
				
				int nonpayment = 0;
				if(Integer.parseInt(addDB_amount) < pay+Integer.parseInt(addDB_payment))
					nonpayment = 0;
				else
					nonpayment = Integer.parseInt(addDB_amount) - (pay+Integer.parseInt(addDB_payment));
				//service 변경
				sql="UPDATE servicedb SET service_amount=service_amount+?, service_nonpayment=service_nonpayment + ?, ";
				sql+="service_defence=?, service_line='defence' ";
				sql+="WHERE service_code=?";
				pstmt5=conn.prepareStatement(sql);
				pstmt5.setString(1, addDB_amount);
				pstmt5.setString(2, Integer.toString(nonpayment));
				pstmt5.setString(3, service_defence);
				pstmt5.setString(4, service_code);
				pstmt5.executeUpdate();
				
				
				String account = "incomplete";
				//adddb 수정
				sql="UPDATE adddb SET adddb_amount=?, adddb_nonpayment=?, adddb_payment=?, adddb_code=?, adddb_accountStatus=? ";
				sql+="WHERE service_code=? AND adddb_case='defence' ";
				pstmt10 = conn.prepareStatement(sql);
				pstmt10.setString(1, addDB_amount);
				pstmt10.setString(2, Integer.toString(nonpayment));
				int payment = pay+Integer.parseInt(addDB_payment);
				if(nonpayment==0)
				{
					payment = Integer.parseInt(addDB_amount);
					account = "complete";
				}
				pstmt10.setString(3, Integer.toString(payment));
				pstmt10.setString(4, addDB_code);
				pstmt10.setString(5, account);
				pstmt10.setString(6, service_code);
				pstmt10.executeUpdate();
			}
			catch (Exception e) 
			{
				System.out.println("IdcServiceAddHandleCmd - updateDefence 에서의 exception");
				e.printStackTrace();
			}
			finally
			{
				try 
				{
					if(conn!=null) conn.close();
					if(pstmt!=null)pstmt.close();
					if(pstmt2!=null)pstmt2.close();
					if(pstmt3!=null)pstmt3.close();
					if(pstmt4!=null)pstmt4.close();
					if(pstmt5!=null)pstmt5.close();
					if(pstmt6!=null)pstmt6.close();
					if(pstmt7!=null)pstmt7.close();
					if(pstmt8!=null)pstmt8.close();
					if(pstmt9!=null)pstmt9.close();
					if(pstmt10!=null)pstmt10.close();
					if(pstmt11!=null)pstmt11.close();
					if(rs!=null)rs.close();
					if(rs3!=null)rs3.close();
					if(rs6!=null)rs6.close();
					if(rs8!=null)rs8.close();
					if(rs11!=null)rs11.close();
				}
				catch (SQLException e) 
				{
					System.out.println("IdcServiceAddHandleCmd - updateDefence 에서의 sqlexception");
					e.printStackTrace();
				}
			}
		}
		
//	통합일 경우 결제일 동일하게
	private Date getPayment_date(String service_code)
	{
		Date payment_date = null;
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT adddb_payment_date FROM adddb WHERE service_code=? AND adddb_case='service' ";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs=pstmt.executeQuery();
			if(rs.next())
				payment_date = rs.getDate("adddb_payment_date");
		}
		catch (Exception e) 
		{
			System.out.println("IdcServiceAddHandleCmd 에서의 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("IdcServiceAddHandleCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return payment_date;
	}		
}