package com.style24.scm.biz.web;

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

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections4.CollectionUtils;
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.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.fasterxml.jackson.databind.ObjectMapper;
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;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Order;
import com.style24.scm.biz.service.TssOrderService;
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;


/**
 * 주문 Controller
 *
 * @author gagamel
 * @since 2020. 10. 19
 */
@Controller
@RequestMapping("/order")
@Slf4j
public class TssOrderController extends TssBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TssRendererService rendererService;
	
	@Autowired
	private TssOrderService orderService;
	
	@Autowired
	private Environment env;

	/**
	 * 입점업체미발주목록화면
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 11. 30
	 */
	@GetMapping("/seller/unorder/list/form")
	public ModelAndView orderSellerUnorderListForm() {
		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)); 	// 공급업제목록
		mav.addObject("ordDtlStatList"	, rendererService.getAvailCommonCodeList("G013"));				// 주문상세상태코드
		mav.addObject("shipCompanyList"	, rendererService.getShipCompanyList());						// 택배사 목록

		mav.setViewName("order/OrderSellerListForm");

		return mav;
	}
	
	/**
	 * 입점업체미발주 주문목록 조회
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 16
	 */
	@PostMapping("/seller/unorder/list")
	@ResponseBody
	public Collection<Order> getOrderSellerUnorderList(@RequestBody Order order) throws Exception {		
		Collection<Order> orderList = orderService.getOrderSellerUnorderList(order); 
		return orderList;
	}
	
	/**
	 * 입점업체미발주목록 - 엑셀다운로드시 주문상태값 변경(출고완료)
	 *
	 * @param orderList - 미발주목록
	 * @return GagaResponse
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@PostMapping("/seller/unorder/status/save")
	@ResponseBody
	public GagaResponse saveUnorderStatus(@RequestBody Collection<Order> orderList) {
		orderService.saveUnorderStatus(orderList);
		return super.ok("");
	}
	
	/**
	 * 입점업체미발주목록 - 엑셀다운로드
	 *
	 * @param request - request
	 * @return ResponseEntity<InputStreamResource>
	 * @throws Exception - exception
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@GetMapping("/seller/unorder/excel/list")
	public ResponseEntity<InputStreamResource> downloadPickingGoodsExcelList(HttpServletRequest request) throws Exception {
		String excelfileName 	= "입점출고목록_" + GagaDateUtil.getTodayDateTime() + ".xlsx";
		String excelFilePath 	= GagaFileUtil.getConcatenationPath(env.getProperty("download.path"), "excel", excelfileName);
		
		Order order = new Order();
		order.setRegNo(TssSession.getInfo().getUserNo());
		order.setSearch("EXCEL");

		orderService.geSellerUnorderExcelList(order, excelFilePath);
		
		return GagaFileUtil.writeFile(request, excelFilePath);
	}
	
	/**
	 * 입점 송장 엑셀 업로드
	 *
	 * @param order - 주문정보
	 * @return GagaMap
	 * @throws Exception - exception
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@PostMapping("/seller/unorder/invoice/excelupload/save")
	@ResponseBody
	public GagaMap saveSellerUnorderInvoiceExcelupload(@RequestBody Order order) throws Exception {

		ObjectMapper mapper = new ObjectMapper();
		
		// 1. UPLOAD 경로 조회
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.excel.target.path"), "excel");
		
		// 2. DB 처리 시 사용되는 파라미터명(셀명) 설정
		String[] cellName = {
			"ordNo"
			, "ordDtlNo"
			, "goodsCd"
			, "optCd2"
			, "ordQty"
			, "shipCompCd"
			, "invoiceNo"
		};
		
		Collection<GagaMap> ecxelList = GagaExcelUtil.getList(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()), 0, cellName, 0);
		
		// 3. 주문목록 매퍼 등록
		Collection<Order> orderList = new ArrayList<>();
		for (GagaMap map : ecxelList) {
			Order tmpGoods = mapper.convertValue(map, Order.class);
			orderList.add(tmpGoods);
		}
		
		// 4. 업로드된 임시 엑셀파일 삭제
		if (CollectionUtils.isEmpty(orderList)) {
			try {
				GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()));
			} catch (IOException e) {
				// Nothing Do
			}
			//throw new IllegalStateException(message.getMessage("FAIL_1001"));
			throw new IllegalStateException("실패 했습니다.");
		}
		
		// 4. 주문상세번호 기준으로 송장번호 등록
		String result = orderService.saveUnorderInvoice(orderList);
		GagaMap map = new GagaMap();
		map.set("msg", result);

		// 5. 파일 삭제 (중복처리?)
		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()));

		return map;
	}
	
	/**
	 * 입점업체미발주목록 - 송장번호 입력(출고완료)
	 *
	 * @param orderList - 송방번호 입력된 주문리스트
	 * @return GagaMap
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@PostMapping(value = "/seller/unorder/invoice/save")
	@ResponseBody
	public GagaMap saveUnorderInvoice(@RequestBody Collection<Order> orderList) {
		// 1. 송장번호 개별 등록
		String result = orderService.saveUnorderInvoice(orderList);
		GagaMap map = new GagaMap();
		map.set("msg", result);
		return map;
	}

}
