package sgc.portal.cw.cw0804.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import sgc.portal.base.exception.BusinessException;
import sgc.portal.base.util.EasyHashMap;
import sgc.portal.cw.cw0804.model.CW08040004P;
import sgc.portal.cw.cw0804.persistence.CW08040004PMapper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Service
public class CW08040004PService {
    private final CW08040004PMapper mapper;

    public CW08040004PService(CW08040004PMapper mapper) {
        this.mapper = mapper;
    }

	@Transactional
    public Map<String, String> save(CW08040004P cW08040004P) {
		List<String> weekList = cW08040004P.getWeekList();
		if (weekList != null && weekList.size() > 0) {
			for(String wType : weekList) {
				switch(wType) {
				case "FR" :
					cW08040004P.setWeekFr("Y");
					break;
				case "MU" :
					cW08040004P.setWeekMu("Y");
					break;
				case "TH" :
					cW08040004P.setWeekTh("Y");
					break;
				case "TU" :
					cW08040004P.setWeekTu("Y");
					break;
				case "WE" :
					cW08040004P.setWeekWe("Y");
					break;
				}
			}
		}
		
    	Map<String,String> result = new HashMap<>();
    	
    	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.KOREA);
    	Date sDate 	= null;
    	try {sDate 	= dateFormat.parse(cW08040004P.getStartYyyymmdd());} catch (ParseException e) {e.printStackTrace();}
    	Date eDate 	= null;
    	try {eDate 	= dateFormat.parse(cW08040004P.getEndYyyymmdd());} catch (ParseException e) {e.printStackTrace();}
    	int period 	= (int)((eDate.getTime() - sDate.getTime()) / (24 * 60 * 60 * 1000));
    	
    	String s_temp 	= "";
    	Calendar cal_t 	= Calendar.getInstance();
    	int day 		= 0; //요일 
    	
