package com.style24.scm.biz.web;

import java.io.PrintWriter;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gagaframework.web.parameter.GagaMap;
import com.style24.core.biz.checkout.base.ChangedProductOrderInfo;
import com.style24.core.biz.checkout.base.ProductOrderChangeType;
import com.style24.core.biz.service.TscNaverPayService;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Order;
import com.style24.scm.biz.service.TssOrderService;
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("/naverpay")
@Slf4j
public class TssNaverpayController extends TssBaseController {

	@Autowired
	private TscMessageByLocale message;
	
	@Autowired
	private TssOrderService orderService;

	@Autowired
	private TscOrderService coreOrderService;
	
	@Autowired
	private Environment env;

	@Autowired
	private TscNaverPayService coreNaverPayService;

	/**
	 * 취소 신청 승인 데이터 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 20.
	 */
	@GetMapping("/send/cancel/complete")
	@ResponseBody
	public String sendNaverpayCancelComplete(HttpServletRequest request, HttpServletResponse response) {
		Order order = new Order();
		order.setOrdNo(Integer.parseInt(request.getParameter("ordNo")));
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		order.setNpayOrdDtlNo(request.getParameter("npayOrdDtlNo"));
		// order.setOrdChgSq(Integer.parseInt(request.getParameter("ordChgSq")));
		order.setRegNo(Integer.parseInt(request.getParameter("userNo")));

		return coreNaverPayService.sendNaverPayOrderCancelConfirm(order);
	}

