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

import java.util.Collection;

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

import com.gagaframework.web.parameter.GagaMap;
import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbDeliveryService;
import com.style24.batch.biz.service.TsbWmsDeliveryService;
import com.style24.batch.biz.service.TsbCjDeliveryService;
import com.style24.persistence.domain.Delivery;

import lombok.extern.slf4j.Slf4j;

/**
 * 회수송장번호 수신
 *
 * @author moon
 * @since 2021. 04. 09
 */
@Component
@Slf4j
public class TsbCjWithdrawInvoiceJob extends TsbAbstractJob<Collection<Delivery>, Collection<Delivery>, Collection<Delivery>> {

	@Autowired
	private TsbDeliveryService deliveryService;

	@Autowired
	private TsbWmsDeliveryService wmsDeliveryService;
	
	@Autowired
	private TsbCjDeliveryService cjDeliveryService;
	
	private int succCnt = 0;
	private int failCnt = 0;

	@Override
	public Collection<Delivery> read() throws Exception {

		// 1. cj   회수 송장번호 조회 
		Collection<Delivery> invcRcpList = cjDeliveryService.getCjWdInvoiceList();
		return invcRcpList;
	}

	@Override
	public Collection<Delivery> process(Collection<Delivery> invcRcpList) throws Exception {
		succCnt = 0;
		failCnt = 0;
		/**
		 * 1. cj   회수 송장번호 조회 
		 * 2. wms  회수요청 테이블에 등록! 
		 * 3. mall tb_order_change 테이블  update 
		 * 4. cj   회수 송장번호 수신결과 update 
		 * */
		for(Delivery data : invcRcpList) {
			try {
			
				
			// 2. wms  회수요청 테이블에 등록!
				data.setOrdChgSq(Integer.parseInt(data.getCjOrdChgSq()));
				data.setOrdNo(Integer.parseInt(data.getCjOrdNo()));
				
				wmsDeliveryService.updateWmsRecallInvoice(data);
			
			// 3. mall tb_order_change 테이블  update 
			deliveryService.updateTbOrderChaneInvoc(data);
			
			// 4. cj   회수 송장번호 수신결과 update 
			cjDeliveryService.updateCjInvcNo(data);
				succCnt ++;
			}catch(Exception e) {
				failCnt++;
			}
		}
		

		/**
		 * 1. cj  회수 상태 조회 
		 * 2. mall tb_order_change 상태값 업뎃 , tb_order_change_detail 변경상태 업데이트
		 * 3. cj  완료 업데이트
		 * */

		Collection<Delivery> statList = cjDeliveryService.getCjWdStatList();
		
		 for(Delivery data : statList) {
			 
			 // 2. mall tb_order_change 상태값 업뎃 , tb_order_change_detail 변경상태 업데이트 (배송완료일경우)
			 deliveryService.updateTbOrderChangeStat(data);
			 
			 // 3. cj  완료 업데이트
			 cjDeliveryService.updateCjWdStat(data);
		 }
		
		succCnt = 1;
		failCnt = 0;
		
		
		
		return invcRcpList;
	}

	@Override
	public Collection<Delivery> write(Collection<Delivery> invcRcpList) throws Exception {

		return invcRcpList;
	}

	@Override
	public void notify(Collection<Delivery> invcRcpList) throws Exception {
		super.printResult(succCnt, failCnt);
	}

}