package com.style24.scm.biz.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

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.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.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.core.biz.service.TscKakaotalkService;
import com.style24.core.biz.service.TscNaverPayService;
import com.style24.core.biz.service.TscOrderChangeService;
import com.style24.core.biz.service.TscOrderService;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.TscPageRequest;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.OrderChange;
import com.style24.scm.biz.service.TssOrderService;
import com.style24.scm.biz.service.TssRendererService;
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("/order")
@Slf4j
public class TssOrderController extends TssBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TssRendererService rendererService;
	
	@Autowired
	private TssOrderService orderService;

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

	@Autowired
	private TscNaverPayService coreNaverPayService;
	
	@Autowired
	private TscOrderChangeService coreOrderChangeService;
	
	@Autowired
	private TscKakaotalkService coreKakaotalkService;

	/**
	 * 입점업체미발주목록화면
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 11. 30
	 */
	@GetMapping("/seller/unorder/list/form")
	public ModelAndView orderSellerUnorderListForm() {
		ModelAndView mav = new ModelAndView();
		
		// 공급업체
		String supplyCompCd 	= "";
		String selfYn 			= "Y";
		
		// 입점업체담당자
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {	
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "N";
		}
		// 촬영업체
		else if ("G001_E000".equals(TssSession.getInfo().getRoleCd())) {	
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "Y";
		}
		
		mav.addObject("supplyCompList"	, rendererService.getSupplyCompanyList(supplyCompCd, selfYn)); 	// 공급업제목록
		mav.addObject("ordDtlStatList"	, rendererService.getAvailCommonCodeList("G013"));				// 주문상세상태코드
		mav.addObject("shipCompanyList"	, rendererService.getShipCompanyList());						// 택배사 목록

		mav.setViewName("order/OrderSellerListForm");

		return mav;
	}
	
	/**
	 * 입점업체미발주 주문목록 조회
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 16
	 */
	@PostMapping("/seller/unorder/list")
	@ResponseBody
	public GagaMap getOrderSellerUnorderList(@RequestBody Order order) {
		GagaMap result = new GagaMap();

		order.setPageable(new TscPageRequest(0, 10000));

		// 주문전체건수 조회
		int totalCount = coreOrderService.getOrderSellerUnorderListCount(order);
		order.getPageable().setTotalCount(totalCount);

		Collection<Order> orderList = coreOrderService.getOrderSellerUnorderList(order);

		result.set("pageing"	, order);
		result.set("orderList"	, orderList);

		return result;
	}
	
	/**
	 * 입점업체미발주목록 - 엑셀다운로드시 주문상태값 변경(상품준비중)
	 *
	 * @param orderList - 미발주목록
	 * @return GagaResponse
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@PostMapping("/seller/unorder/status/save")
	@ResponseBody
	public GagaResponse saveUnorderStatus(@RequestBody Collection<Order> orderList) {
		int userNo = TssSession.getInfo().getUserNo();
		coreOrderService.saveUnorderStatus(orderList, userNo);
		return super.ok("");
	}
	
	/**
	 * 입점업체미발주목록 - 엑셀다운로드
	 *
	 * @param request - request
	 * @return ResponseEntity<InputStreamResource>
	 * @throws Exception - exception
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@GetMapping("/seller/unorder/excel/list")
	public ResponseEntity<InputStreamResource> downloadPickingGoodsExcelList(HttpServletRequest request, Order param) throws Exception {
		String excelfileName 	= "입점출고목록_" + GagaDateUtil.getTodayDateTime() + ".xlsx";
		String excelFilePath 	= GagaFileUtil.getConcatenationPath(env.getProperty("download.path"), "excel", excelfileName);
		
		param.setRegNo(TssSession.getInfo().getUserNo());
		param.setSearch("EXCEL");

		coreOrderService.geSellerUnorderExcelList(param, excelFilePath);

		return GagaFileUtil.writeFile(request, excelFilePath);
	}
	
	/**
	 * 입점 송장 엑셀 업로드
	 *
	 * @param order - 주문정보
	 * @return GagaMap
	 * @throws Exception - exception
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@PostMapping("/seller/unorder/invoice/excelupload/save")
	@ResponseBody
	public GagaMap saveSellerUnorderInvoiceExcelupload(@RequestBody Order order) throws Exception {

		ObjectMapper mapper = new ObjectMapper();
		
		// 1. UPLOAD 경로 조회
		String targetPath = GagaFileUtil.getConcatenationPath(env.getProperty("upload.excel.target.path"), "excel");
		
		// 2. DB 처리 시 사용되는 파라미터명(셀명) 설정
		String[] cellName = {
				  "supplyCompNm"
				, "brandKnm"
				, "ordNo"
				, "ordDtlNo"
				, "ordDtlStatNm"
				, "ordNm"
				, "ordDt"
				, "payMeansNm"
				, "ordPhnno"
				, "recipNm"
				, "recipPhnno"
				, "recipZipcode"
				, "recipBaseAddr"
				, "recipDtlAddr"
				, "supplyGoodsCd"
				, "goodsCd"
				, "goodsNm"
				, "optCd2"
				, "opt"
				, "ordQty"
				, "cnclRtnQty"
				, "ordAmt"
				, "cnclRtnAmt"
				, "totDcAmt"
				, "realOrdAmt"
				, "realDelvAmt"
				, "shipCompCd"
				, "invoiceNo"
				, "delvMemo"
		};
		
		Collection<GagaMap> ecxelList = GagaExcelUtil.getList(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()), 2, cellName, 0);
		
		// 3. 주문목록 매퍼 등록
		Collection<Order> orderList = new ArrayList<>();
		for (GagaMap map : ecxelList) {
			Order tmpGoods = mapper.convertValue(map, Order.class);
			orderList.add(tmpGoods);
		}
		
		// 4. 업로드된 임시 엑셀파일 삭제
		if (CollectionUtils.isEmpty(orderList)) {
			try {
				GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()));
			} catch (IOException e) {
				// Nothing Do
			}
			//throw new IllegalStateException(message.getMessage("FAIL_1001"));
			throw new IllegalStateException("실패 했습니다.");
		}
		
		// 4. 주문상세번호 기준으로 송장번호 등록
		int userNo = TssSession.getInfo().getUserNo();
		String result = coreOrderService.saveUnorderInvoice(orderList, userNo);
		GagaMap map = new GagaMap();
		map.set("msg", result);

		// 5. 파일 삭제 (중복처리?)
		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, order.getExcelFileNm()));

		return map;
	}
	
	/**
	 * 입점업체미발주목록 - 송장번호 입력(자사 : 배송준비중, 입점 : 배송준비중)
	 *
	 * @param orderList - 송방번호 입력된 주문리스트
	 * @return GagaMap
	 * @author jsh77b
	 * @since 2020. 12. 01
	 */
	@PostMapping(value = "/seller/unorder/invoice/save")
	@ResponseBody
	public GagaMap saveUnorderInvoice(@RequestBody Collection<Order> orderList) {
		// 1. 송장번호 개별 등록
		int userNo = TssSession.getInfo().getUserNo();
		String result = coreOrderService.saveUnorderInvoice(orderList, userNo);
		GagaMap map = new GagaMap();
		map.set("msg", result);
		return map;
	}

	/**
	 * 입점업체 최종 배송 확인
	 *
	 * @return ModelAndView
	 * @author xodud1202
	 * @since 2021. 04. 20
	 */
	@GetMapping("/seller/final/delv/list/form")
	public ModelAndView sellerFinalDelvListForm() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("shipCompanyList", rendererService.getShipCompanyList());						// 택배사 목록
		mav.addObject("supplyCompCd", TssSession.getInfo().getSupplyCompCd());						// 입점업체 권한
		mav.setViewName("order/OrderSellerDelvListForm");
		return mav;
	}

	/**
	 * 입점업체 배송준비중 목록 조회
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2020. 11. 16
	 */
	@PostMapping("/seller/final/delv/list")
	@ResponseBody
	public Collection<Order> sellerFinalDelvList(@RequestBody Order order) throws Exception {
		Collection<Order> orderList = coreOrderService.getOrderSellerUnorderList(order);
		return orderList;
	}

	/**
	 * 입점 상품 배송중 처리
	 *
	 * @param orderList - 미발주목록
	 * @return GagaResponse
	 * @author xodud1202
	 * @since 2021. ?. ?
	 */
	@PostMapping("/seller/delv/started")
	@ResponseBody
	public GagaResponse sellerDelvStarted(@RequestBody Collection<Order> orderList) {
		int userNo = TssSession.getInfo().getUserNo();
		Collection<OrderChange> cancelDataList = coreOrderService.getCancelDataList(orderList, userNo);
		
		log.info("cancelDataList >>> {}", cancelDataList);
		log.info("size >>> {}", cancelDataList.size());

		// [주문배송] 리스트로 지정된 주문상세번호와 취소수량 배열로 변경 후 취소
		for (OrderChange change : cancelDataList) {
			change.setOrdDtlNoArr(change.getOrdDtlNoList().stream().mapToInt(i->i).toArray());
			change.setCnclRtnReqQtyArr(change.getCnclRtnReqQtyList().stream().mapToInt(i->i).toArray());

			// 2021.07.15 교환배송건인 경우는 취소처리 대상에서 예외 처리
			if (change.getOrdChgSq() == null || change.getOrdChgSq() < 1) {

				// PG구분:KCP, 결제수단:무통장입금, 환불계좌가 없는경우 취소접수단계로 처리
				// 2021.09.10 card007 핸드폰결제, 무통장입금은 부분취소 시 에러 발생함으로 취소접수로 처리
				// 2022.01.04 card007 취소접수 로직 현금환불처리로 변경
				GagaMap result;
				// 무통장입금
				if (TscConstants.PgGb.KCP.value().equals(change.getPgGb()) && TscConstants.PayMeans.BANK_DEPOSIT.value().equals(change.getPayMeans())) {
					change.setCashRefundReason(TscConstants.CashRefundReason.BANK_DEPOSIT.value());
					result = coreOrderChangeService.cashRefund(change, userNo);
				}
				// 신용카드(부분취소불가)
				else if (TscConstants.PgGb.KCP.value().equals(change.getPgGb()) && TscConstants.PayMeans.CREDIT_CARD.value().equals(change.getPayMeans()) && "N".equals(change.getCardPcableYn())) {
					change.setCashRefundReason(TscConstants.CashRefundReason.CREDIT_CARD.value());
					result = coreOrderChangeService.cashRefund(change, userNo);
				}
				// 휴대폰결제
				else if (TscConstants.PgGb.KCP.value().equals(change.getPgGb()) && TscConstants.PayMeans.CELL_PHONE.value().equals(change.getPayMeans())) {
					change.setCashRefundReason(TscConstants.CashRefundReason.CELL_PHONE.value());
					result = coreOrderChangeService.cashRefund(change, userNo);
				}
				// 무통장입금 주문 중 환불계좌정보 없을 경우 제외는 취소처리
				// 2021.09.10 card007 핸드폰결제, 무통장입금 제외로 변경
				else {
					// 취소완료처리
					result = coreOrderChangeService.orderCancelPreInfo(change, userNo);
				}

				// 3. 취소완료 카카오알림톡 발송
				Integer ordChgSq = result.getInt("ordChgSq");

				if (ordChgSq != null && ordChgSq > 0) {

					// 네이버페이 품절취소 송부
					if(TscConstants.PgGb.NAVER_ORDER.value().equals(change.getPgGb())) {
						for (int i = 0; i < change.getOrdDtlNoArr().length; i++) {
							Order order = new Order();
							order.setOrdDtlNo(change.getOrdDtlNoArr()[i]);
							try {
								coreNaverPayService.sendNaverPaySoldoutCancel(order, userNo);        // 품절취소
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					}

					try {
						// 취소 알림톡 관련 정보 조회
						OrderChange orderChange = new OrderChange();
						orderChange = coreOrderChangeService.getKakaoOrderCancelInfo(ordChgSq);

						// 취소 알림톡 발송
						orderChange.setChgGb(TscConstants.OrderCancelReason.SOLDOUT_CANCEL.value());
						coreKakaotalkService.sendOrderCancelComplete(orderChange, userNo);
					} catch (Exception e) {
						e.printStackTrace();
					}

					// TODO 취소 메일 송부를 품절취소에서도 보내는지 ?
				}
			}
		}

		String result = coreOrderService.updateSellerDelvStart(orderList, cancelDataList, userNo);

		return super.ok(result);
	}

	/**
	 * 입점 상품 주문 목록
	 * @param orderList - 주문목록화면
	 * @return ModelAndView
	 * @author xodud1202
	 * @since 2020. 06. 07
	 */
	@GetMapping("/seller/delv/list/form")
	public ModelAndView sellerDelvListForm() {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		String supplyCompCd 	= "";
		String selfYn 			= "Y";

		// 입점업체담당자
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "N";
		}
		// 촬영업체
		else if ("G001_E000".equals(TssSession.getInfo().getRoleCd())) {
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "Y";
		}

		mav.addObject("supplyCompList"	, rendererService.getSupplyCompanyList(supplyCompCd, selfYn)); 	// 공급업제목록
		mav.addObject("ordDtlStatList"	, rendererService.getAvailCommonCodeList("G013"));		// 주문상세상태코드
		mav.addObject("shipCompanyList"	, rendererService.getShipCompanyList());						// 택배사 목록

		mav.setViewName("order/OrderSellerDelvEndListForm");

		return mav;
	}

	/**
	 * 입점업체 주문 목록 조회
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author xodud1202
	 * @since 2021. 06. 07
	 */
	@PostMapping("/seller/order/list")
	@ResponseBody
	public GagaMap getOrderSellerOrderList(@RequestBody Order order) {
		GagaMap result = new GagaMap();

		order.setPageable(new TscPageRequest(order.getPageNo() - 1, order.getPageSize()));

		// 주문전체건수 조회
		int totalCount = coreOrderService.getOrderSellerUnorderListCount(order);
		order.getPageable().setTotalCount(totalCount);

		order.setIfYn("Y");			// 취소, 반품 신청/대기 건 제외하지 않도록 구분값 지정
		Collection<Order> orderList = coreOrderService.getOrderSellerUnorderList(order);

		result.set("pageing"	, order);
		result.set("orderList"	, orderList);

		return result;
	}
	
	/**
	 * 입점입고대상목록(교환,반품접수)
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2021. 05. 17
	 */
	@GetMapping("/seller/claim/list/form")
	public ModelAndView orderSellerClaimListForm() {
		ModelAndView mav = new ModelAndView();
		
		// 공급업체
		String supplyCompCd 	= "";
		String selfYn 			= "Y";
		
		// 입점업체담당자
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {	
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "N";
		}
		// 촬영업체
		else if ("G001_E000".equals(TssSession.getInfo().getRoleCd())) {
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "Y";
		}
		
		mav.addObject("supplyCompList"	, rendererService.getSupplyCompanyList(supplyCompCd, selfYn)); 	// 공급업제목록
		mav.addObject(" chgStatList"	, rendererService.getAvailCommonCodeList("G685"));				// 클렘임상태코드
		mav.setViewName("order/OrderSellerClaimListForm");

		return mav;
	}
	
	/**
	 * 입점클레임목록조회(교환,반품접수)
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2021. 05. 17
	 */
	@PostMapping("/seller/claim/list")
	@ResponseBody
	public GagaMap getOrderSellerClaimList(@RequestBody Order order) throws Exception {
		
		GagaMap result = new GagaMap();
		
		order.setPageable(new TscPageRequest(order.getPageNo() - 1, order.getPageSize()));
		
		// 주문전체건수 조회
		int totalCount = (int) coreOrderService.getOrderSellerClaimCount(order);
		order.getPageable().setTotalCount(totalCount);
		
		Collection<Order> orderSellerClaimList = coreOrderService.getOrderSellerClaimList(order);
		
		result.set("pageing"				, order);
		result.set("orderSellerClaimList"	, orderSellerClaimList);
				
		return result;
	}
	
	/**
	 * 취소, 반품 완료 상세 화면 (SCM)
	 * 
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2021. 12. 17
	 */
	@GetMapping("/scm/cnclRtn/complete/view")
	public ModelAndView cnclCompleteView(@RequestParam(value = "ordNo") int ordNo, @RequestParam(value = "ordDtlNo") int ordDtlNo
			, @RequestParam(value = "delvFeeCd") String delvFeeCd, @RequestParam(value = "delvFeeCdGrp") String delvFeeCdGrp
			, @RequestParam(value = "chgStat") String chgStat, @RequestParam(value = "ordChgSq") int ordChgSq) {
		
		ModelAndView mav = new ModelAndView();
		
		// 2021.01.26 취소요청 화면, 취소요청정보확인 화면 통합
		Order order = new Order();
		order.setOrdChgSq(ordChgSq);
		order.setOrdNo(ordNo);
		
		// 결제전취소, 결제후취소 일때 상태값 환입 취소완료 변경
		if ("G685_17".equals(chgStat) || "G685_18".equals(chgStat)) {
			order.setChgStat("G720_30");
		}
		else if ("G685_60".equals(chgStat)) {
			order.setChgStat("G720_50");
		}
		
		List<Order> cnclRtnCompleteList = coreOrderService.getCnclRtnCompleteList(order);
		
		// 2021.08.04 AS-IS  데이타를 위해서 생성 처리
		if (cnclRtnCompleteList == null || cnclRtnCompleteList.size() < 1) {
			OrderChange orderChange = new OrderChange();
			orderChange.setOrdChgSq(ordChgSq);
			GagaMap resultMap = coreOrderChangeService.getCreCancelDetailInfo(orderChange);
			mav.addObject("oneData"				, resultMap.get("oneData"));
		}
		
		Collection<Order> orderInfoList = coreOrderService.getOrderInfoList(order);
		
		mav.addObject("cnclRtnCompleteList"		, cnclRtnCompleteList);							// 취소완료목록
		mav.addObject("orderInfoList"			, orderInfoList);								// 주문기본정보
		mav.addObject("chgStat"					, order.getChgStat());							// 변경요청상태값(정산상태구분)
		mav.addObject("addDelvFeeObj"			, coreOrderService.getAddDelvFee(order));		// 추가배송비 결제여부 조회
		mav.addObject("ordChgSq"				, ordChgSq);									// 변경번호
		
		mav.setViewName("order/ScmCnclCompleteView");
		
		return mav;
	}
	
	/**
	 * 반품신청화면 (관리자)
	 * 
	 * @param ordNo - 주문번호
	 * @param cncWait - 취소대기요청 구분
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2020. 12. 22
	 */
	@GetMapping("/scm/rtn/req/form")
	public ModelAndView rtnReqForm(Order order) {
		ModelAndView mav = new ModelAndView();
		List<Integer> ordDtlNoList = new ArrayList<>();
		List<Integer> chgQtyList = new ArrayList<>();
		String ordChgGb = order.getOrdChgGb();
		String chgStat = "";

		// 1. 반품가능 주문상세상탭값 설정
		// 2021.09.14 card007 구매확정 반품신청
		String[] ordDtlStatArr = new String[5];
		ordDtlStatArr[0] = TscConstants.OrderDetailStat.SHIPPING.value();
		ordDtlStatArr[1] = TscConstants.OrderDetailStat.SHIP_COMPLETE.value();
		ordDtlStatArr[2] = TscConstants.OrderDetailStat.DELIVERY_COMPLETE.value();
		ordDtlStatArr[3] = TscConstants.OrderDetailStat.DELIVERY_PREPARE.value();
		ordDtlStatArr[4] = TscConstants.OrderDetailStat.PURCHASE_CONFIRM.value();
		order.setOrdDtlStatArr(ordDtlStatArr);

		// 2. 변경신청된 주문상세번호를 체크 후 있으면 해당 취소가능수량값 업데이트
		// 2021.09.07 관리자 반품 요청 화면은 정상 동작 처리
		//order.setChgGb(TscConstants.OrderChangeGb.RETURN.value());
		List<Order> cancelRequestTargetList 		= coreOrderService.getCancelRequestTargetList2(order);
		List<Order> orderChangeDetailList 			= coreOrderChangeService.getOrderChangeDetailList(order);
		Collection<Order> orderInfoList 			= coreOrderService.getOrderInfoList(order);

		// 반품상세화면 처리
		if (order.getOrdChgSq() > 0) {
			Collection<Order> returnDetailList;

			// 반품TO반품 처리 시 미착 수량 설정
			if (StringUtils.isNotBlank(ordChgGb) && TscConstants.ChangeGb.RETURN_TO_RETURN.value().equals(ordChgGb.toUpperCase())) {
				returnDetailList = coreOrderChangeService.getNonArrivalInfo(order);
			} else {
				returnDetailList = orderChangeDetailList;
			}

			// 반품상세 정보 설정
			if (returnDetailList != null && returnDetailList.size() > 0) {
				for (Order tmp : returnDetailList) {
					if (tmp.getChgQty() > 0 && !ordDtlNoList.contains(tmp.getOrdDtlNo())) {
						ordDtlNoList.add(tmp.getOrdDtlNo());
						chgQtyList.add(tmp.getChgQty());

						if (StringUtils.isNotBlank(tmp.getChgStat())) {
							chgStat = tmp.getChgStat();
						}
					}
				}
			}

			// 회수 예외 정보 설정
			mav.addObject("recallExceptionInfo"		, coreOrderChangeService.getRecallExceptionInfo(order));
		}
		// 확정후품절 처리
		else if (TscConstants.ChangeGb.SOLDOUT_AFTER_DECISION.value().equals(ordChgGb)) {
			ordDtlNoList = Arrays.stream(order.getOrdDtlNoArr()).boxed().collect(Collectors.toList());
			chgQtyList = Arrays.stream(order.getCnclRtnReqQtyArr()).boxed().collect(Collectors.toList());
		}

		// 반품 대상 목록 설정
		if (ordDtlNoList.size() > 0) {
			List<Order> tmpList = new ArrayList<>();
			for (Order tmp : cancelRequestTargetList) {
				if (ordDtlNoList.contains(tmp.getOrdDtlNo())) {
					int chgQty = chgQtyList.get(ordDtlNoList.indexOf(tmp.getOrdDtlNo()));
					tmp.setChgQty(chgQty);

					// 반품TO반품, 확정후품절 수량 설정
					if (StringUtils.isNotBlank(ordChgGb) && (TscConstants.ChangeGb.RETURN_TO_RETURN.value().equals(ordChgGb.toUpperCase()) || TscConstants.ChangeGb.SOLDOUT_AFTER_DECISION.value().equals(ordChgGb.toUpperCase()))) {
						tmp.setOrdCanChgQty(chgQty);
					}

					tmpList.add(tmp);
				}
			}

			cancelRequestTargetList = tmpList;
		}

		// 2021.01.26 취소요청 화면, 취소요청정보확인 화면 통합
		mav.addObject("chgReasonList"				, rendererService.getAvailCommonCodeList("G688"));				// 취소사유
		mav.addObject("cancelRequestTargetList"		, cancelRequestTargetList);										// 취소요청대상 목록
		mav.addObject("orderInfoList"				, orderInfoList);												// 주문정보
		mav.addObject("ordNo"						, order.getOrdNo());											// 주문번호
		mav.addObject("ordChgSq"					, order.getOrdChgSq());											// 주문변경번호
		mav.addObject("delvFeeCd"					, order.getDelvFeeCd());										// 배송정책코드
		mav.addObject("delvFeeCdGrp"				, order.getDelvFeeCdGrp());										// 배송정책그룹코드
		mav.addObject("orderChangeDetailList"		, orderChangeDetailList);										// 변경신청목록 (취소/반품/교환)
		mav.addObject("rtnLocInfo"					, coreOrderChangeService.getRtnLocInfo(order));					// 반송지주소정보
		mav.addObject("orderDelvRtnAddrInfo"		, coreOrderService.getDeliveryAddrList(order));					// 배송정보
		mav.addObject("TelExcNoList"				, rendererService.getAvailCommonCodeList("G095"));				// 전화번호국번
		mav.addObject("PhnExcNoList"				, rendererService.getAvailCommonCodeList("G096"));				// (휴대전화)번호국번
		mav.addObject("chgStat"						, chgStat);														// 변경상태
		mav.addObject("ordChgGb"					, StringUtils.isBlank(ordChgGb) ? "" : ordChgGb.toUpperCase());	// 주문변경요쳥변경구분
		mav.addObject("addDelvFeeObj"				, coreOrderService.getAddDelvFee(order));						// 추가배송비 결제여부 조회

		mav.setViewName("order/ScmRtnReqForm");
		
		return mav;
	}
	
	/**
	 * 교환요청 화면
	 *
	 * @param ordNo - 주문번호
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2021. 12. 22
	 */
	@GetMapping("/scm/exchange/request/form")
	public ModelAndView exchangeRequestFrom(Order order) {
		ModelAndView mav = new ModelAndView();
		String ordChgGb = order.getOrdChgGb();
		Integer ordChgSq = order.getOrdChgSq();

		if (ordChgSq == null || ordChgSq == 0) {
			// 교환가능 주문상세상탭값 설정
			// 2021.09.14 card007 구매확정 교환신청 처리
			String[] ordDtlStatArr = new String[4];
			ordDtlStatArr[0] = TscConstants.OrderDetailStat.SHIPPING.value();
			ordDtlStatArr[1] = TscConstants.OrderDetailStat.SHIP_COMPLETE.value();
			ordDtlStatArr[2] = TscConstants.OrderDetailStat.DELIVERY_COMPLETE.value();
			ordDtlStatArr[3] = TscConstants.OrderDetailStat.PURCHASE_CONFIRM.value();
			order.setOrdDtlStatArr(ordDtlStatArr);
		}
		
		// 2021.09.07 관리자 교환 요청 화면은 정상 동작 처리
		//order.setChgGb(TscConstants.OrderChangeGb.EXCHANGE.value());
		Collection<Order> cancelRequestTargetList = coreOrderService.getCancelRequestTargetList(order);
		Collection<Order> orderChangeDetailList = coreOrderChangeService.getOrderChangeDetailList(order);
		Collection<Order> orderInfoList = coreOrderService.getOrderInfoList(order);

		String chgStat = "";
		String canRequestCancelYn = "";
		String wdBfSendYn = "";
		if (order.getOrdChgSq() > 0) {
			Collection<Order> exchangeInfoList = coreOrderChangeService.getExchangeInfo(order);

			// 교환TO교환 처리 시 미착 수량 설정
			Collection<Order> exchangeDetailList;
			if (StringUtils.isNotBlank(ordChgGb) && TscConstants.ChangeGb.EXCHANGE_TO_EXCHANGE.value().equals(ordChgGb.toUpperCase())) {
				exchangeDetailList = coreOrderChangeService.getNonArrivalInfo(order);
			} else {
				exchangeDetailList = orderChangeDetailList;
			}

			// 교환상세 정보 설정
			List<Integer> ordDtlNoList = new ArrayList<>();
			List<Integer> chgQtyList = new ArrayList<>();
			if (exchangeDetailList != null && exchangeDetailList.size() > 0) {
				for (Order tmp : exchangeDetailList) {
					if (tmp.getChgQty() > 0 && !ordDtlNoList.contains(tmp.getOrdDtlNo())) {
						ordDtlNoList.add(tmp.getOrdDtlNo());
						chgQtyList.add(tmp.getChgQty());

						if (StringUtils.isNotBlank(tmp.getChgStat())) {
							chgStat = tmp.getChgStat();
						}
					}
				}

				Collection<Order> tmpList = new ArrayList<>();
				for (Order tmp : cancelRequestTargetList) {
					if(ordDtlNoList.contains(tmp.getOrdDtlNo())) {
						int chgQty = chgQtyList.get(ordDtlNoList.indexOf(tmp.getOrdDtlNo()));
						tmp.setChgQty(chgQty);
						tmpList.add(tmp);
					}
				}

				cancelRequestTargetList = tmpList;
				canRequestCancelYn = orderChangeDetailList.iterator().next().getCanRequestCancelYn();
				wdBfSendYn = orderChangeDetailList.iterator().next().getWdBfSendYn();
			}

			String chgOrdDtlStat = "";
			String wdGb = "";
			if (exchangeInfoList != null && exchangeInfoList.size() > 0) {
				chgOrdDtlStat = exchangeInfoList.iterator().next().getOrdDtlStat();
				wdGb = exchangeInfoList.iterator().next().getWdGb();
			}

			// 교환배송비 취소가능여부 조회
			OrderChange orderChange = new OrderChange();
			orderChange.setOrdChgSq(order.getOrdChgSq());
			Collection<Order> paymentList = coreOrderChangeService.getAddDeliveryFeePayment(orderChange);
			
			String canDeliveryCancelYn = "";
			if (paymentList != null && paymentList.size() > 0) {
				canDeliveryCancelYn = paymentList.iterator().next().getCanDeliveryCancelYn();
			}

			mav.addObject("exchangeInfoList"		, exchangeInfoList);											// 교환정보
			mav.addObject("chgOrdDtlStat"			, chgOrdDtlStat);												// 교환상품상세상태
			mav.addObject("wdGb"					, wdGb);														// 회수방법
			mav.addObject("recallExceptionInfo"		, coreOrderChangeService.getRecallExceptionInfo(order));		// 회수 예외 정보
			mav.addObject("canDeliveryCancelYn"		, canDeliveryCancelYn);											// 교환배송비 취소가능 여부
		}

		mav.addObject("wdBfSendYn"					, wdBfSendYn);													// 선발송여부
		mav.addObject("canRequestCancelYn"			, canRequestCancelYn);											// 철회가능여부
		mav.addObject("chgReasonList"				, rendererService.getAvailCommonCodeList("G689"));				// 교환사유
		mav.addObject("cancelRequestTargetList"		, cancelRequestTargetList);										// 교환요청대상 목록
		mav.addObject("orderChangeDetailList"		, orderChangeDetailList);										// 변경신청목록 (취소/반품/교환)
		mav.addObject("orderInfoList"				, orderInfoList);												// 주문정보
		mav.addObject("rtnLocInfo"					, coreOrderChangeService.getRtnLocInfo(order));					// 반송지주소정보
		mav.addObject("ordNo"						, order.getOrdNo());											// 주문번호
		mav.addObject("ordChgSq"					, order.getOrdChgSq());											// 주문변경번호
		mav.addObject("delvFeeCd"					, order.getDelvFeeCd());										// 배송정책코드
		mav.addObject("delvFeeCdGrp"				, order.getDelvFeeCdGrp());										// 배송정책그룹코드
		mav.addObject("orderDelvAddrInfo"			, coreOrderService.getDeliveryAddrList(order));					// 배송정보
		mav.addObject("TelExcNoList"				, rendererService.getAvailCommonCodeList("G095"));				// 전화번호국번
		mav.addObject("PhnExcNoList"				, rendererService.getAvailCommonCodeList("G096"));				// (휴대전화)번호국번
		mav.addObject("chgStat"						, chgStat);														// 변경상태
		mav.addObject("ordChgGb"					, StringUtils.isBlank(ordChgGb) ? "" : ordChgGb.toUpperCase());	// 주문변경요쳥변경정보		
		mav.addObject("addDelvFeeObj"				, coreOrderService.getAddDelvFee(order));						// 추가배송비 결제여부 조회

		mav.setViewName("order/ScmExchangeRequestForm");

		return mav;
	}
	
	/**
	 * 입점입고대상목록(교환,반품접수)
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2021. 05. 17
	 */
	@GetMapping("/seller/claim/target/list/form")
	public ModelAndView orderSellerClaimTargetListForm() {
		ModelAndView mav = new ModelAndView();
		
		// 공급업체
		String supplyCompCd 	= "";
		String selfYn 			= "Y";
		
		// 입점업체담당자
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {	
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "N";
		}
		// 촬영업체
		else if ("G001_E000".equals(TssSession.getInfo().getRoleCd())) {
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "Y";
		}
		
		mav.addObject("supplyCompList"	, rendererService.getSupplyCompanyList(supplyCompCd, selfYn)); 	// 공급업제목록
		mav.addObject(" chgStatList"	, rendererService.getAvailCommonCodeList("G685"));				// 클렘임상태코드
		mav.setViewName("order/OrderSellerClaimTargetListForm");

		return mav;
	}
	
	/**
	 * 입점클레임목록조회(교환,반품접수)
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2021. 05. 17
	 */
	@PostMapping("/seller/claim/target/list")
	@ResponseBody
	public Collection<Order> getOrderSellerClaimTargetList(@RequestBody Order order) throws Exception {
		
		// 값이없으면 반품접수, 교환접수
		String [] multiChgStat = new String[3];
		if (order.getChgStat() == null || "".equals(order.getChgStat())) {
			multiChgStat[0] = TscConstants.OrderChangeStat.EXCHANGE.value();
			multiChgStat[1] = TscConstants.OrderChangeStat.RETURN.value();
			multiChgStat[2] = TscConstants.OrderChangeStat.WITHDRAW.value();
		} else {
			multiChgStat[0] = order.getChgStat();
		}
		
		// 페이징쿼리때문에
		order.setMultiChgStat(multiChgStat);
		order.setPageable(new TscPageRequest(1 - 1, 1000));
		
		Collection<Order> OrderSellerClaimList = coreOrderService.getOrderSellerClaimList(order);
		return OrderSellerClaimList;
	}
	
	/**
	 * 입점클레임목록 - 입고확인
	 *
	 * @param orderList
	 * @return GagaMap
	 * @author jsh77b
	 * @since 2021. 05. 17
	 */
	@PostMapping(value = "/seller/claim/chgStat31/save")
	@ResponseBody
	public GagaMap saveClaimChgStat31(@RequestBody Collection<Order> orderList) {
		
		// 1. 입고확인
		int userNo = TssSession.getInfo().getUserNo();
		String result = coreOrderService.saveClaimChgStat31(orderList, userNo);
		GagaMap map = new GagaMap();
		map.set("msg", result);
		return map;
	}
	
	/**
	 * 입점상품검수중목록(상품검수중)
	 *
	 * @return ModelAndView
	 * @author jsh77b
	 * @since 2021. 05. 17
	 */
	@GetMapping("/seller/withdraw/list/form")
	public ModelAndView orderSellerWidthdrawListForm() {
		ModelAndView mav = new ModelAndView();
		
		// 공급업체
		String supplyCompCd 	= "";
		String selfYn 			= "Y";
		
		// 입점업체담당자
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {	
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "N";
		}
		// 촬영업체
		else if ("G001_E000".equals(TssSession.getInfo().getRoleCd())) {	
			supplyCompCd = TssSession.getInfo().getSupplyCompCd();
			selfYn = "Y";
		}
		
		mav.addObject("supplyCompList"	, rendererService.getSupplyCompanyList(supplyCompCd, selfYn)); 	// 공급업제목록
		mav.addObject("chgStatList"		, rendererService.getAvailCommonCodeList("G685"));					// 클렘임상태코드
		mav.setViewName("order/OrderSellerWithdrawListForm");

		return mav;
	}
	
	/**
	 * 입점상품검수중목록조회(상품검수중)
	 *
	 * @param order - 주문정보
	 * @return Collection<Order>
	 * @author jsh77b
	 * @since 2021. 05. 17
	 */
	@PostMapping("/seller/withdraw/list")
	@ResponseBody
	public Collection<Order> getOrderSellerWithdrawList(@RequestBody Order order) throws Exception {
		
		// 값이없으면 반품접수, 교환접수
		String [] multiChgStat = new String[1];
		multiChgStat[0] = TscConstants.OrderChangeStat.WITHDRAW_GOODS_CHECK.value();
		
		order.setMultiChgStat(multiChgStat);
		
		// 페이징쿼리때문에
		order.setMultiChgStat(multiChgStat);
		order.setPageable(new TscPageRequest(1 - 1, 1000));
				
		Collection<Order> OrderSellerClaimList = coreOrderService.getOrderSellerClaimList(order);
		return OrderSellerClaimList;
	}
}
