package com.style24.admin.biz.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
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.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.style24.admin.biz.dao.TsaGoodsDao;
import com.style24.admin.support.env.TsaConstants;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.biz.thirdparty.NaverLowestPriceApi;
import com.style24.core.biz.thirdparty.SafetyKoreaApi;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.AdKeyword;
import com.style24.persistence.domain.AdKeywordGoods;
import com.style24.persistence.domain.Brand;
import com.style24.persistence.domain.Color;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.GoodsCompose;
import com.style24.persistence.domain.GoodsDesc;
import com.style24.persistence.domain.GoodsEpSkip;
import com.style24.persistence.domain.GoodsHst;
import com.style24.persistence.domain.GoodsImg;
import com.style24.persistence.domain.GoodsNaverLowestPrice;
import com.style24.persistence.domain.GoodsNotiInfo;
import com.style24.persistence.domain.GoodsPriceRes;
import com.style24.persistence.domain.GoodsResSell;
import com.style24.persistence.domain.GoodsSafeNo;
import com.style24.persistence.domain.GoodsSearch;
import com.style24.persistence.domain.GoodsTnmRes;
import com.style24.persistence.domain.GoodsVideo;
import com.style24.persistence.domain.Itemkind;
import com.style24.persistence.domain.NaverLowestPrice;
import com.style24.persistence.domain.NotiInfo;
import com.style24.persistence.domain.Notice;
import com.style24.persistence.domain.NoticeGoods;
import com.style24.persistence.domain.Option;
import com.style24.persistence.domain.ReinboundInform;
import com.style24.persistence.domain.SearchData;
import com.style24.persistence.domain.Video;
import com.style24.persistence.domain.WmsColorMapping;
import com.style24.persistence.domain.WmsSeasonMapping;
import com.style24.persistence.domain.WmsStyleYearMapping;

import io.netty.util.internal.StringUtil;

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.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.gagaframework.web.util.GagaStringUtil;

/**
 *상품관리 Service
 *
 * @author eskim
 * @since 2020. 10. 16
 */
@Service
@Slf4j
public class TsaGoodsService {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TsaGoodsDao goodsDao;

	@Autowired
	private TsaBusinessService businessService;

	@Autowired
	private TsaCommonService commonService;

	@Autowired
	private TsaRendererService rendererService;

	@Autowired
	private TsaNoticeService noticeService;

	@Autowired
	private SafetyKoreaApi safetyKoreaApi;

	@Autowired
	private NaverLowestPriceApi naverLowestPriceApi;


	@Autowired
	private ObjectMapper mapper;

	private static final String NUMBER_PATTERN = "^[0-9]+$";

	private static final String SELF_GOOODS_AFTER = "STY";

	/**
	 * 상품 할인율 계산
	 *
	 * @param value
	 * @param len
	 * @param pad
	 * @return
	 */
	private long getDcRate(int listPrice, int currPrice) {
		double rate = (double)(currPrice) / (double)(listPrice);
		return 100 - (long)((Math.round(rate * 100) / 100.0) * 100);
	}

	/**
	 * 품목 목록
	 * @param itemkind
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	public Collection<Itemkind> getItemkindList(Itemkind itemkind) {
		return goodsDao.getItemkindList(itemkind);
	}

	/**
	 * 품목 저장
	 *
	 * @param itemkindList - 품목 정보 목록
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@Transactional("shopTxnManager")
	public void saveItemkindInfo(Collection<Itemkind> itemkindList) {
		for (Itemkind itemkind : itemkindList) {
			itemkind.setRegNo(TsaSession.getInfo().getUserNo());
			itemkind.setUpdNo(TsaSession.getInfo().getUserNo());
			itemkind.setItemkindNm(GagaStringUtil.replace(GagaStringUtil.replace(itemkind.getItemkindNm(), "&lt;", "<"),"&gt;", ">"));
			//itemkind.setItemkindEnm(GagaStringUtil.replace(GagaStringUtil.replace(itemkind.getItemkindEnm(), "&lt;", "<"),"&gt;", ">"));
			goodsDao.saveItemkindInfo(itemkind);
		}
	}

	/**
	 * 품목 삭제
	 *
	 * @param itemkindList - 품목 정보 목록
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@Transactional("shopTxnManager")
	public void deleteItemkindInfo(Collection<Itemkind> itemkindList) {
		for (Itemkind itemkind : itemkindList) {
			goodsDao.deleteItemkindInfo(itemkind);
		}
	}

	/**
	 * 색상목록 조회
	 *
	 * @param color
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	public Collection<Color> getColorList(Color color) {
		return goodsDao.getColorList(color);
	}

	/**
	 * 색상 저장
	 *
	 * @param colorList
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@Transactional("shopTxnManager")
	public void saveColor(Collection<Color> colorList) {

		for (Color color : colorList) {

			color.setRegNo(TsaSession.getInfo().getUserNo());
			color.setUpdNo(TsaSession.getInfo().getUserNo());

			goodsDao.saveColor(color);
		}
	}

	/**
	 * 상품정보고시 목록
	 *
	 * @param notiInfo
	 * @return
	 * @author eskim
	 * @since 2010. 10. 19
	 */
	public Collection<NotiInfo> getNotiInfoList(NotiInfo notiInfo) {
		return goodsDao.getNotiInfoList(notiInfo);
	}

	/**
	 * 상품정보고시 항목 목록
	 *
	 * @param notiInfo
	 * @return
	 * @author eskim
	 * @since 2010. 10. 19
	 */
	public Collection<NotiInfo> getNotiInfoItemList(NotiInfo notiInfo) {
		return goodsDao.getNotiInfoItemList(notiInfo);
	}

	/**
	 * 상품정보고시 항목 저장
	 *
	 * @param notiInfoList
	 * @return
	 * @author eskim
	 * @since 2010. 10. 19
	 */
	@Transactional("shopTxnManager")
	public void saveNotiInfoItem(Collection<NotiInfo> notiInfoList) {
		if (notiInfoList == null || notiInfoList.isEmpty())
			throw new IllegalStateException(message.getMessage("FAIL_1001"));

		for (NotiInfo notiInfo : notiInfoList) {
			if (!StringUtils.isEmpty(notiInfo.getNiContent())) {
				notiInfo.setNiContent(GagaStringUtil.replace(GagaStringUtil.replace(notiInfo.getNiContent(),"&lt;", "<"),"&gt;", ">"));
			}
			notiInfo.setRegNo(TsaSession.getInfo().getUserNo());
			notiInfo.setUpdNo(TsaSession.getInfo().getUserNo());
			goodsDao.saveNotiInfo(notiInfo);
		}
	}

	/**
	 * WMS 색상 매핑목록 조회
	 *
	 * @param color
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	public Collection<WmsColorMapping> getWmsColorMappingList(WmsColorMapping wmsColorMapping) {
		return goodsDao.getWmsColorMappingList(wmsColorMapping);
	}

	/**
	 * WMS 색상 매핑 저장
	 *
	 * @param colorList
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@Transactional("shopTxnManager")
	public void saveWmsColorMapping(Collection<WmsColorMapping> wmsColorMappingList) {

		for (WmsColorMapping wmsColorMapping : wmsColorMappingList) {

			wmsColorMapping.setRegNo(TsaSession.getInfo().getUserNo());
			wmsColorMapping.setUpdNo(TsaSession.getInfo().getUserNo());

			goodsDao.saveWmsColorMapping(wmsColorMapping);
		}
	}

	/**
	 * WMS 스타일년도 매핑목록 조회
	 *
	 * @param wmsStyleYearMapping
	 * @return
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	public Collection<WmsStyleYearMapping> getWmsStyleYearMappingList(WmsStyleYearMapping wmsStyleYearMapping) {
		return goodsDao.getWmsStyleYearMappingList(wmsStyleYearMapping);
	}

	/**
	 * WMS 스타일년도 매핑 저장
	 *
	 * @param wmsStyleYearMappingList
	 * @return
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	@Transactional("shopTxnManager")
	public void saveWmsStyleYearMapping(Collection<WmsStyleYearMapping> wmsStyleYearMappingList) {

		for (WmsStyleYearMapping wmsStyleYearMapping : wmsStyleYearMappingList) {

			wmsStyleYearMapping.setRegNo(TsaSession.getInfo().getUserNo());
			wmsStyleYearMapping.setUpdNo(TsaSession.getInfo().getUserNo());

			goodsDao.saveWmsStyleYearMapping(wmsStyleYearMapping);
		}
	}

	/**
	 * WMS 시즌 매핑목록 조회
	 *
	 * @param wmsSeasonMapping
	 * @return
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	public Collection<WmsSeasonMapping> getWmsSeasonMappingList(WmsSeasonMapping wmsSeasonMapping) {
		return goodsDao.getWmsSeasonMappingList(wmsSeasonMapping);
	}

	/**
	 * WMS 시즌 매핑 저장
	 *
	 * @param wmsSeasonMappingList
	 * @return
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	@Transactional("shopTxnManager")
	public void saveWmsSeasonMapping(Collection<WmsSeasonMapping> wmsSeasonMappingList) {

		for (WmsSeasonMapping wmsSeasonMapping : wmsSeasonMappingList) {

			wmsSeasonMapping.setRegNo(TsaSession.getInfo().getUserNo());
			wmsSeasonMapping.setUpdNo(TsaSession.getInfo().getUserNo());

			goodsDao.saveWmsSeasonMapping(wmsSeasonMapping);
		}
	}

	/**
	 * 상품 목록 건수
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 10. 20
	 */
	public int getGoodsListCount(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsListCount(goodsSearch);
	}

	/**
	 * 상품 목록
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 10. 20
	 */
	public Collection<Goods> getGoodsList(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsList(goodsSearch);
	}

