package com.style24.scm.biz.web;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.TssPageRequest;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.GoodsHst;
import com.style24.persistence.domain.GoodsImg;
import com.style24.persistence.domain.GoodsNotiInfo;
import com.style24.persistence.domain.GoodsPriceRes;
import com.style24.persistence.domain.GoodsSearch;
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.User;
import com.style24.scm.biz.service.TssCommonService;
import com.style24.scm.biz.service.TssGoodsService;
import com.style24.scm.biz.service.TssRendererService;
import com.style24.scm.biz.service.TssSystemService;
import com.style24.scm.support.controller.TssBaseController;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.excel.GagaExcelUtil;
import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.rest.server.GagaResponse;
import com.gagaframework.web.rest.server.GagaResponseStatus;
import com.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.gagaframework.web.util.GagaStringUtil;

/**
 * 상품관리 Controller
 *
 * @author gagamel
 * @since 2020. 10. 19
 */
@Controller
@RequestMapping("/goods")
@Slf4j
public class TssGoodsController extends TssBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TssGoodsService goodsService;

	@Autowired
	private TssRendererService rendererService;

	@Autowired
	private TssCommonService commonService;

	@Autowired
	private TssSystemService systemService;

	/**
	 * 상품목록 화면
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@GetMapping("/list/form")
	public ModelAndView listForm() {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		String supplyCompCd = "";
		String selfYn = "Y";
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {	//입점업체담당자
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "N";
		} else if ("G001_E000".equals(TssSession.getInfo().getRoleCd())) {	// 촬영업체
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "Y";
		}
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, selfYn));
		// 상품상태
		String[] exceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", exceptCds));

		// 상품상태
		String[] statChangeExceptCds = {"G008_00", "G008_90"};
		mav.addObject("goodsStatChangeList", rendererService.getCommonCodeList("G008", "Y", statChangeExceptCds));
		// 정상이월
		mav.addObject("formalGbList", rendererService.getAvailCommonCodeList("G009"));
		// 성별
		mav.addObject("sexGbList", rendererService.getAvailCommonCodeList("G007"));
		// 시즌
		mav.addObject("seasonList", rendererService.getAvailCommonCodeList("G006"));
		// 년도
		int toYear = Integer.parseInt(GagaDateUtil.getToday("yyyy")) - 4;
		mav.addObject("styleYearList", rendererService.getYearList(toYear, 0, 5));
		// 연령대
		mav.addObject("ageGrpCdList", rendererService.getAvailCommonCodeList("G023"));
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));
		// 품목
		mav.addObject("itemkindList", rendererService.getAllItemkindList());
		// 상품유형
		mav.addObject("goodsTypeList", rendererService.getAvailCommonCodeList("G056"));
		// MD
		mav.addObject("brandMdList", rendererService.getBrandMdList());

		mav.setViewName("goods/GoodsListForm");

		return mav;
	}

	/**
	 * 상품목록 조회
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 10. 20
	 */
	@PostMapping("/list")
	@ResponseBody
	public GagaMap getGoodsList(@RequestBody GoodsSearch goodsSearch) {

		GagaMap result = new GagaMap();

		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			goodsSearch.setSupplyCompCd(TssSession.getInfo().getSupplyCompCd());
			goodsSearch.setMdNo(TssSession.getInfo().getUserNo().toString());
		}

		// multi row 검색관련 처리
		if (!StringUtils.isEmpty(goodsSearch.getCondition())) {
			goodsSearch.setConditionList(goodsSearch.getCondition().replaceAll("\r", "").split("\n"));

			if ("searchExtendGoodsCd".equals(goodsSearch.getSearch())) {
				goodsSearch.setSearchGb("EXTEND");
			} else if ("searchMasterGoodsCd".equals(goodsSearch.getSearch())) {
				goodsSearch.setSearchGb("MASTER");
			}
		}

		goodsSearch.setRegNo(TssSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		goodsSearch.setPageable(new TssPageRequest(goodsSearch.getPageNo() - 1, goodsSearch.getPageSize()));
		goodsSearch.getPageable().setTotalCount(goodsService.getGoodsListCount(goodsSearch));

		result.set("pageing", goodsSearch);
		result.set("goodsList", goodsService.getGoodsList(goodsSearch));

		return result;
	}

	/**
	 * 상품목록 - 기본정보 엑셀다운로드
	 *
	 * @param goodsSearch
	 * @return
	 * @author eskim
	 * @since 2020. 10. 21
	 */
	@GetMapping("/info/excel/list")
	public ResponseEntity<InputStreamResource> downloadGoodsInfoExcelList(HttpServletRequest request, GoodsSearch goodsSearch) throws Exception {
		String excelfileName = "상품_기본정보_" + GagaDateUtil.getTodayDateTime() + ".xlsx";
		String excelFilenameWithPath = GagaFileUtil.getConcatenationPath(env.getProperty("download.path"), "excel", excelfileName);

		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			goodsSearch.setSupplyCompCd(TssSession.getInfo().getSupplyCompCd());
			goodsSearch.setMdNo(TssSession.getInfo().getUserNo().toString());
		}
		goodsSearch.setRegNo(TssSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용

		// multi row 검색관련 처리
		if (!StringUtils.isEmpty(goodsSearch.getCondition())) {
			goodsSearch.setConditionList(goodsSearch.getCondition().replaceAll("\r", "").split("\n"));

			if ("searchExtendGoodsCd".equals(goodsSearch.getSearch())) {
				goodsSearch.setSearchGb("EXTEND");
			} else if ("searchMasterGoodsCd".equals(goodsSearch.getSearch())) {
				goodsSearch.setSearchGb("MASTER");
			}
		}

		// 대용량엑셀파일다운로드는 이런 식으로 ...
		goodsService.getGoodsInfoExcelList(goodsSearch, excelFilenameWithPath);

		return GagaFileUtil.writeFile(request, excelFilenameWithPath);
	}

	/**
	 * 상품 수정 항목 일괄변경
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 01. 17
	 */
	@PostMapping("/state/update")
	@ResponseBody
	public GagaMap updateGoodsState(@RequestBody Goods goods) {

		GagaMap result = new GagaMap();
		result.set("status", GagaResponseStatus.SUCCESS.getCode()); // 200
		result.set("procJob", goods.getProcJob());
		// result.set("message", message.getMessage("SUCC_0001"));

		String returnGoods = "";
		String resultFlag = "SUCC";

		// 입점 담당자만 일괄 변경 가능
		if (!"G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			throw new IllegalStateException("권한이 없습니다.");
		}

		// 상품 상태 변경일 경우 체크
		if ("goodsStat".equals(goods.getProcJob()) && ("G008_40".equals(goods.getGoodsStat()))) {

			// 이미지
			Collection<Goods> goodsList = goodsService.getGoodsImgsYn(goods);

			for (Goods tmpGoods : goodsList) {
				if ("N".equals(tmpGoods.getGoodsImageYn())) {
					returnGoods += tmpGoods.getGoodsCd() + ",";
				} else {

					// 택가/판매가 입력 여부 확인
					Goods dataGoods = goodsService.getGoods(tmpGoods);
					if (dataGoods == null) {
						returnGoods += tmpGoods.getGoodsCd() + ",";
						continue;
					}
					if (dataGoods.getListPrice() <= 0 || dataGoods.getCurrPrice() <= 0) {
						returnGoods += tmpGoods.getGoodsCd() + ",";
						continue;
					}
					// 사이즈 등록 여부 확인
					if ("G056_N".equals(dataGoods.getGoodsType())) {
						Option stock = new Option();
						stock.setGoodsCd(tmpGoods.getGoodsCd());
						int stockCnt = goodsService.getGoodsOptionCount(stock);
						if (stockCnt <= 0) {
							returnGoods += tmpGoods.getGoodsCd() + ",";
							continue;
						}
					}

					//고시정보
					GoodsNotiInfo goodsNotiInfo = new GoodsNotiInfo();
					goodsNotiInfo.setGoodsCd(tmpGoods.getGoodsCd());
					goodsNotiInfo.setSupplyCompCd(tmpGoods.getSupplyCompCd());
					goodsNotiInfo.setNiClsfCd(tmpGoods.getNiClsfCd());
					Collection<GoodsNotiInfo> goodsNotiInfoList = goodsService.getGoodsNotiInfoList(goodsNotiInfo);
					if (goodsNotiInfoList == null || goodsNotiInfoList.isEmpty()) {
						returnGoods += tmpGoods.getGoodsCd() + ",";
					} else {
						for (GoodsNotiInfo tmpGoodsNotiInfo : goodsNotiInfoList) {
							if ("Y".equals(tmpGoodsNotiInfo.getReqYn()) || "Y".equals(tmpGoodsNotiInfo.getDispYn())) {
								if (StringUtils.isEmpty(tmpGoodsNotiInfo.getNiContent())) {
									returnGoods += tmpGoods.getGoodsCd() + ",";
									break;
								}
							}
						}
					}
				}
			}

			if (returnGoods.length() > 0) {
				returnGoods = returnGoods.substring(0, returnGoods.lastIndexOf(","));
				returnGoods = returnGoods.replaceAll(",", ",<br/>");
				resultFlag = "FAIL";
				result.set("resultFlag", resultFlag);
				result.set("returnGoods", returnGoods);
				return result;
			}
		}

		goodsService.updateGoodsState(goods);

		result.set("resultFlag", resultFlag);
		result.set("returnGoods", returnGoods);
		return result;
	}

	/**
	 * 엑셀조회용 상품 저장
	 *
	 * @param goods
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 10. 20
	 */
	@PostMapping("/search/excelupload/save")
	@ResponseBody
	public GagaResponse saveExceluploadGoods(@RequestBody Goods goods) throws Exception {

		int cnt = 0;
		ObjectMapper mapper = new ObjectMapper();

		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.excel.target.path"), "excel");

		// DB 처리 시 사용되는 파라미터명(셀명) 설정
		String[] cellName = {"goodsCd", "supplyGoodsCd"};

		Collection<GagaMap> ecxelGoodsList = GagaExcelUtil.getList(GagaFileUtil.getConcatenationPath(targetPath, goods.getExcelFileNm()), 0, cellName, 0);

		Collection<Goods> goodsList = new ArrayList<>();
		for (GagaMap map : ecxelGoodsList) {
			Goods tmpGoods = mapper.convertValue(map, Goods.class);
			tmpGoods.setRegNo(TssSession.getInfo().getUserNo());
			tmpGoods.setProcJob(goods.getProcJob());
			goodsList.add(tmpGoods);
			cnt++;
		}

		goodsService.saveExceluploadGoods(goodsList, goods.getExcelFileNm());

		// 파일 삭제
		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, goods.getExcelFileNm()));

		return super.ok("");
	}

	/**
	 * 엑셀 업로드 상품 조회
	 *
	 * @param
	 * @return GagaMap
	 * @author eskim
	 * @since 2020. 11. 02
	 */
	@PostMapping("/excel/upload/goods/list")
	@ResponseBody
	public GagaMap getExcelUploadGoodsList() {
		GagaMap result = new GagaMap();
		GoodsSearch goodsSearch = new GoodsSearch();
		goodsSearch.setSearchGb("EXCEL");
		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			goodsSearch.setSupplyCompCd(TssSession.getInfo().getSupplyCompCd());
			goodsSearch.setMdNo(TssSession.getInfo().getUserNo().toString());
		}
		goodsSearch.setRegNo(TssSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		result.set("goodsExcelList", goodsService.getGoodsList(goodsSearch));
		return result;
	}

	/**
	 * 상품 상세 화면
	 *
	 * @param goodsCode - 상품코드
	 * @return
	 * @author eskim
	 * @since 2020. 10. 23
	 */
	@GetMapping("/detail/form")
	@ResponseBody
	public ModelAndView detailForm(Goods goods) {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		String supplyCompCd = "";
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd));
//		String selfYn = "Y";
//		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
//			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
//			selfYn = "N";
//		}
//		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, selfYn));

		String[] goodsStatExceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", goodsStatExceptCds));

		// 정상이월
		mav.addObject("formalGbList", rendererService.getAvailCommonCodeList("G009"));
		// 성별
		mav.addObject("sexGbList", rendererService.getAvailCommonCodeList("G007"));
		// 시즌
		mav.addObject("seasonList", rendererService.getAvailCommonCodeList("G006"));
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));
		// 품목
		mav.addObject("itemkindList", rendererService.getAllItemkindList());
		// 정보고시 분류
		mav.addObject("niClsfCdList", rendererService.getAvailCommonCodeList("G004"));
		// 사용자 브랜드 조회
		mav.addObject("authBrandList", rendererService.getAuthBrandList(TssSession.getInfo().getUserNo()));
		// 상품타입
		mav.addObject("goodsTypeList", rendererService.getAvailCommonCodeList("G056"));
		// 상품구분
		mav.addObject("goodsGbList", rendererService.getAvailCommonCodeList("G073"));
		// 유통구분
		//String[] distributionGbExceptCds = {"G065_20"};
		//mav.addObject("distributionGbList", rendererService.getCommonCodeList("G065", "Y", distributionGbExceptCds));
		mav.addObject("distributionGbList", rendererService.getCommonCodeList("G065", "Y"));
		// 상품연령대
		mav.addObject("ageGrpCdList", rendererService.getAvailCommonCodeList("G023"));
		// 년도
		int toYear = Integer.parseInt(GagaDateUtil.getToday("yyyy")) - 4;
		mav.addObject("styleYearList", rendererService.getYearList(toYear, 0, 5));
		// 회원등급
		//mav.addObject("custGradeList", rendererService.getAvailCommonCodeList("G101"));

		mav.addObject("params", goods);

		mav.setViewName("goods/GoodsDetailForm");

		return mav;
	}

	/**
	 * 상품 상세 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2019. 12. 11
	 */
	@PostMapping("/detail")
	@ResponseBody
	public Goods getGoodsDetail(Goods goods) {
		return goodsService.getGoods(goods);
	}

	/**
	 * 상품 이력 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2019. 12. 12
	 */
	@GetMapping("/detail/hst/list")
	@ResponseBody
	public Collection<GoodsHst> getGoodsDetailHstList(Goods goods) {
		return goodsService.getGoodsHstList(goods);
	}

	/**
	 * 컬러 옵셥 재고
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 26
	 */
	@PostMapping("/detail/sizeStock/form")
	public ModelAndView getGoodsDetailSizeStockForm(Goods goods) {

		ModelAndView mav = new ModelAndView();
		mav.addObject("goods", goodsService.getGoods(goods));
		mav.addObject("goodsSizeList", goodsService.getGoodsSizeList(goods));
		mav.addObject("goodsColorList", goodsService.getGoodsColorList(goods));
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));

		mav.setViewName("goods/GoodsDetailSizeStockForm");

		return mav;
	}

	/**
	 * 상품 정보고시 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2019. 12. 12
	 */
	@PostMapping("/detail/notiInfo/list")
	@ResponseBody
	public Collection<GoodsNotiInfo> getGoodsDetailNotiInfoList(Goods goods) {

		GoodsNotiInfo goodsInfo = new GoodsNotiInfo();
		goodsInfo.setGoodsCd(goods.getGoodsCd());
		goodsInfo.setNiClsfCd(goods.getNiClsfCd());
		goodsInfo.setSupplyCompCd(goods.getSupplyCompCd());

		return goodsService.getGoodsNotiInfoList(goodsInfo);
	}

	/**
	 * 상품 구매등급 조회
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 12. 11
	 */
	@PostMapping("/detail/order/grade/list")
	@ResponseBody
	public Collection<Goods> getGoodsDetailOrderGradeList(Goods goods) {
		return goodsService.getGoodsDetailOrderGradeList(goods);
	}

	/**
	 * 상품의 정보고시 항목 목록
	 *
	 * @param notiInfo
	 * @return
	 * @author eskim
	 * @since 2010. 11. 18
	 */
	@PostMapping("/noti/goodsInfo/list")
	@ResponseBody
	public Collection<NotiInfo> getNotiGoodsInfoList(NotiInfo notiInfo) {
		return goodsService.getNotiGoodsInfoList(notiInfo);
	}

	/**
	 * 상품 상세 저장
	 *
	 * @param goods
	 * @return
	 * @author eskim
	 * @since 2020. 10. 27
	 */
	@PostMapping("/detail/save")
	@ResponseBody
	public GagaResponse saveGoodsDetail(@RequestBody Goods goods) {

		// 상품상태에 따른 이미지 정보 확인 - 상품상태가 승인대기일 경우
		if ("G008_40".equals(goods.getGoodsStat())) {
			Collection<Goods> goodsList = goodsService.getGoodsImgsYn(goods);
			String goodsImageYn = "N";
			for (Goods tmpGoods : goodsList) {
				goodsImageYn = tmpGoods.getGoodsImageYn();
			}
			if ("N".equals(goodsImageYn)) {
				throw new IllegalStateException("필수 이미지가 등록되지 않은 상품은 <br/>'승인대기' 상태로 변경할 수 없습니다.");
			}
		}

		Collection<GoodsNotiInfo> notiList = null;
//		Collection<GoodsCompose> goodComposeList = null;
		ObjectMapper mapper = new ObjectMapper();
		try {
			if (goods.getNotiList() != null) {
				notiList = mapper.readValue(goods.getNotiList(), new TypeReference<Collection<GoodsNotiInfo>>() {
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//		try {
//			if (goods.getGoodsComposeList() != null) {
//				goodComposeList = mapper.readValue(goods.getGoodsComposeList(), new TypeReference<Collection<GoodsCompose>>() {
//				});
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}

		goods.setNotiListNew(notiList);
//		goods.setGoodsComposeListNew(goodComposeList);

		goodsService.saveGoodsDetail(goods);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 상품 이미지 보기 화면
	 *
	 * @param goodsCode - 상품코드
	 * @return
	 * @author eskim
	 * @since 2020. 12. 23
	 */
	@GetMapping("/image/form")
	@ResponseBody
	public ModelAndView imageMassForm(GoodsImg goodsImg) {
		ModelAndView mav = new ModelAndView();

		Collection<GoodsImg> goodsImgList = goodsService.getGoodsImgList(goodsImg);

		if (goodsImgList != null && !goodsImgList.isEmpty()) {

			mav.addObject("goodsImgList", goodsImgList);

			for (GoodsImg goodsImgInfo : goodsImgList) {
				if (goodsImgInfo.getDefaultImgYn().equals("Y")) {
					mav.addObject("defaultImgOrd", goodsImgInfo.getDispOrd());
				}
			}
		} else { // 대표이미지와 마우스오버이미지가 없으면
			mav.addObject("goodsImgList", new ArrayList<GoodsImg>());
			mav.addObject("defaultImgOrd", "1");
		}

		mav.addObject("goodsImg", goodsImg);
		mav.setViewName("goods/GoodsImageForm");
		return mav;
	}

	/**
	 * 상품 썸네일 이미지 저장 처리
	 * @param goodsImgList - 상품이미지 목록
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 112. 23
	 */
	@RequestMapping(value = "/thumbnail/image/save", method = RequestMethod.POST)
	@ResponseBody
	public GagaResponse saveGoodsThumbnailImageList(@RequestBody Collection<GoodsImg> goodsImgList) throws Exception {
		if (goodsImgList == null || goodsImgList.isEmpty())
			throw new IllegalStateException(message.getMessage("FAIL_1001"));

		String dextUploadPath = env.getProperty("upload.dext.target.path");
		String goodsTargetPath = env.getProperty("upload.goods.target.path");

		int index = 1;
		String strBrandNo = "";

		// 오류 파일 목록
		Collection<File> errorFileList = new ArrayList<File>();

		// 1.업로드된 파일 rename 및 순서 재정렬
		for (GoodsImg goodsImg : goodsImgList) {
			// dx5에서 삭제한 파일은 skip
			if (goodsImg.getMode().equals("D")) {
				continue;
			}

			// 상품의 브랜드 번호 추출
			if (strBrandNo.isEmpty()) {
				Goods goods = new Goods();
				goods.setGoodsCd(goodsImg.getGoodsCd());
				Goods goodsInfo = goodsService.getGoods(goods);
				if (goodsInfo == null || goodsInfo.getGoodsCd().isEmpty())
					throw new IllegalStateException(message.getMessage("FAIL_1001"));

				strBrandNo = String.valueOf(goodsInfo.getBrandNo());
			}
			String brandDir = GagaStringUtil.getLPadding(strBrandNo, 10, "0");

			if (goodsImg.getMode().equals("C")) { // 업로드 된 파일 rename 처리
//				String newFilename = goodsImg.getGoodsCd()
//						+ "_" + goodsImg.getColorCd()
//						+ "_" + String.valueOf(index)
//						+ "(" + GagaDateUtil.getTodayTime() + ")"
//						+ "." + StringUtils.getFilenameExtension(goodsImg.getSysImgNm());
				String newFilename = goodsImg.getSysImgNm();

				//브랜드 폴더 확인
				String goodsUploadPath = GagaFileUtil.getConcatenationPath(goodsTargetPath, brandDir); // 브랜드 폴더
				File brandPath = new File(goodsUploadPath);
				if (!brandPath.exists()) {
					brandPath.mkdir();
				}

				goodsUploadPath = GagaFileUtil.getConcatenationPath(goodsUploadPath, GagaDateUtil.getToday());		//브랜드+/+YYYYMMDD(UPLOAD 일 )
				String brandYmdDir = GagaFileUtil.getConcatenationPath(brandDir, GagaDateUtil.getToday());	//디비 저장용

				File uniqueFile = GagaFileUtil.getUniqueFile(new File(GagaFileUtil.getConcatenationPath(goodsUploadPath, newFilename)));
				File newFile = new File(GagaFileUtil.getConcatenationPath(goodsUploadPath,  uniqueFile.getName()));
				log.info("newFile.getPath(): {}", newFile.getPath());

				// resizing 처리 시 오류가 발생할 경우 삭제하기 위해 설정
				errorFileList.add(newFile);

				File oldFile = new File(GagaFileUtil.getConcatenationPath(dextUploadPath, goodsImg.getSysImgNm()));
				log.info("oldFile.getPath(): {}", oldFile.getPath());

				File path = new File(goodsUploadPath);
				if (!path.exists()) {
					log.info("mkdir ={}", goodsUploadPath);
					path.mkdir();
				}

				boolean copyFlag = GagaFileUtil.copyFile(oldFile, newFile);
				if (copyFlag) {
					//기존이미지 삭제
					GagaFileUtil.deleteFile(oldFile.getPath());
				}

				goodsImg.setDispOrd(index++);
				goodsImg.setOrgImgNm(GagaFileUtil.getConcatenationPath(brandYmdDir,newFile.getName()));
				goodsImg.setSysImgNm(GagaFileUtil.getConcatenationPath(brandYmdDir,newFile.getName()));
			} else {
				goodsImg.setOrgImgNm(GagaFileUtil.getConcatenationPath(goodsImg.getSysImgUrl() ,goodsImg.getSysImgNm()));
				goodsImg.setSysImgNm(GagaFileUtil.getConcatenationPath(goodsImg.getSysImgUrl() ,goodsImg.getSysImgNm()));
				goodsImg.setDispOrd(index++);
			}
		}

		// 2.dx5에서 삭제한 파일 실제 삭제 처리
		for (GoodsImg goodsImg : goodsImgList) {
			if (goodsImg.getMode().equals("D")) {
				log.info("Original file to delete: {}", GagaFileUtil.getConcatenationPath(goodsTargetPath, goodsImg.getSysImgUrl(), goodsImg.getSysImgNm()));

				// 상품이미지 삭제
				GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(goodsTargetPath, goodsImg.getSysImgUrl(), goodsImg.getSysImgNm()));

			}
		}

		// 상품이미지 저장 처리
		goodsService.saveGoodsImageList(goodsImgList);

		return super.ok(message.getMessage("SUCC_0007"));
	}

	/**
	 * 상품 이미지 대량관리 화면(자사)
	 *
	 * @param goodsCode - 상품코드
	 * @return
	 * @author eskim
	 * @since 2020. 11. 09
	 */
	@GetMapping("/image/mass/form")
	@ResponseBody
	public ModelAndView imageMassForm(Goods goods) {
		ModelAndView mav = new ModelAndView();

//		goods = goodsService.getGoods(goods);
//		// mav.addObject("goodsImgList", goodsService.getGoodsImgList(goods)); //이미지 - 행
//		mav.addObject("goodsImgInfo", goodsService.getGoodsImg(goods)); // 이미지 - 열
//
		mav.addObject("params", goods);
		mav.setViewName("goods/GoodsImageMassForm");
		return mav;
	}

	/**
	 * 상품 대량 등록 화면
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@GetMapping("/mass/register/form")
	public ModelAndView massRegisterForm() {
		ModelAndView mav = new ModelAndView();

		// 상품상태
		mav.addObject("goodsStatList", rendererService.getAvailCommonCodeList("G008"));
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));
		// ERP 연동여부
		mav.addObject("erpSyncYn", commonService.getErpSyncYn());
		// 정보고시 목록
		mav.addObject("niClsfCdList", rendererService.getAvailCommonCodeList("G004"));
		// 사용자 업체
		User loginInfo = systemService.getUser(TssSession.getInfo().getUserNo());
		String supplyCompCd = "NONE";
		if (loginInfo != null) {
			supplyCompCd = loginInfo.getSupplyCompCd();
		}
		mav.addObject("supplyCompCd", supplyCompCd);
		mav.setViewName("goods/GoodsMassRegisterForm");

		return mav;
	}

	/**
	 * 입점 가격 관리 화면
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@GetMapping("/supply/price/form")
	public ModelAndView priceForm() {
		ModelAndView mav = new ModelAndView();
		// 공급업체
		String supplyCompCd = "";
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
		}
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, "N"));
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));
		// 상품상태
		String[] exceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", exceptCds));
		// 정상이월
		mav.addObject("formalGbList", rendererService.getAvailCommonCodeList("G009"));
		mav.setViewName("goods/GoodsSupplyPriceForm");

		return mav;
	}

	/**
	 * 상품 가격승인관리 목록 조회
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 11. 26
	 */
	@PostMapping("/supply/price/list")
	@ResponseBody
	public GagaMap getGoodsSupplyPriceList(@RequestBody GoodsPriceRes goodsPriceRes) {

		GagaMap result = new GagaMap();


		goodsPriceRes.setRegNo(TssSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		goodsPriceRes.setPageable(new TssPageRequest(goodsPriceRes.getPageNo() - 1, goodsPriceRes.getPageSize()));
		goodsPriceRes.getPageable().setTotalCount(goodsService.getGoodsSupplyPriceCount(goodsPriceRes));

		result.set("pageing", goodsPriceRes);
		result.set("goodsList", goodsService.getGoodsSupplyPriceList(goodsPriceRes));

		return result;
	}

	/**
	 * 상품 상세공지 화면
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 10. 16
	 */
	@GetMapping("/notice/form")
	public ModelAndView detailNoticeForm() {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		String supplyCompCd = "";
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
		}
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, "N"));

		mav.setViewName("goods/GoodsNoticeForm");

		return mav;
	}

	/**
	 * 상품 상세공지 목록
	 * @param notice - 공지사항 정보
	 * @return
	 * @author eskim
	 * @since 2020. 11. 27
	 */
	@PostMapping("/notice/list")
	@ResponseBody
	public Collection<Notice> getNoticeList(@RequestBody GoodsSearch goodsSearch) {

		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			goodsSearch.setSupplyCompCd(TssSession.getInfo().getSupplyCompCd());
			goodsSearch.setMdNo(TssSession.getInfo().getUserNo().toString());
		}

		// multi row 검색관련 처리
		if (!StringUtils.isEmpty(goodsSearch.getCondition())) {
			goodsSearch.setConditionList(goodsSearch.getCondition().replaceAll("\r", "").split("\n"));
		}

		return goodsService.getNoticeList(goodsSearch);
	}

	/**
	 * 상품 상세공지 상품목록
	 * @param notice - 공지사항 정보
	 * @return
	 * @author eskim
	 * @since 2020. 11. 27
	 */
	@GetMapping("/notice/goods/list/{noticeSq}")
	@ResponseBody
	public Collection<NoticeGoods> getNoticeGoodsList(@PathVariable Integer noticeSq) {
		Notice notice = new Notice();
		notice.setNoticeSq(noticeSq);
		return goodsService.getNoticeGoodsList(notice);
	}

	/**
	 * 상품 상세공지 저장/등록
	 *
	 * @param
	 * @return
	 * @author eskim
	 * @since 2020. 11. 27
	 */
	@PostMapping("/notice/save")
	@ResponseBody
	public GagaResponse saveNotice(@RequestBody Notice notice) {
		goodsService.saveNotice(notice);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 상품 상세공지상품 삭제
	 *
	 * @param
	 * @return
	 * @author eskim
	 * @since 2020. 11. 09
	 */
	@PostMapping("/notice/goods/delete")
	@ResponseBody
	public GagaResponse deleteNoticeGoods(@RequestBody NoticeGoods noticeGoods) {
		goodsService.deleteNoticeGoods(noticeGoods);
		return super.ok(message.getMessage("SUCC_0003"));
	}

	/**
	 * 상품조회 팝업
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 10. 26
	 */
	@GetMapping("/popup/list/form")
	@ResponseBody
	public ModelAndView relationListForm(GoodsSearch goodsSearch) {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		String supplyCompCd = "";
		String selfYn = "Y";
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "N";
		}
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, selfYn));
		//mav.addObject("supplyCompList", rendererService.getSupplyCompanyList());
		// 상품상태
		String[] exceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", exceptCds));
		// 정상이월
		mav.addObject("formalGbList", rendererService.getAvailCommonCodeList("G009"));
		// 성별
		mav.addObject("sexGbList", rendererService.getAvailCommonCodeList("G007"));
		// 시즌
		mav.addObject("seasonList", rendererService.getAvailCommonCodeList("G006"));
		// 연령대
		mav.addObject("ageGrpCdList", rendererService.getAvailCommonCodeList("G023"));
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));
		// 품목
		mav.addObject("itemkindList", rendererService.getAllItemkindList());
		// 상품유형
		mav.addObject("goodsTypeList", rendererService.getAvailCommonCodeList("G056"));
		// MD
		mav.addObject("brandMdList", rendererService.getBrandMdList());
		// 년도
		int toYear = Integer.parseInt(GagaDateUtil.getToday("yyyy")) - 4;
		mav.addObject("styleYearList", rendererService.getYearList(toYear,0,5));

		mav.addObject("params", goodsSearch);

		mav.setViewName("goods/GoodsPopupListForm");

		return mav;
	}

	/**
	 * 상품조회 팝업 조회
	 *
	 * @return
	 * @author eskim
	 * @since 2020. 10. 26
	 */
	@PostMapping("/popup/list")
	@ResponseBody
	public GagaMap getPopupGoodsList(@RequestBody GoodsSearch goodsSearch) {

		GagaMap result = new GagaMap();

		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			goodsSearch.setSupplyCompCd(TssSession.getInfo().getSupplyCompCd());
			goodsSearch.setMdNo(TssSession.getInfo().getUserNo().toString());
		}

		// multi row 검색관련 처리
		if (!StringUtils.isEmpty(goodsSearch.getCondition())) {
			goodsSearch.setConditionList(goodsSearch.getCondition().replaceAll("\r", "").split("\n"));

			if ("searchExtendGoodsCd".equals(goodsSearch.getSearch())) {
				goodsSearch.setSearchGb("EXTEND");
			} else if ("searchMasterGoodsCd".equals(goodsSearch.getSearch())) {
				goodsSearch.setSearchGb("MASTER");
			}
		}

		goodsSearch.setRegNo(TssSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		goodsSearch.setPageable(new TssPageRequest(goodsSearch.getPageNo() - 1, goodsSearch.getPageSize()));
		goodsSearch.getPageable().setTotalCount(goodsService.getGoodsListCount(goodsSearch));

		result.set("pageing", goodsSearch);
		result.set("goodsList", goodsService.getGoodsList(goodsSearch));

		return result;
	}
}
