package idc.service.command;

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

import java.sql.*;

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

public class IdcServiceWriteCmd 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 ip_amount = "100000";
		String cs_amount = "50000";
		int ip_total = 0;
		int cs_total = 0;
		String service_status = request.getParameter("service_status");
		long milliseconds = System.currentTimeMillis(); 
		String service_code = "s"+milliseconds;
		
		String client_code = request.getParameter("client_code");
		String service_line = request.getParameter("service_line");
		String server_code = request.getParameter("server_code");
		
		String service_sw = request.getParameter("service_sw");
		String service_os = request.getParameter("service_os");
		String service_ip = request.getParameter("service_ip");		
		String cs_code = request.getParameter("cs_code");
		String service_defence = request.getParameter("service_defence");
						
		String str_service_request_date = request.getParameter("service_request_date");
		String str_service_payment_date = request.getParameter("service_payment_date");
		String str_service_open_date = request.getParameter("service_open_date");
				
		String service_note = request.getParameter("service_note");		
		String service_cost = request.getParameter("service_cost");
		
		StringToDate st = new StringToDate();
		
		Date request_date;		
		if(str_service_request_date == "" || str_service_request_date == null){
			request_date = null;
		}else{
			request_date = st.stringToDate(str_service_request_date);
		}
		
		Date payment_date;
		if(str_service_payment_date == "" || str_service_payment_date == null){
			payment_date = null;
		}else{
			payment_date = st.stringToDate(str_service_payment_date);
		}
		
		Date open_date;
		if(str_service_open_date == "" || str_service_open_date == null){
			open_date = null;
		}else{
			open_date = st.stringToDate(str_service_open_date);
		}
																		
		//과금부분
		String amount_rack = request.getParameter("amount_rack");
		String amount_line = request.getParameter("amount_line");
		String rack_etc = request.getParameter("rack_etc");
		String line_etc = request.getParameter("line_etc");
		
		if(amount_rack.equals("etc")){
			amount_rack = rack_etc;
		}
		if(amount_line.equals("etc")){
			amount_line = line_etc;
		}

		String amount_cpu = request.getParameter("amount_cpu");
		String ip_count = request.getParameter("ip_count");
		String amount_ip = request.getParameter("amount_ip");
		String cs_count = request.getParameter("cs_count");
		String amount_cs = request.getParameter("amount_cs");		
		String amount_defence = request.getParameter("amount_defence");
		String amount_reseller = request.getParameter("amount_reseller");
		String amount_long = request.getParameter("amount_long");
		String solo_amount_long = request.getParameter("solo_amount_long");
		String amount_pre = request.getParameter("amount_pre");
		String amount_authority = request.getParameter("amount_authority");
		String amount_contact = request.getParameter("amount_contact");
		String amount_total_discount = request.getParameter("amount_total_discount");
		String service_amount = request.getParameter("service_amount"); 
		String last_long = request.getParameter("last_long");
		String last_pre = request.getParameter("last_pre");
		String amount_cost = request.getParameter("amount_cost");
		//서비스 일할 금액
		String service_deduction = request.getParameter("service_deduction");
		int deducted = Integer.parseInt(service_amount) - Integer.parseInt(service_deduction); 	
		String amount_sub_discount = request.getParameter("amount_sub_discount");
		
		//추가 CS처리
		String addCs_address[] = request.getParameterValues("addCs_address");
		for(int i=0;i<Integer.parseInt(cs_count);i++)
		{
			IdcSetCS.setCS(service_code, server_code, addCs_address[i]);
		}
		
		//추가 IP처리
		String addIp_address[] = request.getParameterValues("addIp_address");						
		for(int i=0; i < Integer.parseInt(ip_count); i++){
			
			if(addIp_address[i] != null && addIp_address[i] != "")
			{
				IdcSetIP.SetIP("ip_sub", IdcGetClientNameCode.getClientName(client_code), 0, null, service_code, addIp_address[i]);
				String addDB_code = "IP-"+String.format("%03d", i + 1);
				String addDB_ip = addIp_address[i];
				String addDB_case = "ip";				
				addDBHandle(addDB_case, service_code, request_date, addDB_code, client_code, addDB_ip, ip_amount, payment_date);				
				ip_total += 100000;
			}			
		}		
		
		IdcMemberDBDTO dto1 = (IdcMemberDBDTO)request.getSession().getAttribute("member");
		String service_manager = dto1.getId();
		
		idcServiceWrite(service_status, service_code, client_code, service_line, server_code, service_sw, service_os, 
				service_ip, request_date, open_date, payment_date, service_amount, service_note, service_defence, service_cost,
				service_deduction, cs_code, service_manager, Integer.parseInt(cs_count));
		if(!service_line.equals("soloLine"))
			idcHaveListUpdate(server_code, service_line, client_code);		

