package com.style24.scm.biz.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gagaframework.excel.GagaExcelUtil;
import com.gagaframework.excel.env.GagaExcelConstants;
import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.rest.server.GagaResponseStatus;
import com.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaStringUtil;
import com.style24.core.biz.dao.TscOrderChangeDao;
import com.style24.core.biz.dao.TscOrderDao;
import com.style24.core.biz.thirdparty.HansaeErp;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.env.TscConstants.OrderDetailStat;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Erp;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.Pos;
import com.style24.scm.biz.dao.TssPosDao;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

/**
 * 매장POS Service
 *
 * @author moon
 * @since 2021. 06. 11
 */
@Service
@Slf4j
public class TssPosService {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TssPosDao posDao;

	@Autowired
	private TscOrderDao orderDao;	
	
	@Autowired
	private TscOrderChangeDao orderChangeDao;
	
	@Autowired
	private HansaeErp hansaeErp;
	
	/**
	 * 매장로그인 정보 조회
	 * @param  Pos
	 * @return 
	 * @author moon
	 * @since  2021. 06. 11
	 */
	@Transactional("shopTxnManager")
	public Pos getStoreLoginInfo(Pos pos) {
		return posDao.getStoreLoginInfo(pos);
	}
	
	
	/**
	 * 출고대기/출고목록
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 11
	 */
	public Collection<Pos> getPosDeliveryList(Pos pos) {
		return posDao.getPosDeliveryList(pos);
	}
	
	/**
	 * 확정대기목록 
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 21
	 */
	public Collection<Pos> getPosConfirmList(Pos pos) {
		return posDao.getPosConfirmList(pos);
	}	
	
	/**
	 * 매장POS - 출고수락
	 *
	 * @param Pos 
	 * @return String
	 * @author moon
	 * @since 2021. 06. 13
	 */
	@Transactional("shopTxnManager")
	public String savePosDeliveryLocAssign(Pos pos) {
		String rtn = "";
		String chkYn = "";
		Pos chk = posDao.getDelvLocChk(pos);
		rtn = chk.getDelvLocCdChk();
		chkYn = chk.getChkYn();
		
		if("S".equals(rtn)) {
			if("Y".equals(chkYn)) {
				Integer userNo = TssSession.getInfo().getUserNo();
				pos.setRegNo(userNo);
				pos.setUpdNo(userNo);
				pos.setDelvArNo(userNo);
		
				pos.setAssignQty(pos.getOrdQty());
				// 출고처 수락
				posDao.updateDeliveryAssign(pos);
				// 출고처지정 이력 삽입
				posDao.createDeliveryAssignHst(pos);
		
				pos.setOrdDtlStat(OrderDetailStat.GOODS_PREPARE.value()); // 상품준비중
		
				// G013_35(출고처지정) -> G013_30(배송준비중) 변경
				posDao.updateOrderDetail(pos);
				
				// 주문상세이력
				Order order = new Order();
				order.setOrdDtlNo(pos.getOrdDtlNo());
				order.setUpdNo(userNo);
				order.setRegNo(userNo);
				orderDao.createOrderDetailHst(order);
			} else {
				rtn = chkYn;
			}
		}
		return rtn;
	}
	
	/**
	 * 매장POS - 출고거부
	 *
	 * @param Pos 
	 * @return String
	 * @author moon
	 * @since 2021. 06. 13
	 */
	@Transactional("shopTxnManager")
	public String savePosDeliveryLocReject(Pos pos) {
		String rtn   = "";
		String chkYn = "";
		Pos chk = posDao.getDelvLocChk(pos);
		rtn   = chk.getDelvLocCdChk();
		chkYn = chk.getChkYn();
		
		if("S".equals(rtn)) {
			if("Y".equals(chkYn)) {
				Integer userNo = TssSession.getInfo().getUserNo();
				pos.setRegNo(userNo);
				pos.setUpdNo(userNo);
				pos.setDelvArNo(userNo);
				pos.setAssignQty(pos.getOrdQty());

				// 출고처 거부
				posDao.updateDeliveryAssign(pos);
		
				// 출고처지정 이력 삽입
				posDao.createDeliveryAssignHst(pos);
				
				// 주문상세번호로  아이템리스트 조회 
				Collection<Pos> ordDtlItemList = posDao.getOrdDtlItemList(pos);
				for (Pos param : ordDtlItemList) {
					param.setDelvBanStdt(GagaDateUtil.getToday());
					param.setDelvBanEddt(GagaDateUtil.getOffsetDate(2));
					param.setRegNo(userNo);
					param.setUpdNo(userNo);
					// 출고금지상품 등록
					posDao.createBangoods(param);
				} 
				
				pos.setOrdDtlStat(OrderDetailStat.PAYMENT_COMPLETE.value()); // 결제완료 
		
				// 주문상세 출고처 업데이트
				posDao.updateOrderDetail(pos);
		
				// 주문상세 이력 삽입
				Order order = new Order();
				order.setOrdDtlNo(pos.getOrdDtlNo()); 
				order.setUpdNo(userNo);
				order.setRegNo(userNo);
				orderDao.createOrderDetailHst(order);
				

			} else {
				rtn = chkYn;
			}
		}
		return rtn;
	}
	


