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.TsbCustomerService;
import com.style24.core.support.env.TscConstants;
import com.style24.persistence.domain.CustCoupon;
import com.style24.persistence.domain.CustomerSearch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 생일자 쿠폰 안내
 *
 * @author jsshin
 * @since 2021.05.10
 */
@Component
@Slf4j
public class TsbBirthdayCouponNoticeJob extends TsbAbstractJob<CustomerSearch, String, String> {

	@Autowired
	TsbCustomerService customerService;

	private static final int PAGE_SIZE = 10000;
	private int succCnt = 0;
	private int failCnt = 0;

	@Override
	public CustomerSearch read() throws Exception {
		CustomerSearch customerSearch = new CustomerSearch();
		customerSearch.setSiteCd(TscConstants.Site.STYLE24.value());
		return customerSearch;
	}

	@Override
	public String process(CustomerSearch customerSearch) throws Exception {
		int totalCount = customerService.getBirthDayTargetListCount(customerSearch);
		if (totalCount < 1 ) {
			return "OK";
		}

		int totalPage = totalCount / PAGE_SIZE;
		if (totalCount % PAGE_SIZE > 0) {
			totalPage++;
		}

		for (int page = 0; page < totalPage; page++) {
			int limitStartRow = (page * PAGE_SIZE + 1) - 1;
			customerSearch.setLimitStartRow(limitStartRow);
			customerSearch.setPageSize(PAGE_SIZE);
			Collection<CustCoupon> couponCollection = customerService.getBirthDayTargetList(customerSearch);
			GagaMap result = customerService.sendBirthDayCouponNotice(couponCollection);
			succCnt += result.getInt("succCnt");
			failCnt += result.getInt("failCnt");
		}
		return "OK";
	}

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

	@Override
	public void notify(String String) throws Exception {
		log.info("--------------------------------------------------------------------------------");
		log.info("생일축하 메시지 성공: {}건, 생일축하 메시지 실패: {}건", succCnt, failCnt);
		log.info("--------------------------------------------------------------------------------");
	}
}