//	메인ip,cs 등록
		IdcSetIP.SetIP("ip_main", IdcGetClientNameCode.getClientName(client_code), 0, null, service_code, service_ip);
		
		insertAmountDB(service_code, amount_rack, amount_line, amount_cpu, ip_count, amount_ip, amount_defence, amount_reseller,
				amount_long, solo_amount_long, amount_pre, amount_authority, amount_contact, amount_total_discount, service_amount, 
				 last_long, last_pre, service_cost, amount_cs, cs_count, amount_sub_discount);
		
		//IdcMemberDBDTO temp = (IdcMemberDBDTO)request.getSession().getAttribute("member");
		
		String set_id = request.getParameter("mkworker");
		setAdddb(service_code, service_cost, client_code, service_ip, set_id, payment_date, Integer.parseInt(service_deduction));
		if(service_line.equals("defence"))
		{
			String adddb_amount = Integer.toString(Integer.parseInt(amount_defence));
			setAdddbDefence(service_code,"defence" , adddb_amount, request_date, service_defence, set_id, client_code);
		}
		
		//일일변동사항 DB에 업데이트 - changeDB
		updateChangeDB( client_code,  server_code,  amount_reseller, service_line);
				
	}
	
	//방어라인 부가서비스처럼 등록하기.
	private void setAdddbDefence(String service_code, String adddb_case, String adddb_amount, Date payment_date, 
												String addDB_code, String setID, String client_code)
												
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String 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(),?,?)";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, adddb_case);
			pstmt.setString(2, service_code);
			pstmt.setString(3, adddb_amount);
			pstmt.setString(4, "incomplete");
			pstmt.setDate(5, payment_date);
			pstmt.setString(6, null);
			pstmt.setString(7, client_code);
			pstmt.setString(8, setID);
			pstmt.setString(9, adddb_amount);
			pstmt.setString(10, "0");
			pstmt.setString(11, "o");
			pstmt.setDate(12, payment_date);
			pstmt.setString(13, addDB_code);
			pstmt.executeUpdate();
			
		}
		catch (Exception e) 
		{
			System.out.println("IdcServiceWriteCmd - setAdddbDefence 에서의 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("IdcServiceWriteCmd - setAdddbDefence 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	//adddb에 추가하기(원가)
	private void setAdddb(String service_code, String service_cost, String client_code, String set_ip, String set_id, Date payment_date, int deducted)
	{
		Connection conn=null;
		PreparedStatement pstmt=null,pstmt2=null;
		ResultSet rs=null;
		int num=0;
		try	
		{
			conn=dao.getConn();
			String sql = "SELECT max(adddb_num) as a FROM adddb";
			pstmt2=conn.prepareStatement(sql);
			rs=pstmt2.executeQuery();
			if(rs.next())
				num=rs.getInt("a")+1;
			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, adddb_handle_date, ";
			sql+="adddb_original_date) ";
			sql+="values(?,?,curdate(),?,?,?,?,?,?,?,?,?,curdate(),?)";
			pstmt =conn.prepareStatement(sql);
			int i=1;
	
			pstmt.setString(i++, "service");
			pstmt.setString(i++, service_code);
			pstmt.setString(i++, service_cost);
			pstmt.setString(i++, "incomplete");
			pstmt.setDate(i++, payment_date);
			pstmt.setString(i++, set_ip);
			pstmt.setString(i++, client_code);
			pstmt.setString(i++, set_id);
			pstmt.setString(i++, Integer.toString(Integer.parseInt(service_cost)-deducted));
			pstmt.setString(i++, Integer.toString(deducted));
			pstmt.setString(i++, "o");
			pstmt.setDate(i++, payment_date);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcServiceWriteCmd - setAdddb  에서의 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("IdcServiceWriteCmd - setAdddb 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	//server_location 정하기.
	private String getLocation(String location)
	{
		String lo;
		if(location.equalsIgnoreCase("tokyo"))
			lo="_t";
		else
			lo="_c";
		return lo;
	}
	//total 값 정하기
	private String getTotal(String str, String line)
	{
		String result="";
		
		if(line.equalsIgnoreCase("test"))
		{
			result="test_total=test_total+1 ";
		}
		else 
		{
			result=str + "=" + str + "+1, total_total=total_total+1 ";
		}
		
		return result;
	}
	private String getClient_name(int re,String client_name)
	{
		String name="";
		if(re==0)
			name="IDCJP";
		else
			name=client_name;
		
		return name;
	}
	
	//서버 보유현황에 데이터 업데이트.
	public void idcHaveListUpdate(String s_code, String line, String c_code)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null, pstmt3=null;
		ResultSet rs=null,rs3=null;
		try	
		{
			String location="";
			String client_code="";
			int re=0;
			conn=dao.getConn();
			String sql="SELECT server_location FROM serverdb WHERE server_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, s_code);
			rs=pstmt.executeQuery();
			
			//로케이션 얻기(위치얻기)
			if(rs.next())
				location = rs.getString("server_location");
			location = getLocation(location);
			//어느 라인(전용 ,일반, 방어,테스트, 대체 등)
			String col = line.concat(location);
			//토탈값 더하기(테스트인경우 별도로)
			String tot = "total";
			tot=tot.concat(location);
			String totSql=getTotal(tot, line);
			sql="SELECT client_reseller FROM clientdb WHERE client_code=?";
			pstmt3 = conn.prepareStatement(sql);
			pstmt3.setString(1, c_code);
			rs3 = pstmt3.executeQuery();
			if(rs3.next())
				re=rs3.getInt("client_reseller");
			client_code = getClient_name(re, c_code);
			
			sql="UPDATE havelist SET " + col +"=" + col+"+1, "+totSql;
			sql+="WHERE client_code='"+ client_code+"'";
			
			System.out.println(sql);
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.executeUpdate();
			
		}
		catch (Exception e) 
		{
			System.out.println("IDCLINEIPWRITECMD 에서의 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(rs!=null)rs.close();
				if(rs3!=null)rs3.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IDCLINEIPWRITECMD 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	//서비스 등록 기능 수행
	public void idcServiceWrite(String service_status, String service_code, String client_code, String service_line, String server_code, 
			String service_sw, String service_os, String service_ip, Date service_request_date, Date service_open_date, 
			Date service_payment_date, String service_amount, String service_note, 
			String service_defence, String service_cost, String service_deduction, String service_cs, String service_manager, int cs_count){
		
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt1= null, pstmt2 = null;
		ResultSet rs = null;
		int service_num = 1;
		
		try {
			conn = dao.getConn();
			String sql = "SELECT IFNULL(MAX(service_num), 0) + 1 AS service_num FROM serviceDB";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				service_num = rs.getInt("service_num");
			}
			
			//service_amount에서 일할 과금을 뺀 금액
			int deducted = Integer.parseInt(service_amount) - Integer.parseInt(service_deduction); 
			
			sql = "INSERT INTO serviceDB (service_num, service_status, service_code, client_code, service_line, server_code, service_sw, service_os, service_ip, ";
			sql += " service_request_date, service_open_date, service_payment_date, service_amount, service_note, ";
			sql += " service_nonpayment, service_defence, service_cost, service_unitedAmount, service_original_date, service_deduction, service_cs, service_manager, cs_count ) values";
			sql += "(?, ?, ?, ?, ?,"
					+ "?, ?, ?, ?, ?, "
					+ "?, ?, ?, ?, ?, "
					+ "?, ?, ?, ?, ?,"
					+ "?, ? ,?)";
			
			pstmt1 = conn.prepareStatement(sql);
			
			pstmt1.setInt(1, service_num);
			pstmt1.setString(2, service_status);
			pstmt1.setString(3, service_code);
			pstmt1.setString(4, client_code);
			pstmt1.setString(5, service_line);
			pstmt1.setString(6, server_code);
			pstmt1.setString(7, service_sw);
			pstmt1.setString(8, service_os);
			pstmt1.setString(9, service_ip);					
			pstmt1.setDate(10, service_request_date);
			pstmt1.setDate(11, service_open_date);
			pstmt1.setDate(12, service_payment_date);
			pstmt1.setString(13, service_amount);
			pstmt1.setString(14, service_note);
			pstmt1.setString(15, deducted+"");
			pstmt1.setString(16, service_defence);
			pstmt1.setString(17, service_cost);
			pstmt1.setString(18, deducted+"");
			pstmt1.setDate(19, service_payment_date);
			pstmt1.setString(20, service_deduction);
			pstmt1.setString(21, service_cs);
			pstmt1.setString(22, service_manager);
			pstmt1.setInt(23, cs_count);
			pstmt1.executeUpdate();
									
			sql = "UPDATE serverDB s, clientDB c SET s.server_use_status='n', ";
			sql += "s.server_rental_date=CURDATE() , ";
			sql += "s.server_now_user=c.client_name "; 
			sql += " WHERE s.server_code=? and c.client_code=?";			

			pstmt2 = conn.prepareStatement(sql);						
			pstmt2.setString(1, server_code);
			pstmt2.setString(2, client_code);
			pstmt2.executeUpdate();
			
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(pstmt1 != null) pstmt1.close();
				if(pstmt2 != null) pstmt2.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	//amountDB에 서비스 과금 등록
	public void insertAmountDB(String service_code, String amount_rack, String amount_line, String amount_cpu, String ip_count,
			 String amount_ip, String amount_defence, String amount_reseller, String amount_long, String solo_amount_long,  
			 String amount_pre, String amount_authority, String amount_contact, String amount_total_discount, String service_amount, 
			 String last_long, String last_pre, String amount_cost, String amount_cs, String cs_count, String amount_sub_discount
			 ){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql;
		
		try {
			conn = dao.getConn();									
			sql = "INSERT INTO amountDB (service_code, amount_rack, amount_line, amount_cpu, ip_count, amount_ip, amount_defence, ";
			sql += " amount_reseller, amount_long, solo_amount_long, amount_pre, amount_authority, amount_contact, amount_total_discount, ";
			sql += " service_amount, last_long, last_pre, amount_cost, amount_cs, cs_count, amount_kcs, amount_sub_discount) ";
			sql += " values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'0', ?)";
			
			pstmt = conn.prepareStatement(sql);
			int index = 1;
			
			pstmt.setString(index++, service_code);
			pstmt.setString(index++, amount_rack);
			pstmt.setString(index++, amount_line);
			pstmt.setString(index++, amount_cpu);
			pstmt.setString(index++, ip_count);
			pstmt.setString(index++, amount_ip);
			pstmt.setString(index++, amount_defence);
			pstmt.setString(index++, amount_reseller);
			pstmt.setString(index++, amount_long);
			pstmt.setString(index++, solo_amount_long);
			pstmt.setString(index++, amount_pre);
			pstmt.setString(index++, amount_authority);
			pstmt.setString(index++, amount_contact);
			pstmt.setString(index++, amount_total_discount);
			pstmt.setString(index++, service_amount);
			pstmt.setString(index++, last_long);
			pstmt.setString(index++, last_pre);
			pstmt.setString(index++, amount_cost);
			pstmt.setString(index++, amount_cs);
			pstmt.setString(index++, cs_count);
			pstmt.setString(index++, amount_sub_discount);
			pstmt.executeUpdate();
			
		} 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();
			}
		}
	}	
	
	//addDB추가
	private void addDBHandle(String addDB_case, String service_code, Date request_date, String addDB_code, 
			String client_code, String addDB_ip, String addDB_amount, Date payment_date){
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null;
		ResultSet rs = null,rs2=null;
		String sql;
		int adddb_num=0;
		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_ip, addDB_code, client_code, ";
			sql += "addDB_amount,  adddb_payment_date, adddb_united, adddb_nonpayment, adddb_payment, adddb_accountStatus, ";
			sql += "adddb_original_date) ";
			sql += "values(?, ?, ?, ?, ?, ?, ?, ?, 'o', ?, '0', 'incomplete',curdate())";
			
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, addDB_case);
			pstmt.setString(2, service_code);
			pstmt.setDate(3, request_date);			
			pstmt.setString(4, addDB_ip);
			pstmt.setString(5, addDB_code);
			pstmt.setString(6, client_code);
			pstmt.setString(7, addDB_amount);
			pstmt.setDate(8, payment_date);
			pstmt.setString(9, addDB_amount);
			pstmt.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();
			}
		}
	}
	
	private void updateChangeDB(String client_code, String server_code, String amount_reseller, String service_line){
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null, pstmt3=null;
		ResultSet rs = null,rs2=null;
		int num = 0;
		String sql;
		String server_location = "";
		String location = "";
		String client_name = "";
		
		try {
			conn = dao.getConn();
			
			//일반 서버인 경우
			if(service_line.equals("vpn")){
				return;				
			//테스트 서버일 경우
			}else if(service_line.equals("test")){
				sql="SELECT s.server_location, c.client_name FROM serverdb s, clientDB c where c.client_code=? and s.server_code=?";
				pstmt =conn.prepareStatement(sql);
				pstmt.setString(1, client_code);
				pstmt.setString(2, server_code);
				rs=pstmt.executeQuery();			
				
				if(rs.next()){
					server_location = rs.getString("server_location");
					client_name = rs.getString("client_name");
					//System.out.println("client_name " + client_name);
				}
				
				if(server_location.equals("tokyo")){
					location = "test_t";
				}else{
					location = "test_c";
				}
			//일반 서버일 경우	
			}else{
				//서버 위치 및 고객 명 받기
				sql="SELECT s.server_location, c.client_name FROM serverdb s, clientDB c where c.client_code=? and s.server_code=?";
				pstmt =conn.prepareStatement(sql);
				pstmt.setString(1, client_code);
				pstmt.setString(2, server_code);
				rs=pstmt.executeQuery();			
				
				if(rs.next()){
					server_location = rs.getString("server_location");
					client_name = rs.getString("client_name");
					//System.out.println("client_name " + client_name);
				}
				
				if(server_location.equals("tokyo")){
					location = "new_t";
				}else{
					location = "new_c";
				}
			}
			
			if(amount_reseller.equals("0")){
				client_name = "IDCJP";
			}
			
			//changeDB 오늘날짜 변동 사항이 있는지 확인
			sql = "SELECT count(num) AS NUM FROM changeDB where change_date = curdate() and client_name=?";
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, client_name);
			rs2 = pstmt2.executeQuery();
			
			if(rs2.next()){
				num = rs2.getInt("num");
			}
			
			//기존에 changeDB가 없다면
			if(num == 0){
				sql = "INSERT INTO changeDB (client_name, "+location+", change_date) ";
				sql += " values(?, ?, curdate())";
				pstmt3 =conn.prepareStatement(sql);
				pstmt3.setString(1, client_name);
				pstmt3.setInt(2, 1);
				pstmt3.executeUpdate();
			}else{				
				sql = "UPDATE changeDB SET "+location+"="+location +"+1 WHERE change_date = curdate() AND client_name=? ";				
				pstmt3 =conn.prepareStatement(sql);
				pstmt3.setString(1, client_name);
				pstmt3.executeUpdate();
			}
							
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(rs2 != null) rs2.close();
				if(pstmt != null) pstmt.close();								
				if(pstmt2 != null) pstmt2.close();
				if(pstmt3 != null) pstmt3.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
