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

import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbCartService;
import com.style24.batch.support.env.TsbConstants;
import com.style24.core.biz.dao.TscEnvsetDao;
import com.style24.core.biz.service.TscEnvsetService;
import com.style24.core.biz.service.TscFingerPushService;
import com.style24.core.biz.thirdparty.FingerPushSender;
import com.style24.core.support.env.TscConstants;
import com.style24.persistence.domain.Customer;
import com.style24.persistence.domain.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 장바구니 혜택 추가 푸시
 *
 * @author xodud1202
 * @since 2021. 07. 09
 */
@Component
@Slf4j
public class TsbCartAddCouponPushJob extends TsbAbstractJob<Collection<Order>, Collection<Order>, Order> {

	@Autowired
	private TsbCartService cartService;

	@Autowired
	private TscFingerPushService coreFingerPushService;

	private int succCnt = 0;
	private int failCnt = 0;

	@Override
	public Collection<Order> read() throws Exception {
		// 추가 다운로드 받을 수 있는 쿠폰 조회
		Order param = new Order();
		param.setBenefitGb("C");		// 장바구니
		return cartService.getAddCouponList(param);
	}

	@Override
	public Collection<Order> process(Collection<Order> params) throws Exception {
		try {
			if(params != null && params.size() > 0) {
				int[] cpnIdArr = new int[params.size()];
				int i = 0;

				for(Order param : params) {
					cpnIdArr[i++] = param.getCpnId();
				}

				// 추가된 쿠폰이 적용된 장바구니 상품을 가진 고객 조회
				Order cpn = new Order();
				cpn.setCpnIdArr(cpnIdArr);
				Collection<Customer> custList = cartService.getCartAddBenefitPushCustomerList(cpn);

				// 핑거푸시
				for(Customer cust : custList) {
					int ansSq = FingerPushSender.FingerPushSq.SHOPPING_BAG_DISCOUNT.value();
					cust.setContactType(TscConstants.ContactType.SHOPPING_BAG_DISCOUNT.value());
					cust.setContactContents("쇼핑백 할인혜택 안내");
					cust.setRegNo(TsbConstants.REG_NO);
					cust.setUpdNo(TsbConstants.REG_NO);

					// 앱 푸시 데이터 insert
					coreFingerPushService.send(cust, ansSq);
					succCnt++;
				}

				// 송부 이력 저장
				for(Order param : params) {
					param.setRegNo(TsbConstants.REG_NO);	// 등록자
					param.setBenefitGb("C");				// 장바구니
					cartService.createCouponNoticeSended(param);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			failCnt++;
		}

		return params;
	}

	@Override
	public Order write(Collection<Order> params) throws Exception {
		return null;
	}

	@Override
	public void notify(Order param) throws Exception {
		super.printResult(succCnt, failCnt);
	}

}