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

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbOrderService;
import com.style24.core.biz.service.TscNaverPayService;
import com.style24.persistence.domain.Order;

import lombok.extern.slf4j.Slf4j;

/**
 * 네이버페이 결제형 구매확정 처리 
 *
 * @author card007
 * @since 2021. 09. 23
 */
@Component
@Slf4j
public class TsbNaverPayOrderDecisionJob extends TsbAbstractJob<Collection<Order>, Collection<Order> , Collection<Order>> {

	@Autowired
	private TsbOrderService orderService;
	
	@Autowired
	private TscNaverPayService coreNaverPayService;

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

	@Override
	public Collection<Order> read() throws Exception {
		// 네이버페이 결제형 구매확정 대상 리스트 조회
		return orderService.getNaverPayOrderDecisionList();
	}

	@Override
	public Collection<Order> process(Collection<Order> dataList) throws Exception {
		succCnt = 0;
		failCnt = 0;

		for(Order order: dataList) {
			try {
				Order result = coreNaverPayService.decideNaverPayOrder(order);

				// 성공
				if ("200".equals(result.getResultCd())) {
					if ("Success".equals(result.getResultMsg()) || "AlreadyConfirm".equals(result.getResultMsg())) {
						// 네이버페이 결제형 구매확정 여부 수정
						orderService.updateNaverPayOrderDecision(result);

						succCnt++;
					} else {
						failCnt++;
					}
				}
				// 실패
				else {
					failCnt++;
				}
			}catch(Exception e) {
				e.printStackTrace();

				failCnt++;
			}
		}
		return dataList;
	}

	@Override
	public Collection<Order> write(Collection<Order> dataList) throws Exception {
		return dataList;
	}

	@Override
	public void notify(Collection<Order> invoiceList) throws Exception {
		super.printResult(succCnt, failCnt);
	}

}