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.TscKakaotalkService;
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.apache.commons.lang3.StringUtils;
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, GagaMap, GagaMap> {

	@Autowired
	private TsbCustomerService customerService;

	@Autowired
	private TscKakaotalkService kakaotalkService;

	private int custGradeHstCnt = 0;
	private int custHstCnt = 0;
	private int custGradeCnt = 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 GagaMap 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());
		Collection<Customer> customerCollection = customerService.getCustGradeChangeTargetList(customerSearch);

		for (Customer customer: customerCollection) {
			if (StringUtils.isNotBlank(customer.getCellPhnno()) && "Y".equals(customer.getSmsAgreeYn())) {
				kakaotalkService.sendGradeNotice(customer, TsbConstants.REG_NO);
			}
		}

		return result;
	}

	@Override
	public GagaMap write(GagaMap result) throws Exception {

		return null;
	}

	@Override
	public void notify(GagaMap resultItem) throws Exception {
		log.info("--------------------------------------------------------------------------------");
		log.info("등급이력생성: {}건, 회원이력생성: {}건, 회원등급변경: {}건", custGradeHstCnt, custHstCnt, custGradeCnt);
		log.info("--------------------------------------------------------------------------------");
	}
}
