package com.style24.front.biz.web;

import java.io.PrintWriter;
import java.util.Map;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.gagaframework.web.parameter.GagaMap;
import com.style24.core.biz.service.TscKakaotalkService;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.env.TscConstants;
import com.style24.front.biz.service.TsfCustomerService;
import com.style24.front.biz.service.TsfOrderService;
import com.style24.front.support.controller.TsfBaseController;
import com.style24.persistence.domain.CustContactHst;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.Payment;

import kr.co.kcp.net.connection.ConnectionKCP;
import kr.co.kcp.net.connection.dto.ParamData;
import kr.co.kcp.net.connection.util.HttpJsonXml;
import kr.co.kcp.net.connection.util.OpenHash;
import lombok.extern.slf4j.Slf4j;

@Controller
@RequestMapping("/pg")
@Slf4j
public class TsfPgController extends TsfBaseController {
	
	@Autowired
	private TscOrderService coreOrderService;

	@Autowired
	private TsfOrderService orderService;

	@Autowired
	private Environment env;
	
	@Autowired
	private TsfCustomerService customerService;
	
	@Autowired
	private TscKakaotalkService kakaotalkService;

	/**
	 * 무통장입금 입금통보
	 *
	 * @param
	 * @return
	 * @author xodud1202
	 * @since 2021. 03. 05
	 */
	@ResponseBody
	@RequestMapping(value = "/kcp/vBankEndBack")
	public ModelAndView vBankEndBack(Payment param, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		try {	request.setCharacterEncoding("euc-kr");	} catch(Exception e) {	}
		PrintWriter out = response.getWriter();
		String result = "0000";

		try {
			String opCd = request.getParameter("op_cd");		// 13이 오면 입금이 잘못된 경우로 취소 노티가 온다고함. 13이 아닌 경우에만 진행해야할듯함.
			String txCd = request.getParameter("tx_cd");		// 무통장 입금 통보는 TX00(PC), TX08(MOB). 아닐경우 처리 X
			
			if("13".equals(opCd) || !("TX00".equals(txCd) || "TX08".equals(txCd))) {
				return null;
			}

			// 2021.03.15 jsh77b 무통장입금 결제완료 처리
			Order order = new Order();
			order.setOrdNo(Integer.parseInt(request.getParameter("order_no")));
			order.setPgTid(request.getParameter("tno"));
			order.setCashAuthNo(request.getParameter("cash_a_no"));
			order.setCashTradeNo(request.getParameter("cash_no"));
			order.setCustNo(0);
			order.setUpdNo(0);
			coreOrderService.updateOrderInfoVBank(order);

			// USAFE 보증보험 입금확인 송부
			orderService.uSafeGuaranteeDepositCompleted(order);
			
			// 2021.06.18
			GagaMap resultMap = coreOrderService.getOrderCompleteInfo(order);
			Order orderInfo = (Order) resultMap.get("orderInfo");

			// 2021.06.18 알림톡 이전 발송이력 조회
			CustContactHst custContactHst = new CustContactHst();
			custContactHst.setContactType(TscConstants.ContactType.BANK_DEPOSIT_INFO.value());
			custContactHst.setContactMethod(TscConstants.ContactMethod.KAKAOTALK.value());
			custContactHst.setContactMemo(String.valueOf(order.getOrdNo()));

			int count = customerService.getGiftKakaoSendInfo(custContactHst);
			
			if (count < 1) {
				if (StringUtils.isNotBlank(orderInfo.getOrdPhnno())) {
					Integer userNo = orderInfo.getCustNo();
					try {
						orderInfo.setGoodsNm((String) resultMap.get("goodsNm"));
						orderInfo.setGoodsCnt(String.valueOf(resultMap.get("goodsCnt")));
						kakaotalkService.sendDepositComplete(orderInfo, userNo);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch(Exception e) {
			result = "9999";		// 실패. return 하지 말것.
		}

		// 결과 데이터 세팅 ("0000"은 성공, 그 외에는 실패. 실패시에 입금 결과 재통보)
		out.print("<html><body><form><input type='hidden' name='result' value='" + result + "'></form></body></html>");
		out.flush();
		out.close();
		return null;
	}
	
	/**
	 * 무통장입금 입금통보
	 *
	 * @param
	 * @return
	 * @author jsh77b
	 * @since 2021. 09. 01
	 */
	@ResponseBody
	@PostMapping(value = "/kcp/vBankEnd")
	public ModelAndView vBankEnd(@RequestBody Payment param, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		try {	request.setCharacterEncoding("euc-kr");	} catch(Exception e) {	}
		PrintWriter out = response.getWriter();
		String result = "0000";

		try {
			String opCd = param.getOp_cd();		// 13이 오면 입금이 잘못된 경우로 취소 노티가 온다고함. 13이 아닌 경우에만 진행해야할듯함.
			String txCd = param.getTx_cd();		// 무통장 입금 통보는 TX00(PC), TX08(MOB). 아닐경우 처리 X
			
			if("13".equals(opCd) || !("TX00".equals(txCd) || "TX08".equals(txCd))) {
				return null;
			}

			// 2021.03.15 jsh77b 무통장입금 결제완료 처리
			Order order = new Order();
			order.setOrdNo(Integer.parseInt(param.getOrder_no()));
			order.setPgTid(param.getTno());
			order.setCashAuthNo(param.getCash_a_no());
			order.setCashTradeNo(param.getCash_no());
			order.setCustNo(0);
			order.setUpdNo(0);
			coreOrderService.updateOrderInfoVBank(order);

			// USAFE 보증보험 입금확인 송부
			orderService.uSafeGuaranteeDepositCompleted(order);
			
			// 2021.06.18
			GagaMap resultMap = coreOrderService.getOrderCompleteInfo(order);
			Order orderInfo = (Order) resultMap.get("orderInfo");

			// 2021.06.18 알림톡 이전 발송이력 조회
			CustContactHst custContactHst = new CustContactHst();
			custContactHst.setContactType(TscConstants.ContactType.BANK_DEPOSIT_INFO.value());
			custContactHst.setContactMethod(TscConstants.ContactMethod.KAKAOTALK.value());
			custContactHst.setContactMemo(String.valueOf(order.getOrdNo()));

			int count = customerService.getGiftKakaoSendInfo(custContactHst);
			
			if (count < 1) {
				if (StringUtils.isNotBlank(orderInfo.getOrdPhnno())) {
					Integer userNo = orderInfo.getCustNo();
					try {
						orderInfo.setGoodsNm((String) resultMap.get("goodsNm"));
						orderInfo.setGoodsCnt(String.valueOf(resultMap.get("goodsCnt")));
						kakaotalkService.sendDepositComplete(orderInfo, userNo);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		} catch(Exception e) {
			result = "9999";		// 실패. return 하지 말것.
		}

		// 결과 데이터 세팅 ("0000"은 성공, 그 외에는 실패. 실패시에 입금 결과 재통보)
		out.print("<html><body><form><input type='hidden' name='result' value='" + result + "'></form></body></html>");
		out.flush();
		out.close();
		return null;
	}

	/**
	 * KCP 모바일 appoval 페이지
	 *
	 * @param
	 * @return
	 * @author xodud1202
	 * @since 2021. 03. 05
	 */
	@RequestMapping(value = "/kcp/approval")
	public ModelAndView kcpApproval(Payment param, HttpServletRequest request, HttpServletResponse response, Model model) throws Exception{
		/*try {	request.setCharacterEncoding("euc-kr");	} catch(Exception e) {	}
		response.setContentType("text/html;charset=euc-kr");*/
		log.info("CHECK INFO ::::: {}", param.toString());
		response.setHeader("Cache-Control","no-store");
		response.setHeader("Pragma","no-cache");
		response.setDateHeader("Expires",0);

		PrintWriter out = response.getWriter();

		ConnectionKCP suc = new ConnectionKCP();		// KCP 인증 정보를 저장하기 위한 Object                     ( 통신의 기본이 되는 객체 ) - 필수
		OpenHash oh  = new OpenHash();					// KCP 와 통신시 데이터 위변조를 확인 하기 위한 Hash Object ( 업체와 KCP 간의 통신시 데이터 위변조를 확인 하기 위해 필요. 미설정시 통신 구간만 라이브러리에서 자체적으로 hash 처리 )
		HttpJsonXml   hjx = new HttpJsonXml();			// 응답값 get value 형식으로 가져올수 있는 Object           ( Java 또는 JSP 내에서 데이터를 파싱할때 필요 - XML 또는 JSON )
		ParamData pd  = new ParamData();				// 파라메타 값을 세팅할수 있는 bean Object                  ( String, HashMap 등으로 대체 가능 )

		/*pd.setGood_mny(String.valueOf(param.getGoodMny()));
		pd.setGood_name(param.getGoodName());
		pd.setOrdr_idxx(param.getOrdrIdxx());
		pd.setPay_method(param.getPayMethod());
		pd.setRet_URL(coreOrderService.simpleEncode(param.getRetUrl()));
		pd.setSite_cd(param.getSiteCd());
		pd.setEscw_used(param.getEscwUsed() == null ? "" : param.getEscwUsed());*/

		pd.setGood_mny(request.getParameter("good_mny"));
		pd.setGood_name(request.getParameter("good_name"));
		pd.setOrdr_idxx(request.getParameter("ordr_idxx"));
		pd.setPay_method(request.getParameter("pay_method"));
		pd.setRet_URL(request.getParameter("Ret_URL"));
		pd.setSite_cd(request.getParameter("site_cd"));
		pd.setEscw_used(request.getParameter("escw_used") == null ? "" : request.getParameter("escw_used"));

		String responseType = request.getParameter("response_type");
		if("JSON".equals(responseType) || "XML".equals(responseType)) {
			pd.setResponse_type(responseType);
		}

		String result = suc.kcpPaymentSmartPhone(request, Boolean.parseBoolean(env.getProperty("pg.kcp.server")), pd, env.getProperty("pg.kcp.log.dir"));
		log.info("CHECK KCP MOBILE RESULT ::::: {}", result);
		out.println(result); // 이클립스 상에서 메서드를 클릭 후 F2를 누르면 상세 내용이 나옵니다.

		return null;
	}

	/**
	 * 네이버 페이 결제 모듈
	 * @param request
	 * @param response
	 * @param cart
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@PostMapping("/nPayReq")
	public GagaMap nPayReq(@RequestBody Order param, HttpServletRequest request, HttpServletResponse response) {
		return orderService.nPayReq50(param, request, response);
	}

	/**
	 * 네이버 페이 상품정보 연동
	 * @param request
	 * @param response
	 * @param cart
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/create/npay/goodsxml")
	public void createNpayGoodsXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
		orderService.createNpayGoodsXml50(request, response);
	}

	/**
	 * 네이버 페이 찜하기 전송
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@PostMapping("/create/npay/zzim")
	public GagaMap nPayReq(@RequestBody Goods goods, HttpServletRequest request, HttpServletResponse response) throws Exception {
		return orderService.sendZzimToNC(goods, request, response);
	}
}
