package com.style24.batch.biz.job.shoplinker;

import java.io.File;
import java.util.Calendar;
import java.util.Locale;

import com.style24.batch.support.env.TsbConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbShoplinkerService;
import com.style24.core.biz.service.TscOrderOcmService;
import com.style24.core.biz.service.TscShoplinkerService;
import com.style24.core.support.env.TscConstants;
import com.style24.persistence.domain.ShoplinkerOrder;
import com.style24.persistence.domain.ShoplinkerSearch;

import lombok.extern.slf4j.Slf4j;


/**
 * 샵링커 주문수집
 *
 * @author jmh
 * @since 2021.06.22
*/
@Component
@Slf4j
public class TsbShoplinkerOrderJob extends TsbAbstractJob<String, String, String>{

	@Autowired
	private TscShoplinkerService shoplinkerService;

	@Autowired
	private TsbShoplinkerService tbsShoplinkerService;

	@Autowired
	private TscOrderOcmService orderOcmService;

	@Autowired
	private Environment env;


	@Override
	public String read() throws Exception {
		return "OK";
	}

	@Override
	public String process(String result) throws Exception {
		/*********************************************************************
		 * 공휴일,토,일 : 수집안함 (샵링커 수집주문건 없음)
		 * 월요일 5시 : 저번주 금요일 15:00 ~ 금일 05:00
		 * 화~금 5시 : 어제 15:00 ~ 금일 05:00
		 * 월~금 6시~15 한시간 단위 :
		 *   - 6시 : 05:00 ~ 06:00
		 *   - 7시 : 06:00 ~ 07:00
		 *      ...
		 *   - 15 : 14:00 ~ 15:00
		 *********************************************************************/

		// 공휴일 체크된 시작, 종료 날짜 가져옴
		ShoplinkerSearch ordDateInfo = tbsShoplinkerService.getOrdDateInfo(); // 실제 날짜
		
		if( null != ordDateInfo ) {
			if("Y".equals(ordDateInfo.getBizdayYn())) {
				
				String toDt = GagaDateUtil.getToday("yyyyMMdd");
				ShoplinkerOrder shoplinkerOrder = new ShoplinkerOrder();
				ShoplinkerSearch slkSearch = new ShoplinkerSearch();

				// 기본 수집할 날짜 & 시간세팅
				Calendar calendar = Calendar.getInstance();
				int hours = calendar.get(Calendar.HOUR_OF_DAY);

				String stDay = "";
				String edDay = "";
				String stTime = "";
				String edtime = "";
				int strHour = 0;
				int endHour = 0;

				if( 5 == hours ) {
					stDay = ordDateInfo.getStartDt();	// 전주 또는 전일
					edDay = ordDateInfo.getToDt();		// 금일
					stTime = "150000";  // 전일 15시
					edtime = "050000";	// 금일 5시

				} else {
					stDay = ordDateInfo.getToDt();		// 금일
					edDay = ordDateInfo.getToDt();		// 금일
					strHour = hours - 1;
					endHour = hours;

					// 중간에 배치 건너뛴 시간 있을 경우 체크해서 시작 시간 늘림
					ShoplinkerSearch slkBatchInfo = tbsShoplinkerService.getShoplinkerOrderLastBatchInfo();
					if( null != slkBatchInfo ) {
						int lastHour = slkBatchInfo.getBatchOrdLastHour();
						if( lastHour < strHour ) {
							strHour = lastHour;
						}
					}

					if( strHour < 10 ) {
						stTime = "0" + strHour+"0000";
					}else {
						stTime = strHour+"0000";
					}

					if( endHour < 10 ) {
						edtime = "0" + endHour+"0000";
					}else {
						edtime = endHour+"0000";
					}
				}
				
				if("20210902".equals(toDt)) {
					if( 5 == hours ) {
						stDay = "20210831";
						edDay = "20210831";
						stTime = "150000";
						edtime = "235959";
					}									
				}
				
				shoplinkerOrder.setStDate(stDay);
				shoplinkerOrder.setEdDate(edDay);
				shoplinkerOrder.setStTime(stTime);
				shoplinkerOrder.setEdTime(edtime);

				try {
					
					// 1. 기본세팅정보
					shoplinkerOrder.setXmlPath(env.getProperty("shoplinker.xml.path")+"/order/"+toDt);		// xml path
					shoplinkerOrder.setDomainUrl(env.getProperty("shoplinker.xml.view")+"/order/"+toDt);	// xml 확인domain url
					shoplinkerOrder.setProfiles(env.getProperty("spring.profiles.active").toLowerCase());
					shoplinkerOrder.setCustomerId(env.getProperty("shoplinker.customer_id"));
					shoplinkerOrder.setShoplinkerId(env.getProperty("shoplinker.shoplinker_id"));
					shoplinkerOrder.setRegNo(TsbConstants.REG_NO);
					shoplinkerOrder.setAcType("BATCH");
					shoplinkerOrder.setInfoStr(stDay+"~"+edDay+"/"+stTime+"~"+edtime);	// shoplinker_runable.txt 에 참고할 텍스트

					// 2. 하위폴더존재확인(주문)
					String slFolder = GagaFileUtil.getConcatenationPath(shoplinkerOrder.getXmlPath());
					File slPath = new File(slFolder);
					if (!slPath.exists()) {
						slPath.mkdir();
					}

					// 3. API 호출 이력 저장 시작
					slkSearch.setSid(GagaDateUtil.getTodayDateTime());
					slkSearch.setApiType("BATCH-ORDER");
					slkSearch.setRegNo(TsbConstants.REG_NO);
					shoplinkerService.saveCallApiRunable(slkSearch);

					// 4. 샵링커 api 호출 샵링커주문수집 등록
					shoplinkerOrder.setSid(slkSearch.getSid());
					GagaMap rtnMap = shoplinkerService.insertShoplinkerOrderStep1(shoplinkerOrder);

					if(TscConstants.ShoplinkerApiStat.TRUE.value().equals(rtnMap.getString("RESULT_TYPE"))) {
						// 5. 제휴몰 주문등록
						slkSearch.setTxt("=>제휴몰");
						shoplinkerService.updateCallApiRunable(slkSearch);
						shoplinkerService.insertShoplinkerOrderStep2(shoplinkerOrder);

						// 6. 스타일24 주문등록 (제휴몰 - 대기상태인 것들)
						slkSearch.setTxt("=>스타일24");
						shoplinkerService.updateCallApiRunable(slkSearch);
						orderOcmService.createShoplinkerOrder("S", 0);
					}

					slkSearch.setRunStat(TscConstants.ShoplinkerApiStat.END.value());	// 상태값지정
					slkSearch.setTxt("=>FINISH");

				}catch (Exception e) {

					log.error("TsbShoplinkerOrderJob.process => error \n"+e);
					slkSearch.setRunStat(TscConstants.ShoplinkerApiStat.ERROR.value());	// 상태값지정
					slkSearch.setTxt("=>ERROR : "+StringUtils.abbreviate(e.getMessage(), 0 , 120));

				}finally {
					// 7. API 호출 이력 저장 종료
					shoplinkerService.saveCallApiRunable(slkSearch);
				}
			}

		}
		return result;
	}

	@Override
	public String write(String result) throws Exception {
		return result;
	}

	@Override
	public void notify(String result) throws Exception {
		// Do nothing
	}
}
