package com.style24.scm.biz.service;

import java.util.Collection;

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.env.GagaExcelConstants;
import com.gagaframework.excel.xssf.GagaExcelResultHandler;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.Order;
import com.style24.scm.biz.dao.TssOrderDao;
import com.style24.scm.support.security.session.TssSession;

import lombok.extern.slf4j.Slf4j;

import com.style24.scm.support.util.TsitUtil;

/**
 * 주문 Service
 *
 * @author gagamel
 * @since 2020. 10. 19
 */
@Service
@Slf4j
public class TssOrderService {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TssOrderDao orderDao;
	
	/**
	 * 주문목록
	 * @param Order
	 * @return
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getOrderList(Order order) {
		return orderDao.getOrderList(order);
	}
	
	/**
	 * 주문리스트 합계
	 *
	 * @param order
	 * @return Order - 합계정보
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Order getOrderListSumInfo(Order order) {
		// multi row 검색관련 처리
		if (StringUtils.isNotBlank(order.getCondition())) {
			TsitUtil tsitUtil = new TsitUtil();
			String searchCondition = tsitUtil.replaceMultiSelectParamsArr(order.getCondition());
			order.setConditions(searchCondition.split(","));
		}

		// 외부몰권한일 때 외부몰벤더ID 설정
		//if (TsaSession.getInfo().getRoleCd().startsWith("C")) {
			//order.setMallGb(TsaConstants.MallGb.EXTMALL.value());
			//order.setVendorId(TsaSession.getInfo().getVendorId());
		//}
		
		return orderDao.getOrderListSumInfo(order);
	}
	
	/**
	 * 주문상세 정보
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getOrderInfoList(Order order) {
		return orderDao.getOrderInfoList(order);
	}
	
	/**
	 * 주문상세 목록
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getOrderDetailList(Order order) {
		return orderDao.getOrderDetailList(order);
	}
	
	/**
	 * 배송정보
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getDeliveryAddrList(Order order) {
		return orderDao.getDeliveryAddrList(order);
	}
	
	/**
	 * 주문상세 단품 목록
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getOrderDetailItemList(Order order) {
		return orderDao.getOrderDetailItemList(order);
	}
	
	/**
	 * 결제내역 > 결제 기본정보
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getOrderPaymentBasicInfoList(Order order) {
		return orderDao.getOrderPaymentBasicInfoList(order);
	}
	
	/**
	 * 배송비 정보
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getDeliveryFeeList(Order order) {
		return orderDao.getDeliveryFeeList(order);
	}
	
	/**
	 * 취소/반품/교환 요청 정보
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getOrderChangeList(Order order) {
		return orderDao.getOrderChangeList(order);
	}
	
	/**
	 * 환불정보
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> orderRefundInfo(Order order) {
		return orderDao.orderRefundInfo(order);
	}
	
	/**
	 * 상담내역
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> orderCounselInfo(Order order) {
		return orderDao.orderCounselInfo(order);
	}
	
	/**
	 * 변경내역 > 주문요청 관리자 메모
	 *
	 * @param order - 주문 정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 18
	 */
	public Collection<Order> getOrderTsainMemoList(Order order) {
		order.setDelYn("N");
		return orderDao.getOrderTsainMemoList(order);
	}
	
	/**
	 * 입점업체미발주 주문목록
	 * @param Order
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 30
	 */
	public Collection<Order> getOrderSellerUnorderList(Order order) {
		return orderDao.getOrderSellerUnorderList(order);
	}
	
	/**
	 * 입점업체미발주목록 - 엑셀다운로드시 주문상태값 변경(상품준비중)
	 *
	 * @param orderList - 주문 정보
	 * @author jsh77b
	 * @since 2020. 11. 30
	 */
	@Transactional("shopTxnManager")
	public void saveUnorderStatus(Collection<Order> orderList) {

		// 1. 임시테이블 삭제
		Order deleteOrder = new Order();
		deleteOrder.setRegNo(TssSession.getInfo().getUserNo());
		orderDao.deleteEntryExcelDownTmp(deleteOrder);

		for (Order oneData : orderList) {

			Order updateData = new Order();

			updateData.setOrdNo(oneData.getOrdNo());
			updateData.setOrdDtlNo(oneData.getOrdDtlNo());
			updateData.setBrandCd(oneData.getBrandCd());
			updateData.setSupplyCompCd(oneData.getSupplyCompCd());
			updateData.setRegNo(TssSession.getInfo().getUserNo());
			updateData.setUpdNo(TssSession.getInfo().getUserNo());
			
			log.info("updateData={}", updateData);

			// 2. 주문상세상태값 변경
			int result = orderDao.updateOrderDetailStat(updateData);
			if (result > 0) {
				// 3. 주문상세상태 변경 이력생성
				orderDao.createOrderDetailHst(updateData);
			}
			
			// 4. 엑셀 다운로드용 임시테이블 데이타 체크
			result = orderDao.getEntryUploadExcelCheck(updateData);
			if (result < 1) {
				// 5. 엑셀 다운로드용 임시테이블 저장
				orderDao.createEntryExcelDownTmp(updateData);
			}
		}
	}
	
