package com.style24.admin.biz.web;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.ModelAndView;

import com.style24.admin.biz.service.TsaRendererService;
import com.style24.admin.biz.service.TsaDeliveryService;
import com.style24.admin.support.controller.TsaBaseController;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.TscPageRequest;
import com.style24.persistence.domain.Delivery;
import com.style24.persistence.domain.DeliveryLoc;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.rest.server.GagaResponse;

/**
 * 배송 Controller
 *
 * @author moon
 * @since 2020. 11. 05
 */
@Controller
@RequestMapping("/delivery")
@Slf4j
public class TsaDeliveryController extends TsaBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private Environment env;

	@Autowired
	private TsaRendererService rendererService;

	@Autowired
	private TsaDeliveryService deliveryService;

	
	
	
	@Value("${upload.default.target.path}")
	private String uploadTargetPath;

	/**
	 * 배송 목록 화면
	 * @return
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@GetMapping("/list/form")
	public ModelAndView deliveryListForm() {
		ModelAndView mav = new ModelAndView();

		// 몰구분
		//mav.addObject("mallGbList", rendererService.getMallGbCommonCodeList(TsaSession.getInfo().getRoleCd()));
		mav.addObject("mallGbList", rendererService.getAvailCommonCodeList("G011"));
		// 주문상세상태코드
		mav.addObject("ordDtlStatList", rendererService.getAvailCommonCodeList("G013"));
		// 출고처
		mav.addObject("deliveryLocList", rendererService.getDeliveryLocAllList());
		// 사이트구분
		mav.addObject("siteCdList", rendererService.getAvailCommonCodeList("G000"));
		// 택배사명 목록
		mav.addObject("shipCompanyList", rendererService.getShipCompanyList());
		// 출고처분류
		// mav.addObject("delvTypeList", rendererService.getAvailCommonCodeList("G024"));
		
		String supplyCompCd = "";
		if ("G001_B000".equals(TsaSession.getInfo().getRoleCd())) {
			supplyCompCd = TsaSession.getInfo().getSupplyCompCd();
		}
		
		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList("","Y"));
        //mav.addObject("vendorList", rendererService.getVendorCommonCodeList(TsaSession.getInfo().getRoleCd()));

		mav.setViewName("delivery/DeliveryListForm");

		return mav;
	}

	/**
	 * 배송 목록 화면 - 배송 목록
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@PostMapping("/list")
	@ResponseBody
	public GagaMap getDeliveryList(@RequestBody Delivery delivery) throws Exception {
		
		GagaMap result = new GagaMap();
		delivery.setPageable(new TscPageRequest(delivery.getPageNo() - 1, delivery.getPageSize()));
		delivery.getPageable().setTotalCount(deliveryService.getDeliveryListCount(delivery));


		if ("N".equals(delivery.getPageingYn())) {
			delivery.setPageable(null);
		}		
		
		result.set("pageing", delivery);
		result.set("deliveryList", deliveryService.getDeliveryList(delivery));
		
		return result;
	}

	/**
	 * 주문상세 단품 목록
	 *
	 * @param ordDtlNo - 주문상세번호
	 * @return ModelAndView
	 * @author moon
	 * @since 2021. 03. 05
	 */
	@GetMapping("/detail/item/form/{ordDtlNo}")
	@ResponseBody
	public ModelAndView detailItemFrom(@PathVariable(value = "ordDtlNo") Integer ordDtlNo) {
		ModelAndView mav = new ModelAndView();
		Collection<Delivery> delvDetailItemList = deliveryService.getDelvDetailItemList(ordDtlNo);
		
		mav.addObject("delvDetailItemList", delvDetailItemList);
		
		mav.setViewName("delivery/DeliveryDetailItemForm");
		return mav;
	}
	
	/**
	 * 배송완료처리
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 03. 05
	 */
	@PostMapping("/complete/save")
	@ResponseBody
	public GagaResponse saveDeliveryComplete(@RequestBody Delivery delivery) throws Exception {

		if (delivery == null) {
			throw new IllegalStateException(message.getMessage("FAIL_1002"));
		}

		deliveryService.saveDeliveryComplete(delivery);

		return super.ok(message.getMessage("SUCC_0004"));
	}

	
	/**
	 * 배송 목록 화면 - 품절처리
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 04. 22
	 */
	@PostMapping("/list/soldout")
	@ResponseBody
	public GagaResponse soldoutDeliveryList(@RequestBody Collection<Delivery> deliveryList) throws Exception {
		if (deliveryList == null || deliveryList.isEmpty()) {
			throw new IllegalStateException(message.getMessage("FAIL_1002"));
		}
		deliveryService.cancelSoldout(deliveryList);

		return super.ok(message.getMessage("SUCC_0004"));
	}
	
	/**
	 * 배송 목록 화면 - 송장번호변경(팝업)
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 03. 06
	 */
	@GetMapping("/save/invoice/form/{ordDtlNo}")
	@ResponseBody
	public ModelAndView saveInvoiceForm(@PathVariable(value = "ordDtlNo") Integer ordDtlNo) {
		ModelAndView mav = new ModelAndView();
		Collection<Delivery> ordDeliveryList = deliveryService.getOrderDetail(ordDtlNo);
		Delivery ordDelivery = ordDeliveryList.iterator().next();
		// 택배사명 목록
		mav.addObject("shipCompanyList", rendererService.getShipCompanyList());
		mav.addObject("ordDelivery", ordDelivery);
		
		mav.setViewName("delivery/SaveInvoiceForm");
		return mav;
	} 
	
	/**
	 * 배송 목록 화면 - 송장번호변경(팝업) - 송장번호수정
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 03. 06
	 */
	@PostMapping("/orderDetail/save")
	@ResponseBody
	public GagaResponse saveOrderDetail(@RequestBody Collection<Delivery> deliveryList) throws Exception {

		if (deliveryList == null) {
			throw new IllegalStateException(message.getMessage("FAIL_1002"));
		}

		deliveryService.saveChangeInvoice(deliveryList);

		return super.ok(message.getMessage("SUCC_0004"));
	}
	
	/**
	 * 출고금지상품관리 화면
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@GetMapping("/ban/goods/form")
	@ResponseBody
	public ModelAndView bangoodsListForm() throws Exception {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList("","Y"));
		// 출고처 목록
		mav.addObject("getDeliveryLocList", rendererService.getDeliveryLocAllList());
		
		mav.setViewName("delivery/BangoodsListForm");

		return mav;
	}
	
	/**
	 * 출고금지상품관리 화면 - 출고금지상품목록
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@PostMapping("/bangoods/list")
	@ResponseBody
	public Collection<Delivery> getBangoodsList(@RequestBody Delivery delivery) throws Exception {
		Collection<Delivery> dataList = deliveryService.getBangoodsList(delivery);
		return dataList;
	}	
	
	/**
	 * 출고금지상품관리 화면 - 출고금지상품 삭제
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@PostMapping("/bangoods/delete")
	@ResponseBody
	public GagaResponse deleteBangoods(@RequestBody Collection<Delivery> deliveryList) throws Exception {
		deliveryService.deleteBangoods(deliveryList);
		return super.ok(message.getMessage("SUCC_0001"));
	}
	
	/**
	 * 출고금지상품관리 화면 - 출고금지상품 등록 화면(팝업)
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@GetMapping("/bangoods/regist/form")
	@ResponseBody
	public ModelAndView registBangoodsForm() throws Exception {
		ModelAndView mav = new ModelAndView();

		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList("","Y"));
		// 출고처 목록
		mav.addObject("getDeliveryLocList", rendererService.getDeliveryLocAllList());
		
		// 상품상태
		mav.addObject("goodsStatList", rendererService.getAvailCommonCodeList("G008"));

		mav.setViewName("delivery/BanGoodsRegistForm");

		return mav;
	}	

	/**
	 * 출고금지상품관리 화면 - 출고금지상품 등록 화면(팝업) - 출고금지상품 등록 대상목록
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@PostMapping("/bangoods/regist/list")
	@ResponseBody
	public Collection<Delivery> getBangoodsRegistList(@RequestBody Delivery delivery) throws Exception {
		Collection<Delivery> dataList = deliveryService.getBangoodsRegistList(delivery);
		return dataList;
	}

	/**
	 * 출고금지상품관리 화면 - 출고금지상품 등록 화면(팝업) - 출고금지상품 등록
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@PostMapping("/bangoods/regist/save")
	@ResponseBody
	public GagaResponse createBangoods(@RequestBody Collection<Delivery> deliveryList) throws Exception {
		deliveryService.createBangoods(deliveryList);
		return super.ok(message.getMessage("SUCC_0001"));
	}
	
	/**
	 * 배송/회수지시목록 화면
	 * 
	 * @return ModelAndView
	 * @throws Exception
	 * @author moon
	 * @since 2021. 03. 12
	 */
	@RequestMapping(value = "/dwdirect/list/form")
	public ModelAndView deliveryWithdrawDirectiveListForm() throws Exception {
		ModelAndView mav = new ModelAndView();

		// 사이트구분
		mav.addObject("siteCdList", rendererService.getAvailCommonCodeList("G000"));

		mav.setViewName("delivery/DeliveryWithdrawDirectiveListForm");

		return mav;
	}

	/**
	 * 배송/회수지시 목록
	 * 
	 * @param dwDirective - 배송/회수지시 정보
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 03. 12
	 */
	@RequestMapping(value = "/dwdirect/list", method = RequestMethod.POST)
	@ResponseBody
	public GagaMap getDeliveryWithdrawDirectiveList(@RequestBody Delivery dwDirective) throws Exception {

		GagaMap result = new GagaMap();

		dwDirective.setPageable(new TscPageRequest(dwDirective.getPageNo() - 1, dwDirective.getPageSize()));
		dwDirective.getPageable().setTotalCount(deliveryService.getDeliveryWithdrawDirectiveListCount(dwDirective)); 


		if ("N".equals(dwDirective.getPageingYn())) {
			dwDirective.setPageable(null);
		}		
		
		result.set("pageing", dwDirective);
		result.set("dwdirectList", deliveryService.getDeliveryWithdrawDirectiveList(dwDirective));		
		
		return result;
	}	

	
	/**
	 * 출고처지정 관리
	 * 
	 * @return ModelAndView
	 * @throws Exception
	 * @author moon
	 * @since 2021. 04. 19
	 */
	@RequestMapping(value = "/assign/form")
	public ModelAndView assignListForm() throws Exception {
		ModelAndView mav = new ModelAndView();

		// 몰구분
		mav.addObject("mallGbList", rendererService.getAvailCommonCodeList("G011"));
		// 주문상세상태코드
		mav.addObject("ordDtlStatList", rendererService.getAvailCommonCodeList("G013"));
		// 출고처
		mav.addObject("deliveryLocList", rendererService.getDeliveryLocList(""));
		// 사이트구분
		mav.addObject("siteCdList", rendererService.getAvailCommonCodeList("G000"));

		
		
		mav.setViewName("delivery/AssignListForm");

		return mav;
	}	
	
	/**
	 * 출고처지정 관리 - 출고처지정 목록  
	 * 
	 * @param 
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 03. 12
	 */
	@PostMapping("/assign/list")
	@ResponseBody
	public GagaMap getAssignList(@RequestBody Delivery delivery) throws Exception {
		
		GagaMap result = new GagaMap();

		delivery.setPageable(new TscPageRequest(delivery.getPageNo() - 1, delivery.getPageSize()));
		delivery.getPageable().setTotalCount(deliveryService.getAssignListCount(delivery));


		if ("N".equals(delivery.getPageingYn())) {
			delivery.setPageable(null);
		}
		
		result.set("pageing", delivery);
		result.set("assignList", deliveryService.getAssignList(delivery));
		
		return result;
	}

	/**
	 * 출고처지정 팝업 화변
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 08. 11
	 */
	@GetMapping("/assign/popup/form/{ordDtlNo}")
	public ModelAndView getDeliveryLocAssignPopupForm(@PathVariable(value = "ordDtlNo") Integer ordDtlNo) throws Exception {
		ModelAndView mav = new ModelAndView();

		Delivery delvList = deliveryService.getDeliveryAssignPopup(ordDtlNo);

		mav.addObject("orderDetail", delvList);

		mav.setViewName("delivery/AssignPopupForm");
		return mav;
	}	
	
	
	/**
	 * 출고처지정 팝업 리스트 
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 04. 19
	 */
	@PostMapping("/assign/popup/list")
	@ResponseBody
	public Collection<Delivery> getDeliveryLocAssingPopupList(@RequestBody Delivery delivery) throws Exception {
		log.debug("delivery : {}", delivery);
		if (delivery == null) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}

		Collection<Delivery> dataList = deliveryService.getDeliveryLocStockList(delivery);
		return dataList;
	}

	/**
	 * 출고처지정 처리
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2021. 04. 20
	 */
	@PostMapping("/assign/save")
	@ResponseBody
	public GagaResponse saveDeliveryLocAssign(@RequestBody Delivery delivery) throws Exception {
		if (delivery == null) {
			throw new IllegalStateException(message.getMessage("FAIL_1001"));
		}
		log.info("delivery {}"+delivery);
		int succ = deliveryService.saveDeliveryLocAssign(delivery);
		
		if(succ == 1) {
			return super.ok(message.getMessage("SUCC_0004"));
		} else {
			return super.ok("이미 출고처가 지정되었습니다.");
		}	
	}
	
	/**
	 * 출고처지정 취소 
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 04. 20
	 */
	@PostMapping("/cancel/assignDelvLoc")
	@ResponseBody
	public GagaResponse cancelAssignDelvLoc(@RequestBody Delivery param) throws Exception {
		deliveryService.cancelAssignDelvLoc(param);
		return super.ok(message.getMessage("SUCC_0001"));
	}
	
	/**
	 * 교환배송미출고대상
	 * 
	 * @return ModelAndView
	 * @throws Exception
	 * @author jsh77b
	 * @since 2021. 06. 07
	 */
	@RequestMapping(value = "/exchangeDelvFail/list/form")
	public ModelAndView deliveryExchangeDelvFailListForm() throws Exception {
		ModelAndView mav = new ModelAndView();

		mav.setViewName("delivery/ExchangeDelvFailListForm");

		return mav;
	}
	
	/**
	 * 교환배송미출고대상 목록
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author jsh77b
	 * @since 2021. 06. 07
	 */
	@PostMapping("/exchangeDelvFail/list")
	@ResponseBody
	public Collection<Delivery> getExchangeDelvFailList(@RequestBody Delivery delivery) throws Exception {
		Collection<Delivery> dataList = deliveryService.getExchangeDelvFailList(delivery);
		return dataList;
	}
	
}