	/**
	 * 품절취소 데이터 네이버페이 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 21.
	 */
	@GetMapping("/send/soldout/cancel")
	@ResponseBody
	public String sendNaverpaySoldoutCancel(HttpServletRequest request, HttpServletResponse response) {
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));

		String result = "";
		try {
			result = coreNaverPayService.sendNaverPaySoldoutCancel(order, userNo);
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}

		return result;
	}

	/**
	 * 교환 반려(철회) 데이터 네이버페이 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 21.
	 */
	@GetMapping("/send/reject/exchange")
	@ResponseBody
	public String sendNaverpayRejectExchange(HttpServletRequest request, HttpServletResponse response) {
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));

		String result = "";
		try {
			result = coreNaverPayService.sendNaverPayRejectExchange(order, userNo);
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}

		return result;
	}

	/**
	 * 반품 반려(철회) 데이터 네이버페이 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 21.
	 */
	@GetMapping("/send/reject/return")
	@ResponseBody
	public String sendNaverpayRejectReturn(HttpServletRequest request, HttpServletResponse response) {
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));

		String result = "";
		try {
			result = coreNaverPayService.sendNaverPayRejectReturn(order, userNo);
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}

		return result;
	}

	/**
	 * 품절 반품 접수 네이버페이 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 21.
	 */
	@GetMapping("/send/soldout/return/req")
	@ResponseBody
	public String sendNaverpaySoldoutReturnReq(HttpServletRequest request, HttpServletResponse response) {
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));
		String result = "";

		try {
			result = coreNaverPayService.sendNaverPaySoldoutReturnReq(order, userNo);
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}

		return result;
	}

	/**
	 * 품절 반품 완료 네이버페이 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 21.
	 */
	@GetMapping("/send/return/complete")
	@ResponseBody
	public String sendNaverpayReturnComplete(HttpServletRequest request, HttpServletResponse response) {
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));
		String result = "";

		try {
			result = coreNaverPayService.sendNaverPayReturnComplete(order, userNo);
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}

		return result;
	}

	/**
	 * 원주문 배송중 주문 정보 네이버페이 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 21.
	 */
	@GetMapping("/send/order/delivery/start")
	@ResponseBody
	public GagaMap sendNaverpayOrderDeliveryStart(HttpServletRequest request, HttpServletResponse response) {
		GagaMap result = new GagaMap();
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));

		try {
			result = coreNaverPayService.sendNaverPayDeliveryStartOrder(order, "SHIPPING", userNo);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 네이버페이 교환 배송중 정보 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 22.
	 */
	@GetMapping("/send/exchange/delivery")
	@ResponseBody
	public GagaMap sendNaverpayExchangeReDelivery(HttpServletRequest request, HttpServletResponse response) {
		GagaMap result = new GagaMap();
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));

		try {
			result = coreNaverPayService.sendNaverPayExchangeReDelivery(order, userNo);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 네이버페이 교환 회수완료 정보 송부
	 * @param request
	 * @param response
	 * @return
	 * @author xodud1202
	 * @since 2021. 07. 22.
	 */
	@GetMapping("/send/exchange/collect/complete")
	@ResponseBody
	public String sendNaverPayExchangeCollectComplete(HttpServletRequest request, HttpServletResponse response) {
		Order order = new Order();
		order.setOrdDtlNo(Integer.parseInt(request.getParameter("ordDtlNo")));
		int userNo = Integer.parseInt(request.getParameter("userNo"));
		String result = "";

		try {
			result = coreNaverPayService.sendNaverPayExchangeCollectComplete(order, userNo);
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}

		return result;
	}

	@GetMapping("/recv/order/complete")
	public ModelAndView naverpayRecvOrderComplete(HttpServletRequest request, HttpServletResponse response) {
		try {
			log.info("<<<< 결제완료 수신 시작 >>>>");

			PrintWriter out = response.getWriter();
			Order time = coreNaverPayService.setInitData();
			ChangedProductOrderInfo[] changedProductOrderList = coreNaverPayService.changedProductOrderList(ProductOrderChangeType.PAYED, time.getFrom(), time.getTo(), TssSession.getInfo().getUserNo()); // 변경 상품주문 조회;

			if(changedProductOrderList != null) {
				log.info("<<<< 수신건수: [{}]건 >>>>", changedProductOrderList.length);
				Order result = coreNaverPayService.createOrderInfo(changedProductOrderList, 99999);
			}

			log.info("<<<< 결제완료 수신 종료 >>>>");

			out.print("<html><body><form><h1>ORDER COMPLETE SUCCESS</h1></body></html>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@GetMapping("/send/ready/delivery")
	public ModelAndView naverpaySendReadyDelivery(HttpServletRequest request, HttpServletResponse response) {
		try {
			PrintWriter out = response.getWriter();
			log.info("<<<< 배송준비중 송신 시작 >>>>");
			Order time = coreNaverPayService.setInitData();
			Collection<Order> readyDeliveryList = coreNaverPayService.getReadyDeliveryList(time); // 네이버페이 주문형 배송준비중 테스트

			if (readyDeliveryList != null) {
				// 배송 준비중 데이터 네이버로 송신
				Order result = coreNaverPayService.sendNaverPayReadyDeliveryOrder(readyDeliveryList, 99999);
			}

			log.info("<<<< 배송준비중 송신 종료 >>>>");

			out.print("<html><body><form><h1>DELIVERY READY SUCCESS</h1></body></html>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@GetMapping("/recv/order/cancel/req")
	public ModelAndView naverpayRecvOrderCancelReq(HttpServletRequest request, HttpServletResponse response) {
		try {
			log.info("<<<< 취소접수 수신 시작 >>>>");

			PrintWriter out = response.getWriter();
			Order time = coreNaverPayService.setInitData();
			ChangedProductOrderInfo[] changedProductOrderList = coreNaverPayService.changedProductOrderList(ProductOrderChangeType.CANCEL_REQUESTED, time.getFrom(), time.getTo(), TssSession.getInfo().getUserNo()); // 변경 상품주문 조회;

			if(changedProductOrderList != null) {
				log.info("<<<< 수신건수: [{}]건 >>>>", changedProductOrderList.length);
				Order result = coreNaverPayService.cancelReqOrderInfo(changedProductOrderList, 99999);
			}

			log.info("<<<< 취소접수 수신 종료 >>>>");

			out.print("<html><body><form><h1>RECV ORDER CANCEL REQ SUCCESS</h1></body></html>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@GetMapping("/recv/order/exchange/req")
	public ModelAndView naverpayRecvOrderExchangeReq(HttpServletRequest request, HttpServletResponse response) {
		try {
			log.info("<<<< 교환접수 수신 시작 >>>>");

			PrintWriter out = response.getWriter();
			Order time = coreNaverPayService.setInitData();
			ChangedProductOrderInfo[] changedProductOrderList = coreNaverPayService.changedProductOrderList(ProductOrderChangeType.EXCHANGE_REQUESTED, time.getFrom(), time.getTo(), 99999); // 변경 상품주문 조회;

			if(changedProductOrderList != null) {
				log.info("<<<< 수신건수: [{}]건 >>>>", changedProductOrderList.length);
				Order result = coreNaverPayService.recvExchangeReqOrder(changedProductOrderList, 99999);
			}

			log.info("<<<< 교환접수 수신 종료 >>>>");

			out.print("<html><body><form><h1>RECV ORDER EXCHANGE REQ SUCCESS</h1></body></html>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	@GetMapping("/recv/order/return/req")
	public ModelAndView naverpayRecvOrderReturnReq(HttpServletRequest request, HttpServletResponse response) {
		try {
			log.info("<<<< 반품접수 수신 시작 >>>>");

			PrintWriter out = response.getWriter();
			Order time = coreNaverPayService.setInitData();
			ChangedProductOrderInfo[] changedProductOrderList = coreNaverPayService.changedProductOrderList(ProductOrderChangeType.RETURN_REQUESTED, time.getFrom(), time.getTo(), 99999); // 변경 상품주문 조회;

			if(changedProductOrderList != null) {
				log.info("<<<< 수신건수: [{}]건 >>>>", changedProductOrderList.length);
				Order result = coreNaverPayService.recvReturnReqOrder(changedProductOrderList, 99999);
			}

			log.info("<<<< 반품접수 수신 종료 >>>>");

			out.print("<html><body><form><h1>RECV ORDER RETURN REQ SUCCESS</h1></body></html>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
}
