package sgc.portal.cw.cw1502.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.cw1502.dto.CW15020003PSearch;
import sgc.portal.cw.cw1502.model.CW15020003P;
import sgc.portal.cw.cw1502.model.CW15020004P;
import sgc.portal.cw.cw1502.persistence.CW15020003PMapper;

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

@Service
public class CW15020003PService {
    private final CW15020003PMapper mapper;

    public CW15020003PService(CW15020003PMapper mapper) {
        this.mapper = mapper;
    }
    
    public EasyHashMap<String, Object> getSelectRemInfo(CW15020003PSearch search) {
        return mapper.getSelectRemInfo(search);
    }

	@Transactional
    public Map<String, String> save(CW15020003P cW15020003P) throws ParseException {
    	Map<String,String> result = new HashMap<>();
    	
    	String str = cW15020003P.getEndYyyymmdd()+cW15020003P.getEndHhmm();
    	String str2 = cW15020003P.getCloseYyyymmdd()+cW15020003P.getCloseHhmm();

    	long date1 = Long.parseLong(str);
    	long date2 = Long.parseLong(str2);
    	
        Date format1 = new SimpleDateFormat("yyyyMMdd").parse(cW15020003P.getEndYyyymmdd());  //예약종료
        Date format2 = new SimpleDateFormat("yyyyMMdd").parse(cW15020003P.getCloseYyyymmdd()); //실제반납
        
        long diffSec = (format1.getTime() - format2.getTime()) / 1000; //초 차이, 예약종료 - 실제반납
        long diffDays = diffSec / (24*60*60); //일자수 차이

        long diffSec2 = (format2.getTime() - format1.getTime()) / 1000; //초 차이, 실제반납 - 예약종료 
        long diffDays2 = diffSec2 / (24*60*60); //일자수 차이

    	Calendar cal1 = Calendar.getInstance();
    	Calendar cal2 = Calendar.getInstance();
    	Calendar cal3 = Calendar.getInstance();
    	Calendar cal4 = Calendar.getInstance();
    	
    	cal1.setTime(format1);
    	cal2.setTime(format2);
    	cal3.setTime(format1);
    	cal4.setTime(format2);

        cal1.add(Calendar.DATE, 1); //예약종료 +1일
        cal2.add(Calendar.DATE, -1); //실제반납일 -1일
        cal3.add(Calendar.DATE, -1); //예약종료 -1일
        cal4.add(Calendar.DATE, 1); //실제반납일 +1일

        String format3 = new SimpleDateFormat("yyyyMMdd").format(cal1.getTime());
        String format4 = new SimpleDateFormat("yyyyMMdd").format(cal2.getTime());
        String format5 = new SimpleDateFormat("yyyyMMdd").format(cal3.getTime());
        String format6 = new SimpleDateFormat("yyyyMMdd").format(cal4.getTime());
    	
    	updateRes(cW15020003P);	//기존 예약 status,시간 업데이트
    	
    	//int dist = mapper.getDepartAccumDist(cW15020003P); // 최근 누적거리
    	//cW15020003P.setDepartAccumDist(dist);
    	insertLog(cW15020003P);	//운행기록부 등록
    	
    	if(date1 >= date2) { // 예약시간 내 반납
    		if(diffDays > 1) {
                cW15020003P.setSearchYmd1(format6); // 실제반납일 +1일
                cW15020003P.setSearchYmd2(format5); // 예약종료일자 -1일
                cW15020003P.setSearchYmd3(cW15020003P.getCloseYyyymmdd()); // 실제반납일
                cW15020003P.setSearchYmd4(cW15020003P.getEndYyyymmdd()); // 예약종료일
                
            	cW15020003P.setCheck1(disColCount1(cW15020003P, 1));//실제반납일 디스플레이 컬럼수
            	cW15020003P.setCheck2(disColCount2(cW15020003P, 1));//예약종료일자 디스플레이 컬럼수

				updateDis(cW15020003P, 1, cW15020003P.getCheck1());//실제반납일
				updateDis2(cW15020003P, 1);//종료일자
				updateDis3(cW15020003P, 1);//중간일자
				
    		} else if(diffDays > 0) {
                cW15020003P.setSearchYmd3(cW15020003P.getCloseYyyymmdd()); // 실제반납일
                cW15020003P.setSearchYmd4(cW15020003P.getEndYyyymmdd()); // 예약종료일
                
            	cW15020003P.setCheck1(disColCount1(cW15020003P, 1));//실제반납일 디스플레이 컬럼수
            	cW15020003P.setCheck2(disColCount2(cW15020003P, 1));//예약종료일자 디스플레이 컬럼수
            	
				updateDis(cW15020003P, 1, cW15020003P.getCheck1());//실제반납일
				updateDis2(cW15020003P, 1);//종료일자
    			
    		} else if(diffDays == 0) {
                cW15020003P.setSearchYmd3(cW15020003P.getCloseYyyymmdd()); // 실제반납일
                
            	cW15020003P.setCheck(disColCount(cW15020003P, 1));//디스플레이 컬럼수
				updateDis(cW15020003P, 1, cW15020003P.getCheck());//실제반납일
    			
    		}
    	} else { // 예약시간 초과
    		int checkR = mapper.getCheckReservation(cW15020003P); //예약종료시간~반납시간 이후 예약건수 체크
    		
    		if(checkR > 0) { //다른 예약 없을 경우
    	    	updateRes2(cW15020003P);//다른에약건 상태변경
    		}

    		int checkR2 = mapper.getCheckReservation2(cW15020003P); //예약시작~종료 사이 반납 여부 체크

    		if(checkR2 > 0) {
    	    	updateRes3(cW15020003P);//다른에약건 시간변경
    		}

    		if(diffDays2 > 1) {
                cW15020003P.setSearchYmd1(format3); // 예약종료일자 +1일
                cW15020003P.setSearchYmd2(format4); // 실제반납일 -1일
                cW15020003P.setSearchYmd3(cW15020003P.getEndYyyymmdd()); // 예약종료일
                cW15020003P.setSearchYmd4(cW15020003P.getCloseYyyymmdd()); // 실제반납일

            	cW15020003P.setCheck1(disColCount1(cW15020003P, 2));//예약종료일자 디스플레이 컬럼수
            	cW15020003P.setCheck2(disColCount2(cW15020003P, 2));//실제반납일 디스플레이 컬럼수

				updateDis(cW15020003P, 2, cW15020003P.getCheck1());//예약종료일자
				updateDis2(cW15020003P, 2);//실제반납일
				updateDis3(cW15020003P, 2);//중간일자
    		} else if(diffDays2 > 0) { 
                cW15020003P.setSearchYmd3(cW15020003P.getEndYyyymmdd()); // 예약종료일
                cW15020003P.setSearchYmd4(cW15020003P.getCloseYyyymmdd()); // 실제반납일
                
            	cW15020003P.setCheck1(disColCount1(cW15020003P, 2));//시작일자 디스플레이 컬럼수
            	cW15020003P.setCheck2(disColCount2(cW15020003P, 2));//종료일자 디스플레이 컬럼수
            	
				updateDis(cW15020003P, 2, cW15020003P.getCheck1());//예약종료일자
				updateDis2(cW15020003P, 2);//실제반납일
    			
    		} else if(diffDays2 == 0) {
                cW15020003P.setSearchYmd3(cW15020003P.getEndYyyymmdd()); // 예약종료일
                
            	cW15020003P.setCheck(disColCount(cW15020003P, 2));//디스플레이 컬럼수
            	
				updateDis(cW15020003P, 2, cW15020003P.getCheck());//예약종료일자
    		}
    	}
        return result;
    }
	
