package com.style24.scm.biz.web;

import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

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.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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 lombok.extern.slf4j.Slf4j;

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.persistence.domain.CommonCode;
import com.style24.persistence.domain.Pos;
import com.style24.persistence.domain.DeliveryLoc;
import com.style24.scm.support.controller.TssBaseController;
import com.style24.scm.support.security.session.TssSession;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.scm.biz.service.TssPosService;
import com.style24.scm.biz.service.TssRendererService;

/**
 * 매장 Controller
 * 
 * @author moon
 * @since 2021. 06. 11
 */
@Controller
@RequestMapping("/pos")
@Slf4j
public class TssPosController extends TssBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TssPosService posService;

	//@Autowired
	//private TsaDeliveryService deliveryService;

	@Autowired
	private TssRendererService rendererService;

	//@Autowired
	//private TsaStatisticsService statisticsService;

	/**
	 * 매장POS 로그인 처리
	 * 
	 * @param sellStoreCd - 매장코드
	 * @param session - HttpSession
	 * @return String - 포스메인화면이동
	 * @author moon
	 * @since 2020. 11. 13
	 */
//	@GetMapping("/login")
//	public String posLogin(@RequestParam("delvLocCd") String delvLocCd, HttpSession session) {
//		String returnUrl = "forward:/pos/main";
//		if (TsaSession.isStoreLogin()) {
//			// 로그인 정보와 다른 매장코드로 접근시 기존 로그인 세션 삭제
//			log.info("delvLocCd {}", delvLocCd);
//			log.info("TsaSession.getPosInfo() {}", TsaSession.getPosInfo());
//			if (!delvLocCd.equals(TsaSession.getPosInfo().getDelvLocCd())) {
//				session.removeAttribute("sessionPosInfo");
//			}
//		}
//
//		Pos posParam = new Pos();
//		posParam.setDelvLocCd(delvLocCd);
//		Pos posInfo = posService.getStoreLoginInfo(posParam);
//
//		if (posInfo == null) {
//			log.debug(String.format("StoreCode={} was not found!", delvLocCd));
//			throw new UsernameNotFoundException(message.getMessage("LOGN_0001"));
//		}
//		// 세션 설정
//		session.setAttribute("sessionPosInfo", posInfo);
//
//		log.info("posInfo{}", posInfo);
//
//		return returnUrl;
//	}

	/**
	 * 매장POS 메인
	 * 
	 * @return ModelAndView
	 * @author moon
	 * @since 2020. 11. 13
	 */
	@GetMapping("/main")
	public ModelAndView posMain() {
		ModelAndView mav = new ModelAndView();
		Pos pos = new Pos();
		log.info("getInfo: "+TssSession.getInfo());
		
		pos.setDelvLocCd(TssSession.getInfo().getUserId());
		
		Pos posInfo = posService.getStoreLoginInfo(pos);
		
		log.info("posInfo{}", posInfo);
		mav.addObject("posInfo",posInfo);
		mav.addObject("delvLocNm",posInfo.getDelvLocNm());
		mav.addObject("supplyCompCd",posInfo.getSupplyCompCd());
		mav.addObject("delvLocCd",posInfo.getDelvLocCd());
		mav.addObject("delvFeeRate",posInfo.getDelvFeeRate());
		
		
		//TssSession.getInfo()
		//mav.addObject("delvLocNm", TssSession.getPosInfo().getDelvLocNm());
		//mav.addObject("delvLocCd", TssSession.getPosInfo().getDelvLocCd());

		// 택배사명 목록
		mav.addObject("shipCompanyList", rendererService.getShipCompanyList());

		// 주문상세상태 
		mav.addObject("orderDtlSateList", rendererService.getCommonCodeList("G013"));
		
		// 출고거부사유
		mav.addObject("g300List", rendererService.getCommonCodeList("G300"));

		mav.setViewName("pos/PosMainForm");
		return mav;
	}

	/**
	 * 출고대기목록 / 출고목록
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 11
	 */
	@PostMapping("/wait/order/list")
	@ResponseBody
	public Collection<Pos> getPosWaitOrderList(@RequestBody Pos pos) {

		return posService.getPosDeliveryList(pos);
	}

	/**
	 * 출고목록
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2020. 06. 11
	 */
	@PostMapping("/delivery/order/list")
	@ResponseBody
	public Collection<Pos> getPosDeliveryList(@RequestBody Pos pos) {

		return posService.getPosDeliveryList(pos);
	}

	/**
	 * 확정대기목록
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2020. 06. 21
	 */
	@PostMapping("/confirm/order/list")
	@ResponseBody
	public Collection<Pos> getPosConfirmList(@RequestBody Pos pos) {

		return posService.getPosConfirmList(pos);
	}
	
	/**
	 * 출고수락 / 출고거부 처리
	 * 
	 * @param pos - 매장정보
	 * @return GagaResponse
	 * @author moon
	 * @since 2020. 11. 13
	 */
	@PostMapping("/delivery/assign/save")
	@ResponseBody
	public GagaResponse savePosDeliveryAssign(@RequestBody Pos pos) {
		
		log.info("pos {}"+pos);
		


		String rtn = "";
		if ("Y".equals(pos.getDelvArGb())) { //출고수락
			rtn = posService.savePosDeliveryLocAssign(pos);
		} else {
			rtn = posService.savePosDeliveryLocReject(pos);
		}
		if ("S".equals(rtn)) {
			if ("Y".equals(pos.getDelvArGb())) { //출고수락
				return super.ok("출고수락 되었습니다.\n출고목록에서 확인 가능합니다.");
			} else {
				return super.ok(message.getMessage("SUCC_0001"));
			}
			
		} else if("N".equals(rtn)) {
			return super.ok("상태값이 변경되었습니다.\n조회 후 다시 진행해주세요.");
		} else {
			return super.ok("다른 출고처로 지정되었습니다.");
		}
		

	}

	/**
	 * 출고수락목록 CnPlus 엑셀다운 - 배송준비중
	 * 
	 * @param pos - 매장정보
	 * @return Collection<TsaPos>
	 * @author moon
	 * @since 2020. 06. 14   == 삭제!!!
	 */
	@PostMapping("/invoice/save")
	@ResponseBody
	public Collection<GagaMap> saveInvoice(@RequestBody Collection<Pos> posList) {


		Collection<GagaMap> resultList = new ArrayList<>();
		Collection<Pos> dtlNoList = new ArrayList<Pos>();

		for (Pos posParam : posList) {

			// 세트상품일경우 주문상세번호 중복제거 
			String chk = "N";
			for (Pos param : dtlNoList) {
				if (param.getOrdDtlNo() == posParam.getOrdDtlNo()) {
					chk = "Y";
				}
			}
			if ("N".equals(chk)) {
				Pos data = new Pos();
				data.setOrdNo(posParam.getOrdNo());
				data.setOrdDtlNo(posParam.getOrdDtlNo());

				GagaMap result = posService.savePos(data);

				dtlNoList.add(posParam);
				resultList.add(result);
			}

		}
		return resultList;
	}
	
	/**
	 * CnPlus 엑셀 다운로드 
	 * 
	 * @param pos - 매장정보
	 * @return Collection<TsaPos>
	 * @author moon
	 * @since 2021. 06. 14
	 */	
	@GetMapping("/order/excel/list")
	public ResponseEntity<InputStreamResource> downloadOrderExcelList(HttpServletRequest request, Pos pos) throws Exception {
		if (StringUtils.isBlank(pos.getOrdDtlNos())) {
			throw new IllegalStateException(message.getMessage("FAIL_1003"));
		}
		String excelfileName = "CNPlus 엑셀양식_" + GagaDateUtil.getTodayDateTime() + ".xlsx";
		String excelFilenameWithPath = GagaFileUtil.getConcatenationPath(env.getProperty("download.path"), "excel", excelfileName);
		log.info("pos {}", pos.getOrdDtlNos());
		if (StringUtils.isNotBlank(pos.getOrdDtlNos())) {
			pos.setOrdDtlNoArr(pos.getOrdDtlNos().split(","));
		}
		// 대용량엑셀파일다운로드는 이런 식으로 ...
		posService.getOrderExcelList(pos, excelFilenameWithPath);

		return GagaFileUtil.writeFile(request, excelFilenameWithPath);
	}
	
	/**
	 * 출고수락목록 송상등록
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 21
	 */
	@PostMapping("/invoice/save/invoiceno")
	@ResponseBody
	public Collection<GagaMap> savePosInvoice(@RequestBody Collection<Pos> posList) {
		Integer userNo = TssSession.getInfo().getUserNo();
		Collection<GagaMap> resultList = new ArrayList<>();
		Collection<Pos> dtlNoList = new ArrayList<Pos>();

		for (Pos posParam : posList) {

			// 세트상품일경우 주문상세번호 중복제거 
			String chk = "N";
			for (Pos param : dtlNoList) {
				if (param.getOrdDtlNo().equals(posParam.getOrdDtlNo())) {
					chk = "Y";
				}
			}
			if (!"Y".equals(chk)) {
				Pos data = new Pos();
				data.setOrdNo(posParam.getOrdNo());
				data.setOrdDtlNo(posParam.getOrdDtlNo()); 
				data.setUpdNo(userNo);
				data.setRegNo(userNo);
				data.setDelvFeeRate(posParam.getDelvFeeRate());
				data.setInvoiceNo(posParam.getInvoiceNo());
				data.setShipCompCd(posParam.getShipCompCd());

				GagaMap result = posService.savePosInvoice(data);

				dtlNoList.add(posParam);
				resultList.add(result);
			}
		}
		return resultList;
	}

	
	/**
	 * 수락취소
	 * 
	 * @param pos - 매장정보
	 * @return GagaResponse
	 * @author moon
	 * @since 2021. 06. 21
	 */
	@PostMapping("/delivery/assign/save/cancel")
	@ResponseBody
	public GagaResponse savePosDeliveryAssignCancel(@RequestBody Pos pos) {

		GagaMap result = posService.getPosDeliveryLocValidation(pos);
		boolean validation = result.getBoolean("validation");
		String resultMsg   = result.getString("resultMsg");
		
		//deliveryService.savePosDeliveryLocRejectCancel(delivery);
		if (validation) {
			posService.savePosDeliveryLocRejectCancel(pos);
		}
		return super.ok(resultMsg);
	}
	
	/**
	 * 출고확정 
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 21
	 */
	@PostMapping("/confirm/save")
	@ResponseBody
	public Collection<GagaMap> saveConfirmation(@RequestBody Collection<Pos> posList) {
		Integer userNo = TssSession.getInfo().getUserNo();
		Collection<GagaMap> resultList = new ArrayList<>();
		Collection<Pos> dtlNoList = new ArrayList<Pos>();
		int cnt =0;
		for (Pos posParam : posList) {

			// 세트상품일경우 주문상세번호 중복제거 
			String chk = "N";
			for (Pos param : dtlNoList) {
				if (param.getOrdDtlNo().equals(posParam.getOrdDtlNo())) {
					chk = "Y";
				}
			}
			if (!"Y".equals(chk)) {
				Pos data = new Pos();
				data.setOrdNo(posParam.getOrdNo());
				data.setOrdDtlNo(posParam.getOrdDtlNo()); 
				data.setUpdNo(userNo);
				data.setRegNo(userNo);
				data.setDelvFeeRate(posParam.getDelvFeeRate());
				data.setInvoiceNo(posParam.getInvoiceNo());
				data.setShipCompCd(posParam.getShipCompCd());
				cnt = cnt+1;
				GagaMap result = posService.saveConfirmation(data,cnt);

				dtlNoList.add(posParam);
				resultList.add(result);
			}
		}
		return resultList;
	}
	

	/**
	 * 정산내역
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2021. 06. 21
	 */
	@PostMapping("/usac/list")
	@ResponseBody
	public Collection<Pos> getPosUsacList(@RequestBody Pos pos) {
		return posService.getPosUsacList(pos);
	}

	/**
	 * 출고거부이력 목록
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2020. 11. 13
	 */
	@PostMapping("/ban/delivery/list")
	@ResponseBody
	public Collection<Pos> getPosBanDeliveryList(@RequestBody Pos pos) {
		/*
		 * Delivery delivery = new Delivery();
		 * delivery.setDelvLocCd(TsaSession.getPosInfo().getDelvLocCd());
		 * delivery.setGoodsGb("goodsCd"); delivery.setSearchTxt(pos.getGoodsCd());
		 * Collection<Delivery> rejectList = new ArrayList<Delivery>(); return
		 * rejectList; //deliveryService.getDeliveryAssignList(delivery);
		 */		
		return posService.getDeliveryAssignList(pos);
		
	}

	/**
	 * 출고수락목록 배송준비중
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2020. 11. 13
	 */
