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.RequestParam;
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.domain.Delivery;
import com.style24.persistence.domain.DeliveryLoc;

import lombok.extern.slf4j.Slf4j;

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.getDeliveryLocList(""));
		// 사이트구분
		mav.addObject("siteCdList", rendererService.getAvailCommonCodeList("G000"));
		// 택배사명 목록
		mav.addObject("shipCompanyList", rendererService.getShipCompanyList());
		// 출고처분류
		mav.addObject("delvTypeList", rendererService.getAvailCommonCodeList("G024"));
		
		String supplyCompCd = "";
		if ("B000".equals(TsaSession.getInfo().getRoleCd())) {
			supplyCompCd = TsaSession.getInfo().getSupplyCompCd();
		}
		
		// 공급업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd));
        //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 Collection<Delivery> getDeliveryList(@RequestBody Delivery delivery) throws Exception {
		Collection<Delivery> dataList = deliveryService.getDeliveryList(delivery);
		return dataList;
	}

	/**
	 * 배송 목록 화면 - 품절처리
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@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"));
		}
		// 세트상품일경우 주문번호, 주문상세기준으로 data 정비 
		Collection<Delivery> orderDtlList = new ArrayList<Delivery>();

		int orderDtlListCnt = 0;
		for (Delivery delivery : deliveryList) {
			Delivery dtlno = new Delivery();
			dtlno.setOrdNo(delivery.getOrdNo());
			dtlno.setOrdDtlNo(delivery.getOrdDtlNo());
			dtlno.setSaleQty(delivery.getSaleQty());
			dtlno.setCustNo(delivery.getCustNo());
			dtlno.setDelvLocClsf(delivery.getDelvLocClsf());
			if (orderDtlListCnt == 0) {
				orderDtlList.add(dtlno);
			} else {
				int dupChk = 0;
				for (Delivery param : orderDtlList) {
					if (delivery.getOrdNo().equals(param.getOrdNo()) && delivery.getOrdDtlNo().equals(param.getOrdDtlNo())) {
						dupChk++;
					}
				}
				if (dupChk == 0) {
					orderDtlList.add(dtlno);
				}
				orderDtlListCnt++;
			}
		}
		/*
		// 주문 취소 형식에 맞게 data 정비 
		Collection<TsaOrder> orderlist = new ArrayList<TsaOrder>();

		for (TsaDelivery delivery : orderDtlList) {
			TsaOrder param = new TsaOrder();
			param.setOrdNo(delivery.getOrdNo() + "");
			param.setOrdDtlNo(delivery.getOrdDtlNo() + "");
			param.setOrdDtlNos(delivery.getOrdDtlNo() + "");
			param.setCustNo(delivery.getCustNo());
			param.setChgQty(delivery.getSaleQty());
			param.setChgQtys(delivery.getSaleQty() + "");  // getChgQtys
			param.setDelvLocClsf(delivery.getDelvLocClsf());

			if (orderlist == null || orderlist.isEmpty()) {
				orderlist.add(param);
			} else {
				int cnt = 0;
				for (TsaOrder order : orderlist) {
					if (delivery.getOrdNo().equals(order.getOrdNo())) {
						order.setOrdDtlNos(order.getOrdDtlNos() + "," + param.getOrdDtlNo());
						order.setChgQtys(order.getChgQtys() + "," + param.getChgQty());
						cnt = 1;
					}
				}
				if (cnt == 0) {
					orderlist.add(param);
				}
			}
		}

		for (TsaOrder order : orderlist) {
			deliveryService.saveGoodsSoldout(order);
		}
		*/
		return super.ok(message.getMessage("SUCC_0004"));
	}
	
	/**
	 * 배송 목록 화면 - 송장번호변경(팝업)
	 *
	 * @param
	 * @return
	 * @throws Exception
	 * @author moon
	 * @since 2020. 11. 05
	 */
	@GetMapping("/save/invoice/form")
	public ModelAndView saveInvoiceForm(@RequestParam(value = "ordDtlNo", required = true)long 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 2020. 11. 05
	 */
	@PostMapping("/orderDetail/save")
	@ResponseBody
	public GagaResponse saveOrderDetail(@RequestBody Collection<Delivery> deliveryList) throws Exception {

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

		deliveryService.saveOrderDetail(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());
		// 출고처 목록
		DeliveryLoc deliLoc = new DeliveryLoc(); 
		mav.addObject("getDeliveryLocList", rendererService.getDeliveryLocList(deliLoc));
		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());
		// 출고처 목록
		DeliveryLoc deliLoc = new DeliveryLoc();
		mav.addObject("getDeliveryLocList", rendererService.getDeliveryLocList(deliLoc));
		// 상품상태
		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"));
	}
	
}