	/**
	 * CNPlus 엑셀다운로드
	 * 
	 * @param pos - 매장정보
	 * @return Pos
	 * @author moon
	 * @since 2021. 06. 14
	 */
	public void getOrderExcelList(Pos pos, String excelFilenameWithPath) {

		// 헤더 title 설정

		String[] listTitles = {"예약구분", "집하예정일", "받는분성명"  //3
			, "받는분전화번호", "받는분기타연락처", "받는분우편번호" //3
			, "받는분주소(전체, 분할)", "운송장번호", "고객주문번호" //3
			, "품목명", "박스수량", "박스타입", "기본운임"  //4
			, "배송메세지1", "배송메세지2", "품목명"};  //3

		// DB 처리 시 사용되는 파라미터명(셀명) 설정
		String[] cellNames = {"RSRVT_GB", "SCHDL_CLDT", "RECIP_NM"  //3
			, "RECIP_PHNNO", "RECIP_TELNO", "RECIP_ZIPCODE" //3
			, "RECIP_ADDR", "INVOICE_NO", "ORD_NO"  //3
			, "GOODS_NM", "BOX_QTY", "BOX_TYPE", "FEE" //4
			, "DELV_MEMO", "DELV_MEMO2", "GOODS_CD"}; //3

		String[] cellTypes = {GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name(),
			GagaExcelConstants.CellType.CHAR_LEFT.name(), GagaExcelConstants.CellType.CHAR_LEFT.name()
		};
		Collection<GagaMap> dataList = posDao.getOrderExcelList(pos); // map형식으로 조회
		try {
			GagaExcelUtil.createExcel(excelFilenameWithPath, dataList,"" ,listTitles, cellNames, cellTypes);
			//GagaExcelUtil.createExcel(excelFilenameWithPath, dataList,"테스트" ,listTitles, cellNames, cellTypes,"",true);
			//GagaExcelUtil.createExcel(excelFilenameWithPath, dataList , cellNames, cellTypes);
 
		} catch (Exception e) {
			throw new IllegalStateException(e);
		}
	}
	
	/**
	 * 매장POS -송장번호 생성,배송처리
	 *
	 * @param Pos 
	 * @return GagaMap
	 * @author moon
	 * @since 2021. 06. 21
	 */
	@Transactional("shopTxnManager")
	public GagaMap savePosInvoice(Pos pos) {

		Pos stat = new Pos();
		stat.setOrdDtlNo(pos.getOrdDtlNo());
		Pos orderStat = posDao.getOrderDtlStat(stat);
		GagaMap result = new GagaMap();

		if ("G013_30".equals(orderStat.getOrdDtlStat()) && StringUtils.isBlank(orderStat.getInvoiceNo())) {

			String invoiceNo = pos.getInvoiceNo();
			Pos params = new Pos();
			params.setOrdDtlNo(pos.getOrdDtlNo());
			params.setOrdDtlStat(OrderDetailStat.DELIVERY_PREPARE.value()); // 배송준비중 
			params.setUpdNo(pos.getUpdNo());
			params.setRegNo(pos.getUpdNo());
			params.setInvoiceNo(invoiceNo);
			params.setDelvFeeRate(pos.getDelvFeeRate());

			// 주문상세상태 변경
			params.setShipCompCd(pos.getShipCompCd()); // 배송업체코드
			posDao.updateOrderDetail(params);

			// 주문상세 이력 삽입
			Order order = new Order();
			order.setOrdDtlNo(pos.getOrdDtlNo());
			order.setUpdNo(pos.getUpdNo());
			order.setRegNo(pos.getUpdNo());
			orderDao.createOrderDetailHst(order);



			// 송장번호 저장
			Pos invoNo = new Pos();
			invoNo.setOrdNo(orderStat.getOrdNo());
			invoNo.setOrdDtlNo(pos.getOrdDtlNo());
			invoNo.setInvoiceNo(invoiceNo);
			invoNo.setRegNo(pos.getUpdNo());
			invoNo.setDelYn("N");

			posDao.insertTbOderDetailInvoice(invoNo);


			result.set("status", GagaResponseStatus.SUCCESS.getCode());
			result.setString("message", "정상처리 되었습니다.");
		} else {
			if ("99".equals(orderStat.getOrdDtlStat())) {
				result.setString("message", "취소된 주문건 입니다.");
			}
			if (StringUtils.isNotBlank(orderStat.getInvoiceNo())) {
				result.setString("message", "이미 송장번호가 있습니다.");
			}
			result.set("status", GagaResponseStatus.FAIL.getCode());
		}
		result.setString("ordNo", pos.getOrdNo() + "");
		result.setString("ordDtlNo", pos.getOrdDtlNo() + "");

		return result;
	}	
	