//	@PostMapping("/invoice/save")
//	@ResponseBody
//	public Collection<GagaMap> saveInvoice(@RequestBody Collection<Pos> posList) {
//		String delvLocCd = TsaSession.getPosInfo().getDelvLocCd();
//		Double delvFeeRate = TsaSession.getPosInfo().getDelvFeeRate();
//
//		Collection<GagaMap> resultList = new ArrayList<>();
//		Collection<Pos> dtlNoList = new ArrayList<Pos>();
//
//		for (Pos posParam : posList) {
//
//			// 세트상품일경우 주문상세번호 중복제거 
//			String chk = "N";
//			for (Pos param : dtlNoList) {
//				if (param.getOrdDtlNo() == posParam.getOrdDtlNo()) {
//					chk = "Y";
//				}
//			}
//			if (!"Y".equals(chk)) {
//				Delivery delivery = new Delivery();
//				delivery.setOrdNo(posParam.getOrdNo());
//				delivery.setOrdDtlNo(posParam.getOrdDtlNo());
//				// TODO: 매장코드는 id 생성후 매핑???
//				//delivery.setUpdNo(delvLocCd);
//				//delivery.setRegNo(delvLocCd);
//				delivery.setDelvFeeRate(delvFeeRate);
//
//
//				GagaMap result = null;//deliveryService.savePos(delivery);
//
//				dtlNoList.add(posParam);
//				resultList.add(result);
//			}
//
//		}
//		return resultList;
//	}


	/**
	 * 엑셀다운로드
	 * 
	 * @param pos - 매장정보
	 * @return Collection<Pos>
	 * @author moon
	 * @since 2020. 11. 13
	 */	