	/**
	 * 상품목록 - 기본정보 엑셀다운로드
	 *
	 * @param goodsSearch
	 * @param excelFilenameWithPath - 경로를 포함한 엑셀파일명
	 * @return
	 * @author eskim
	 * @since 2020. 10. 21
	 */
	public void getGoodsInfoExcelList(GoodsSearch goodsSearch, String excelFilenameWithPath) {

		if ("Y".equals(goodsSearch.getImageViewYn())) {
			// 헤더 title 설정
			String[] listTitles = {"이미지", "상품코드", "업체명", "브랜드명", "상품명", "품목", "재고", "상품상태", "스타일년도", "시즌",
				"정상가", "판매가", "할인율", "가격변경일", "ERP재고연동여부", "정상이월구분", "반품가능 여부","승인일시"};

			// DB 처리 시 사용되는 파라미터명(셀명) 설정
			String[] cellNames = {"SYS_IMG_NM", "GOODS_CD", "SUPPLY_COMP_CD", "BRAND_GRP_NM", "GOODS_NM", "ITEMKIND_NM",
				"STOCK_QTY_SUM", "GOODS_STAT", "STYLE_YEAR", "SEASON_CD",  "LIST_PRICE", "CURR_PRICE",
				"DC_RATE", "PRICE_UPD_DT", "ERP_STOCK_LINK_YN", "FORMAL_GB", "RETURNABLE_YN", "FRST_CFRM_DT"};

			String[] cellTypes = {GagaExcelConstants.CellType.IMAGE.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_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_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name(),
				GagaExcelConstants.CellType.CHAR_CENTER.name(),
				GagaExcelConstants.CellType.CHAR_CENTER.name(), GagaExcelConstants.CellType.CHAR_CENTER.name()};

			String targetPath = env.getProperty("upload.goods.view");
			Collection<GagaMap> dataList = goodsDao.getGoodsInfoExcelList(goodsSearch); // map형식으로 조회
			if (dataList != null && !dataList.isEmpty()) {
				for (GagaMap gagaMap : dataList) {
					if (!StringUtils.isEmpty(gagaMap.get("SYS_IMG_NM").toString()) ) {
						gagaMap.set("SYS_IMG_NM", targetPath + '/' +  gagaMap.get("SYS_IMG_NM").toString());
					}
				}
			}

			try {
				GagaExcelUtil.createExcel(excelFilenameWithPath, dataList, "상품 정보", listTitles, cellNames, cellTypes, TsaConstants.EXCEL_FOOTER_TITLE);
			} catch (Exception e) {
				throw new IllegalStateException(e);
			}

		} else {
			// 헤더 title 설정
			String[] listTitles = {"상품코드", "업체명", "브랜드명", "상품명", "품목", "재고", "상품상태", "스타일년도",
				"시즌",  "정상가", "판매가", "할인율", "가격변경일", "ERP재고연동여부", "정상이월구분", "반품가능 여부", "승인일시"};

			// DB 처리 시 사용되는 파라미터명(셀명) 설정
			String[] cellNames = {"GOODS_CD", "SUPPLY_COMP_CD", "BRAND_GRP_NM", "GOODS_NM", "ITEMKIND_NM", "STOCK_QTY_SUM", "GOODS_STAT", "STYLE_YEAR",
				"SEASON_CD",  "LIST_PRICE", "CURR_PRICE", "DC_RATE", "PRICE_UPD_DT", "ERP_STOCK_LINK_YN", "FORMAL_GB", "RETURNABLE_YN", "FRST_CFRM_DT"};

			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_RIGHT.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_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()};

			Collection<GagaMap> dataList = goodsDao.getGoodsInfoExcelList(goodsSearch);

			try {
				GagaExcelUtil.createExcel(excelFilenameWithPath, dataList, "상품 정보", listTitles, cellNames, cellTypes, TsaConstants.EXCEL_FOOTER_TITLE);
			} catch (Exception e) {
				throw new IllegalStateException(e);
			}
		}
	}

	/**
	 * 상품 이미지 등록여부 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 21
	 */
	public Collection<Goods> getGoodsImgsYn(Goods goods) {
		return goodsDao.getGoodsImgsYn(goods);
	}

	/**
	 * 상품 상세
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 22
	 */
	public Goods getGoods(Goods goods) {
		// 상품기본정보
		Goods resultGoods = goodsDao.getGoods(goods);

		// 상품 상세
		this.getGoodsDesc(resultGoods);
		return resultGoods;
	}

	/**
	 * 상품 상세 조회
	 *
	 * @param resultGoods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 22
	 */
	private Goods getGoodsDesc(Goods resultGoods) {

		GoodsDesc goods = new GoodsDesc();
		goods.setGoodsCd(resultGoods.getGoodsCd());

		//		goods.setDescGb("10");
		//		String goodsDesc = this.getGoodsDescList(goods);
		//		resultGoods.setGoodsDesc(goodsDesc);

		// 상품 상세 pc 상단
		goods.setDescGb("20");
		String goodsPcTopDesc = this.getGoodsDescList(goods);
		resultGoods.setGoodsPcTopDesc(goodsPcTopDesc);

		// 상품 상세  pc 하단
		goods.setDescGb("30");
		String goodsPcDownDesc = this.getGoodsDescList(goods);
		resultGoods.setGoodsPcDownDesc(goodsPcDownDesc);

		// 상품 상세 mobile 상단
		goods.setDescGb("40");
		String goodsMobileTopDesc = this.getGoodsDescList(goods);
		resultGoods.setGoodsMobileTopDesc(goodsMobileTopDesc);

		// 상품 상세 mpbile 하단
		goods.setDescGb("50");
		String goodsMobileDownDesc = this.getGoodsDescList(goods);
		resultGoods.setGoodsMobileDownDesc(goodsMobileDownDesc);

		return resultGoods;
	}

	/**
	 * 상품 상세구분별 컨텐츠 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 22
	 */
	private String getGoodsDescList(GoodsDesc goodsDesc) {
		Collection<GoodsDesc> goodsDescList = goodsDao.getGoodsDescList(goodsDesc);
		StringBuilder goodsDescSb = new StringBuilder();
		if (goodsDescList != null && !goodsDescList.isEmpty()) {
			for (GoodsDesc tmpGoodsDesc : goodsDescList) {
				goodsDescSb.append(tmpGoodsDesc.getGoodsDesc());
			}
		}
		return goodsDescSb.toString();
	}

	/**
	 * 상품 정보 이력 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2019. 12. 12
	 */
	public Collection<GoodsHst> getGoodsHstList(Goods goods) {
		return goodsDao.getGoodsHstList(goods);
	}

	/**
	 * 상품 옵션 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 26
	 */
	public Collection<Option> getGoodsSizeList(Goods goods) {
		return goodsDao.getGoodsSizeList(goods);
	}

	/**
	 * 상품 색상목록 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 11. 18
	 */
	public Collection<GoodsImg> getGoodsColorList(Goods goods) {
		return goodsDao.getGoodsColorList(goods);
	}

	/**
	 * 상품 정보고시 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 22
	 */
	public Collection<GoodsNotiInfo> getGoodsNotiInfoList(GoodsNotiInfo goodsNotiInfo) {
		return goodsDao.getGoodsNotiInfoList(goodsNotiInfo);
	}

	/**
	 * 상품의 정보고시 항목 목록
	 *
	 * @param notiInfo
	 * @return
	 * @author eskim
	 * @since 2020. 11. 18
	 */
	public Collection<NotiInfo> getNotiGoodsInfoList(NotiInfo notiInfo) {
		return goodsDao.getNotiGoodsInfoList(notiInfo);
	}

	/**
	 * 상품 구매등급 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 11. 18
	 */
	public Collection<Goods> getGoodsDetailOrderGradeList(Goods goods) {
		return goodsDao.getGoodsDetailOrderGradeList(goods);
	}

	/**
	 * 구성상품 목록
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 27
	 */
	public Collection<GoodsCompose> getGoodsDetailComposeList(Goods goods) {
		return goodsDao.getGoodsDetailComposeList(goods);
	}

	/**
	 * 안전인증번호
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 12. 07
	 */
	public GagaMap getGoodsDetailCertNum(String goodsCd) {
		GagaMap result = new GagaMap();
		return result;
	}

	/**
	 * 안전인증번호 저장
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 12. 07
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsDetailCertNum(Goods goods) {
		try {
			GagaMap result = safetyKoreaApi.getKoreaCertifyDetail(goods.getCertNum());
			if (result != null || !StringUtil.isNullOrEmpty(result.get("certNum").toString())) {
				GoodsSafeNo goodsSafeNo = new GoodsSafeNo();
				goodsSafeNo.setGoodsCd(goods.getGoodsCd());
				goodsSafeNo.setCertDt(result.get("certDt").toString());
				goodsSafeNo.setCertNum(result.get("certNum").toString());
				goodsSafeNo.setCertState(result.get("certState").toString());
				goodsSafeNo.setCertDiv(result.get("certDiv").toString());
				goodsSafeNo.setRegNo(TsaSession.getInfo().getUserNo());
				goodsSafeNo.setUpdNo(TsaSession.getInfo().getUserNo());
				goodsDao.saveGoodsSafeNo(goodsSafeNo);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 상품 수정 항목 일괄변경
	 *
	 * @param goods
	 * @author eskim
	 * @since 2020. 01. 17
	 */
	@Transactional("shopTxnManager")
	public void updateGoodsState(Goods goods) {
		if (goods == null || (goods.getArrGoodsCd() == null && goods.getArrGoodsCd().length <= 0)) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		goods.setRegNo(TsaSession.getInfo().getUserNo());
		goods.setUpdNo(TsaSession.getInfo().getUserNo());

		if (goods.getArrGoodsCd().length > 0) {
			for (String goodsCd : goods.getArrGoodsCd()) {

				goods.setGoodsCd(goodsCd);
				// 이력생성
				goodsDao.createGoodsHst(goods);

				if ("formalGb".equals(goods.getProcJob())) {
					// 상품브랜드 조회
					Goods originGoods = goodsDao.getGoods(goods);
					// 브랜드 확인
					goods.setPntPrate(originGoods.getPntPrate()); // 포인트적립율(PC)
					goods.setPntMrate(originGoods.getPntMrate()); // 포인트적립율(MOBILE)
					Brand brand = new Brand();
					brand.setBrandCd(originGoods.getBrandCd());
					Collection<Brand> brandList = businessService.getBrandList(brand);
					if (brandList != null && !brandList.isEmpty()) {
						float pntPrate = 0;
						float pntMrate = 0;
						for (Brand tmpBrand : brandList) {
							if ("G009_10".equals(goods.getFormalGb())) {
								pntPrate = tmpBrand.getPntPrate10();
								pntMrate = tmpBrand.getPntMrate10();
							} else {
								pntPrate = tmpBrand.getPntPrate20();
								pntMrate = tmpBrand.getPntMrate20();
							}
						}
						goods.setPntPrate(pntPrate); // 포인트적립율(PC)
						goods.setPntMrate(pntMrate); // 포인트적립율(MOBILE)
					}
				} else if ("goodsStat".equals(goods.getProcJob())) {
					// 상품브랜드 조회
					Goods originGoods = goodsDao.getGoods(goods);

					// 승인일
					if (!goods.getGoodsStat().equals(originGoods.getGoodsStat()) && "G008_90".equals(goods.getGoodsStat())) {
						goods.setChGoodsStatYn("Y");
					}
				}
				// 상품정보 변경
				goodsDao.updateGoodsState(goods);
			}

		} else {

			// 이력생성
			goodsDao.createGoodsHst(goods);
			if ("formalGb".equals(goods.getProcJob())) {
				// 상품브랜드 조회
				Goods originGoods = goodsDao.getGoods(goods);
				// 브랜드 확인
				goods.setPntPrate(originGoods.getPntPrate()); // 포인트적립율(PC)
				goods.setPntMrate(originGoods.getPntMrate()); // 포인트적립율(MOBILE)
				Brand brand = new Brand();
				brand.setBrandCd(originGoods.getBrandCd());
				Collection<Brand> brandList = businessService.getBrandList(brand);
				if (brandList != null && !brandList.isEmpty()) {
					float pntPrate = 0;
					float pntMrate = 0;
					for (Brand tmpBrand : brandList) {
						if ("G009_10".equals(goods.getFormalGb())) {
							pntPrate = tmpBrand.getPntPrate10();
							pntMrate = tmpBrand.getPntMrate10();
						} else {
							pntPrate = tmpBrand.getPntPrate20();
							pntMrate = tmpBrand.getPntMrate20();
						}
					}
					goods.setPntPrate(pntPrate); // 포인트적립율(PC)
					goods.setPntMrate(pntMrate); // 포인트적립율(MOBILE)
				}
			}
			// 상품정보 변경
			goodsDao.updateGoodsState(goods);
		}
	}

	/**
	 * 엑셀조회용 상품 저장
	 *
	 * @param procJob : goodsExcelUpload
	 * @param goodsList
	 * @return
	 * @author eskim
	 * @since 2020. 10. 22
	 */
	@Transactional("shopTxnManager")
	public void saveExceluploadGoods(Collection<Goods> goodsList, String excelFilename) {

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

		int index = 0;
		String goodsCdFlag = "";
		String goodsNumFlag = "";
		for (Goods goods : goodsList) {

			if (!StringUtils.isEmpty(goodsCdFlag) && !StringUtils.isEmpty(goodsNumFlag)) {
				throw new IllegalStateException("상품코드와 원코드 중 한 개의 셀에만 값을 입력해서 조회하세요.");
			}

			if (!StringUtils.isEmpty(goods.getSupplyCompCd())) {
				goods.setGoodsCd(goods.getSupplyCompCd());
			}

			SearchData searchData = new SearchData();
			searchData.setRegNo(goods.getRegNo());
			searchData.setSearchCd(goods.getGoodsCd());
			if (index == 0) {
				commonService.deleteExceluploadSearCh(searchData);
			}

			commonService.createExceluploadSearch(searchData);
			index++;
		}
	}

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

	/**
	 * 상품 품목 변경 저장
	 *
	 * @param goodsList
	 * @return
	 * @author eskim
	 * @since 2020. 10. 23
	 */
	@Transactional("shopTxnManager")
	//@CacheEvict(value = "cate", allEntries = true)
	public void saveItemKindChange(Collection<Goods> goodsList) {
		for (Goods goods : goodsList) {
			goods.setRegNo(TsaSession.getInfo().getUserNo());
			goods.setUpdNo(TsaSession.getInfo().getUserNo());
			goods.setItemkindCd(goods.getItemkindCd().toUpperCase());
			// 품목확인
			Itemkind itemkind = new Itemkind();
			itemkind.setItemkindCd(goods.getItemkindCd());
			itemkind.setUseYn("Y");
			Collection<Itemkind> itemkindList = goodsDao.getItemkindList(itemkind);
			if (itemkindList == null || itemkindList.isEmpty()) {
				throw new IllegalStateException(goods.getGoodsCd() + " 상품의 품목코드를 확인해주세요.");
			}

			// 상품이력
			goodsDao.createGoodsHst(goods);
			// 품목변경
			goodsDao.updateGoodItemKindCd(goods);

			// 검색어 변경
			String goodsSnm = goodsDao.getGoodsSnm(goods.getGoodsCd());
			Goods tmpGoods = goodsDao.getGoods(goods);
			if (tmpGoods != null && !StringUtils.isEmpty(tmpGoods.getGoodsSnm1())) {
				String[] arrGoodsSnm = tmpGoods.getGoodsSnm1().split(";");
				StringBuilder tempGoodsSnm = new StringBuilder();
				for (String loopGoodsSnm : arrGoodsSnm) {
					if (goodsSnm.toUpperCase().indexOf(loopGoodsSnm.toUpperCase()) <= -1) {
						tempGoodsSnm.append(loopGoodsSnm).append(";");
					}
				}
				goods.setGoodsSnm(tempGoodsSnm.toString() + goodsSnm);

			} else {
				goods.setGoodsSnm(goodsSnm);
			}
			goodsDao.updateGoodsSnm(goods);

			Collection<GoodsNotiInfo> goodsNotiInfoList = goodsDao.getNewNotiInfo(goods);
			goodsDao.deleteGoodsNotiInfo(goods);

			for (GoodsNotiInfo goodsNotiInfo : goodsNotiInfoList) {
				goodsNotiInfo.setRegNo(TsaSession.getInfo().getUserNo());
				goodsNotiInfo.setUpdNo(TsaSession.getInfo().getUserNo());
				goodsNotiInfo.setGoodsCd(goods.getGoodsCd());
				goodsDao.saveGoodsNotiInfo(goodsNotiInfo);
			}

			this.saveGoodsCategory(goods);
		}
	}

	/**
	 * 상품 품목 기준 카테고리 저장
	 *
	 * @param goods
	 * @author eskim
	 * @since 2020. 4. 21.
	 */
	private void saveGoodsCategory(Goods goods) {

//		GoodsCategory goodsCategory = new GoodsCategory();
//		goodsCategory.setRegNo(TsaSession.getInfo().getUserNo());
//		goodsCategory.setUpdNo(TsaSession.getInfo().getUserNo());
//		goodsCategory.setGoodsCd(goods.getGoodsCd());
//		displayService.deleteGoodsCategory(goodsCategory);
//
//		Collection<ItemkindCategory> itemkindCategoryList = displayService.getItemkindCategoryList(goods.getItemkindCd());
//		for ItemkindCategory itemkindCategory : itemkindCategoryList) {
//			Category category = new Category();
//			category.setCateGb(itemkindCategory.getCateGb());
//			category.setCateCd(itemkindCategory.getCateCd());
//			category = displayService.getCategory4srch(category);
//
//			CategoryGoods categoryGoods = new CategoryGoods();
//			categoryGoods.setRegNo(TsaSession.getInfo().getUserNo());
//			categoryGoods.setUpdNo(TsaSession.getInfo().getUserNo());
//			String[] goodsCdArr = {goods.getGoodsCd()};
//			categoryGoods.setGoodsCdArr(goodsCdArr);
//			if (category.getCateGb() != null) {
//				categoryGoods.setNcateGb(String.valueOf(category.getCateGb()));
//			}
//			if (category.getCateType() != null) {
//				categoryGoods.setNcateType(String.valueOf(category.getCateType()));
//			}
//			if (category.getCateCd() != null) {
//				categoryGoods.setNcateCd(String.valueOf(category.getCateCd()));
//			}
//			if (category.getTcateCd() != null) {
//				categoryGoods.setNtcateCd(String.valueOf(category.getTcateCd()));
//			}
//			if (category.getMcateCd() != null) {
//				categoryGoods.setNmcateCd(String.valueOf(category.getMcateCd()));
//			}
//			if (category.getScateCd() != null) {
//				categoryGoods.setNscateCd(String.valueOf(category.getScateCd()));
//			}
//			if (category.getDcateCd() != null) {
//				categoryGoods.setNdcateCd(String.valueOf(category.getDcateCd()));
//			}
//			displayService.moveCategoryGoods(categoryGoods);
//		}
	}

	/**
	 * 상품 저장
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 27
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsDetail(Goods goods) {

		// <,> replace 처리
		goods.setRegNo(TsaSession.getInfo().getUserNo());
		goods.setUpdNo(TsaSession.getInfo().getUserNo());

		goods.setGoodsPcTopDesc(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsPcTopDesc(), "&lt;", "<"), "&gt;", ">"));
		goods.setGoodsMobileTopDesc(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsMobileTopDesc(), "&lt;", "<"), "&gt;", ">"));
		goods.setGoodsPcDownDesc(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsPcDownDesc(), "&lt;", "<"), "&gt;", ">"));
		goods.setGoodsMobileDownDesc(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsMobileDownDesc(), "&lt;", "<"), "&gt;", ">"));

		goods.setGoodsNm(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsNm(), "&lt;", "<"), "&gt;", ">"));
		goods.setGoodsTnm(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsTnm(), "&lt;", "<"), "&gt;", ">"));
		goods.setGoodsSnm1(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsSnm1(), "&lt;", "<"), "&gt;", ">"));

		// 세트일 경우 상품 가격 확인
		if ("G056_S".equals(goods.getGoodsType())) {

			Collection<GoodsCompose> goodsExtendList = goods.getGoodsComposeListNew();
			int currPriceSum = 0;
			for (GoodsCompose regGoodsExtend : goodsExtendList) {
				currPriceSum  = currPriceSum + regGoodsExtend.getCompsCurrPrice();
			}

			if (currPriceSum != goods.getCurrPriceOrg()) {
				goods.setCurrBprice(goods.getCurrPriceOrg());
				goods.setCurrPrice(currPriceSum);
				goods.setDcRate((int)(this.getDcRate(goods.getListPrice() , currPriceSum)));
			}
		}else {
			// 가격변경일
			if (goods.getCurrPrice() != goods.getCurrPriceOrg()) {
				goods.setCurrBprice(goods.getCurrPriceOrg());
			} else {
				goods.setCurrPrice(goods.getCurrPriceOrg());
			}
		}

		// 승인일
		if (!goods.getGoodsStat().equals(goods.getGoodsStatOrg()) && "G008_90".equals(goods.getGoodsStat())) {
			goods.setChGoodsStatYn("Y");
		}
		// 사용자 검색어를 검색어에 적용
		String goodsSnm = goodsDao.getGoodsSnm(goods.getGoodsCd());
		if (!StringUtils.isEmpty(goods.getGoodsSnm1())) {
			goods.setGoodsSnm1(GagaStringUtil.replace(goods.getGoodsSnm1(), " ", "")); // 빈값 삭제
			String[] arrGoodsSnm = goods.getGoodsSnm1().split(";");
			StringBuilder tempGoodsSnm = new StringBuilder();
			for (String loopGoodsSnm : arrGoodsSnm) {
				if (goodsSnm.toUpperCase().indexOf(loopGoodsSnm.toUpperCase()) <= -1) {
					tempGoodsSnm.append(loopGoodsSnm).append(";");
				}
			}
			goods.setGoodsSnm(tempGoodsSnm.toString() + goodsSnm);

		} else if (!goodsSnm.equals(goods.getGoodsSnm())) {
			goods.setGoodsSnm(goodsSnm);
		}

		goods.setFormalGb(goods.getFormalGb());
		// 브랜드 확인
		if (!"G056_N".equals(goods.getGoodsType())) {
			if (!goods.getFormalGb().equals(goods.getFormalGbOrg())) {
				Brand brand = new Brand();
				brand.setBrandCd(goods.getBrandCd());
				Collection<Brand> brandList = businessService.getBrandList(brand);
				if (brandList != null && !brandList.isEmpty()) {
					float pntPrate = 0.0f;
					float pntMrate = 0.0f;
					for (Brand tmpBrand : brandList) {
						if ("G009_10".equals(goods.getFormalGb())) {
							pntPrate = tmpBrand.getPntPrate10();
							pntMrate = tmpBrand.getPntMrate10();
						} else {
							pntPrate = tmpBrand.getPntPrate20();
							pntMrate = tmpBrand.getPntMrate20();
						}
					}
					goods.setPntPrate(pntPrate); // 포인트적립율(PC)
					goods.setPntMrate(pntMrate); // 포인트적립율(MOBILE)
				}
			}
		}

		// 기본정보 변경
		if ("Y".equals(goods.getChDataYn())) {
			goodsDao.createGoodsHst(goods);
			goodsDao.updateGoods(goods);
		}

		// 상품상세정보 변경
		if (!"Y".equals(goods.getChkDescKeep())) {
			this.saveGoodsDetailDesc(goods);
		}

		int idx = 1;
		// 구성상품 변경
		if (!"G056_N".equals(goods.getGoodsType())) {

			Collection<GoodsCompose> goodsExtendList = goods.getGoodsComposeListNew();
			for (GoodsCompose regGoodsExtend : goodsExtendList) {
				regGoodsExtend.setDispOrd(idx);
				regGoodsExtend.setRegNo(TsaSession.getInfo().getUserNo());
				regGoodsExtend.setUpdNo(TsaSession.getInfo().getUserNo());
				goodsDao.saveGoodsCompose(regGoodsExtend); // 구성상품기본 저장

				idx++;
			}
		}

		// 옵션/재고 변경
		if (goods.getOptCd() != null && goods.getOptCd().length > 0 && "Y".equals(goods.getChStockDataYn())) {
			this.saveStock(goods);
		}

		// 상품 정보고시 변경
		this.saveGoodsNotiInfo(goods);

		// 상품 구매등급 적용
		if (goods.getGoodsOrderGrade() != null && goods.getGoodsOrderGrade().length > 0) {
			Goods goodsOrderGrade = new Goods();
			goodsOrderGrade.setGoodsCd(goods.getGoodsCd());
			goodsOrderGrade.setRegNo(TsaSession.getInfo().getUserNo());
			goodsDao.deleteGoodsCustGrade(goodsOrderGrade);
			for(String custGrade : goods.getGoodsOrderGrade()) {
				goodsOrderGrade.setCustGrade(custGrade);
				goodsDao.createGoodsCustGrade(goodsOrderGrade);
			}
		}else {
			Goods goodsOrderGrade = new Goods();
			goodsOrderGrade.setGoodsCd(goods.getGoodsCd());
			goodsOrderGrade.setRegNo(TsaSession.getInfo().getUserNo());
			goodsDao.deleteGoodsCustGrade(goodsOrderGrade);
		}
	}

	/**
	 * 상품상세정보 변경 - 상품상세
	 *
	 * @param goods
	 * @author eskim
	 * @since 2020. 10. 27.
	 */
	private void saveGoodsDetailDesc(Goods goods) {
		// 상품상세 구분(10:상품설명, 20:상위컨텐츠, 30:하위컨텐츠, 40:하위컨텐츠-모바일, 50:상위컨텐츠-모바일)
		GoodsDesc goodsDesc = new GoodsDesc();
		goodsDesc.setGoodsCd(goods.getGoodsCd());
		goodsDesc.setRegNo(goods.getRegNo());
		goodsDesc.setUpdNo(goods.getUpdNo());

		// PC 상단
		goodsDesc.setDescGb("10");
		goodsDesc.setGoodsDesc(goods.getGoodsPcTopDesc());
		this.saveGoodsDesc(goodsDesc);

		// PC 하단
		goodsDesc.setDescGb("20");
		goodsDesc.setGoodsDesc(goods.getGoodsPcTopDesc());
		this.saveGoodsDesc(goodsDesc);

		// 공용 하단
		goodsDesc.setDescGb("30");
		goodsDesc.setGoodsDesc(goods.getGoodsPcDownDesc());
		this.saveGoodsDesc(goodsDesc);

		// MO 상단
		goodsDesc.setDescGb("40");
		goodsDesc.setGoodsDesc(goods.getGoodsMobileTopDesc());
		this.saveGoodsDesc(goodsDesc);

		//		// 상품상세 저장

		//
		//		// 세트상품의 구서상품으로 있을경우 처리
		//		this.saveGoodsSetDesc(goodsDesc);

		// MO 하단
		goodsDesc.setDescGb("50");
		goodsDesc.setGoodsDesc(goods.getGoodsMobileDownDesc());
		this.saveGoodsDesc(goodsDesc);

	}

	/**
	 * 상품 상세 저장
	 *
	 * @param goodsDesc
	 * @return
	 * @author eskim
	 * @since 2020. 10. 27
	 */
	private void saveGoodsDesc(GoodsDesc goodsDesc) {

		goodsDao.deleteGoodsDesc(goodsDesc);

		String[] arrProdHtml = null;
		arrProdHtml = makeArrayToString(goodsDesc.getGoodsDesc(), 3900);
		if (arrProdHtml.length > 0) {
			for (int i = 0; i < arrProdHtml.length; i++) {
				if (!arrProdHtml[i].isEmpty()) {
					goodsDesc.setSeq(i + 1);
					goodsDesc.setGoodsDesc(arrProdHtml[i]);
					goodsDao.createGoodsDesc(goodsDesc);
				}
			}
		}
	}

	/**
	 * String => byte array
	 *
	 * @param raw
	 * @param len
	 * @return
	 * @author eskim
	 * @since 2020. 10. 27
	 */
	public static String[] makeArrayToString(String raw, int len) {

		String[] ary = null;

		if (raw == null) {
			return ary;
		}

		try {

			// raw 의 byte
			byte[] rawBytes = raw.getBytes("UTF-8"); // MS949
			int rawLength = rawBytes.length;

			if (rawLength > len) {
				int aryLength = (rawLength / len) + (rawLength % len != 0 ? 1 : 0);
				ary = new String[aryLength];

				int endCharIndex = 0; // 문자열이 끝나는 위치
				String tmp;
				for (int i = 0; i < aryLength; i++) {

					if (i == (aryLength - 1)) {
						tmp = raw.substring(endCharIndex);
					} else {

						int useByteLength = 0;
						int rSize = 0;
						for (; endCharIndex < raw.length(); endCharIndex++) {

							if (raw.charAt(endCharIndex) > 0x007F) {
								useByteLength += 3;
							} else {
								useByteLength++;
							}
							if (useByteLength > len) {
								break;
							}
							rSize++;
						}
						tmp = raw.substring((endCharIndex - rSize), endCharIndex);
					}

					ary[i] = tmp;
				}

			} else {
				ary = new String[] {raw};
			}

		} catch (java.io.UnsupportedEncodingException e) {
		}

		return ary;
	}

	/**
	 * 옵션/재고 변경 - 상품상세
	 *
	 * @param goods
	 * @param index
	 * @author eskim
	 * @since 2020. 10. 27
	 */
	private void saveStock(Goods goods) {
		int index = 0;
		Option stock = new Option();
		stock.setGoodsCd(goods.getGoodsCd());
		stock.setUpdNo(goods.getUpdNo());
		stock.setRegNo(goods.getRegNo());
		goodsDao.createStockHst(stock);
		log.info("saveStock goods={}", goods);
		for (String optCd : goods.getOptCd()) {
			log.info("saveStock index={}", index);
			log.info("saveStock optCd={}", optCd);
			Option goodsStock = new Option();
			goodsStock.setGoodsCd(goods.getCompsGoodsCd()[index]); // 구성상품 코드
			goodsStock.setOptCd(optCd);
			goodsStock.setOptCd1(goods.getOptCd1()[index]);
			goodsStock.setOptCd2(goods.getOptCd2()[index]);
			goodsStock.setBaseStockQty(Integer.parseInt(goods.getBaseStockQty()[index]));
			goodsStock.setSoldoutYn(goods.getSoldoutYn()[index]);
			goodsStock.setDispOrd(goods.getDispOrd()[index]);
			goodsStock.setDispYn(goods.getDispYn()[index]);
			goodsStock.setRegNo(goods.getRegNo());
			goodsStock.setUpdNo(goods.getUpdNo());

			if ("N".equals(goods.getSelfGoodsYn())) {
				goodsStock.setSelfGoodsYn(goods.getSelfGoodsYn());
				goodsStock.setCurrStockQty(Integer.parseInt(goods.getEditCurrStockQty()[index]));
			}
			goodsDao.saveStock(goodsStock);
			index++;
		}
	}


	/**
	 * 상품 사이즈 옵션정보 이력 생성
	 *
	 * @param goods
	 * @author eskim
	 * @since 2020. 11. 17
	 */
	@Transactional("shopTxnManager")
	public void createStockHst(Option option) {
		goodsDao.createStockHst(option);
	}

	/**
	 * 상품 정보고시 변경 - 상품상세
	 *
	 * @param goods
	 * @author eskim
	 * @since 2020. 10. 27
	 */
	private void saveGoodsNotiInfo(Goods goods) {
		int index;
		if (goods.getNotiListNew() != null && !goods.getNotiListNew().isEmpty()) {
			index = 0;
			for (GoodsNotiInfo goodsNotiInfo : goods.getNotiListNew()) {
				if (index == 0) {
					goodsDao.deleteGoodsNotiInfo(goods);
				}
				goodsNotiInfo.setNiContent(GagaStringUtil.replace(GagaStringUtil.replace(goodsNotiInfo.getNiContent(), "&lt;", "<"), "&gt;", ">"));
				goodsNotiInfo.setRegNo(goods.getRegNo());
				goodsNotiInfo.setUpdNo(goods.getUpdNo());
				goodsDao.saveGoodsNotiInfo(goodsNotiInfo);
				index++;
			}
		}
	}

	/**
	 * 딜상품 저장
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 30
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsDeal(Goods goods) {

		Goods regGoods = new Goods();

		// <,> replace 처리
		regGoods.setRegNo(TsaSession.getInfo().getUserNo());
		regGoods.setUpdNo(TsaSession.getInfo().getUserNo());

		String goodsCd = this.getGoodsCodeSeq("D", "D");
		regGoods.setGoodsCd(goodsCd);
		regGoods.setSupplyGoodsCd(goodsCd);
		regGoods.setGoodsType("G056_D");
		regGoods.setSupplyCompCd(goods.getSupplyCompCd());
		regGoods.setBrandCd(goods.getBrandCd());
		regGoods.setItemkindCd(goods.getItemkindCd());
		regGoods.setGoodsNm(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsNm(), "&lt;", "<"), "&gt;", ">"));
		regGoods.setStyleYear(goods.getStyleYear());
		regGoods.setSeasonCd(goods.getSeasonCd());
		regGoods.setSexGb(goods.getSexGb());
		regGoods.setMainColorCd("00");
		regGoods.setOriginCd(goods.getOriginCd());
		regGoods.setMakeYmd(goods.getMakeYmd());
		regGoods.setSelfMallYn(goods.getSelfMallYn());
		regGoods.setGoodsStat("G008_20"); // 정보부족
		regGoods.setFormalGb("G009_10"); // 정상 기본값 처리
		regGoods.setGoodsGb("G073_11"); // 자사상품은 신규
		regGoods.setDistributionGb("G065_12"); // 유통구분
		regGoods.setTaxGb("10"); // 과세구분
		regGoods.setGoodsNum(goodsCd);

		regGoods.setListPrice(goods.getCurrPrice());
		regGoods.setCurrPrice(goods.getCurrPrice());
		regGoods.setDcRate((int)(this.getDcRate(goods.getCurrPrice(), goods.getCurrPrice())));

		Collection<GoodsCompose> goodsComposeList = null;
		try {
			goodsComposeList = mapper.readValue(goods.getGoodsComposeList(), new TypeReference<Collection<GoodsCompose>>() {
			});
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalStateException(message.getMessage("딜상품 저장 중 오류로 인해 저장되지 않았습니다."));
		}

		for (GoodsCompose goodsCompose : goodsComposeList) {
			goodsCompose.setGoodsCd(regGoods.getGoodsCd());
			goodsCompose.setGoodsType(regGoods.getGoodsType());
			goodsCompose.setRegNo(TsaSession.getInfo().getUserNo());
			goodsCompose.setUpdNo(TsaSession.getInfo().getUserNo());

			Goods extendGoods = new Goods();
			extendGoods.setGoodsCd(goodsCompose.getCompsGoodsCd());
			extendGoods = goodsDao.getGoods(extendGoods);
			if (StringUtils.isEmpty(extendGoods.getBrandCd())) {
				throw new IllegalStateException(message.getMessage("구성상품 중 " + goodsCompose.getCompsGoodsCd() + " 상품 정보를 확인해 주세요."));
			}

			if ("Y".equals(goodsCompose.getBaseYn())) {
				regGoods.setBrandCd(extendGoods.getBrandCd());
				regGoods.setItemkindCd(extendGoods.getItemkindCd());
				regGoods.setSupplyCompCd(extendGoods.getSupplyCompCd());
				regGoods.setFormalGb(extendGoods.getFormalGb());
			}
		}

		this.createGoodsExtend(regGoods, goodsComposeList); // 딜상품 관련 정보 저장
	}

	/**
	 * 세트상품 저장
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 11. 04
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsSet(Goods goods) {

		Goods regGoods = new Goods();

		// <,> replace 처리
		regGoods.setRegNo(TsaSession.getInfo().getUserNo());
		regGoods.setUpdNo(TsaSession.getInfo().getUserNo());

		String goodsCd = this.getGoodsCodeSeq("S", "S");
		regGoods.setGoodsCd(goodsCd);
		regGoods.setSupplyGoodsCd(goodsCd);
		regGoods.setGoodsType("G056_S");
		regGoods.setSupplyCompCd(goods.getSupplyCompCd());
		regGoods.setBrandCd(goods.getBrandCd());
		regGoods.setItemkindCd(goods.getItemkindCd());
		regGoods.setGoodsNm(GagaStringUtil.replace(GagaStringUtil.replace(goods.getGoodsNm(), "&lt;", "<"), "&gt;", ">"));
		regGoods.setStyleYear(goods.getStyleYear());
		regGoods.setSeasonCd(goods.getSeasonCd());
		regGoods.setSexGb(goods.getSexGb());
		regGoods.setMainColorCd("00");
		regGoods.setOriginCd(goods.getOriginCd());
		regGoods.setMakeYmd(goods.getMakeYmd());
		regGoods.setSelfMallYn(goods.getSelfMallYn());
		regGoods.setGoodsStat("G008_20"); // 정보부족
		regGoods.setFormalGb("G009_10"); // 정상 기본값 처리
		regGoods.setGoodsGb("G073_11"); // 자사상품은 신규
		regGoods.setDistributionGb("G065_12"); // 유통구분
		regGoods.setTaxGb("10"); // 과세구분
		regGoods.setGoodsNum(goodsCd);

		Collection<GoodsCompose> goodsComposeList = null;
		try {
			goodsComposeList = mapper.readValue(goods.getGoodsComposeList(), new TypeReference<Collection<GoodsCompose>>() {
			});
		} catch (Exception e) {
			throw new IllegalStateException(message.getMessage("세트상품 저장 중 오류로 인해 저장되지 않았습니다."));
		}

		int listPriceSum = 0;
		int currPriceSum = 0;
		for (GoodsCompose goodsCompose : goodsComposeList) {
			goodsCompose.setGoodsCd(regGoods.getGoodsCd());
			goodsCompose.setGoodsType(regGoods.getGoodsType());
			goodsCompose.setRegNo(TsaSession.getInfo().getUserNo());
			goodsCompose.setUpdNo(TsaSession.getInfo().getUserNo());

			Goods extendGoods = new Goods();
			extendGoods.setGoodsCd(goodsCompose.getCompsGoodsCd());
			extendGoods = goodsDao.getGoods(extendGoods);
			if (StringUtils.isEmpty(extendGoods.getBrandCd())) {
				throw new IllegalStateException(message.getMessage("구성상품 중 " + goodsCompose.getCompsGoodsCd() + " 상품 정보를 확인해 주세요."));
			}
			listPriceSum += extendGoods.getListPrice() * goodsCompose.getQty() ;
			currPriceSum += goodsCompose.getCompsCurrPrice(); // 입력값

			if ("Y".equals(goodsCompose.getBaseYn())) {
				regGoods.setBrandCd(extendGoods.getBrandCd());
				regGoods.setItemkindCd(extendGoods.getItemkindCd());
				regGoods.setGoodsNum(extendGoods.getGoodsNum());
				regGoods.setSupplyCompCd(extendGoods.getSupplyCompCd());
				regGoods.setFormalGb(extendGoods.getFormalGb());
			}
		}

		regGoods.setListPrice(listPriceSum);
		regGoods.setCurrPrice(currPriceSum);
		regGoods.setCostPrice(0);	// 원가 0원처리
		regGoods.setDcRate((int)(this.getDcRate(listPriceSum, currPriceSum)));

		this.createGoodsExtend(regGoods, goodsComposeList); // 세트상품 관련 정보 저장
	}

	/**
	 * 세트/딜 상품 관련 저장
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 30
	 */
	private void createGoodsExtend(Goods regGoods, Collection<GoodsCompose> goodsComposeList) {
		// 브랜드 확인
		Brand brand = new Brand();
		brand.setBrandCd(regGoods.getBrandCd());
		brand.setSupplyCompCd(regGoods.getSupplyCompCd());
		Collection<Brand> brandList = businessService.getBrandList(brand);
		if (brandList == null || brandList.isEmpty()) {
			throw new IllegalStateException(message.getMessage("구성상품 중 기준 상품의 브랜드를 확인해 주세요."));
		}

		float pntPrate = 0.0f;
		float pntMrate = 0.0f;
		float sellFeeRate = 0.0f;
		String delvFeeCd = "";
		for (Brand tmpBrand : brandList) {

			if ("10".equals(regGoods.getFormalGb())) {
				pntPrate = tmpBrand.getPntPrate10();
				pntMrate = tmpBrand.getPntMrate10();
			} else {
				pntPrate = tmpBrand.getPntPrate20();
				pntMrate = tmpBrand.getPntMrate20();
			}
			sellFeeRate = tmpBrand.getSellFeeRate();
			delvFeeCd = tmpBrand.getDelvFeeCd();
		}
		regGoods.setDelvFeeCd(delvFeeCd);// 배송비전책코드
		regGoods.setPntPrate(pntPrate); // 포인트적립율(PC)
		regGoods.setPntMrate(pntMrate); // 포인트적립율(MOBILE)
		regGoods.setSellFeeRate(sellFeeRate); // 판매수수료율
		regGoods.setSelfGoodsYn("Y");

		// 스타일 연도
		regGoods.setStyleYear(regGoods.getStyleYear());

		goodsDao.createGoods(regGoods); // 상품기본 저장
		goodsDao.createGoodsSmmary(regGoods); // 상품통계 생성

		StringBuilder goodsDescSb = new StringBuilder(); // 상품상세

		int dispOrd = 1;
		for (GoodsCompose regGoodsExtend : goodsComposeList) {
			regGoodsExtend.setDispOrd(dispOrd);
			goodsDao.saveGoodsCompose(regGoodsExtend); // 구성상품기본 저장
			dispOrd++;
		}


		// 사용자 검색어를 검색어에 적용
		String goodsSnm = goodsDao.getGoodsSnm(regGoods.getGoodsCd());
		regGoods.setGoodsSnm(goodsSnm);
		goodsDao.updateGoodsSnm(regGoods);
		// 카테고리 전시
		// 추후 작업 해야함 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		//goodsDao.createCategoryGoods(regGoods);

		// 추후 작업 해야함 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		// 대표 이미지만 생성
//		GoodsImg goodsImg = new GoodsImg();
//		goodsImg.setGoodsCd(regGoods.getGoodsCd());
//		goodsImg.setImgType("A");
//		// 이미지 경로 확인하자!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//		goodsImg.setImgPath1(this.getGoodsImgPath(regGoods.getGoodsCd(), regGoods.getBrandCd()) + "01.jpg");
//		goodsImg.setRegNo(TsaSession.getInfo().getUserNo());
//		goodsImg.setUpdNo(TsaSession.getInfo().getUserNo());
//		goodsDao.saveGoodsImgInfo(goodsImg);
	}

