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.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.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.rest.server.GagaResponseStatus;
import com.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.admin.biz.service.TsaPgService;
import com.style24.admin.biz.service.TsaRendererService;
import com.style24.admin.support.controller.TsaBaseController;
import com.style24.admin.support.env.TsaConstants;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.TscPageRequest;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.OrderSample;

import lombok.extern.slf4j.Slf4j;

/**
 * 주문관리 Controller
 *
 * @author jsh77b
 * @since 2020. 11. 16
 */
@Controller
@RequestMapping("/order")
@Slf4j
public class TsaOrderController extends TsaBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TsaRendererService rendererService;

	@Autowired
	private TscOrderService orderService;
	
	@Autowired
	private TsaPgService pgService;
	
	@Autowired
	private ObjectMapper mapper;

	/**
	 * 주문목록조회
	 *
	 * @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());				// 공급업제목록
		
		// 2021.05.11 프론트기준으로 상태값 정리
		mav.addObject("ordDtlStatList"	, rendererService.getCommonCodeList("G013", "Y", new String[] {"G013_10", "G013_11", "G013_25", "G013_35", "G013_55", "G013_97", "G013_98", "G013_99"}));
		mav.addObject("chgStatList"		, rendererService.getAvailCommonCodeList("G685"));		// 주문변경요청상태코드
		mav.addObject("chgGbList"		, rendererService.getAvailCommonCodeList("G680"));		// 주문변경구분코드
		mav.addObject("pgGbList"		, rendererService.getAvailCommonCodeList("G015"));		// 결제타입
		mav.addObject("payMeansList"	, rendererService.getAvailCommonCodeList("G014"));		// 결제수단
		mav.addObject("siteCdList"		, rendererService.getAvailCommonCodeList("G000"));		// 사이트구분
		mav.addObject("formalGbList"	, rendererService.getAvailCommonCodeList("G009"));		// 정상/이월

		mav.addObject("userNo"			, TsaSession.getInfo().getUserNo());

		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 TscPageRequest(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;
			}
		}
		
		// 2021.07.13 업체,브랜드 검색방법 변경
		if (!StringUtils.isBlank(order.getBrandList())) {
			try {
				String[] arrBrandCd = mapper.readValue(order.getBrandList(), String[].class);
				order.setMultiBrand(arrBrandCd);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("브랜드코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		if (!StringUtils.isBlank(order.getSupplyCompList())) {
			try {
				String[] arrSupplyComp = mapper.readValue(order.getSupplyCompList(), String[].class);
				order.setMultiSupplyCompCd(arrSupplyComp);
			} catch (Exception e) {
				e.printStackTrace();
				throw new IllegalStateException("업체코드 검색중 오류로 인해 조회되지 않았습니다.");
			}
		}

		if (!StringUtils.isBlank(order.getCondition())) {
			order.setConditions(order.getCondition().replaceAll("\r", "").trim().split("\n"));
		}

		// 주문전체건수 조회
		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 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");
		
		// 2021.05.11 배송비수정여부추가
		Collection<Order> orderDetailList = orderService.getOrderDetailList(order);
		String allCanYn = "Y";
		for (Order orderDetail : orderDetailList) {
			if ("Y".equals(allCanYn)
				&& !TsaConstants.OrderDetailStat.DEPOSIT_WAIT.value().equals(orderDetail.getOrdDtlStat())
				&& !TsaConstants.OrderDetailStat.PAYMENT_COMPLETE.value().equals(orderDetail.getOrdDtlStat())
				&& !TsaConstants.OrderDetailStat.GOODS_PREPARE.value().equals(orderDetail.getOrdDtlStat())) {
				allCanYn = "N";
			}
		}

		// 1. 주문기본정보
		mav.addObject("ordNo"					, ordNo);												// 주문번호
		mav.addObject("userNo"					, TsaSession.getInfo().getUserNo());					// 관리자번호

		mav.addObject("orderInfo"				, orderService.getOrderInfoList(order));				// 주문기본정보
		mav.addObject("orderGoodsInfo"			, orderDetailList);										// 주문상품정보
		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.getOrderRefundInfo(order));				// 환불정보

		// 3. 주문메모정보
		mav.addObject("orderCounselInfo"		, orderService.getOrderCounselInfo(order));				// 상담내역
		mav.addObject("orderAdminMemoInfo"		, orderService.getOrderMemoList(order));				// 관리자메모목록
		mav.addObject("allCanYn"				, allCanYn);											// 배송지수정가능여부

		mav.setViewName("order/OrderDetailForm");

		return mav;
	}

	/**
	 * 주문상세 > 주문요청 관리자 메모 > 등록폼
	 *
	 * @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.getOrderMemoList(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;
	}

	/**
	 * 주문상세상태를 변경
	 *
	 * @param order - 주문정보
	 * @return GagaResponse
	 * @author jsh77b
	 * @since 2020. 12. 22.
	 */
	@PostMapping("/detail/ordDtlStat/changed")
	@ResponseBody
	public GagaResponse changedOrdDtlStat(@RequestBody Order order) {
		int userNo = TsaSession.getInfo().getUserNo();
		order.setUpdNo(userNo);
		order.setRegNo(userNo);

		orderService.changedOrdDtlStat(order);

		return super.ok("성공");
	}
	
	/**
	 * 배송 > 배송지 정보 수정
	 *
	 * @param deliveryAddr - 배송지정보
	 * @return GagaResponse
	 * @author jsh77b
	 * @since 2021. 01. 15
	 */
	@PostMapping("/deliver/addr/update")
	@ResponseBody
	public GagaResponse udpateDeliveryAddrUpdate(@RequestBody Order order) {
		order.setUpdNo(TsaSession.getInfo().getUserNo());
		orderService.updateOrderAddr(order);
		return super.ok(message.getMessage("SUCC_0002"));
	}
	
	/**
	 * 반품/교환 > 회수지 정보 수정
	 *
	 * @param order - 주문번호
	 * @return GagaResponse
	 * @author jsh77b
	 * @since 2021. 01. 18
	 */
	@PostMapping("/change/info/addr/update")
	@ResponseBody
	public GagaResponse udpateChangeInfoAddr(@RequestBody Order order) {
		order.setUpdNo(TsaSession.getInfo().getUserNo());
		orderService.updateOrderChange(order);
		return super.ok(message.getMessage("SUCC_0002"));
	}


	/* 주문 샘플 데이터 (추후 삭제 예정) */
	@GetMapping("/sample/create/form")
	@ResponseBody
	public ModelAndView orderSamplePopupForm() {
		ModelAndView mav = new ModelAndView();

		// 상품상태
		String[] exceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", exceptCds));
		// 정상이월
		mav.addObject("formalGbList", rendererService.getAvailCommonCodeList("G009"));
		// 시즌
		mav.addObject("seasonList", rendererService.getAvailCommonCodeList("G006"));
		
		mav.setViewName("order/OrderSamplePopupForm");
		
		return mav;
	}
	
	@PostMapping("/sample/create")
	@ResponseBody
	public GagaMap createOrderSample(@RequestBody OrderSample orderSample) {
		GagaMap result = new GagaMap();
		result.set("status", GagaResponseStatus.FAIL.getCode());

		log.info("orderSample >>> {}", orderSample);
		
		result = pgService.createOrderSample(orderSample);
		
		// 처리 결과 코드에 따른 메세지 설정
		if (result.get("status").equals(GagaResponseStatus.SUCCESS.getCode())) {
			result.set("message", message.getMessage("SUCC_0004"));
		} else {
			result.set("message", message.getMessage("FAIL_0004"));
		}

		return result;
	}

	@PostMapping("/sample/goods/info")
	@ResponseBody
	public Collection<Goods> getOrderSampleGoodsInfo(@RequestBody String[] arrGoodsCd) {
		Goods goods = new Goods();
		goods.setArrGoodsCd(arrGoodsCd);
		
		return pgService.getOrderSampleGoodsInfo(goods);
	}

	@PostMapping("/sample/goods/stock")
	@ResponseBody
	public Goods getOrderSampleGoodsStock(@RequestBody Goods goods) {
		return pgService.getOrderSampleGoodsStock(goods);
	}
	
	/* //주문 샘플 데이터 (추후 삭제 예정) */
	
	/**
	 * 스윗트래커 정보 조회
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2021. 06. 17
	 */
	@GetMapping("/delivery/sweetTrackerDeliveryInfo")
	public ModelAndView sweetTrackerDeliveryInfo(Order order) {
		ModelAndView mav = new ModelAndView();

		Collection<Order> sweetTrackerDeliveryList = orderService.getSweetTrackerDeliveryInfo(order);
		mav.addObject("sweetTrackerDeliveryList"	, sweetTrackerDeliveryList); // 택배사 목록
		
		mav.setViewName("order/SweetTrackerDeliveryList");

		return mav;
	}
}










