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

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbOrderService;
import com.style24.batch.support.env.TsbConstants;
import com.style24.core.biz.service.TscKakaotalkService;
import com.style24.core.biz.service.TscOrderChangeService;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.env.TscConstants;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.OrderChange;

import lombok.extern.slf4j.Slf4j;

/**
 * 무통장입금 입금 기한 만료 주문 취소
 *
 * @author xodud1202
 * @since 2021. 05. 03
 */
@Component
@Slf4j
public class TsbOrderDepositExpirationJob extends TsbAbstractJob<Collection<Order>, Collection<Order>, OrderChange> {

	@Autowired
	private TscOrderChangeService coreOrderChangeService;

	@Autowired
	private TscOrderService coreOrderService;

	@Autowired
	private TsbOrderService orderService;

	@Autowired
	private TscKakaotalkService coreKakaotalkService;

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

	@Override
	public Collection<Order> read() throws Exception {
		return orderService.getOrderDepositExpirationList();
	}

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

	@Override
	public OrderChange write(Collection<Order> params) throws Exception {
		OrderChange result = new OrderChange();
		for(Order order : params) {
			OrderChange orderChange = new OrderChange();
			orderChange.setOrdNo(order.getOrdNo());
			orderChange.setReqGbn("cnclComplete");		// 전체취소
			orderChange.setChgReason(TscConstants.OrderCancelReason.ADMIN_CANCEL.value());
			orderChange.setChgReasonNm("전체취소 - 무통장 입금 기한 만료");
			orderChange.setPgStat("N");					// PG점프 여부
			orderChange.setRegNo(TsbConstants.REG_NO);
			orderChange.setUpdNo(TsbConstants.REG_NO);
			orderChange.setBatchYn("Y");

			try {
				int ordChgSq = coreOrderChangeService.allCnclComplete(orderChange);
				succCnt++;

				try {
					// 무통장 입금 전 취소 알림톡 송부
					OrderChange change = new OrderChange();
					change = coreOrderChangeService.getKakaoOrderCancelInfo(ordChgSq);

					// 취소 알림톡 발송
					orderChange.setChgGb(TscConstants.OrderCancelReason.ADMIN_CANCEL.value());
					coreKakaotalkService.sendOrderCancelComplete(change, TsbConstants.REG_NO);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				failCnt++;
				e.printStackTrace();
			}
		}

		return result;
	}

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

}