package com.style24.scm.biz.web;

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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.TssPageRequest;
import com.style24.persistence.domain.GoodsSearch;
import com.style24.scm.biz.service.TssGoodsService;
import com.style24.scm.biz.service.TssRendererService;
import com.style24.scm.support.controller.TssBaseController;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

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

/**
 * 상품관리 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;

	/**
	 * 상품목록 화면
	 *
	 * @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";
		}
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, selfYn));
		// 상품상태
		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"));
		// 년도
		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);
	}
}