	/**
	 * 매장POS -배송처리
	 *
	 * @param Pos 
	 * @return void
	 * @author moon
	 * @since 2021. 06. 14   == 삭제!!!
	 */
	@Transactional("shopTxnManager")
	public GagaMap savePos(Pos data) {
		
		GagaMap result = new GagaMap();
		Integer userNo = TssSession.getInfo().getUserNo();
		
		Pos stat = new Pos();
		stat.setOrdDtlNo(data.getOrdDtlNo());
		Pos orderStat = posDao.getOrderDtlStat(stat);

		if ("G013_30".equals(orderStat.getOrdDtlStat()) && StringUtils.isBlank(orderStat.getInvoiceNo())) {

			Pos params = new Pos();
			params.setOrdDtlNo(data.getOrdDtlNo());
			params.setOrdDtlStat(OrderDetailStat.DELIVERY_PREPARE.value()); // 40 배송준비중

			params.setUpdNo(userNo);
			params.setRegNo(userNo);

			posDao.updateOrderDetail(params);

			// 주문상세 이력 삽입
			Order order = new Order();
			order.setOrdDtlNo(data.getOrdDtlNo());
			order.setUpdNo(userNo);
			order.setRegNo(userNo);
			orderDao.createOrderDetailHst(order);
			
			result.set("status", GagaResponseStatus.SUCCESS.getCode());
			result.setString("message", "정상처리 되었습니다.");
		} else {
			if ("G013_99".equals(orderStat.getOrdDtlStat())) {
				result.setString("message", "취소된 주문건 입니다.");
			}
			if (StringUtils.isNotBlank(orderStat.getInvoiceNo())) {
				result.setString("message", "이미 송장번호가 있습니다.");
			}
			result.set("status", GagaResponseStatus.FAIL.getCode());
		}

		result.setString("ordNo", data.getOrdNo() + "");
		result.setString("ordDtlNo", data.getOrdDtlNo() + "");

		return result;
	}
	
	/**
	 * 매장POS - 수락취소시 주문정보 validation 확인
	 *
	 * @param Pos 
	 * @return GagaMap
	 * @author moon
	 * @since 2021. 06. 21
	 */
	public GagaMap getPosDeliveryLocValidation(Pos pos) {
		GagaMap result = new GagaMap();
		
		boolean validation = true;
		String resultMsg = message.getMessage("SUCC_0001");
		int status = GagaResponseStatus.SUCCESS.getCode();
		
		Pos orderStat = posDao.getOrderDtlStat(pos);
		log.info("pos.getDelvLocCd() :"+pos.getDelvLocCd());
		if(!pos.getDelvLocCd().equals(orderStat.getDelvLocCd())) {
			validation = false;
			resultMsg  = "출고처가 변경되었습니다.";
		} else if(OrderDetailStat.PAYMENT_AFTER_CANCEL.value().equals(orderStat.getOrdDtlStat())) {
			validation = false;
			resultMsg  = "취소된 주문입니다.";
		} else if(orderStat.getOrdDtlStat().equals(OrderDetailStat.SHIPPING.value()) || orderStat.getOrdDtlStat().equals(OrderDetailStat.DELIVERY_COMPLETE.value()) || orderStat.getOrdDtlStat().equals(OrderDetailStat.PURCHASE_CONFIRM.value())) {
			validation = false;
			resultMsg  = "확정완료되어 취소 할 수 없습니다.";
		}
		if (!validation) {
			status = GagaResponseStatus.FAIL.getCode();
		}
		
		result.setBoolean("validation", validation);
		result.setString("resultMsg", resultMsg);
		result.set("status", status);
		
		return result;
	}
	
