package com.style24.admin.biz.web;

import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
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.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.databind.ObjectMapper;
import com.style24.admin.biz.service.TsaRendererService;
import com.style24.admin.biz.service.TsaStockService;
import com.style24.admin.support.controller.TsaBaseController;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.TscPageRequest;
import com.style24.persistence.domain.Color;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.GoodsSearch;
import com.style24.persistence.domain.Option;

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

/**
 * 상품 재고 Controller
 *
 * @author eskim
 * @since 2020. 11. 17
 */
@Controller
@RequestMapping("/stock")
@Slf4j
public class TsaStockController extends TsaBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TsaStockService stockService;

	@Autowired
	private TsaRendererService rendererService;

	@Autowired
	private ObjectMapper mapper;
	
	private static final int EXCEL_ROW_COUNT = 500;

	/**
	 * 사이즈별재고현황 화면
	 *
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 11. 17
	 */
	@RequestMapping(value = "/size/form", method = RequestMethod.GET)
	public ModelAndView goodsSizeStockListForm() {

		ModelAndView mav = new ModelAndView();

//		String supplyCompCd = "";
//		if ("G001_B000".equals(TsaSession.getInfo().getRoleCd())) {
//			supplyCompCd = TsaSession.getInfo().getSupplyCompCd();
//		}
//		// 공급업체
//		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, "Y"));
		// 상품상태
		String[] exceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", exceptCds));
		// 정상이월
		mav.addObject("formalGbList", rendererService.getAvailCommonCodeList("G009"));
		// 시즌
		mav.addObject("seasonList", rendererService.getAvailCommonCodeList("G006"));
		// 년도
		int toYear = Integer.parseInt(GagaDateUtil.getToday("yyyy")) - 4;
		mav.addObject("styleYearList", rendererService.getYearList(toYear,0,5));
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));
		// 품목
		mav.addObject("itemkindList", rendererService.getAllItemkindList());
		// MD
		mav.addObject("brandMdList", rendererService.getBrandMdList());
		// 색상
		Color color = new Color();
		mav.addObject("colorList", rendererService.getColorList(color));

		mav.setViewName("stock/GoodsSizeStockForm");

		return mav;
	}

	/**
	 * 사이즈별재고현황 조회
	 *
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 11. 17
	 */
	@RequestMapping(value = "/sizeStock/list", method = RequestMethod.POST)
	@ResponseBody
	public GagaMap getGoodsSizeStockList(@RequestBody GoodsSearch goodsSearch) {

		GagaMap result = new GagaMap();

		//입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TsaSession.getInfo().getRoleCd())) {
			goodsSearch.setSupplyCompCd(TsaSession.getInfo().getSupplyCompCd());
			goodsSearch.setMdNo(TsaSession.getInfo().getUserNo().toString());
		}
		if (!StringUtils.isBlank(goodsSearch.getCondition())) {
			goodsSearch.setConditionList(goodsSearch.getCondition().replaceAll("\r", "").trim().split("\n"));
		}
		// multi row 검색관련 처리
		if (!StringUtils.isBlank(goodsSearch.getBrandList())) {
			try {
				String [] arrBrandCd = mapper.readValue(goodsSearch.getBrandList(), String[].class);
				goodsSearch.setMultiBrand(arrBrandCd);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException(message.getMessage("브랜드코드 검색중 오류로 인해 조회되지 않았습니다."));
			}
		}

		if (!StringUtils.isBlank(goodsSearch.getSupplyCompList())) {
			try {
				String [] arrSupplyComp = mapper.readValue(goodsSearch.getSupplyCompList(), String[].class);
				goodsSearch.setMultiSupplyCompCd(arrSupplyComp);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException(message.getMessage("업체코드 검색중 오류로 인해 조회되지 않았습니다."));
			}
		}
		
		//log.info("[goodsSearch] goodsSearch =>{}", goodsSearch);
		goodsSearch.setRegNo(TsaSession.getInfo().getUserNo());	//엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		goodsSearch.setPageable(new TscPageRequest(goodsSearch.getPageNo() - 1, goodsSearch.getPageSize()));
		goodsSearch.getPageable().setTotalCount(stockService.getGoodsSizeStockCount(goodsSearch));

		result.set("pageing", goodsSearch);
		result.set("goodsSizeStockList", stockService.getGoodsSizeStockList(goodsSearch));

		return result;
	}

	/**
	 * 사이즈별재고현황 - 엑셀다운로드
	 *
	 * @param goodsSearch
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 11. 17
	 */
	@RequestMapping(value = "/sizeStock/excel/list", method = RequestMethod.GET)
	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);

		//log.info("downloadGoodsInfoExcelList goodsSearch= {}", goodsSearch);
		//입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TsaSession.getInfo().getRoleCd())) {
			goodsSearch.setSupplyCompCd(TsaSession.getInfo().getSupplyCompCd());
			goodsSearch.setMdNo(TsaSession.getInfo().getUserNo().toString());
		}
		if (!StringUtils.isBlank(goodsSearch.getCondition())) {
			goodsSearch.setConditionList(goodsSearch.getCondition().replaceAll("\r", "").trim().split("\n"));
		}
		// multi row 검색관련 처리
		if (!StringUtils.isBlank(goodsSearch.getBrandList())) {
			try {
				String [] arrBrandCd = mapper.readValue(goodsSearch.getBrandList(), String[].class);
				goodsSearch.setMultiBrand(arrBrandCd);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException(message.getMessage("브랜드코드 검색중 오류로 인해 조회되지 않았습니다."));
			}
		}

		if (!StringUtils.isBlank(goodsSearch.getSupplyCompList())) {
			try {
				String [] arrSupplyComp = mapper.readValue(goodsSearch.getSupplyCompList(), String[].class);
				goodsSearch.setMultiSupplyCompCd(arrSupplyComp);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException(message.getMessage("업체코드 검색중 오류로 인해 조회되지 않았습니다."));
			}
		}
		goodsSearch.setRegNo(TsaSession.getInfo().getUserNo());	//엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		goodsSearch.setPageable(new TscPageRequest(goodsSearch.getPageNo() - 1, goodsSearch.getPageSize()));
		goodsSearch.getPageable().setTotalCount(stockService.getGoodsSizeStockCount(goodsSearch));
		
		// 대용량엑셀파일다운로드는 이런 식으로 ...
		stockService.getGoodsSizeStockExcelList(goodsSearch, excelFilenameWithPath);

		return GagaFileUtil.writeFile(request, excelFilenameWithPath);
	}

	/**
	 * 상품 사이즈별 품절/안전재고 변경
	 *
	 * @param goods
	 * @return
	 * @throws Exception
	 * @author eskim
	 * @since 2020. 02. 20
	 */
	@PostMapping("/sizeSoldout/excelupload/save")
	@ResponseBody
	public GagaResponse saveGoodsSizeSoldoutExcelupload(@RequestBody Goods goods) throws Exception {
		//log.info("[saveGoodsSizeSoldoutExcelupload]Goods = >{}", goods);
		ObjectMapper mapper = new ObjectMapper();

		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.excel.target.path"), "excel");
		// DB 처리 시 사용되는 파라미터명(셀명) 설정
		String[] cellName = { "brandEnm", "goodsNm", "itemkindCd","goodsStat","goodsCd", "optCd", "optCd1", "optCd2",  "soldoutYn",
								"currStockQty", "baseStockQty","saleStockQty", "ableStockQty"};
		//log.info("[saveGoodsSizeSoldoutExcelupload]targetPath = >{}", targetPath);
		//log.info("[saveGoodsSizeSoldoutExcelupload]getExcelFileNm = >{}", GagaFileUtil.getConcatenationPath(targetPath, goods.getExcelFileNm()));
		Collection<GagaMap> ecxelGoodsList = GagaExcelUtil.getList(GagaFileUtil.getConcatenationPath(targetPath, goods.getExcelFileNm()), 0, cellName, 0);

		//건수
		if (ecxelGoodsList != null && ecxelGoodsList.size() > EXCEL_ROW_COUNT) {
			throw new IllegalStateException("엑셀 파일의 건수를 " +EXCEL_ROW_COUNT + "건 이하로 사용하세요.");
		}
		
		Collection<Option> goodsSizeList = new ArrayList<>();
		for (GagaMap map : ecxelGoodsList) {
			Option tmpGoods = mapper.convertValue(map, Option.class);
			goodsSizeList.add(tmpGoods);
		}

		stockService.saveGoodsSizeSoldoutExcelupload(goodsSizeList, goods.getExcelFileNm());

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

		return super.ok("");
	}
}
