package idc.client.command;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

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

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

public class IdcClientDBUpdateCmd 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("code");
		String client_name = request.getParameter("name");
		String client_reseller = request.getParameter("reseller");
		String client_phone1 = request.getParameter("phone1");
		String client_phone2 = request.getParameter("phone2");
		String client_email1 = request.getParameter("email1");
		String client_email2 = request.getParameter("email2");
		String str_date1 = request.getParameter("date1");
		String str_date2 = request.getParameter("date2");
		
		StringToDate st = new StringToDate();
		Date client_receive_date;		
		if(str_date1 == "" || str_date1 == null){
			client_receive_date = null;
		}else{
			client_receive_date = st.stringToDate(str_date1);			
		}
		
		Date client_renew_date;		
		if(str_date2 == "" || str_date2 == null){
			client_renew_date = null;
		}else{
			client_renew_date = st.stringToDate(str_date2);			
		}
		
		
		
		String client_note = request.getParameter("note");
				
	
		int set = checkRe(client_reseller, client_name);
		idcClientDBModify(client_code, client_name, client_reseller, client_phone1, client_phone2, client_email1, 
				client_email2,  client_note, client_receive_date, client_renew_date); 

		
		if(set>0)
		{
			addReseller(client_name);
		}
		else if(set<0)
		{
			divReseller(client_name);
		}
	}
	private void IdcupdateCmd(String client_code, int reseller)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs= null;
		String sql="";
		try	
		{
			conn=dao.getConn();
			sql="SELECT service_code FROM servicedb WHERE client_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, client_code);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				String service_code = rs.getString("service_code");
				setAmount(service_code, reseller);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcClientDBUpdateCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
					if(rs!=null)rs.close();
					if(pstmt!=null)pstmt.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcClientDBUpdateCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	private void setAmount(String service_code, int reseller)
	{
		Connection conn=null;
		PreparedStatement pstmt[]=new PreparedStatement[8];
		ResultSet rs[]=new ResultSet[8];
		String sql="";
		int rack=0, line=0, cpu=0, ip=0, cs=0, defence=0, ilast_long=0, ilast_pre=0, authority=0, contact=0, sub_discount=0;
		int etc=0;
		int sub_amount=0, sub_payment=0;
		try	
		{
			conn=dao.getConn();
			sql="SELECT * FROM amountdb WHERE service_code=?";
			pstmt[0] =conn.prepareStatement(sql);
			pstmt[0].setString(1, service_code);
			rs[0] = pstmt[0].executeQuery();
			if(rs[0].next())
			{
				rack=rs[0].getInt("amount_rack");
				line=rs[0].getInt("amount_line");
				cpu=rs[0].getInt("amount_cpu");
				ip=rs[0].getInt("amount_ip");
				cs=rs[0].getInt("amount_cs");
				defence=rs[0].getInt("amount_defence");
				ilast_long=rs[0].getInt("last_long");
				ilast_pre=rs[0].getInt("last_pre");
				sub_discount=rs[0].getInt("amount_sub_discount");
				etc=rs[0].getInt("amount_etc");
				
				//2017년 12월 19일 회원정보시 변경되는 값 초기화값 가져 오기
				authority=rs[0].getInt("last_authority");
				contact=rs[0].getInt("last_contact");
			}
			
			sql="SELECT sum(adddb_payment) as pay FROM adddb ";
			sql+="WHERE service_code=? ";
			pstmt[1] =conn.prepareStatement(sql);
			pstmt[1].setString(1, service_code);
			rs[1] = pstmt[1].executeQuery();
			if(rs[1].next())
			{		
					sub_payment = rs[1].getInt("pay");
			}
			
			sql="SELECT sum(onetime_amount) as amo, sum(onetime_payment) as pay FROM onetimedb WHERE service_code=? AND onetime_accountStatus='incomplete' ";
			pstmt[2] = conn.prepareStatement(sql);
			pstmt[2].setString(1, service_code);
			rs[2] = pstmt[2].executeQuery();
			if(rs[2].next())
			{
				sub_amount = rs[2].getInt("amo");
				sub_payment += rs[2].getInt("pay"); 
			}
			
			int temp=(rack+line+cpu-authority-contact);
			int cost_price = temp + ip + cs + defence + etc;
			int temp2=0;
			int first_dis=0, second_dis = 0;
			int iservice_cost = 0;
			int iamount_total_discount=0;//cost_price-service_calc;
			if(reseller==0)
			{
				first_dis = temp*ilast_long/100;
			}
			else
			{
				first_dis = temp*reseller/100;
			}
			temp2 = temp-first_dis;
			second_dis = temp2*ilast_pre/100;
			iamount_total_discount =(int)(Math.ceil((first_dis+second_dis)/1000.0)*1000);
			iservice_cost = temp-iamount_total_discount - sub_discount;
			int service_calc = iservice_cost + ip + cs + defence + etc;

			
			System.out.println("costprice"+cost_price);
			System.out.println("temp"+temp);
			System.out.println("iservice_cost"+iservice_cost);
			System.out.println("service_calc"+service_calc);
			System.out.println("iamount_total_discount"+iamount_total_discount);
			System.out.println("service_calc="+service_calc);
			System.out.println("sub_amount="+sub_amount);
			//System.out.println("service_deduction"+service_deduction);
			System.out.println("sub_payment"+sub_payment);
			System.out.println("sub_amount"+sub_amount);
			
			//service 변경
			sql="UPDATE servicedb SET service_amount=?, service_nonpayment=?, service_cost=?, service_unitedAmount=? ";
			sql+="WHERE service_code=?";
			pstmt[3]=conn.prepareStatement(sql);
			pstmt[3].setString(1, Integer.toString(service_calc+sub_amount));
			int nonpayment = service_calc+sub_amount - sub_payment;
			if(nonpayment<0)
				nonpayment=0;
			pstmt[3].setString(2, Integer.toString(nonpayment));
			pstmt[3].setString(3, Integer.toString(iservice_cost));
			pstmt[3].setString(4, Integer.toString(service_calc));
			pstmt[3].setString(5, service_code);
			pstmt[3].executeUpdate();
			
			sql= "SELECT adddb_payment FROM adddb WHERE service_code=? AND adddb_case='service' ";
			pstmt[4] = conn.prepareStatement(sql);
			pstmt[4].setString(1, service_code);
			rs[4] = pstmt[4].executeQuery();
			int spayment = 0;
			if(rs[4].next())
			{
				spayment = rs[4].getInt("adddb_payment");
			}
			int ideduc = 0;
			String account = "incomplete";

			if(iservice_cost<spayment+ideduc)
			{
				spayment = iservice_cost;
				account = "complete";
			}
			else
				spayment += ideduc;
			
			//adddb 수정(service)
			sql="UPDATE adddb SET adddb_amount=?, adddb_nonpayment=?, adddb_payment=?, adddb_accountstatus=? ";
			sql+="WHERE service_code=? AND adddb_case='service' ";
			pstmt[5] = conn.prepareStatement(sql);
			pstmt[5].setString(1, Integer.toString(iservice_cost));
			pstmt[5].setString(2, Integer.toString(iservice_cost-spayment));
			pstmt[5].setString(3, Integer.toString(spayment));
			pstmt[5].setString(4, account);
			pstmt[5].setString(5, service_code);
			pstmt[5].executeUpdate();
			
			
//			amount 변경
			sql = "UPDATE amountDB SET amount_rack=?, amount_line=?, amount_cpu=?, amount_ip=?, amount_cs=?, ";
			sql += "amount_defence=?, amount_authority=?, amount_contact=?, amount_total_discount=?, ";
			sql +=" service_amount=?, last_long=?, last_pre=?, amount_cost=?, amount_reseller=? ";
			sql +=" WHERE service_code=?";
			
			pstmt[6] = conn.prepareStatement(sql);
			int index = 1;
			
			pstmt[6].setString(index++, Integer.toString(rack));
			pstmt[6].setString(index++, Integer.toString(line));
			pstmt[6].setString(index++, Integer.toString(cpu));
			pstmt[6].setString(index++, Integer.toString(ip));
			pstmt[6].setString(index++, Integer.toString(cs));
			
			pstmt[6].setString(index++, Integer.toString(defence));
			pstmt[6].setString(index++, Integer.toString(authority));
			System.out.println("IdcClientDBUpdateCmd - authority 값:"+authority);
			pstmt[6].setString(index++, Integer.toString(contact));
			pstmt[6].setString(index++, Integer.toString(iamount_total_discount));
			
			pstmt[6].setString(index++, Integer.toString(service_calc));
			pstmt[6].setString(index++, Integer.toString(ilast_long));
			pstmt[6].setString(index++, Integer.toString(ilast_pre));
			pstmt[6].setString(index++, Integer.toString(iservice_cost));						
			pstmt[6].setString(index++, Integer.toString(reseller));
			pstmt[6].setString(index++, service_code);
			pstmt[6].executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcClientDBUpdateCmd - setAmount 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				for(int i=0;i<pstmt.length;i++)
				{
					if(rs[i]!=null)rs[i].close();
					if(pstmt[i]!=null)pstmt[i].close();
				}
			}
			catch (SQLException e) 
			{
				System.out.println("IdcClientDBUpdateCmd - setAmount 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	private void divReseller(String name)
	{
		String code = IdcGetClientNameCode.getClientCode(name);
		ArrayList<String[]> codeList = new ArrayList<String[]>();
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		PreparedStatement[] p1 = null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT service_line, server_location FROM serverdb as s, ";
					sql+="(SELECT * FROM servicedb WHERE client_code=?) as t ";
					sql+="WHERE t.server_code=s.server_code";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, code);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				String[] temp = new String[2];
				temp[0] = rs.getString("service_line");
				temp[1] = getLocation(rs.getString("server_location"));
				codeList.add(temp);
			}
			
			sql = "DELETE FROM havelist WHERE client_code=?";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setString(1, code);
			pstmt2.executeUpdate();
			
			p1 = new PreparedStatement[codeList.size()];
			
			for(int i=0;i<codeList.size();i++)
			{
				String t[] = codeList.get(i);
				String col = t[0].concat(t[1]);
				String total="";
				if(t[0].equalsIgnoreCase("test"))
				{
					total = col+"="+col+"+1, ";
					total+="test_total=test_total+1";
				}
				else
				{
					total = col+"="+col+"+1, total"+t[1]+"=total"+t[1]+"+1, ";
					total += "total_total=total_total+1";
				}
				
				sql = "UPDATE havelist SET "+ total +" WHERE client_code = 'IDCJP' ";
				p1[i] = conn.prepareStatement(sql);
				p1[i].executeUpdate();
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcClientDBModifyCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
				if(pstmt2!=null)pstmt2.close();
				for(int i=0;i<p1.length;i++)
				{
					if(p1[i]!=null)
						p1[i].close();
				}
			}
			catch (SQLException e) 
			{
				System.out.println("IdcClientDBModifyCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	private void addReseller(String name)
	{
		String code = IdcGetClientNameCode.getClientCode(name);
		ArrayList<String[]> codeList = new ArrayList<String[]>();
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		PreparedStatement[] p1 = null, p2 = null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT service_line, server_location FROM serverdb as s, ";
					sql+="(SELECT * FROM servicedb WHERE client_code=?) as t ";
					sql+="WHERE t.server_code=s.server_code";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, code);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				String[] temp = new String[2];
				temp[0] = rs.getString("service_line");
				temp[1] = getLocation(rs.getString("server_location"));
				codeList.add(temp);
			}
			
			sql = "INSERT INTO havelist (client_code, client_name) values(?,?)";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setString(1, code);
			pstmt2.setString(2, name);
			pstmt2.executeUpdate();
			
			p1 = new PreparedStatement[codeList.size()];
			p2 = new PreparedStatement[codeList.size()];
			
			for(int i=0;i<codeList.size();i++)
			{
				String t[] = codeList.get(i);
				String col = t[0].concat(t[1]);
				String total="";
				String add = "";
				if(t[0].equalsIgnoreCase("test"))
				{
					total = col+"="+col+"-1, ";
					total+="test_total=test_total-1";
					
					add = col+"="+col+"+1, ";
					add+="test_total=test_total+1";
				}
				else
				{
					total = col+"="+col+"-1, total"+t[1]+"=total"+t[1]+"-1, ";
					total += "total_total=total_total-1";
					
					add = col+"="+col+"+1, total"+t[1]+"=total"+t[1]+"+1, ";
					add += "total_total=total_total+1";
				}
				
				sql = "UPDATE havelist SET "+ total +" WHERE client_code = 'IDCJP' ";
				p1[i] = conn.prepareStatement(sql);
				p1[i].executeUpdate();

				sql = "UPDATE havelist SET "+ add +" WHERE client_code = '"+code+"' ";
				p2[i] = conn.prepareStatement(sql);
				p2[i].executeUpdate();
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcClientDBModifyCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
				if(pstmt2!=null)pstmt2.close();
				for(int i=0;i<p1.length;i++)
				{
					if(p1[i]!=null)
						p1[i].close();
					if(p2[i]!=null)
						p2[i].close();
				}
			}
			catch (SQLException e) 
			{
				System.out.println("IdcClientDBModifyCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	private String getLocation(String location)
	{
		String result="";

		if(location.equalsIgnoreCase("tokyo"))
			result="_t";
		else
			result = "_c";
		
		return result;
	}
	
	private int checkRe(String r, String name)
	{
		int result =0;
		int in=Integer.parseInt(r), out=0;
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM clientdb WHERE client_name=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, name);
			rs = pstmt.executeQuery();
			
			if(rs.next())
			{
				out= Integer.parseInt(rs.getString("client_reseller"));	
			}
			System.out.println(in +" " + out);
			if(in>0)
			{
				if(out>0)
					result=0;
				else
					result=1;
			}
			else
			{
				if(out>0)
					result=-1;
				else
					result=0;
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcClientDBModifyCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcClientDBModifyCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return result;
	}
	
	//게시글 수정 기능 수행
	public void idcClientDBModify(String client_code, String client_name, String client_reseller, String client_phone1, String client_phone2,
			String client_email1, String client_email2, String client_note, Date client_receive_date, Date client_renew_date ){
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		System.out.println("idcClientDBModify!!!!!!!!!!");
		try 
		{
			conn=dao.getConn();
			String sql = "UPDATE clientdb SET client_name=?,client_reseller=?,client_phone1=?, ";
			sql+="client_phone2=?, client_email1=?, client_email2=?, client_note=?, client_receive_date=?, client_renew_date=? ";
			sql+="WHERE client_code=? ";
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, client_name);
			pstmt.setString(2, client_reseller);
			pstmt.setString(3, client_phone1);
			pstmt.setString(4, client_phone2);
			pstmt.setString(5, client_email1);
			pstmt.setString(6, client_email2);
			pstmt.setString(7, client_note);
			pstmt.setDate(8, client_receive_date);
			pstmt.setDate(9, client_renew_date);
			pstmt.setString(10, client_code);
			pstmt.executeUpdate();
			IdcupdateCmd(client_code, Integer.parseInt(client_reseller));
		}
		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();
	 		}
		}
	}

}