	/**
	 * 매장POS - 수락취소
	 *
	 * @param pos 
	 * @return void
	 * @author moon
	 * @since 2021. 06. 21
	 */
	@Transactional("shopTxnManager")
	public void savePosDeliveryLocRejectCancel(Pos pos) {

		Integer userNo = TssSession.getInfo().getUserNo();
		
		pos.setRegNo(userNo);
		pos.setUpdNo(userNo);
		pos.setDelvArNo(userNo);
		pos.setAssignQty(pos.getOrdQty());

		pos.setDelvBanStdt(GagaDateUtil.getToday());
		pos.setDelvBanEddt(GagaDateUtil.getOffsetDate(3));

		// 출고처 수락/거부
		posDao.updateDeliveryAssignCancel(pos);
		// 출고처지정 이력 삽입
		posDao.createDeliveryAssignHst(pos);
		
		// 주문상세번호로  아이템리스트 조회 
		Collection<Pos> ordDtlItemList = posDao.getOrdDtlItemList(pos);
		for (Pos param : ordDtlItemList) {
			param.setDelvBanStdt(GagaDateUtil.getToday());
			param.setDelvBanEddt(GagaDateUtil.getOffsetDate(2));
			param.setRegNo(userNo);
			param.setUpdNo(userNo);
			// 출고금지상품 등록
			posDao.createBangoods(param);
		} 
		
		pos.setOrdDtlStat(OrderDetailStat.PAYMENT_COMPLETE.value());
		pos.setInvoiceNo("");
		
		// 주문상세 출고처 업데이트
		posDao.updateOrderDetail(pos);
		
		// 주문상세 이력 삽입
		Order order = new Order();
		order.setOrdDtlNo(pos.getOrdDtlNo()); 
		order.setUpdNo(userNo);
		order.setRegNo(userNo);
		orderDao.createOrderDetailHst(order);
		

	}

	/**
	 * 매장POS -출고확정
	 *
	 * @param Pos 
	 * @return GagaMap
	 * @author moon
	 * @since 2021. 06. 21
	 */
	@Transactional("shopTxnManager")
	public GagaMap saveConfirmation(Pos pos, int cnt) {
		GagaMap result = new GagaMap();
		Integer userNo = TssSession.getInfo().getUserNo();
		Collection<Erp> rtList = new ArrayList();
		Collection<Erp> salesList = new ArrayList();
		
		Date date = new Date();

		SimpleDateFormat ifDt = new SimpleDateFormat("yyyymmddhhmmss");
		String noIf =  ifDt.format(date);
		
		Collection<Pos> list = posDao.getSendErpList(pos);
		
		log.info("list {}"+list);
		for(Pos data : list) {
			Erp erpData = new Erp();
			erpData.setCD_RTOUTSHOP(data.getCdRtoutshop());
			erpData.setCD_STYLE(data.getCdStyle());
			erpData.setCD_COLOR(data.getCdColor());
			erpData.setCD_SIZE(data.getCdSize());
			erpData.setQT_RTOUT(data.getQtRtout());
			rtList.add(erpData);
			
			erpData.setNO_IF(noIf+ GagaStringUtil.getLPadding(cnt+"", 4, "0"));
			//erpData.setDT_SALE(data.getDtSale());
			erpData.setDT_SALE("20210731");
			erpData.setQT_SALE(data.getQtSale());
			erpData.setAM_ACSALE(data.getAmAcsale());
			erpData.setDS_REMARK("TEST");
			salesList.add(erpData);
			
		}
		
		// API 호출 재고이동
		//hansaeErp.erpStockRt(HansaeErp.ErpGb.HANSAE_DR.value(), rtList);
		
		// API 호출 매출정보 
		//GagaMap resultMap = hansaeErp.uploadErpSales(HansaeErp.ErpGb.HANSAE_DR.value(), salesList);
		
		// 주문상세 업데이트
		pos.setOrdDtlStat(OrderDetailStat.SHIPPING.value()); // 배송중 
		pos.setInvoiceNo("");
		pos.setDelvArGb("");
		pos.setUpdNo(userNo);
		posDao.updateOrderDetail(pos);

		// 주문상세 이력 삽입
		Order order = new Order();
		order.setOrdDtlNo(pos.getOrdDtlNo()); 
		order.setUpdNo(userNo);
		order.setRegNo(userNo);
		orderDao.createOrderDetailHst(order);
		
		// 주문상세단품 HST 등록???
		for(Pos data : list) {
			Order ordItem = new Order();
			ordItem.setUpdNo(userNo);
			ordItem.setRegNo(userNo);
			ordItem.setOrdDtlStat(""); // ???
			ordItem.setOrdDtlItemSq(data.getOrdDtlItemSq());
			//orderChangeDao.createOrderDetailItemHst(ordItem);
			
			// 2021.06.25 POS 배송중 (정산구분값추가)
			order.setOrdDtlStat(TscConstants.OrdDtlItemStat.SALE_SHIPPING.value());
			orderDao.createOrderDetailItemHst(order);
		}
		
		return result;
	}
	
	/**
	 * 매장POS - 정산내역
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 21
	 */
	public Collection<Pos> getPosUsacList(Pos pos) {
		return posDao.getPosUsacList(pos);
	}
	
	/**
	 * 매장거부 목록
	 *
	 * @param -Pos
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 21
	 */
	public Collection<Pos> getDeliveryAssignList(Pos pos) {
		return posDao.getDeliveryAssignList(pos);
	}	
	
}