    	if(cW08040004P.getWeek().equals("10")) {
    		
    		for( int i = 0; i < period + 1; i++ ){
    			
    			s_temp 	= dateFormat.format(sDate);
	    		cal_t.setTime(sDate);
	    		day 	= cal_t.get(cal_t.DAY_OF_WEEK);
	    		cW08040004P.setCheck(disColCount(cW08040004P));
	    		cW08040004P.setStartDate(s_temp);
	    		
	    		if(day > 1 && day < 7){
	    			if(mapper.getCheckReservation(cW08040004P) == 0) {
	    				if(getCheckReservationDis(cW08040004P) == 0) {
	    					if(mapper.getCheckReservation(cW08040004P) == 0) {
	    						insert(cW08040004P);
	    						if(getCheckReservationDis(cW08040004P) == 0) {
	    	    					updateDis(cW08040004P);
	    	    					insertHis(cW08040004P);
	    	    					//result.put("result", "예약 되었습니다.");
	    	    				} else {
	    	    					throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
	    	    				}
	    					} else {
			        			throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
			        		}
	    				} else {
		        			throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
		        		}
	    			} else {
	        			throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
	        		}
	    		}
	    		sDate = dateAdd(Calendar.DATE, 1,sDate);
    		}
    		
    	} else {
    		
    		for( int i = 0; i < period + 1; i++ ){
    			s_temp 	= dateFormat.format(sDate);
    			cal_t.setTime(sDate);
    			day 	= cal_t.get(cal_t.DAY_OF_WEEK);
    			cW08040004P.setCheck(disColCount(cW08040004P));
	    		cW08040004P.setStartDate(s_temp);
	    		
	    		if( day == 2 && cW08040004P.getWeekMu().equals("Y") ||
	    			day == 3 && cW08040004P.getWeekTu().equals("Y") ||
	    			day == 4 && cW08040004P.getWeekWe().equals("Y") ||
	    			day == 5 && cW08040004P.getWeekTh().equals("Y") ||
	    			day == 6 && cW08040004P.getWeekFr().equals("Y")) {
	    			
	    			if(mapper.getCheckReservation(cW08040004P) == 0) {
	    				if(getCheckReservationDis(cW08040004P) == 0) {
	    					if(mapper.getCheckReservation(cW08040004P) == 0) {
	    						insert(cW08040004P);
	    						if(getCheckReservationDis(cW08040004P) == 0) {
	    	    					updateDis(cW08040004P);
	    	    					insertHis(cW08040004P);
	    	    					//result.put("result", "예약 되었습니다.");
	    	    				} else {
	    	    					throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
	    	    				}
	    					} else {
			        			throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
			        		}
	    				} else {
		        			throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
		        		}
	    			} else {
	        			throw new BusinessException("예약이  중복됩니다. 예약현황을 확인하세요.");
	        		}
	    		}
	    		sDate = dateAdd(Calendar.DATE, 1,sDate);
    		}
    	}
        return result;
    }

    private void insert(CW08040004P cW08040004P) {
        mapper.insert(cW08040004P);
    }
    
    private void updateDis(CW08040004P cW08040004P) {
    	
    	int cnt			= cW08040004P.getCheck();
    	String col 		= "";
    	String colname 	= "";
    	String reinfo 	= mapper.getReservationDis(cW08040004P);
    	
    	colname = "T" + cW08040004P.getStartHhmm().substring(0, 3);
    	col 	= colname + " = '" + reinfo + "'";
    	
    	for( int i = 1; i < cnt; i++ ){
        	//컬럼명 변경
        	if(colname.length()<5){
          		colname = "," + colname;
          	}
          	if(colname.substring(4).equals("0")){
          		colname = colname.substring(0, 4) + "3";
          	}else{
          		colname = String.valueOf(Integer.parseInt(colname.substring(2, 4))+1)+"0";
          		if( colname.length() < 3 ){
          			colname = ",T0" + colname;
          		}else{
          			colname = ",T" + colname;
          		}
          	}
        	col = col + colname + " = '" + reinfo + "'";
    	}
    	cW08040004P.setColname(col);
    	
        mapper.updateDis(cW08040004P);
    }
    
    private void insertHis(CW08040004P cW08040004P) {
        mapper.insertHis(cW08040004P);
    }
    
    private int disColCount(CW08040004P cW08040004P) {
    	
    	int 	cnt		= 0;
    	String 	start_t = "";
        String 	end_t	= "";
        String 	cnt_t	= "";
        
        int i_start_t	= 0;
        int i_end_t		= 0;
        int h			= 0;
        int m			= 0;
        
        start_t = cW08040004P.getStartHhmm().replace(":", "");
    	end_t 	= cW08040004P.getEndHhmm().replace(":", "");
    	
    	i_start_t	= Integer.parseInt(start_t);
    	i_end_t		= Integer.parseInt(end_t);
    	
    	cnt		= i_end_t - i_start_t;
    	cnt_t	= String.valueOf(cnt);
    	
    	if(cnt_t.length()>3){
    		h = Integer.parseInt(cnt_t.substring(0, 2));
    		m = Integer.parseInt(cnt_t.substring(2));
    	}else if(cnt_t.length() > 2){
    		h = Integer.parseInt(cnt_t.substring(0, 1));
    		m = Integer.parseInt(cnt_t.substring(1));
    	}else if(cnt_t.length() > 1){
    		m = Integer.parseInt(cnt_t);
    	}
    	
    	if(m == 0){
    		cnt = h * 2;
    	}else{
    		cnt = (h * 2) + 1;
    	}
    	
    	return cnt;
    }
    
    private int getCheckReservationDis(CW08040004P cW08040004P) {
    	
    	int cnt			= cW08040004P.getCheck();
    	int result		= 0;
    	String col 		= "";
    	String colname 	= "";
    	
    	colname = "T" + cW08040004P.getStartHhmm().substring(0, 3);
    	col 	= colname;
    	
    	for( int i = 1; i < cnt; i++ ){
    		
    		if(colname.length()<5){
          		colname = "," + colname;
          	}
          	if(colname.substring(4).equals("0")){
          		colname = colname.substring(0, 4) + "3";
          	}else{
          		colname = String.valueOf(Integer.parseInt(colname.substring(2, 4))+1)+"0";
          		if( colname.length() < 3 ){
          			colname = ",T0" + colname;
          		}else{
          			colname = ",T" + colname;
          		}
          	}
          	col = col + colname;
    	}
    	
    	cW08040004P.setColname(col);
    	EasyHashMap<String, String> Map = new EasyHashMap<String, String>();
    	Map = mapper.getCheckReservationDis(cW08040004P);
    	
    	for (Map.Entry<String, String> entry : Map.entrySet()) {
            if (!"N".equals(entry.getValue())) {
            	result = 1;
            	break;
            }
    	}
    	return result;
    }
    
    public Date dateAdd(int field, int amount, Date date) {
    	Calendar cal = Calendar.getInstance(); 	/* 날짜 연산을 위해 Calendar 객체를 생성한다. */
    	cal.setTime(date); 						/* Date형으로 넘어온 날짜를 Calendar 객체를 이용하여 현재 시간으로 설정한다 */
    	cal.add(field, amount); 				/* Calendar 객체의 add 메소드를 이용하여 날짜 연산을 수행한다. */
    	Date date_re = cal.getTime();
    	return date_re; 						/* Date형으로 연산된 날짜를 반환한다. */
    }
}
