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

import com.gagaframework.web.parameter.GagaMap;
import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbOrderService;
import com.style24.batch.biz.service.TsbPointService;
import com.style24.batch.support.env.TsbConstants;
import com.style24.core.biz.service.TscEnvsetService;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.biz.service.TscPointService;
import com.style24.core.support.env.TscConstants;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.OrderChange;
import com.style24.persistence.domain.Point;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 자동구매확정 포인트 지급
 *
 * @author jsshin
 * @since 2021.04.23
 */
@Component
@Slf4j
public class TsbAutoBuyConfirmJob extends TsbAbstractJob<Collection<Point>, GagaMap, GagaMap> {

	@Autowired
	private TsbPointService pointService;

	@Autowired
	private TscEnvsetService envsetService;

	@Autowired
	private TscPointService corePointService;

	@Autowired
	private TsbOrderService orderService;

	private int succCnt = 0;
	private int failCnt = 0;

	@Override
	public Collection<Point> read() throws Exception {
		Collection<Point> readItem = new ArrayList<>();
		return readItem;
	}

	@Override
	public GagaMap process(Collection<Point> readItem) throws Exception {
		// 1. 구매확정 임시 테이블 생성 / 데이터 생성
		int confirmCnt = orderService.createTempBuyConfirmData();
		log.info("1. 구매확정 임시테이블 생성 건 : {}", confirmCnt);

		// 대상 있는 경우 구매확정 처리 시작
		if (confirmCnt > 0) {
			// 2. 구매확정 상태 변경
			orderService.cahgneStatButConfirm();

			// 3. 구매확정 대상 중 포인트 지급 대상 조회
			int expireDays = envsetService.getBuyPointExpireDays(TscConstants.Site.STYLE24.value());
			int confirmDays = envsetService.getAutoBuyConfirmDays(TscConstants.Site.STYLE24.value());
			Point point = new Point();
			point.setBuyPointExpireDays(expireDays);
			point.setAutoBuyConfirmDays(confirmDays);
			Collection<Point> pointList = pointService.getAutoBuyConfirmList(point);
			log.info("3. 구매확정 포인트 지급 대상 건 : {}", pointList.size());
			
			for (Point pointInfo : pointList) {
				try {
					pointInfo.setBuyPointExpireDays(expireDays);
					pointInfo.setRegNo(TsbConstants.REG_NO);
					pointInfo.setUpdNo(TsbConstants.REG_NO);
					corePointService.saveAutoBuyConfirm(pointInfo);
					succCnt++;
				} catch (Exception e) {
					failCnt++;
				}

			}

			// 4. 임시테이블 명 변경
			orderService.renameTempBuyConfirmData();
		}

		return null;
	}

	@Override
	public GagaMap write(GagaMap convertedItem) throws Exception {
		return null;
	}

	@Override
	public void notify(GagaMap resultItem) throws Exception {
		super.printResult(succCnt, failCnt);
	}
}