    private void updateRes(CW15020003P cW15020003P) {
        mapper.updateRes(cW15020003P);
    }
	
    private void updateRes2(CW15020003P cW15020003P) {
        mapper.updateRes2(cW15020003P);
    }
	
    private void updateRes3(CW15020003P cW15020003P) {
        mapper.updateRes3(cW15020003P);
    }
	
    private void insertLog(CW15020003P cW15020003P) {
        mapper.insertLog(cW15020003P);
    }
    
    private void updateDis(CW15020003P cW15020003P, int gbn, int checkCnt) {
    	
    	int cnt			= checkCnt;
    	String col 		= "";
    	String colname 	= "";

    	if(cnt > 0) {
	    	if(gbn == 1) {
	    		colname = String.valueOf(Long.parseLong(cW15020003P.getCloseHhmm().substring(0, 2))+1);
	    		if(colname.length()< 2) {
	    			colname = "T0" + colname;
	    		} else {
	    			colname = "T" + colname;
	    		}
	
	        	col = colname + " = 'N'";
	        	
	        	for( int i = 1; i < cnt; i++ ){
	            	//컬럼명 변경
	            	if(colname.length()<4){
	              		colname = "," + colname;
	              	}
	          		colname = String.valueOf(Integer.parseInt(colname.substring(2, 4))+1);
	          		if( colname.length() < 2 ){
	          			colname = ",T0" + colname;
	          		}else{
	          			colname = ",T" + colname;
	          		}
	          		
	            	col = col + colname + " = 'N'";
	        	}
	        	cW15020003P.setColname(col);
	    	} else {
	
	        	String reinfo 	= mapper.getReservationDis(cW15020003P);
	
	    		colname = String.valueOf(Long.parseLong(cW15020003P.getEndHhmm().substring(0, 2))+1);
	    		if(colname.length()< 2) {
	    			colname = "T0" + colname;
	    		} else {
	    			colname = "T" + colname;
	    		}
	    		
	        	col 	= colname + " = '" + reinfo + "'";
	        	
	        	for( int i = 1; i < cnt; i++ ){
	            	//컬럼명 변경
	            	if(colname.length()<4){
	              		colname = "," + colname;
	              	}
	          		colname = String.valueOf(Integer.parseInt(colname.substring(2, 4))+1);
	          		if( colname.length() < 2 ){
	          			colname = ",T0" + colname;
	          		}else{
	          			colname = ",T" + colname;
	          		}
	            	
	            	col = col + colname + " = '" + reinfo + "'";
	        	}
	        	cW15020003P.setColname(col);
	    	}
			mapper.updateDis(cW15020003P); //시작일자
    	}
    }
    
