package idc.service.command;

import idc.model.*;
import java.sql.*;

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

import utility.IdcGetClientNameCode;

public class IdcServiceAccountingHandleCmd 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 checkList[] = request.getParameterValues("checkList");
		String payday[] = request.getParameterValues("payday");
		String payment[] = request.getParameterValues("payment_amount");
		String num[] = request.getParameterValues("num");
				
		if(checkList!=null && num !=null)
		{
			for(int i=0;i<num.length;i++)
			{													
				for(int j=0; j<checkList.length; j++){

					if(num[i].equals(checkList[j])){
						account(Integer.parseInt(num[i]), Date.valueOf(payday[i]), payment[i]);
						continue;
					}
				}								
			}
		}
		
		//서비스 비용처리
		String client_code = request.getParameter("client_code");
		//1회성 비용 처리
		String onetime_check[] = request.getParameterValues("onetime_check");									
		String onetime_num[] = request.getParameterValues("onetime_num");
		String onetime_payment_amount[] = request.getParameterValues("onetime_payment_amount");
		
		if(onetime_num != null && onetime_check != null)
		{
			String checkbox[] = new String[onetime_num.length];
			for(int i=0; i < onetime_num.length; i++){
				checkbox[i] = "n";
				
				int onetime_check_length = onetime_check.length; 
				
				for(int j=0; j<onetime_check_length; j++){
					if(onetime_num[i].equals(onetime_check[j])){
						checkbox[i] = "y";
					}
				}				
			}									
			onetimeAccountHandle(onetime_num, onetime_payment_amount, checkbox, client_code);
		}
		
	}
	
	private void account(int num, Date payday, String payment)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null, pstmt3=null, pstmt4=null, pstmt5=null;
		ResultSet rs=null;
		String service_code="";
		String non = "";
		String com = "incomplete";
		String adddb_case = "";
		String client_code="";
		String adddb_code="";
		try	
		{
			conn=dao.getConn();
			String sql="SELECT service_code, adddb_nonpayment, adddb_case, adddb_code, client_code FROM adddb WHERE adddb_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				service_code=rs.getString("service_code");
				non = rs.getString("adddb_nonpayment");
				adddb_case = rs.getString("adddb_case");
				client_code = rs.getString("client_code");
				adddb_code = rs.getString("adddb_code");
				
				System.out.println("pstmt  " + pstmt.toString());
			}
			
			if(non.equals(payment))
				com="complete";
			//해당 adddb 과금처리(미지급금 깎끼, 지금급 추가, 결제한 날짜 추가)
			sql="UPDATE adddb SET adddb_nonpayment=adddb_nonpayment-?, adddb_payment=adddb_payment+?, adddb_accountday=?, ";
			sql+="adddb_accountStatus=? ";
			sql+="WHERE adddb_num=?";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setString(1, payment);
			pstmt2.setString(2, payment);
			pstmt2.setDate(3, payday);
			pstmt2.setString(4, com);
			pstmt2.setInt(5, num);
			pstmt2.executeUpdate();
			
			//서비스 의 미지급금 깎아주고 해당 항목이 부가서비스 부분이라면 추가로 부가서비스부분의 금액을 까준다.
			if(adddb_case!="service")
				sql="UPDATE servicedb SET service_nonpayment=service_nonpayment-?, service_unitedAmount=service_unitedAmount-? ";
			else
				sql="UPDATE servicedb SET service_nonpayment=service_nonpayment-? ";
			sql+="WHERE service_code=?";
			pstmt3=conn.prepareStatement(sql);
			if(adddb_case!="service")
			{
				pstmt3.setString(1, payment);
				pstmt3.setString(2, payment);
				pstmt3.setString(3, service_code);
			}
			else
			{	
				pstmt3.setString(1, payment);
				pstmt3.setString(2, service_code);
			}
			
			pstmt3.executeUpdate();
			
			sql="UPDATE clientdb SET client_money=client_money-? WHERE client_code=?";
			pstmt4 = conn.prepareStatement(sql);
			pstmt4.setString(1, payment);
			pstmt4.setString(2, client_code);
			pstmt4.executeUpdate();
			
			sql="INSERT paymentlist (client_name, service_code, _case, payment_date, payment, adddb_code) "
					+ "values(?, ?, ?, curdate(), ?, ?)";
			pstmt5=conn.prepareStatement(sql);
			pstmt5.setString(1, IdcGetClientNameCode.getClientName(client_code));
			pstmt5.setString(2, service_code);
			pstmt5.setString(3, adddb_case);
			pstmt5.setString(4, payment);
			pstmt5.setString(5, adddb_code);
			pstmt5.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcServiceAccountingHandleCmd - account 에서의 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();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcServiceAccountingHandleCmd - account 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
		
	public void onetimeAccountHandle(String[] onetime_num, String[] onetime_payment_amount, String[] checkbox, String client_code)
	{
		
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt2=null, pstmt3=null;
		ResultSet rs2 = null;
		String sql;
		int total_payment = 0;
		
		try {
			conn = dao.getConn();			
			for(int i=0; i<onetime_num.length; i++){
				if(checkbox[i] == "y")
				{
					sql = "UPDATE onetimeDB SET onetime_nonpayment=onetime_nonpayment-? WHERE onetime_num=?";			
					pstmt = conn.prepareStatement(sql);
					
					pstmt.setString(1, onetime_payment_amount[i]);
					pstmt.setString(2, onetime_num[i]);			
					pstmt.executeUpdate();
					total_payment += Integer.parseInt(onetime_payment_amount[i]);
					
					sql = "UPDATE onetimeDB SET onetime_accountStatus='complete' WHERE onetime_nonpayment='0' and onetime_num=?";
					pstmt2 = conn.prepareStatement(sql);			
					pstmt2.setString(1, onetime_num[i]);					
					pstmt2.executeUpdate();
					
				}
			}
			
			sql = "UPDATE clientDB SET client_money=client_money-? WHERE client_code=?";
			pstmt3 = conn.prepareStatement(sql);			
			pstmt3.setString(1, total_payment+"");
			pstmt3.setString(2, client_code);
			pstmt3.executeUpdate();						
			
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(pstmt != null) pstmt.close();
				if(pstmt2 != null) pstmt2.close();
				if(pstmt3 != null) pstmt3.close();
				if(rs2 != null) rs2.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}
