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

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

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.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.core.biz.service.TscOrderOcmService;
import com.style24.core.biz.service.TscShoplinkerService;
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 TscOrderOcmService orderOcmService;

	@Autowired
	private Environment env;


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

	@Override
	public String process(String result) throws Exception {

		ShoplinkerOrder shoplinkerOrder = new ShoplinkerOrder();
		ShoplinkerSearch slkSearch = new ShoplinkerSearch();

		// 수집할 날짜 & 시간세팅 (7시~15동인만 배치실행)
		Calendar calendar = Calendar.getInstance();
		int hours = calendar.get(Calendar.HOUR_OF_DAY);

		if( 7 <= hours && hours < 16) {

			String week = GagaDateUtil.getDayOfWeek(calendar, Locale.ENGLISH);

			//String stDay = GagaDateUtil.getOffsetDate(-1, "yyyyMMdd");
			//String edDay = GagaDateUtil.getToday("yyyyMMdd");
			//*****  테스트기간 30일전데이터 수집   ************************//
			String stDay = GagaDateUtil.getOffsetDate(-30, "yyyyMMdd");	// 테스트기간
			String edDay = GagaDateUtil.getOffsetDate(-30, "yyyyMMdd");	//테스트기간
			String stTime = "";
			String edtime = "";
			int strHour = 0;
			int endHour = 0;

			if( 7 == hours ) {

				// 월요일인 7시인 경우 시작일은 저번주 금요일
				if( "MON".equals(week)) {
					//stDay = GagaDateUtil.getOffsetDate(-3, "yyyyMMdd");
					stDay = GagaDateUtil.getOffsetDate(-33, "yyyyMMdd");	//테스트기간
				}

				stTime = "150000";
				edtime = "070000";
			}else if( 8 <= hours && hours < 16) {
				strHour = hours - 1;
				endHour = hours;

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

				if( endHour < 10 ) {
					edtime = "0" + endHour+"0000";
				}else {
					edtime = endHour+"0000";
				}
			}

			shoplinkerOrder.setStDate(stDay);
			shoplinkerOrder.setEdDate(edDay);
			shoplinkerOrder.setStTime(stTime);
			shoplinkerOrder.setEdTime(edtime);

			//System.out.println("## 테스트기간 :: "+stDay +" || "  +edDay );
			//System.out.println("## 테스트시간 :: "+stTime +" || "+edtime);

			try {

				// 1. 기본세팅정보
				shoplinkerOrder.setXmlPath(env.getProperty("shoplinker.xml.path")+"/order");	// xml path
				shoplinkerOrder.setDomainUrl(env.getProperty("shoplinker.xml.view")+"/order");	// 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(0);
				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(0);
				shoplinkerService.saveCallApiRunable(slkSearch);

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

				// 5. 제휴몰 주문등록
				slkSearch.setTxt("=>제휴몰");
				shoplinkerService.updateCallApiRunable(slkSearch);
				shoplinkerService.insertShoplinkerOrderStep2(shoplinkerOrder);

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

			}catch (Exception e) {

				log.error("TsaShoplinkerController.orderReceiveList => error \n"+e);
				slkSearch.setRunStat("ERROR");
				slkSearch.setTxt("=>ERROR : "+StringUtils.abbreviate(e.getMessage(), 0 , 120));

			}finally {
				// 4. API 호출 이력 저장 종료
				if(!"ERROR".equals(slkSearch.getRunStat())){
					slkSearch.setRunStat("END");
					slkSearch.setTxt("=>FINISH");
				}
				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
	}
}
