package com.style24.admin.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.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.RequestParam;
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.admin.biz.service.TsaOrderService;
import com.style24.admin.biz.service.TsaRendererService;
import com.style24.admin.support.controller.TsaBaseController;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.persistence.TsaPageRequest;
import com.style24.persistence.domain.Order;

import lombok.extern.slf4j.Slf4j;

/**
 * 주문관리 Controller
 *
 * @author jsh77b
 * @since 2020. 11. 16
 */
@Controller
@RequestMapping("/order")
@Slf4j
public class TsaOrderController extends TsaBaseController {
	
	@Autowired
	private Environment env;
	
	@Autowired
	private TsaRendererService rendererService;
	
	@Autowired
	private TsaOrderService orderService;
	
	//@Autowired
	//private TsaMessageByLocale message;
	
	/**
	 * 주문 조회 화면
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 11. 16
	 */
	@GetMapping("/list/form")
	public ModelAndView orderListForm() {
		ModelAndView mav = new ModelAndView();
		
		mav.addObject("siteCdList"		, rendererService.getAvailCommonCodeList("G012"));		// 사이트구분
		mav.addObject("mallGbList"		, rendererService.getAvailCommonCodeList("G011"));		// 몰구분		
		mav.addObject("supplyCompList"	, rendererService.getSupplyCompanyList());				// 공급업제목록
		mav.addObject("ordStatList"		, rendererService.getAvailCommonCodeList("G012"));		// 주문상태코드
		mav.addObject("ordDtlStatList"	, rendererService.getAvailCommonCodeList("G013"));		// 주문상세상태코드
		
		mav.addObject("chgStatList"		, rendererService.getAvailCommonCodeList("G685"));		// 주문변경요청상태코드
		mav.addObject("chgGbList"		, rendererService.getAvailCommonCodeList("G680"));		// 주문변경구분코드
		mav.addObject("payMeansList"	, rendererService.getAvailCommonCodeList("G014"));		// 결제수단
		mav.addObject("siteCdList"		, rendererService.getAvailCommonCodeList("G000"));		// 사이트구분
		mav.addObject("formalGbList"	, rendererService.getAvailCommonCodeList("G009"));		// 정상/이월

		mav.setViewName("order/OrderListForm");

		return mav;
	}
	
	/**
	 * 주문 목록
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 16
	 */
	@PostMapping("/list")
	@ResponseBody
	public GagaMap getOrderList(@RequestBody Order order) throws Exception {
		GagaMap result = new GagaMap();
		
		order.setRegNo(TsaSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		order.setPageable(new TsaPageRequest(order.getPageNo() - 1, order.getPageSize()));
		
		// 주문상태 CD_GB 변경
		if (order.getMultiOrdStat() != null) {
			for (int i=0 ; i<order.getMultiOrdStat().length ; i++) {
				String ordStat = order.getMultiOrdStat()[i].replace("G012", "G013"); 
				order.getMultiOrdStat()[i] = ordStat;
			}
		}
		
		// 주문취소상태 CD_GB 변경
		if (order.getChgGb() != null) {
			String chgDtlStat = order.getChgGb().replace("G680", "G685"); 
			order.setChgGb(chgDtlStat);
		}
		
		// 주문전체건수 조회
		int totalCount = orderService.getOrderListCount(order);
		order.getPageable().setTotalCount(totalCount);
		
		// 주문목록 페이지 조회
		Collection<Order> orderList = orderService.getOrderList(order);
		
		result.set("pageing"	, order);
		result.set("orderList"	, orderList);
		
		return result;
	}
	
	/**
	 * 주문 목록 엑셀 조회
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 16
	 */
	@PostMapping("/excel/search")
	@ResponseBody
	public Collection<Order> getOrderListSearchExcel(@RequestBody Order order) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		
		// 1. 엑셀업로드경로설정
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.excel.target.path"), "");
		String[] cellName = new String[1];
		
		// 2. DB 처리 시 사용되는 파라미터명(셀명) 설정
		cellName[0] = "ordNo";
		Collection<GagaMap> dataList = GagaExcelUtil.getList(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()), 0, cellName);
		
		Order searchOrder = new Order();
		int[] ordNoList = new int[dataList.size()];
		int cnt = 0;
		
		for (GagaMap map : dataList) {
			Order tmpOrder = mapper.convertValue(map, Order.class);
			ordNoList[cnt] = tmpOrder.getOrdNo();
			cnt++;
		}
		