	/**
	 * 입점업체미발주목록 엑셀다운로드
	 *
	 * @param order - 주문정보
	 * @param excelFilenameWithPath - 경로를 포함한 엑셀파일명
	 * @author jsh77b
	 * @since 2020. 11. 30
	 */
	public void geSellerUnorderExcelList(Order order, String excelFilenameWithPath) {
		
		// 헤더 title 설정 (23)
		String[] listTitles = {
			"입점업체"
			, "브랜드"
			, "주문번호"
			, "주문상세번호"
			, "주문상세상태"
			, "주문자명"
			, "주문일시"
			, "결제수단"
			, "주문자휴대전화"
			, "수령자명"
			, "수령자휴대전화"
			, "수령자우편번호"
			, "수령자기본주소"
			, "수령자상세주소"
			, "업체상품코드"
			, "상품코드"
			, "상품명"
			, "사이즈"
			, "주문수량"
			, "주문금액"
			, "할인금액"
			, "실결제금액"
			, "송장"
		};

		// DB 처리 시 사용되는 파라미터명(셀명) 설정 (23)
		String[] cellNames = {
			"supplyCompNm"
			, "brandKnm"
			, "ordNo"
			, "ordDtlNo"
			, "ordDtlStatNm"
			, "ordNm"
			, "ordDt"
			, "payMeansNm"
			, "ordPhnno"
			, "recipNm"
			, "recipPhnno"
			, "recipZipNo"
			, "recipBaseAddr"
			, "recipDtlAddr"
			, "supplyGoodsCd"
			, "goodsCd"
			, "goodsNm"
			, "optCd2"
			, "ordQty"
			, "ordAmt"
			, "totDcAmt"
			, "realOrdAmt"
			, "invoiceNo"
		};
		
		String[] cellTypes = {
			GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
			, GagaExcelConstants.CellType.CHAR_CENTER.name()
		};

		GagaExcelResultHandler<Order> handler = new GagaExcelResultHandler<>(excelFilenameWithPath, "출고배송목록(입점)", listTitles, cellNames, cellTypes);
		
		orderDao.getSellerUnorderList(order, handler);
		
		handler.close();
	}
	
	/**
	 * 입점업체미발주목록 - 송장번호 입력(출고완료)
	 *
	 * @param orderList - 주문 정보
	 * @return String - 결과메시지
	 * @author jsh77b
	 * @since 2020. 11. 30
	 */
	@Transactional("shopTxnManager")
	public String saveUnorderInvoice(Collection<Order> orderList) {
		String resultMsg;
		int totalCount 			= 0;	// 전체 카운트
		int failedCount 		= 0;	// 몰 실패 카운트
		int successCount 		= 0;	// 몰 성공 카운트
		String failedGoodCdStr 	= "";	// 실패 상품 리스트
		
		// 1. 송장번호 등록 대상 목록 처리
		for (Order oneData : orderList) {
			// 2. 송장번호, 업체코드 체크 
			if (!StringUtils.isEmpty(oneData.getInvoiceNo()) && !StringUtils.isEmpty(oneData.getShipCompCd())) {
				totalCount++;
				
				Order updateData = new Order();
				updateData.setOrdNo(oneData.getOrdNo());
				updateData.setOrdDtlNo(oneData.getOrdDtlNo());
				updateData.setBrandCd(oneData.getBrandCd());
				updateData.setSupplyCompCd(oneData.getSupplyCompCd());
				updateData.setRegNo(TssSession.getInfo().getUserNo());
				updateData.setUpdNo(TssSession.getInfo().getUserNo());
				updateData.setGoodsCd(oneData.getGoodsCd());
				updateData.setOptCd2(oneData.getOptCd2());
				updateData.setOrdQty(oneData.getOrdQty());
				updateData.setShipCompCd(oneData.getShipCompCd());
				updateData.setInvoiceNo(oneData.getInvoiceNo().replace("-", ""));

				// 3. 원주문 상세정보 조회
				Order orgOrder = orderDao.getOrderDetailInfo(oneData.getOrdDtlNo());
				if (orgOrder == null) {
					failedGoodCdStr += updateData.getGoodsCd() + " /  " + updateData.getOptCd2() + "(Error1)<br/>"; // 상품정보 (상품명 + 칼라명) / 사이즈코드
					failedCount++;
					continue;
				}

				// 4. 상품코드, 사이즈, 주문수량 체크
				if (!orgOrder.getGoodsCd().equals(updateData.getGoodsCd()) || !orgOrder.getOptCd2().equals(updateData.getOptCd2()) || orgOrder.getOrdQty() != updateData.getOrdQty()) {
					failedGoodCdStr += updateData.getGoodsCd() + " /  " + updateData.getOptCd2() + "(Error1)<br/>";
					failedCount++;
					continue;
				}
				
				// 5. 업체코드설정
				updateData.setSupplyCompCd(orgOrder.getSupplyCompCd());
				
				// 6. 송장번호등록
				int result = orderDao.updateOrderDetailInvoice(updateData);
				
				// 7. 주문상세상태 변경 이력 등록
				if (result > 0) {
					successCount++;
					orderDao.createOrderDetailHst(updateData);
				} else {
					failedGoodCdStr += updateData.getGoodsCd() + " /  " + updateData.getOptCd2() + "(Error1)<br/>";
					failedCount++;
				}
			}
		}

		resultMsg = "출고완료 : " + totalCount + "건 / 실패 : " + failedCount + "건 / 성공 : " + successCount + "건 <br/>" + "실패 목록 : " + failedGoodCdStr;

		return resultMsg;
	}

}
