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.support.env.TscConstants;
import com.style24.persistence.domain.CustGrade;
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.05.07
*/
@Component
@Slf4j
public class TsbGradeChangeJob extends TsbAbstractJob<GagaMap, String, String> {

	@Autowired
	private TsbCustomerService customerService;

	private static final int PAGE_SIZE = 10000;
	private int custGradeHstCnt = 0;
	private int custHstCnt = 0;
	private int custGradeCnt = 0;
	private int sendSuccCnt = 0;
	private int sendFailCnt = 0;

	@Override
	public GagaMap read() throws Exception {
		CustGrade custGrade = new CustGrade();
		custGrade.setSiteCd(TscConstants.Site.STYLE24.value());
		custGrade.setRegNo(TsbConstants.REG_NO);
		custGrade.setUpdNo(TsbConstants.REG_NO);
		GagaMap result = customerService.saveCustomerGrade(custGrade);
		return result;
	}

	@Override
	public String process(GagaMap result) throws Exception {
		custGradeHstCnt = result.getInt("custGradeHstCnt");
		custHstCnt = result.getInt("custHstCnt");
		custGradeCnt = result.getInt("custGradeCnt");

		CustomerSearch customerSearch = new CustomerSearch();
		customerSearch.setSiteCd(TscConstants.Site.STYLE24.value());
		int totalCount = customerService.getCustGradeChangeTargetListCount(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.getCustGradeChangeTargetList(customerSearch);
			GagaMap sendResult = customerService.sendCustGradeChangeTarget(customerCollection);
			sendSuccCnt += sendResult.getInt("succCnt");
			sendFailCnt += sendResult.getInt("failCnt");
		}
		return "OK";
	}

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

	@Override
	public void notify(String str) throws Exception {
		log.info("--------------------------------------------------------------------------------");
		log.info("등급이력생성: {}건, 회원이력생성: {}건, 회원등급변경: {}건", custGradeHstCnt, custHstCnt, custGradeCnt);
		log.info("메시지 발송 성공: {}건, 메시지 발송 실패: {}건", sendSuccCnt, sendFailCnt);
		log.info("--------------------------------------------------------------------------------");
	}
}