		// 3. 주문번호 배열에 담고 주문목록 조회
		searchOrder.setOrdNoList(ordNoList);
		Collection<Order> orderList = orderService.getOrderList(searchOrder);
		
		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()));
 
		return orderList;
	}
	
	/**
	 * 주문 목록 데이타 합산
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 16
	 */
	@PostMapping("/list/sum/info")
	@ResponseBody
	public Order getOrderListSumInfo(@RequestBody Order order) {
		return orderService.getOrderListSumInfo(order);
	}

	/**
	 * 주문상세 화면
	 * 
	 * @param ordNo - 주문번호
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 11. 26
	 */
	@GetMapping("/detail/info")
	@ResponseBody
	public ModelAndView orderDetailForm(@RequestParam(value = "ordNo") int ordNo) {
		ModelAndView mav = new ModelAndView();
		
		Order order = new Order();
		order.setOrdNo(ordNo);
		order.setDelYn("N");
		
		// 1. 주문기본정보
		mav.addObject("ordNo"					, ordNo);												// 주문번호
		mav.addObject("userNo"					, TsaSession.getInfo().getUserNo());					// 관리자번호
		
		mav.addObject("orderInfo"				, orderService.getOrderInfoList(order));				// 주문기본정보
		mav.addObject("orderGoodsInfo"			, orderService.getOrderDetailList(order));				// 주문상품정보
		mav.addObject("orderFreeGiftInfo"		, orderService.getOrderFreeGiftList(order));			// 주문사은품정보 2020.12.16 추가
		mav.addObject("orderDeliveryAddrInfo"	, orderService.getDeliveryAddrList(order));				// 배송정보
		mav.addObject("orderPaymentInfo"		, orderService.getOrderPaymentBasicInfoList(order));	// 결제정보
		mav.addObject("orderDeliveryFeeInfo"	, orderService.getDeliveryFeeList(order));				// 배송비정보
		
		// 2. 클레임정보
		mav.addObject("orderChangeInfo"			, orderService.getOrderChangeList(order));				// 취소/반품/교환요청 정보
		mav.addObject("orderRefundInfo"			, orderService.orderRefundInfo(order));					// 환불정보
		
		// 3. 주문메모정보
		mav.addObject("orderCounselInfo"		, orderService.orderCounselInfo(order));				// 상담내역
		mav.addObject("orderAdminMemoInfo"		, orderService.getOrderTsainMemoList(order));			// 관리자메모

		mav.setViewName("order/OrderDetailForm");
		
		return mav;
	}
	
	/**
	 * 입점업체미발주목록화면
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 11. 30
	 */
	@GetMapping("/seller/unorder/list/form")
	public ModelAndView orderSellerUnorderListForm() {
		ModelAndView mav = new ModelAndView();
				
		mav.addObject("supplyCompList"	, rendererService.getSupplyCompanyList());				// 공급업제목록
		mav.addObject("ordStatList"		, rendererService.getAvailCommonCodeList("G012"));		// 주문상태코드
		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(TsaSession.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"
			, "itemCd"
			, "optCd2"
			, "itemOrdQty"
			, "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;
	}
	
	/**
	 * 주문상세 > 주문요청 관리자 메모 > 등록폼
	 *
	 * @param ordNo - 주문번호
	 * @param seq - 시퀀스
	 * @param mode - 신규/수정 구분
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@GetMapping("/memo/create/form")
	@ResponseBody
	public ModelAndView orderMemoCreateFrom(@RequestParam(value = "ordNo") int ordNo, @RequestParam(value = "seq") int seq, @RequestParam(value = "mode") String mode) {
		ModelAndView mav = new ModelAndView();
		int userNo 		= TsaSession.getInfo().getUserNo();
		String userNm 	= TsaSession.getInfo().getUserNm();

		if ("U".equals(mode)) {
			Order order = new Order();
			order.setSeq(seq);
			order.setOrdNo(ordNo);
			order.setDelYn("N");
			
			Order orderMemo = orderService.getOrderMemoInfo(order);
			
			mav.addObject("orderMemo", orderMemo);
		}

		mav.addObject("userNo"	, userNo);
		mav.addObject("userNm"	, userNm);
		mav.addObject("ordNo"	, ordNo);
		mav.addObject("seq"		, seq);
		mav.addObject("mode"	, mode);

		mav.setViewName("order/OrderMemoRegistForm");
		return mav;
	}
	
	/**
	 * 주문상세 > 주문요청 관리자 메모 > 메모저장
	 *
	 * @param order - 주문정보
	 * @return GagaResponse
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@PostMapping("/memo/save")
	@ResponseBody
	public GagaResponse createOrderMemo(@RequestBody Order order) {
		int userNo = TsaSession.getInfo().getUserNo();
		order.setRegNo(userNo);
		order.setUpdNo(userNo);
		
		// 신규
		if ("N".equals(order.getMode())) {
			orderService.createOrderMemo(order);
		}
		// 변경
		else if ("U".equals(order.getMode())) {
			orderService.updateOrderMemo(order);
		}
		
		return super.ok("저장이 완료되었습니다.");
	}
	
	/**
	 * 주문상세 > 주문요청 관리자 메모 > 메모삭제
	 *
	 * @param order - 주문정보
	 * @return GagaResponse
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@PostMapping("memo/delete")
	@ResponseBody
	public GagaResponse deleteOrderMemo(@RequestBody Order order) {
		int userNo = TsaSession.getInfo().getUserNo();
		order.setRegNo(userNo);
		order.setUpdNo(userNo);
		
		orderService.deleteOrderMemo(order);
		
		return super.ok("저장이 완료되었습니다.");
	}
	
	/**
	 * 주문상세 > 주문요청 관리자 메모 > 메모삭제 > 새로고침
	 *
	 * @param ordNo - 주문번호
	 * @return Collection<TsaOrder>
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@GetMapping("/admin/memo/list/{ordNo}")
	@ResponseBody
	public Collection<Order> getOrderTsainMemoList(@PathVariable(value = "ordNo") int ordNo) {
		Order order = new Order();
		order.setOrdNo(ordNo);
		return orderService.getOrderTsainMemoList(order);
	}
	
	/**
	 * 주문상품 상세 변경 이력 화면
	 * 
	 * @param ordDtlNo - 주문상세번호
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@GetMapping("/detail/change/hst/form/{ordDtlNo}")
	@ResponseBody
	public ModelAndView detailChangeHstFrom(@PathVariable(value = "ordDtlNo") int ordDtlNo) {

		Order order = new Order();
		ModelAndView mav = new ModelAndView();

		order.setOrdDtlNo(ordDtlNo);
		Collection<Order> orderDetailHstList = orderService.getOrderDetailHistoryList(order);

		mav.addObject("orderDetailHstList", orderDetailHstList);
		mav.setViewName("order/OrderDetailChangeHst");
		return mav;
	}
	
	/**
	 * 쿠폰사용 내역 팝업 화면
	 * 
	 * @param ordNo - 주문번호
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@GetMapping("/detail/coupon/hst/form/{ordNo}")
	@ResponseBody
	public ModelAndView detailCouponHstFrom(@PathVariable(value = "ordNo") int ordNo) {

		Order order = new Order();
		ModelAndView mav = new ModelAndView();

		order.setOrdNo(ordNo);
		Collection<Order> orderCouponHstList = orderService.getOrderDiscountCouponList(order);

		mav.addObject("orderCouponHstList", orderCouponHstList);
		mav.setViewName("order/OrderDetailCouponHst");
		return mav;
	}
	
	/**
	 * 포인트사용 내역 팝업 화면
	 * 
	 * @param ordNo - 주문번호
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@GetMapping("/detail/point/hst/form/{ordNo}")
	@ResponseBody
	public ModelAndView detailPointHstFrom(@PathVariable(value = "ordNo") int ordNo) {

		Order order = new Order();
		ModelAndView mav = new ModelAndView();

		order.setOrdNo(ordNo);
		Collection<Order> orderPointHstList = orderService.getOrderDiscountPointList(order);

		mav.addObject("orderPointHstList", orderPointHstList);
		mav.setViewName("order/OrderDetailPointHst");
		return mav;
	}
	
	/**
	 * 상품권사용 내역 팝업 화면
	 * 
	 * @param ordNo - 주문번호
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@GetMapping("/detail/giftcard/hst/form/{ordNo}")
	@ResponseBody
	public ModelAndView detailGiftcardHstFrom(@PathVariable(value = "ordNo") int ordNo) {

		Order order = new Order();
		ModelAndView mav = new ModelAndView();

		order.setOrdNo(ordNo);
		Collection<Order> orderGiftcardHstList = orderService.getOrderGiftcardHstList(order);

		mav.addObject("orderGiftcardHstList", orderGiftcardHstList);
		mav.setViewName("order/OrderDetailGiftcardHst");
		return mav;
	}
	
	/**
	 * 다다익선적용 내역 팝업 화면
	 * 
	 * @param ordNo - 주문번호
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 12. 16
	 */
	@GetMapping("/detail/tmtb/hst/form/{ordNo}")
	@ResponseBody
	public ModelAndView detailTmtbHstFrom(@PathVariable(value = "ordNo") int ordNo) {

		Order order = new Order();
		ModelAndView mav = new ModelAndView();

		order.setOrdNo(ordNo);
		Collection<Order> orderTmtbHstList = orderService.getOrderTmtbHstList(order);

		mav.addObject("orderTmtbHstList", orderTmtbHstList);
		mav.setViewName("order/OrderDetailTmtbHst");
		return mav;
	}
}










