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

import java.util.Collection;

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

/**
 * 마케팅 정보 수신동의 내역 안내 발송
 *
 * @author jsshin
 * @since 2021.05.06
 */
@Component
@Slf4j
public class TsbMarketingAgreeNoticeJob extends TsbAbstractJob<CustomerSearch, String, String> {

	@Autowired
	private 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.getMarketingAgreeNoticeTargetListCount(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<Customer> customerCollection = customerService.getMarketingAgreeNoticeTargetList(customerSearch);
			GagaMap result = customerService.sendMarketingAgreeNotice(customerCollection);
			succCnt += result.getInt("succCnt");
			failCnt += result.getInt("failCnt");
		}
		return "OK";
	}

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

	@Override
	public void notify(String resultItem) throws Exception {
		log.info("--------------------------------------------------------------------------------");
		log.info("마케팅수신 메시지 성공: {}건, 마케팅수신 메시지 실패: {}건", succCnt, failCnt);
		log.info("--------------------------------------------------------------------------------");
	}
}