//	@GetMapping("/order/excel/list")
//	public ResponseEntity<InputStreamResource> downloadOrderExcelList(HttpServletRequest request, Pos pos) throws Exception {
//		if (StringUtils.isBlank(pos.getOrdDtlNos())) {
//			throw new IllegalStateException(message.getMessage("FAIL_1003"));
//		}
//		String excelfileName = "CNPlus 엑셀양식_" + GagaDateUtil.getTodayDateTime() + ".xlsx";
//		String excelFilenameWithPath = GagaFileUtil.getConcatenationPath(env.getProperty("download.path"), "excel", excelfileName);
//		log.info("pos {}", pos.getOrdDtlNos());
//		if (StringUtils.isNotBlank(pos.getOrdDtlNos())) {
//			pos.setOrdDtlNoArr(pos.getOrdDtlNos().split(","));
//		}
//		// 대용량엑셀파일다운로드는 이런 식으로 ...
//		posService.getOrderExcelList(pos, excelFilenameWithPath);
//
//		return GagaFileUtil.writeFile(request, excelFilenameWithPath);
//	}

	/**
	 * 매장 출고처지정 수략율 통계화면
	 *
	 * @author card007
	 * @since 2020. 09. 16
	 */
	/*
	@GetMapping("/delivery/assign/statistics/form")
	public ModelAndView storeDeliveryAssignStatisticsForm() {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList());

		mav.setViewName("statistics/DeliveryAssignForm");

		return mav;
	}
	*/

	/**
	 * 매장 출고처지정 수략율 통계 조회
	 *
	 * @param TsaDeliveryAssign - 출고처지정
	 * @return Collection<TsaDeliveryAssign>
	 * @author card007
	 * @since 2020. 09. 16
	 */
	/*
	@PostMapping("/delivery/assign/statistics/list")
	@ResponseBody
	public Collection<TsaDeliveryAssign> getStoreDeliveryAssignStatistics(@RequestBody TsaDeliveryAssign deliveryAssign) {
		return statisticsService.getStoreDeliveryAssignStatistics(deliveryAssign);
	}
	*/
	/**
	 * 매장 출고처지정 상세 데이터 조회
	 *
	 * @param TsaDeliveryAssign - 출고처지정
	 * @return Collection<TsaDeliveryAssign>
	 * @author card007
	 * @since 2020. 09. 16
	 */
	/*
	@GetMapping("/delivery/assign/statistics/detail/{delvLocCd}")
	@ResponseBody
	public ModelAndView storeDeliveryAssignDetailForm(@PathVariable String delvLocCd, @RequestParam(value = "stDate", required = false) String stDate, @RequestParam(value = "edDate", required = false) String edDate, @RequestParam(value = "brandCd", required = false) String brandCd) {
		ModelAndView mav = new ModelAndView();

		TsaDeliveryAssign deliveryAssign = new TsaDeliveryAssign();
		deliveryAssign.setDelvLocCd(delvLocCd);
		deliveryAssign.setBrandCd(brandCd);
		deliveryAssign.setStDate(stDate);
		deliveryAssign.setEdDate(edDate);

		Collection<TsaDeliveryAssign> dataList = statisticsService.getStoreDeliveryAssignDetailList(deliveryAssign);

		mav.addObject("dataList", dataList);

		// 출고거부사유
		mav.addObject("noList", rendererService.getAvailCommonCodeList("G017"));

		mav.setViewName("statistics/DeliveryAssignDetailPopupForm");

		return mav;
	}
	*/

	/**
	 * 입점업체브랜드 목록
	 *
	 * @param supplyCompCd - 입점업체관리일련번호
	 * @return
	 * @author moon
	 * @since 2019. 11. 13
	 */
//	@GetMapping("/delivery/assign/statistics/brand/list/{supplyCompCd}")
//	@ResponseBody
//	public Collection<CommonCode> getSupplyCompanyBrandList(@PathVariable String supplyCompCd) {
//		return rendererService.getSupplyCompanyBrandList(supplyCompCd);
//	}

	/**
	 * 출고처 목록
	 *
	 * @param deliveryLoc - 출고처 정보
	 * @return
	 * @author moon
	 * @since 2020. 11. 13
	 */
//	@GetMapping("/delivery/assign/statistics/store/stock/link/list/{supplyCompCd}")
//	@ResponseBody
//	public Collection<CommonCode> getStoreStockLinkList(@PathVariable String supplyCompCd) {
//		DeliveryLoc deliveryLoc = new DeliveryLoc();
//		deliveryLoc.setSupplyCompCd(supplyCompCd);
//		deliveryLoc.setDelvLocClsf("21");
//		return rendererService.getDeliveryLocList(deliveryLoc);
//	}
}
