package com.eactive.eai.rms.onl.statistics.trand.service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.rms.onl.statistics.eaisvcname.vo.StatisticsForm;
import com.eactive.eai.rms.onl.statistics.trand.dao.TransitionDAO;
import com.eactive.eai.rms.onl.statistics.trand.vo.TrandBean;
import com.eactive.eai.rms.onl.statistics.trand.vo.YearTrandVO;

/**
 * <pre>
 * 1. 기능 :
 * 2. 처리 개요 :
 *     -
 * 3. 주의사항 :
 * </pre>
 * @author  : music75
 * @version : $Revision: 1.2 $
 * @since : rts 1.0
 * @spring.bean id="transitionServiceImpl"
 * @spring.property name="transitionDAO" ref="transitionDAO"
 */
@Service("transitionService")
public class TransitionServiceImpl
        implements TransitionService {

    private static final Logger logger = Logger.getLogger(TransitionServiceImpl.class);

    @Autowired
    @Qualifier("transitionDAO")
    private TransitionDAO transitionDAO = null;

    public List getFindTransitionData(StatisticsForm statisticsForm) throws Exception {
        return transitionDAO.findByTransition(statisticsForm);
    }

    public List findTrandArray(StatisticsForm statisticsForm)
            throws Exception {

        List list = transitionDAO.findTrandArray(statisticsForm.getSearchField(),
            statisticsForm.getSearchText());

        TrandBean[] trandBeans = new TrandBean[list.size()];
        list.toArray(trandBeans);

        YearTrandVO yearTrand = new YearTrandVO();

        ArrayList trandArrays = new ArrayList();

        for (int i = 1; i < trandBeans.length - 10; i++) {
            // 이동평균값
            for (int j = i - 1; j < i + 11; j++) {
                try {
                    trandBeans[i].sumTrsmtNoitm(trandBeans[j].getTrsmtNoitm());
                } catch (ArrayIndexOutOfBoundsException e) {
                	logger.warn("");
                }
            }
            trandBeans[i].setSumTrsmtNoitmToAvg(12);

            if (i != 1) {
                // 이동평균중앙값
                trandBeans[i].setMiddelMoveAvg((trandBeans[i - 1].getMoveAvg() + trandBeans[i].getMoveAvg()) / 2);

            }

            // 월지수
            addMonthPercentageList(trandBeans, yearTrand, i);
        }

        for (int i = 0; i < trandBeans.length; i++) {
            if (logger.isDebugEnabled()) {
                logger.debug(trandBeans[i].getStatcYm() + ":"
                        + trandBeans[i].getTrsmtNoitm() + ":이동평균값:"
                        + trandBeans[i].getMoveAvg() + ":이동평균중간값:"
                        + trandBeans[i].getMiddelMoveAvg() + ":월지수:"
                        + trandBeans[i].getThisMonthPercentage());
            }
        }

        if (logger.isDebugEnabled()) {

            for (int i = 0; i < yearTrand.getMoveAgeList1().size(); i++) {
                yearTrand.setMoveAge1(yearTrand.getMoveAge1()
                        + yearTrand.getMoveAgeList1().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList2().size(); i++) {
                yearTrand.setMoveAge2(yearTrand.getMoveAge2()
                        + yearTrand.getMoveAgeList2().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList3().size(); i++) {
                yearTrand.setMoveAge3(yearTrand.getMoveAge3()
                        + yearTrand.getMoveAgeList3().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList4().size(); i++) {
                yearTrand.setMoveAge4(yearTrand.getMoveAge4()
                        + yearTrand.getMoveAgeList4().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList5().size(); i++) {
                yearTrand.setMoveAge5(yearTrand.getMoveAge5()
                        + yearTrand.getMoveAgeList5().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList6().size(); i++) {
                yearTrand.setMoveAge6(yearTrand.getMoveAge6()
                        + yearTrand.getMoveAgeList6().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList7().size(); i++) {
                yearTrand.setMoveAge7(yearTrand.getMoveAge7()
                        + yearTrand.getMoveAgeList7().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList8().size(); i++) {
                yearTrand.setMoveAge8(yearTrand.getMoveAge8()
                        + yearTrand.getMoveAgeList8().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList9().size(); i++) {
                yearTrand.setMoveAge9(yearTrand.getMoveAge9()
                        + yearTrand.getMoveAgeList9().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList10().size(); i++) {
                yearTrand.setMoveAge10(yearTrand.getMoveAge10()
                        + yearTrand.getMoveAgeList10().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList11().size(); i++) {
                yearTrand.setMoveAge11(yearTrand.getMoveAge11()
                        + yearTrand.getMoveAgeList11().get(i));
            }
            for (int i = 0; i < yearTrand.getMoveAgeList12().size(); i++) {
                yearTrand.setMoveAge12(yearTrand.getMoveAge12()
                        + yearTrand.getMoveAgeList12().get(i));
            }
            yearTrand.setMoveAge1(yearTrand.getMoveAge1()
                    / yearTrand.getMoveAgeList1().size());
            yearTrand.setMoveAge2(yearTrand.getMoveAge2()
                    / yearTrand.getMoveAgeList2().size());
            yearTrand.setMoveAge3(yearTrand.getMoveAge3()
                    / yearTrand.getMoveAgeList3().size());
            yearTrand.setMoveAge4(yearTrand.getMoveAge4()
                    / yearTrand.getMoveAgeList4().size());
            yearTrand.setMoveAge5(yearTrand.getMoveAge5()
                    / yearTrand.getMoveAgeList5().size());
            yearTrand.setMoveAge6(yearTrand.getMoveAge6()
                    / yearTrand.getMoveAgeList6().size());
            yearTrand.setMoveAge7(yearTrand.getMoveAge7()
                    / yearTrand.getMoveAgeList7().size());
            yearTrand.setMoveAge8(yearTrand.getMoveAge8()
                    / yearTrand.getMoveAgeList8().size());
            yearTrand.setMoveAge9(yearTrand.getMoveAge9()
                    / yearTrand.getMoveAgeList9().size());
            yearTrand.setMoveAge10(yearTrand.getMoveAge10()
                    / yearTrand.getMoveAgeList10().size());
            yearTrand.setMoveAge11(yearTrand.getMoveAge11()
                    / yearTrand.getMoveAgeList11().size());
            yearTrand.setMoveAge12(yearTrand.getMoveAge12()
                    / yearTrand.getMoveAgeList12().size());

            // 1월 평균월지수
            if (logger.isDebugEnabled()) {
                logger.debug("1월평균월지수 :" + yearTrand.getMoveAge1());
                logger.debug("2월평균월지수 :" + yearTrand.getMoveAge2());
                logger.debug("3월평균월지수 :" + yearTrand.getMoveAge3());
                logger.debug("4월평균월지수 :" + yearTrand.getMoveAge4());
                logger.debug("5월평균월지수 :" + yearTrand.getMoveAge5());
                logger.debug("6월평균월지수 :" + yearTrand.getMoveAge6());
                logger.debug("7월평균월지수 :" + yearTrand.getMoveAge7());
                logger.debug("8월평균월지수 :" + yearTrand.getMoveAge8());
                logger.debug("9월평균월지수 :" + yearTrand.getMoveAge9());
                logger.debug("10월평균월지수 :" + yearTrand.getMoveAge10());
                logger.debug("11월평균월지수 :" + yearTrand.getMoveAge11());
                logger.debug("12월평균월지수 :" + yearTrand.getMoveAge12());
            }

        }

        //SimpleDateFormat format = new SimpleDateFormat();

        // 2월 예측 월지수

        // 2월 예측값
       // TrandBean tempBean1 = new TrandBean();
        /*
         * 현재달 = 마지막달 + 1 이 13일 경우 1월 아닐 경우 그대로
         */

        if(trandBeans.length > 0){
	        int lastMonth = trandBeans[trandBeans.length - 1].getMonth();
	        int currentMonth = 0;
	        if (lastMonth == 12) {
	            currentMonth = 1;
	        } else {
	            currentMonth = lastMonth + 1;
	        }
	        /*
	         * 추이값
	         * 이전 6개월 6보다 작으면 레코드 수만큼
	         * 레코드 수가 1개 이하면 1
	         */
	        float trandRate = 0f;

	        if (list.size() <= 1) {
	            // 레코드가 1개 이하
	            trandRate = 1;
	        } else {
	            int trandCount = 0;
	            // 레코드가 2개 이상
	            for (int i = trandBeans.length - 1; i > 0; i--) {
	                trandCount++;
	                trandRate = trandRate + trandBeans[i].getTrsmtNoitm()
	                        / trandBeans[i - 1].getTrsmtNoitm();
	            }
	            trandRate = trandRate / trandCount;
	        }
	        /*
	         * 마지막 거래 건수 / 마지막달 월지수 * 현재달 월지수 * 추이값
	         */

	        TrandBean tempTrandBean = null;
	        long trandCount = trandBeans[trandBeans.length - 1].getTrsmtNoitm();

	        int currentYear = trandBeans[trandBeans.length - 1].getStatcYm() / 100;

	        Calendar cal = Calendar.getInstance();
	        cal.set(currentYear, currentMonth - 1, 0);
	        for (int i = 0; i < 12; i++) {
	            tempTrandBean = new TrandBean();
	            cal.add(Calendar.MONTH, 1);
	            lastMonth = currentMonth;
	            currentMonth = cal.get(Calendar.MONTH) + 1;
	            if (list.size() < 24) {
	                // 통계용데이터가 부족 할 경우
	                trandCount = (long) (trandCount * trandRate);
	                tempTrandBean.setTrsmtNoitm(trandCount);
	                tempTrandBean.setStatcYm(cal.get(Calendar.YEAR) * 100
	                        + currentMonth);
	            } else {
	                // 통계용 데이터가 충분 할 경우 현재로 부터 년간의 데이터가 있는 경우
	                trandCount = (long) (trandCount
	                        / yearTrand.getMoveAge(lastMonth)
	                        * yearTrand.getMoveAge(currentMonth) * trandRate);
	                tempTrandBean.setTrsmtNoitm(trandCount);
	                tempTrandBean.setStatcYm(cal.get(Calendar.YEAR) * 100
	                        + currentMonth);

	            }
	            trandArrays.add(tempTrandBean);

	            if (logger.isDebugEnabled()) {
	                logger.debug(tempTrandBean.getStatcYm() + "월:예상 건수"
	                        + trandCount);
	            }

	        }
        }
        return trandArrays;
    }

    private void addMonthPercentageList(TrandBean[] trandBeans,
            YearTrandVO yearTrand, int i)
            throws Exception {
        float thisMonthPercentage = trandBeans[i].getThisMonthPercentage();
        if (thisMonthPercentage > 0) {
            int value = trandBeans[i].getMonth();
            switch (value) {
            case 1:
                yearTrand.getMoveAgeList1().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 2:
                yearTrand.getMoveAgeList2().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 3:
                yearTrand.getMoveAgeList3().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 4:
                yearTrand.getMoveAgeList4().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 5:
                yearTrand.getMoveAgeList5().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 6:
                yearTrand.getMoveAgeList6().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 7:
                yearTrand.getMoveAgeList7().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 8:
                yearTrand.getMoveAgeList8().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 9:
                yearTrand.getMoveAgeList9().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 10:
                yearTrand.getMoveAgeList10().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 11:
                yearTrand.getMoveAgeList11().add(trandBeans[i].getThisMonthPercentage());
                break;
            case 12:
                yearTrand.getMoveAgeList12().add(trandBeans[i].getThisMonthPercentage());
                break;
            default:
                break;
            }
        }
    }

    public int getNextMonth(int currentMonth) {
        if (currentMonth == 12) {
            return 1;
        } else {
            return currentMonth + 1;
        }
    }

}
