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.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.WmsStock;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaDateUtil;

/**
 * WMS 상품재고 수신
 *
 * @author eskim
 * @since 2021. 01. 06
 */
@Component
@Slf4j
public class TsbGoodsWmsGoodsStockJob extends TsbAbstractJob<WmsStock, WmsStock, WmsStock> {

	@Autowired
	private TsbGoodsService goodsService;

	@Autowired
	private TsbWmsGoodsService wmsGoodsService;

	@Autowired
	private TsbCommonService commonService;

	private int succCnt = 0;
	private int failCnt = 0;
	private String jobdate = "";

	@Override
	public WmsStock read() throws Exception {

		WmsStock wmsStock = new WmsStock();
		return wmsStock;
	}

	@Override
	public WmsStock process(WmsStock wmsStock) throws Exception {
		return wmsStock;
	}

	@Override
	public WmsStock write(WmsStock wmsStock) throws Exception {

		jobdate = GagaDateUtil.getToday("yyyyMMddHHmm");

		// WMS 동기화 옵션 여부 확인
		String wmsSyncYn = commonService.getWmsSyncYn();
		if ("N".equals(wmsSyncYn)) {
			log.info("WMS 정보 동기화 미실행 {}, 연동여부 : {}", GagaDateUtil.getToday("yyyy-MM-dd HH:mm:ss"), wmsSyncYn);
			return null;
		} else {

			// TB_WMS_STOCK 작업
			goodsService.deleteWmsStock();

			// TB_WMS_STOCK  생성
			Collection<WmsStock> wmsStockList = wmsGoodsService.getWmsStockList();
			String byrow = "N";
			if ("Y".equals(byrow)) {
				for (WmsStock loopWmsStock : wmsStockList) {
					goodsService.createWmsStockByRow(loopWmsStock);
				}
			} else {

				List<WmsStock> productSukList = new ArrayList<WmsStock>();
				log.info("productSukList.size = {}", productSukList.size());
				GagaMap dataMap = new GagaMap();
				int index = 0;
				for (WmsStock loopWmsStock : wmsStockList) {

					productSukList.add(loopWmsStock);
					index++;
					if (index % 20 == 0 || wmsStockList.size() == index) {
						dataMap.set("productSukList", productSukList);
						goodsService.createWmsStock(dataMap);
						productSukList.clear();
					}
				}
			}
			
			//wms상품재고이력 생성
			goodsService.createWmsStockHst(jobdate);
			
			//매장재고생성 - 출고처별 판매비율 적용
			goodsService.createShopStock(jobdate);

			//온라인 상품 재고 적용
			goodsService.saveGoodsStock(); 
		}

		//온라인 전시 재고 작업
		goodsService.saveGoodsDispStock();

		return wmsStock;
	}

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

}