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

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

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

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaDateUtil;
import com.style24.batch.biz.job.TsbAbstractJob;
import com.style24.batch.biz.service.TsbCommonService;
import com.style24.batch.biz.service.TsbGoodsService;
import com.style24.batch.biz.service.TsbWmsGoodsService;
import com.style24.persistence.domain.GoodsIfProductsku;

import lombok.extern.slf4j.Slf4j;

/**
 * WMS 입고 수신
 *
 * @author jmh
 * @since 2021. 10. 01
 */
@Component
@Slf4j
public class TsbGoodsWmsProductskuJob extends TsbAbstractJob<Collection<GoodsIfProductsku>, Collection<GoodsIfProductsku>, String> {

	@Autowired
	private TsbGoodsService goodsService;

	@Autowired
	private TsbWmsGoodsService wmsGoodsService;
		
	@Autowired
	private TsbCommonService commonService;

	private String jobdate = "";

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

		// WMS 동기화 옵션 여부 확인
		String wmsSyncYn = commonService.getWmsSyncYn();
		if ("N".equals(wmsSyncYn)) {
			log.info("WMS 정보 동기화 미실행 {}, 연동여부 : {}", GagaDateUtil.getToday("yyyy-MM-dd HH:mm:ss"), wmsSyncYn);
			return null;
		}
		// wms 입고상품목록 조회 (등록, 수정건 조회)
		jobdate = GagaDateUtil.getOffsetDate(-1);	//전일자
		Collection<GoodsIfProductsku> wmsIfProductSukList = wmsGoodsService.getWmsProductskuList(jobdate);
		
		return wmsIfProductSukList;
	}

	@Override
	public Collection<GoodsIfProductsku> process(Collection<GoodsIfProductsku> wmsIfProductSukList) throws Exception {
		return wmsIfProductSukList;
	}

	@Override
	public String write(Collection<GoodsIfProductsku> wmsIfProductSukList) throws Exception {
		
		if( null != wmsIfProductSukList && !wmsIfProductSukList.isEmpty()) {
			// 1. 입고상품 IF 테이블에 저장
			List<GoodsIfProductsku> productSukList = new ArrayList<GoodsIfProductsku>();
			GagaMap dataMap = new GagaMap();
			int index = 0;
			for (GoodsIfProductsku ifProductSku : wmsIfProductSukList) {
				
				productSukList.add(ifProductSku);
				index++;
				if (index % 20 == 0 || wmsIfProductSukList.size() == index) {
					dataMap.set("productSukList", productSukList);
					goodsService.saveGoodsWmsProductsku(dataMap);
					productSukList.clear();
				}
			}
			
			// 2. 기존 등록된 상품중, 단품만 추가된 상품 저장
			goodsService.createGoodsOptionList_new(jobdate);
		}
		
		return "OK";
	}

	@Override
	public void notify(String result) throws Exception {
		// Do nothing
	}
}