package com.style24.scm.biz.service;

import java.io.IOException;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.GoodsSearch;
import com.style24.persistence.domain.Option;
import com.style24.persistence.domain.SearchData;
import com.style24.scm.biz.dao.TssStockDao;
import com.style24.scm.support.env.TssConstants;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.excel.GagaExcelUtil;
import com.gagaframework.excel.env.GagaExcelConstants;
import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaFileUtil;


/**
 * 재고관리 Service
 *
 * @author eskim
 * @since 2020. 11. 17
 */
@Service
@Slf4j
public class TssStockService {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TssStockDao stockDao;

	@Autowired
	private Environment env;

	@Autowired
	private TssCommonService commonService;

	@Autowired
	private TssGoodsService goodsService;

	/**
	 * 상품 사이즈별 재고 현황 목록 건수
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2010. 11. 17
	 */
	public int getGoodsSizeStockCount(GoodsSearch goodsSearch) {
		return stockDao.getGoodsSizeStockCount(goodsSearch);
	}

	/**
	 * 상품 사이즈별 재고 현황 목록
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2010. 11. 17
	 */
	public Collection<Option> getGoodsSizeStockList(GoodsSearch goodsSearch) {
		return stockDao.getGoodsSizeStockList(goodsSearch);
	}

	/**
	 * 사이즈별재고현황 - 엑셀다운로드
	 *
	 * @param goodsSearch
	 * @param excelFilenameWithPath - 경로를 포함한 엑셀파일명
	 * @return
	 * @author eskim
	 * @since 2020. 11. 17
	 */
	public void getGoodsSizeStockExcelList(GoodsSearch goodsSearch, String excelFilenameWithPath) {
		// 헤더 title 설정
		String[] listTitles = {"브랜드명","상품명", "품목", "상품상태", "상품코드",  "옵션코드", "색상" , "사이즈", "품절여부",
			"재고", "안전재고","출고대기", "판매가능재고"};

		// DB 처리 시 사용되는 파라미터명(셀명) 설정
		String[] cellNames = { "BRAND_ENM", "GOODS_NM", "ITEMKIND_NM","GOODS_STAT_NM","GOODS_CD", "OPT_CD", "OPT_CD1","OPT_CD2", "SOLDOUT_YN",
			"CURR_STOCK_QTY", "BASE_STOCK_QTY", "SALE_STOCK_QTY", "ABLE_STOCK_QTY"};

		String[] cellTypes = {GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_CENTER.name(),
			GagaExcelConstants.CellType.CHAR_RIGHT.name(), GagaExcelConstants.CellType.CHAR_RIGHT.name(),
			GagaExcelConstants.CellType.CHAR_RIGHT.name(), GagaExcelConstants.CellType.CHAR_RIGHT.name()
		};

		Collection<GagaMap> dataList = stockDao.getGoodsSizeStockExcelList(goodsSearch);

		try {
			GagaExcelUtil.createExcel(excelFilenameWithPath, dataList, "사이즈별재고현황", listTitles, cellNames, cellTypes,
				TssConstants.EXCEL_FOOTER_TITLE);
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}

	/**
	 * 상품 입출고 엑셀조회용 상품 저장
	 *
	 * @param procJob : goodsExcelUpload
	 * @param goodsSizeList
	 * @return
	 * @author eskim
	 * @since 2020. 02. 13
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsSizeSoldoutExcelupload(Collection<Option> goodsSizeList, String excelFilename) {

		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.excel.target.path"), "excel");
		if (goodsSizeList == null || goodsSizeList.isEmpty()) {
			this.deleteExceluploadFile(targetPath, excelFilename);
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		// 입력값 확인
		String goodsSizeSoldoutCheck = getGoodsSizeSoldoutCheck(goodsSizeList);
		if (!"SUCC".equals(goodsSizeSoldoutCheck)) {
			this.deleteExceluploadFile(targetPath, excelFilename);
			throw new IllegalStateException(goodsSizeSoldoutCheck);
		}

		int index = 0;
		for (Option stock : goodsSizeList) {
			stock.setUpdNo(TssSession.getInfo().getUserNo());
			stock.setRegNo(TssSession.getInfo().getUserNo());

			// 엑셀조회를 위한 SEARCH 테이블 생성
			SearchData searchData = new SearchData();
			searchData.setRegNo(stock.getRegNo());
			searchData.setSearchCd(stock.getGoodsCd());
			searchData.setDispOrd(index);
			searchData.setDummy1(stock.getOptCd());
			if (index == 0) {
				commonService.deleteExceluploadSearCh(searchData);
			}

			commonService.createExceluploadSearchByAll(searchData);

			goodsService.createStockHst(stock);

			stockDao.updateStockSoldOut(stock);

			index++;
		}
	}

	/*
	 * 상품 입출고 엑셀조회용 상품 저장 - 입력값 확인
	 */
	private String getGoodsSizeSoldoutCheck(Collection<Option> goodsStockList) {

		int cnt = 0;
		for (Option stock : goodsStockList) {

			if (StringUtils.isEmpty(stock.getGoodsCd())) {
				return (cnt + 2) + "행의 상품코드를 확인해주세요";
			}
			if (StringUtils.isEmpty(stock.getOptCd())) {
				return (cnt + 2) + "행의 사이즈를 확인해주세요.";
			}
			if (!"N".equals(stock.getSoldoutYn()) && !"Y".equals(stock.getSoldoutYn())) {
				return (cnt + 2) + "행의 품절여부  확인해주세요.";
			}
			// 상품코드 옵션 확인
			int stockCnt = goodsService.getGoodsOptionCount(stock);
			if (stockCnt <= 0) {
				return (cnt + 2) + "행의 상품 사이즈는 존재하지 않습니다.<br/>확인해주세요.";
			}
			if (StringUtils.isEmpty(stock.getBaseStockQty())) {
				return (cnt + 2) + "행의 안전재고 수량을 확인해주세요.";
			}

			cnt++;
		}

		return "SUCC";
	}

	/**
	 * 파일 삭제
	 *
	 * @param targetPath
	 * @param excelFilename
	 * @author eskim
	 * @since 2019. 09. 26
	 */
	private void deleteExceluploadFile(String targetPath, String excelFilename) {
		// 파일 삭제
		try {
			GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, excelFilename));
		} catch (IOException e) {
			// Nothing Do
		}
	}

}