//	/**
//	 * 품 이미지 경로생성
//	 *
//	 * @param goodsCd
//	 * @param brandCd
//	 * @return String
//	 * @author eskim
//	 * @since 2020. 10. 30
//	 */
//	private String getGoodsImgPath(String goodsCd, String brandCd) {
//		return "/" + goodsCd.substring(0, 1) + "/" + goodsCd.substring(0, 3) + "/" + goodsCd + "/1000/" + goodsCd + "_";
//	}

	/**
	 * 상품 코드 생성
	 *
	 * @param goodsType - 상품타입
	 * @param goodsCdAfter - 상품시퀀스 앞에 붙는명
	 * @return
	 * @author eskim
	 * @since 2020. 10. 30
	 */
	public String getGoodsCodeSeq(String goodsType, String goodsCdAfter) {

		//상품코드 12자리
		String goodsCd = "";
		Goods goods = new Goods();
		goodsDao.createGoodsSequence(goods);
		String goodsSeq = GagaStringUtil.getLPadding(Integer.toString(goods.getGoodsSq()), 9, "0");
		if ("S".equals(goodsType) || "D".equals(goodsType)) {
			goodsCd = SELF_GOOODS_AFTER + goodsCdAfter + goodsSeq;

		} else {
			goodsCd = goodsCdAfter + goodsSeq; // 입점 : 브랜드코드
		}
		return goodsCd;
	}

	/**
	 * 상품 타이틀 관리 목록 건수
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 11 .02
	 */
	public int getGoodsTitleReserveCount(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsTitleReserveCount(goodsSearch);
	}

	/**
	 * 상품 타이틀 관리 목록
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 11 .02
	 */
	public Collection<GoodsTnmRes> getGoodsTitleReserveList(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsTitleReserveList(goodsSearch);
	}

	/**
	 * 상품 타이틀 예약 등록
	 *
	 * @param goodsTnmRes
	 * @author eskim
	 * @since 2020. 11 .02
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsRsvtTnm(GoodsTnmRes goodsTnmRes) {
		if (goodsTnmRes.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		goodsTnmRes.setGoodsTnm(GagaStringUtil.replace(GagaStringUtil.replace(goodsTnmRes.getGoodsTnm(), "&lt;", "<"), "&gt;", ">"));

		for (String goodsCd : goodsTnmRes.getArrGoodsCd()) {

			goodsTnmRes.setGoodsCd(goodsCd);
			goodsTnmRes.setRegNo(TsaSession.getInfo().getUserNo());
			goodsTnmRes.setUpdNo(TsaSession.getInfo().getUserNo());

			if (goodsDao.getGoodsTnmDupChkCount(goodsTnmRes) > 0) {
				throw new IllegalStateException("이미 등록된 상품 타이틀예약이 등록하려는 예약기간내에 존재합니다. \n(상품코드 : " + goodsCd + ")");
			}

			goodsDao.createGoodTnmRes(goodsTnmRes);

			// 현재일자가 예약기간에 포함되어 있으면 바로 적용한다.
			String toDaytime = GagaDateUtil.getTodayDateTime();
			if (Long.parseLong(toDaytime) >= Long.parseLong(goodsTnmRes.getApplyStdt()) && Long.parseLong(toDaytime) <= Long.parseLong(goodsTnmRes.getApplyEddt())) {

				// 이력생성 및 상품타이틀 수정
				Goods goods = new Goods();
				goods.setGoodsCd(goodsCd);
				goods.setGoodsTnm(goodsTnmRes.getGoodsTnm());
				goods.setRegNo(TsaSession.getInfo().getUserNo());
				goods.setUpdNo(TsaSession.getInfo().getUserNo());

				goodsDao.createGoodsHst(goods);
				goodsDao.updateGoodTnm(goods);
			}

		}
	}

	/**
	 * 상품 타이틀 예약 삭제
	 *
	 * @param goodsTnmRes
	 * @author eskim
	 * @since 2020. 11 .02
	 */
	@Transactional("shopTxnManager")
	public void deleteGoodsRsvtTnm(GoodsTnmRes goodsTnmRes) {
		if (goodsTnmRes.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		int idx = 0;
		for (String goodsCd : goodsTnmRes.getArrGoodsCd()) {

			// 상품 타이틀 예약 삭제
			goodsTnmRes.setGoodsTnmResSq(goodsTnmRes.getArrGoodsTnmResSq()[idx]);
			goodsDao.deleteGoodTnmRes(goodsTnmRes);

			// 상품 타이틀 예약건 초기화
			Goods goods = new Goods();
			goods.setGoodsCd(goodsCd);
			goods = goodsDao.getGoodTnmInit(goods);
			goods.setRegNo(TsaSession.getInfo().getUserNo());
			goods.setUpdNo(TsaSession.getInfo().getUserNo());

			if (!StringUtils.isEmpty(goods.getGoodsTnm()) && !goods.getGoodsTnm().equals(goods.getGoodTnmInit())) {

				// 상품이력 먼저 쌓기
				goodsDao.createGoodsHst(goods);
				// 정보수정
				goods.setGoodsTnm(goods.getGoodTnmInit());
				goodsDao.updateGoodTnm(goods);

			}
			idx++;
		}
	}

	/**
	 * 네이버 EP 제외 상품 목록 건수
	 *
	 * @param goodsSearch
	 * @return int
	 * @author eskim
	 * @since 2020. 11. 03
	 */
	public int getGoodsEpSkipCount(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsEpSkipCount(goodsSearch);
	}

	/**
	 * 네이버 EP 제외 상품 목록
	 *
	 * @param goodsSearch
	 * @return Collection<TsaGoodsEpSkip>
	 * @author eskim
	 * @since 2020. 11. 03
	 */
	public Collection<GoodsEpSkip> getGoodsEpSkipList(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsEpSkipList(goodsSearch);
	}

	/**
	 * 네이버 EP 제외 상품 예약 등록
	 *
	 * @param goodsEpSkip
	 * @return void
	 * @author eskim
	 * @since 2020. 11. 03
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsRsvtEpSkip(GoodsEpSkip goodsEpSkip) {
		if (goodsEpSkip.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		for (String goodsCd : goodsEpSkip.getArrGoodsCd()) {

			goodsEpSkip.setGoodsCd(goodsCd);
			goodsEpSkip.setRegNo(TsaSession.getInfo().getUserNo());
			goodsEpSkip.setUpdNo(TsaSession.getInfo().getUserNo());

			if (goodsDao.getGoodsEpSkipDupChkCount(goodsEpSkip) > 0) {
				throw new IllegalStateException("비노출예약이 중복된 상품이 존재합니다.<br/>(상품코드 : " + goodsCd + ")");
			}
			goodsDao.createGoodEpSkip(goodsEpSkip);
		}
	}

	/**
	 * 네이버 EP 제외 상품 예약 삭제
	 *
	 * @param goodsEpSkip
	 * @return void
	 * @author eskim
	 * @since 2020. 11. 03
	 */
	@Transactional("shopTxnManager")
	public void deleteGoodsEpSkip(GoodsEpSkip goodsEpSkip) {
		if (goodsEpSkip.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}
		int idx = 0;
		for (String goodsCd : goodsEpSkip.getArrGoodsCd()) {
			goodsEpSkip.setGoodsEpSkipSq(goodsEpSkip.getArrGoodsEpSkipSq()[idx]);
			goodsDao.deleteGoodEpSkip(goodsEpSkip);
			idx++;
		}
	}

	/**
	 * 상품예약판매 목록 건수
	 *
	 * @param goodsSearch
	 * @return Integer
	 * @author eskim
	 * @since 2020. 11. 12
	 */
	public int getGoodsResSellCount(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsResSellCount(goodsSearch);
	}

	/**
	 * 상품예약판매 목록
	 *
	 * @param goodsSearch
	 * @return Collection<TsaGoodsResSell>
	 * @author eskim
	 * @since 2020. 11. 12
	 */
	public Collection<GoodsResSell> getGoodsResSellList(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsResSellList(goodsSearch);
	}

	/**
	 * 상품예약판매 등록
	 *
	 * @param goodsResSell
	 * @return void
	 * @author eskim
	 * @since 2020. 11. 12
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsResSell(GoodsResSell goodsResSell) {
		if (goodsResSell.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		for (String goodsCd : goodsResSell.getArrGoodsCd()) {

			goodsResSell.setGoodsCd(goodsCd);
			goodsResSell.setRegNo(TsaSession.getInfo().getUserNo());
			goodsResSell.setUpdNo(TsaSession.getInfo().getUserNo());

			if(goodsDao.getGoodsResSellDupChkCount(goodsResSell) > 0 ) {
				throw new IllegalStateException("이미 등록된 상품예약판매가 존재합니다. \n(상품코드 : " + goodsCd + ")");
			}

			goodsDao.createGoodResSell(goodsResSell);

			Goods goods = new Goods();
			goods.setRegNo(TsaSession.getInfo().getUserNo());
			goods.setUpdNo(TsaSession.getInfo().getUserNo());
			goods.setGoodsCd(goodsResSell.getGoodsCd());

			// 재고연동 비활성화
			goodsDao.createGoodsHst(goods);
			goodsDao.updateGoodsErpStockLinkYn(goods);

		}
	}

	/**
	 * 상품예약판매 삭제
	 *
	 * @param goodsResSell
	 * @return void
	 * @author eskim
	 * @since 2020. 11. 12
	 */
	@Transactional("shopTxnManager")
	public void deleteGoodsResSell(GoodsResSell goodsResSell) {
		if (goodsResSell.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}
		int idx = 0;
		for (String goodsCd : goodsResSell.getArrGoodsCd()) {
			goodsResSell.setGoodsResSellSq(goodsResSell.getArrGoodsResSellSq()[idx]);
			goodsDao.deleteGoodResSell(goodsResSell);
			idx++;
		}
	}

	/**
	 * 상품 상세공지 목록
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 11. 05
	 */
	public Collection<Notice> getNoticeList(GoodsSearch goodsSearch) {
		return goodsDao.getNoticeList(goodsSearch);
	}

	/**
	 * 상품 상세공지 상품 목록
	 *
	 * @param notice
	 * @return
	 * @author eskim
	 * @since 2020. 11. 06
	 */
	public Collection<NoticeGoods> getNoticeGoodsList(Notice notice) {
		return goodsDao.getNoticeGoodsList(notice);
	}

	/**
	 * 공지사항 저장
	 * @param notice - 공지사항 정보
	 * @return
	 * @author eskim
	 * @since 2020. 11. 05
	 */
	@Transactional("shopTxnManager")
	public void saveNotice(Notice notice) {
		notice.setRegNo(TsaSession.getInfo().getUserNo());
		notice.setUpdNo(TsaSession.getInfo().getUserNo());

		// 신규 일때
		if (notice.getNoticeSq() == null) {
			// 공지사항 저장
			noticeService.createNotice(notice);

			// 등록된 사용자번호 값 가져오기
			Integer noticeSq = notice.getNoticeSq();

			notice.setNoticeSq(noticeSq);

		} else {
			// 공지사항 수정
			noticeService.updateNotice(notice);
		}

		if (!StringUtils.isEmpty(notice.getGoodsList())) {
			Collection<NoticeGoods> noticeGoodsList = null;
			try {
				noticeGoodsList = mapper.readValue(notice.getGoodsList(), new TypeReference<Collection<NoticeGoods>>() {
				});
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException(message.getMessage("상품상세공지 저장 중 오류로 인해 저장되지 않았습니다."));
			}
			log.info("noticeGoodsList: {}", noticeGoodsList);
			for (NoticeGoods noticeGoods : noticeGoodsList) {
				noticeGoods.setNoticeSq(notice.getNoticeSq());
				noticeGoods.setRegNo(TsaSession.getInfo().getUserNo());
				noticeGoods.setUpdNo(TsaSession.getInfo().getUserNo());

				goodsDao.saveNoticeGoods(noticeGoods);
			}

		}
	}

	/**
	 * 공지사항 상품 삭제
	 * @param noticeGoods
	 * @return
	 * @author eskim
	 * @since 2020. 11. 06
	 */
	@Transactional("shopTxnManager")
	public void deleteNoticeGoods(NoticeGoods noticeGoods) {

		if (noticeGoods == null || (noticeGoods.getArrGoodsCd() == null && noticeGoods.getArrGoodsCd().length <= 0)) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		if (noticeGoods.getArrGoodsCd().length > 0) {
			for (String goodsCd : noticeGoods.getArrGoodsCd()) {
				noticeGoods.setGoodsCd(goodsCd);
				noticeGoods.setRegNo(TsaSession.getInfo().getUserNo());
				noticeGoods.setUpdNo(TsaSession.getInfo().getUserNo());

				goodsDao.deleteNoticeGoods(noticeGoods);
			}
		}

	}

	/**
	 * 상품 가격예약 목록 건수
	 *
	 * @param goodsSearch
	 * @return Integer
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	public int getGoodsPriceResCount(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsPriceResCount(goodsSearch);
	}

	/**
	 * 상품 가격예약 목록
	 *
	 * @param goodsSearch
	 * @return Collection<TsaGoodsResSell>
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	public Collection<GoodsPriceRes> getGoodsPriceResList(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsPriceResList(goodsSearch);
	}

	/**
	 * 상품 가격예약 등록
	 *
	 * @param goodsPriceRes
	 * @return void
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	@Transactional("shopTxnManager")
	public void createGoodPriceRes(GoodsPriceRes goodsPriceRes) {
		if (goodsPriceRes.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}
		int idx = 0;
		for (String goodsCd : goodsPriceRes.getArrGoodsCd()) {

			goodsPriceRes.setGoodsCd(goodsCd);
			goodsPriceRes.setEndGoodsPrice(goodsPriceRes.getArrEndGoodsPrice()[idx]);
			goodsPriceRes.setRegNo(TsaSession.getInfo().getUserNo());
			goodsPriceRes.setUpdNo(TsaSession.getInfo().getUserNo());

			if(goodsDao.getGoodsPriceResDupChkCount(goodsPriceRes) > 0 ) {
				throw new IllegalStateException("이미 등록된 상품 가격예약이 존재합니다. \n(상품코드 : " + goodsCd + ")");
			}

			goodsDao.createGoodPriceRes(goodsPriceRes);

			Goods goods = new Goods();
			goods.setRegNo(TsaSession.getInfo().getUserNo());
			goods.setUpdNo(TsaSession.getInfo().getUserNo());
			goods.setGoodsCd(goodsPriceRes.getGoodsCd());
			idx++;
		}
	}

	/**
	 * 상품 가격예약 삭제
	 *
	 * @param goodsPriceRes
	 * @return void
	 * @author eskim
	 * @since 2020. 11. 13
	 */
	@Transactional("shopTxnManager")
	public void deleteGoodsPriceRes(GoodsPriceRes goodsPriceRes) {
		if (goodsPriceRes.getArrGoodsCd().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}
		int idx = 0;
		for (String goodsCd : goodsPriceRes.getArrGoodsCd()) {
			goodsPriceRes.setGoodsPriceResSq(goodsPriceRes.getArrGoodsPriceResSq()[idx]);
			goodsDao.deleteGoodPriceRes(goodsPriceRes);
			idx++;
		}
	}

	/**
	 * 상품 가격예약 저장
	 *
	 * @param goodsPriceList
	 * @return
	 * @author eskim
	 * @since 2020. 11. 16
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsPriceExcelupload(Collection<GoodsPriceRes> goodsPriceList, String excelFilename) {

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

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

		int index = 0;
		for (GoodsPriceRes goodsPriceRes : goodsPriceList) {
			goodsPriceRes.setUpdNo(TsaSession.getInfo().getUserNo());
			goodsPriceRes.setRegNo(TsaSession.getInfo().getUserNo());

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

			commonService.createExceluploadSearch(searchData);

			goodsDao.createGoodPriceRes(goodsPriceRes);

			index++;
		}
	}

	/*
	 * 상품 가격예약 엑셀조회용 상품 저장 - 입력값 확인
	 */
	private String getGoodsPriceResvCheck(Collection<GoodsPriceRes> goodsPriceList) {

		int cnt = 0;
		for (GoodsPriceRes goodsPriceRes : goodsPriceList) {

			if (StringUtils.isEmpty(goodsPriceRes.getGoodsCd())) {
				return (cnt + 2) + "행의 상품코드를 확인해주세요";
			}
			if (StringUtils.isEmpty(goodsPriceRes.getResGoodsPrice())) {
				return (cnt + 2) + "행의 예약가격을 확인해주세요.";
			}
			if (goodsPriceRes.getResGoodsPrice() <= 0) {
				return (cnt + 2) + "행의 예약가격을 확인해주세요.";
			}

			String nowDate = GagaDateUtil.getToday();	//yyyyMMdd
			SimpleDateFormat dateFormatParser = new SimpleDateFormat("yyyyMMdd");
			dateFormatParser.setLenient(false);
			try {
				dateFormatParser.parse(goodsPriceRes.getApplyStdt() );
			} catch (Exception e) {
				return (cnt + 2) + "행의 예약시작일을 확인해주세요.";
			}
			try {
				dateFormatParser.parse(goodsPriceRes.getApplyEddt() );
			} catch (Exception e) {
				return (cnt + 2) + "행의 예약종료일을 확인해주세요.";
			}

			if (Integer.parseInt(goodsPriceRes.getApplyStdt()) > Integer.parseInt(goodsPriceRes.getApplyEddt())) {
				return (cnt + 2) + "행의 예약 시작일은 종료일보다 보다 클 수 없습니다.";
			}

			if (Integer.parseInt(goodsPriceRes.getApplyStdt()) <= Integer.parseInt(nowDate)) {
				return (cnt + 2) + "행의 예약 시작일자는 현재일자 보다 작거나 같을 수 없습니다.";
			}

			//정상가와 비교
			Goods searchGoods = new Goods();
			searchGoods.setGoodsCd(goodsPriceRes.getGoodsCd());
			Goods goods = goodsDao.getGoods(searchGoods);
			if (goods == null) {
				return (cnt + 2) + "행의 상품코드를 확인해주세요";
			}
			if (goods.getListPrice() < goodsPriceRes.getResGoodsPrice()) {
				return (cnt + 2) + "행의 상품 정상가보다 예약판매가가 더 큽니다.";
			}
			if (!"Y".equals(goods.getSelfGoodsYn())) {
				return (cnt + 2) + "행의 상품은 자사상품이 아닙니다.";
			}

			if(goodsDao.getGoodsPriceResDupChkCount(goodsPriceRes) > 0 ) {
				return (cnt + 2) + "행은 이미 등록된 상품 가격예약이 존재합니다. \n(상품코드 : " + goodsPriceRes.getGoodsCd() + ")";
			}


			cnt++;
		}

		return "SUCC";
	}


	/**
	 * 상품 동영상 목록 조회
	 *
	 * @param goodsVideo
	 * @return
	 * @author eskim
	 * @since 2020. 11. 16
	 */
	public Collection<GoodsVideo> getGoodsVideoList(GoodsVideo goodsVideo) {
		return goodsDao.getGoodsVideoList(goodsVideo);
	}

	/**
	 * 상품 동영상 삭제로 변경
	 *
	 * @param goodsVideo
	 * @return
	 * @author eskim
	 * @since 2020. 11. 16
	 */
	@Transactional("shopTxnManager")
	public void updateNotUseGoodsVideo(Collection<GoodsVideo> goodsVideos) {
		for (GoodsVideo goodsVideo : goodsVideos) {
			Video video = new Video();
			video.setUpdNo(TsaSession.getInfo().getUserNo());
			video.setVideoSq(goodsVideo.getVideoSq());
			goodsDao.updateNotUseGoodsVideo(video);
		}
	}

	/**
	 * 상품동영상 수정/저장
	 *
	 * @param video
	 * @return
	 * @author eskim
	 * @since 2020. 11. 16
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsVideo(Video video) {
		video.setRegNo(TsaSession.getInfo().getUserNo());
		video.setUpdNo(TsaSession.getInfo().getUserNo());
		if (video.getVideoSq() == null ||  video.getVideoSq() == 0) {

			String videoSeq = goodsDao.getVideoSeq(video);
			if (StringUtils.isEmpty(videoSeq)) {
				goodsDao.createVideo(video);
			}else {
				//video.setVideoSq(Integer.parseInt(videoSeq));  //why?
				//goodsDao.updateVideo(video);
			}
		}

		if (video.getVideoSq() == null ||  video.getVideoSq() == 0) {
			String videoSeq = goodsDao.getVideoSeq(video);

			if (!StringUtils.isEmpty(videoSeq)) {
				video.setVideoSq(Integer.parseInt(videoSeq));
			}
		}

		//goodsDao.delVideoDispLoc(video);  why?
		String[] displocValArr = video.getDisplocValArr();
		for (String displocVal : displocValArr) {
			video.setDisplocVal(displocVal);
			goodsDao.saveVideoDispLoc(video);
		}
	}

	/**
	 * 상품동영상 엑셀파일 등록
	 *
	 * @param dataList
	 * @return
	 * @author eskim
	 * @since 2020. 11. 16
	 */
	@Transactional("shopTxnManager")
	public int saveExcelGoodsVideo(Collection<GagaMap> dataList) {

		int cnt = 0;

		for (GagaMap map : dataList) {
			Video video = mapper.convertValue(map, Video.class);
			video.setUpdNo(TsaSession.getInfo().getUserNo());
			video.setRegNo(TsaSession.getInfo().getUserNo());
			video.setDisplocGb("G");
			video.setDispYn("Y");
			String videoVal = video.getVideoVal();
			if (videoVal.contains("http")) {
				video.setVideoGb("M");
			} else {
				video.setVideoGb("Y");
			}
			String videoSeq = goodsDao.getVideoSeq(video);

			if (StringUtils.isEmpty(videoSeq)) {
				goodsDao.createVideo(video);
			}

			videoSeq = goodsDao.getVideoSeq(video);
			if (!StringUtils.isEmpty(videoSeq)) {
				video.setVideoSq(Integer.parseInt(videoSeq));
			}
			goodsDao.saveVideoDispLoc(video);
			cnt++;
		}

		return cnt;
	}

	/**
	 * 상품별 옵션 등록 여부 확인
	 *
	 * @param
	 * @return
	 * @author eskim
	 * @since 2020. 11. 17
	 */
	public int getGoodsOptionCount(Option option) {

		return goodsDao.getGoodsOptionCount(option);
	}

	/**
	 * 상품 가격승인관리 목록 조회
	 *
	 * @param goodsPriceHst
	 * @return
	 * @author eskim
	 * @since 2020. 11. 26
	 */
	public Collection<GoodsPriceRes> getGoodsSupplyPriceList(GoodsPriceRes goodsPriceHst) {

		return goodsDao.getGoodsSupplyPriceList(goodsPriceHst);
	}

	/**
	 * 상품 가격승인관리 승인 처리
	 *
	 * @param goodsPriceHstList - 상품 가격 승인 목록
	 * @author eskim
	 * @since 2020. 11. 26
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsSupplyPrice(Collection<GoodsPriceRes> goodsPriceHstList) {

		for (GoodsPriceRes goodsPriceRes : goodsPriceHstList) {
			goodsPriceRes.setRegNo(TsaSession.getInfo().getUserNo());
			goodsPriceRes.setUpdNo(TsaSession.getInfo().getUserNo());


			Goods goods = new Goods();
			goods.setRegNo(TsaSession.getInfo().getUserNo());
			goods.setUpdNo(TsaSession.getInfo().getUserNo());
			goods.setGoodsCd(goodsPriceRes.getGoodsCd());

			goodsDao.createGoodsHst(goods);

			// 판매가 변경
			if (goodsPriceRes.getResGoodsPrice() > 0) {
				log.info("goodsPriceRes.getTagPrice() ={}", goodsPriceRes.getListPrice());
				log.info("goodsPriceRes.getResGoodsPrice() ={}", goodsPriceRes.getResGoodsPrice());
				goods.setDcRate((int)(this.getDcRate(goodsPriceRes.getListPrice(), goodsPriceRes.getResGoodsPrice())));
				goods.setCurrBprice(goodsPriceRes.getCurrPrice());
				goods.setCurrPrice(goodsPriceRes.getResGoodsPrice());
				goodsDao.updateGoodsPrice(goods);
			}

			// 판매수수료율 변경
			if (goodsPriceRes.getSellFeeRate() != null) {
				goods.setSellFeeRate(goodsPriceRes.getSellFeeRate());
				goodsDao.updateSellFeeRate(goods);
			}

			goodsDao.updateGoodsSupplyPricecfrmDt(goodsPriceRes);
		}
	}

	/**
	 * 상품 네이버 최저가 목록
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 12. 08
	 */
	public Collection<GoodsNaverLowestPrice> getGoodsNaverPriceList(GoodsSearch goodsSearch) {
		return goodsDao.getGoodsNaverPriceList(goodsSearch);
	}

	/**
	 * 상품 네이버 최저가 목록
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 12. 08
	 */
	@Transactional("shopTxnManager")
	public Collection<GoodsNaverLowestPrice> saveGoodsNaverPrice(GoodsSearch goodsSearch) {

		// 1. 조회 상품 TB_SEARCH_DATA 담기
		int index = 0;
		for (String goodsCd : goodsSearch.getConditionList()) {

			SearchData searchData = new SearchData();
			searchData.setRegNo(TsaSession.getInfo().getUserNo());
			searchData.setSearchCd(goodsCd);
			if (index == 0) {
				commonService.deleteExceluploadSearCh(searchData);
			}

			commonService.createExceluploadSearch(searchData);
			index++;
		}

		// 2. 일 최초 조회이면 테이블 삭제
		String regYmd  = goodsDao.getGoodsNaverLowestPriceReqYmd();
		if (!StringUtils.isEmpty(regYmd) && !regYmd.equals(GagaDateUtil.getToday())) {
			goodsDao.deleteGoodsNaverLowestPrice();
		}

		// 3. 네이버 최저가 조회 저장
		saveGoodsNaverLowestPrice(goodsSearch);

		// 4. 최저가 상품 조회
		goodsSearch.setSearchGb("EXCEL");
		goodsSearch.setRegNo(TsaSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		return goodsDao.getGoodsNaverPriceList(goodsSearch);
	}

	/**
	 * 상품 네이버 최저가 목록
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 12. 08
	 */
	private void saveGoodsNaverLowestPrice(GoodsSearch goodsSearch) {

		for (String goodsCd : goodsSearch.getConditionList()) {
			try {
				log.info("saveGoodsNaverLowestPrice  11 =  {}", GagaDateUtil.getTodayDateTime());
				TaskSleeep();
				log.info("saveGoodsNaverLowestPrice  22 =  {}", GagaDateUtil.getTodayDateTime());
				NaverLowestPrice naverLowestPrice = naverLowestPriceApi.getLowestPrice(goodsCd);

				log.info("[saveGoodsNaverLowestPrice] naverLowestPrice= {}",naverLowestPrice);
				if (naverLowestPrice != null) {
					GoodsNaverLowestPrice goodsNaverLowestPrice = new GoodsNaverLowestPrice();
					goodsNaverLowestPrice.setReqYmd(GagaDateUtil.getToday());
					goodsNaverLowestPrice.setGoodsCd(goodsCd);
					goodsNaverLowestPrice.setMallNm(naverLowestPrice.getItems().iterator().next().getMallName());
					goodsNaverLowestPrice.setMallLink(naverLowestPrice.getItems().iterator().next().getLink());
					goodsNaverLowestPrice.setLowestPrice(naverLowestPrice.getItems().iterator().next().getLprice());
					goodsNaverLowestPrice.setRegNo(TsaSession.getInfo().getUserNo());
					goodsNaverLowestPrice.setUpdNo(TsaSession.getInfo().getUserNo());
					log.info("[saveGoodsNaverLowestPrice] goodsNaverLowestPrice= {}", goodsNaverLowestPrice);
					goodsDao.saveGoodsNaverLowestPrice(goodsNaverLowestPrice);

				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	/**
	 *
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 12. 08
	 */
	static void TaskSleeep() {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 광고 키워드 목록
	 *
	 * @param adKeyword
	 * @return
	 * @author eskim
	 * @since 2020. 12. 15
	 */
	public Collection<AdKeyword> getAdKeywordList(AdKeyword adKeyword) {
		return goodsDao.getAdKeywordList(adKeyword);
	}

	/**
	 * 광고 키워드 상품 목록
	 *
	 * @param adKeyword
	 * @return
	 * @author eskim
	 * @since 2020. 12. 15
	 */
	public Collection<AdKeywordGoods> getAdKeywordGoodsList(AdKeyword adKeyword) {
		return goodsDao.getAdKeywordGoodsList(adKeyword);
	}

	/**
	 * 광고 키워드 저장
	 * @param adKeyword
	 * @return
	 * @author eskim
	 * @since 2020. 12. 15
	 */
	@Transactional("shopTxnManager")
	public void saveAdKeywordGoods(AdKeyword adKeyword) {
		adKeyword.setRegNo(TsaSession.getInfo().getUserNo());
		adKeyword.setUpdNo(TsaSession.getInfo().getUserNo());

		// 신규 일때
		if (adKeyword.getAdKeywordSq() == null) {
			// 공지사항 저장
			goodsDao.saveAdKeyword(adKeyword);

			// 등록된 사용자번호 값 가져오기
			Integer noticeSq = adKeyword.getAdKeywordSq();

			adKeyword.setAdKeywordSq(noticeSq);

		} else {
			// 공지사항 수정
			goodsDao.saveAdKeyword(adKeyword);
		}

		if (!StringUtils.isEmpty(adKeyword.getGoodsList())) {
			Collection<AdKeywordGoods> adKeywordGoodsList = null;
			try {
				adKeywordGoodsList = mapper.readValue(adKeyword.getGoodsList(), new TypeReference<Collection<AdKeywordGoods>>() {
				});
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException(message.getMessage("광고 키워드 저장 중 오류로 인해 저장되지 않았습니다."));
			}
			log.info("adKeywordGoodsList: {}", adKeywordGoodsList);

			int idx = 0;
			for (AdKeywordGoods adKeywordGoods : adKeywordGoodsList) {
				if (idx == 0) goodsDao.deleteAdKeywordGoods(adKeywordGoods); // 전체 상품 삭제
				adKeywordGoods.setAdKeywordSq(adKeyword.getAdKeywordSq());
				adKeywordGoods.setRegNo(TsaSession.getInfo().getUserNo());
				adKeywordGoods.setUpdNo(TsaSession.getInfo().getUserNo());

				goodsDao.saveAdKeywordGoods(adKeywordGoods);
				idx++;
			}
		}
	}

	/**
	 * 광고 키워드 상품 삭제
	 * @param adKeywordGoods
	 * @return
	 * @author eskim
	 * @since 2020. 12. 15
	 */
	@Transactional("shopTxnManager")
	public void deleteAdKeywordGoods(AdKeywordGoods adKeywordGoods) {

		if (adKeywordGoods == null || (adKeywordGoods.getArrGoodsCd() == null && adKeywordGoods.getArrGoodsCd().length <= 0)) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		if (adKeywordGoods.getArrGoodsCd().length > 0) {
			goodsDao.deleteAdKeywordGoods(adKeywordGoods);
		}
	}

	/**
	 * 재입고알림 목록 건수
	 *
	 * @param goodsSearch
	 * @return Integer
	 * @author eskim
	 * @since 2020. 12. 16
	 */
	public int getReinboundInformCount(GoodsSearch goodsSearch) {
		return goodsDao.getReinboundInformCount(goodsSearch);
	}

	/**
	 * 재입고알림 목록
	 *
	 * @param goodsSearch
	 * @return Collection<ReinboundInform>
	 * @author eskim
	 * @since 2020. 12. 16
	 */
	public Collection<ReinboundInform> getReinboundInformList(GoodsSearch goodsSearch) {
		return goodsDao.getReinboundInformList(goodsSearch);
	}


	/**
	 * 재입고알림 발송 처리
	 *
	 * @param params
	 * @return void
	 * @author daehyoung
	 * @since 2020. 07 .21
	 */
	@Transactional("shopTxnManager")
	public void sendReinboundInform(ReinboundInform reinboundInform) {

		if (reinboundInform.getArrRinbdInfoSq().length <= 0) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		int idx = 0;
		for (String rinbdInfoSq : reinboundInform.getArrRinbdInfoSq()) {

			GoodsSearch goodsSearch = new GoodsSearch();
			goodsSearch.setRinbdInfoSq(Integer.parseInt(rinbdInfoSq));

			Collection<ReinboundInform> list = goodsDao.getReinboundInformList(goodsSearch);
			ReinboundInform oneParam = null;
			if (list.size() == 1) {
				oneParam = list.iterator().next();
			} else {
				continue;
			}

			// 재고체크
			if (oneParam.getCurrStockQty() < 1 || "Y".equals(oneParam.getSoldoutYn())) {
				throw new IllegalStateException(oneParam.getGoodsCd() + "상품( 사이즈 : " + oneParam.getOptCd1() + " )은 가용재고가 없습니다.");
			}

			oneParam.setRegNo(TsaSession.getInfo().getUserNo());
			oneParam.setUpdNo(TsaSession.getInfo().getUserNo());

			// **** 알림톡 발송 start ****
			try {
				log.info("[카카오 알림톡 발송 정보] - 재입고알림 발송: " + oneParam.toString());
				/////////////////////////////////////////////////////
				//kakaoService.sendGoodsRestock(oneParam);	//나중에 수정해요 eskim
				/////////////////////////////////////////////////////
			} catch (Exception e) {
				e.getStackTrace();
				throw new IllegalStateException("재입고알림 알림톡 발송을 실패하였습니다.");
			}
			// **** 알림톡 발송 end ****

			// 재입고알림 발송처리
			goodsDao.updateReinboundInform(oneParam);
			idx++;
		}
	}

	/**
	 * 상품이미지 목록
	 *
	 * @param goodsImg
	 * @return Collection<GoodsImg>
	 * @author eskim
	 * @since 2020. 12. 18
	 */
	public Collection<GoodsImg> getGoodsImgList(GoodsImg goodsImg) {
		return goodsDao.getGoodsImageList(goodsImg);
	}

	/**
	 * 상품이미지 저장 처리
	 * @param goodsImgList - 상품이미지 목록
	 * @throws AdmBizException
	 * @author eskim
	 * @since 2020. 12. 21
	 */
	@Transactional("shopTxnManager")
	public void saveGoodsImageList(Collection<GoodsImg> goodsImgList){
		int index = 0;
		for (GoodsImg goodsImg : goodsImgList) {
			// 상품이미지 전체 삭제
			if (index++ == 0) {
				goodsDao.deleteGoodsImageTotal(goodsImg);
			}

			if (!goodsImg.getMode().equals("D")) {
				// 상품이미지 등록
				goodsImg.setRegNo(TsaSession.getInfo().getUserNo());
				goodsDao.createGoodsImage(goodsImg);
			}
		}
	}

}