    private void updateDis2(CW15020003P cW15020003P, int gbn) {
    	
    	int cnt			= cW15020003P.getCheck2();
    	String col 		= "";
    	String colname 	= "";

    	if(gbn == 1) {
        	colname = "T00";
        	col 	= colname + " = 'N'";
        	
        	for( int i = 1; i < cnt; i++ ){
            	//컬럼명 변경
            	if(colname.length()<4){
              		colname = "," + colname;
              	}
          		colname = String.valueOf(Integer.parseInt(colname.substring(2, 4))+1);
          		if( colname.length() < 2 ){
          			colname = ",T0" + colname;
          		}else{
          			colname = ",T" + colname;
          		}
          		
            	col = col + colname + " = 'N'";
        	}
        	cW15020003P.setColname(col);
    	} else {
        	String reinfo 	= mapper.getReservationDis(cW15020003P);
        	
        	colname = "T00";
        	col 	= colname + " = '" + reinfo + "'";
        	
        	for( int i = 1; i < cnt; i++ ){
            	//컬럼명 변경
            	if(colname.length()<4){
              		colname = "," + colname;
              	}
          		colname = String.valueOf(Integer.parseInt(colname.substring(2, 4))+1);
          		if( colname.length() < 2 ){
          			colname = ",T0" + colname;
          		}else{
          			colname = ",T" + colname;
          		}
            	
            	col = col + colname + " = '" + reinfo + "'";
        	}
        	cW15020003P.setColname(col);
    	}
        mapper.updateDis2(cW15020003P); //종료일자
    }
    
    private void updateDis3(CW15020003P cW15020003P, int gbn) {

    	if(gbn == 1) {
            mapper.updateDis3(cW15020003P);
    	} else {
        	String reinfo 	= mapper.getReservationDis(cW15020003P);
        	
        	cW15020003P.setColname(reinfo);
        	
            mapper.updateDis4(cW15020003P);
    	}
    }
    
    private int disColCount(CW15020003P cW15020003P, int gbn) {
    	
    	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;
        
        if(gbn == 1) {
            start_t = cW15020003P.getCloseHhmm().replace(":", "");
            start_t = start_t.substring(0,2)+"59";
        	end_t 	= cW15020003P.getEndHhmm().replace(":", "");
        } else {
        	start_t	= cW15020003P.getEndHhmm().replace(":", "");
        	end_t 	= cW15020003P.getCloseHhmm().replace(":", "");
        	end_t 	= end_t.substring(0,2)+"59";
        }
    	
    	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){
    		h = 1;
    		m = 0;
    	} else {
    		h = 0;
    		m = 0;
    	}

    	if(m == 0){
    		cnt = h;
    	}else{
    		cnt = h + 1;
    	}
    	
    	return cnt;
    }
    
    private int disColCount1(CW15020003P cW15020003P, int gbn) {
    	
    	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;

        if(gbn == 1) {
	        start_t = cW15020003P.getCloseHhmm().replace(":", "");
            start_t = start_t.substring(0,2)+"59";
	    	end_t 	= "2359";
        } else {
	        start_t = cW15020003P.getEndHhmm().replace(":", "");
	    	end_t 	= "2359";
        }
    	
    	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){
    		h = 1;
    		m = 0;
    	} else {
    		h = 0;
    		m = 0;
    	}

    	if(m == 0){
    		cnt = h;
    	}else{
    		cnt = h + 1;
    	}
    	
    	return cnt;
    }
    
    private int disColCount2(CW15020003P cW15020003P, int gbn) {
    	
    	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;

        if(gbn == 1) {
	        start_t = "0000";
	        end_t 	= cW15020003P.getEndHhmm().replace(":", "");
        } else {
	        start_t = "0000";
	        end_t 	= cW15020003P.getCloseHhmm().replace(":", "");
        	end_t 	= end_t.substring(0,2)+"59";
        }
    	
    	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){
    		h = 1;
    		m = 0;
    	} else {
    		h = 0;
    		m = 0;
    	}

    	if(m == 0){
    		cnt = h;
    	}else{
    		cnt = h + 1;
    	}
    	
    	return cnt;
    }
}
