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

import com.gagaframework.web.parameter.GagaMap;
import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbCustomerService;
import com.style24.batch.support.env.TsbConstants;
import com.style24.core.biz.service.TscEnvsetService;
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;

import java.util.Collection;

/**
 * 휴면전환 예정 알림
 *
 * @author jsshin
 * @since 2021.03.08
 */
@Component
@Slf4j
public class TsbDormantScheduleJob extends TsbAbstractJob<CustomerSearch, String, String> {

	@Autowired
	private TsbCustomerService customerService;

	@Autowired
	private TscEnvsetService coreEnvsetService;

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

	@Override
	public CustomerSearch read() throws Exception {
		// 휴면회원선정일수 가져오기
		int selectDays = coreEnvsetService.getDormantMemberSelectDays(TscConstants.Site.STYLE24.value());
		// 휴면회원전환일수
		int dormantConversionDay = coreEnvsetService.getDormantMemberConvertDays(TscConstants.Site.STYLE24.value());
		CustomerSearch customerSearch = new CustomerSearch();
		customerSearch.setDormantSelectDays(selectDays);
		customerSearch.setDormantConversionDay(dormantConversionDay);
		customerSearch.setSiteCd(TscConstants.Site.STYLE24.value());
		customerSearch.setRegNo(TsbConstants.REG_NO);
		customerSearch.setUpdNo(TsbConstants.REG_NO);
		return customerSearch;
	}

	@Override
	public String process(CustomerSearch customerSearch) throws Exception {
		int totalCount = customerService.getDormantCustomerScheduleListCount(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.getDormantCustomerScheduleList(customerSearch);
			GagaMap result = customerService.sendDormantCustomerSchedule(customerCollection);
			succCnt += result.getInt("succCnt");
			failCnt += result.getInt("failCnt");
		}
		return "OK";
	}

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

	@Override
	public void notify(String str) throws Exception {
		log.info("--------------------------------------------------------------------------------");
		log.info("휴면전환예정: {}건, 휴면전환예정실패: {}건", succCnt, failCnt);
		log.info("--------------------------------------------------------------------------------");

	}
}
