package com.style24.scm.biz.web;



import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.style24.core.biz.service.TscCouponService;
import com.style24.persistence.domain.CommonCode;
import com.style24.persistence.domain.Plan;
import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.Brand;
import com.style24.scm.biz.service.TssBusinessService;
import org.apache.commons.lang3.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gagaframework.excel.GagaExcelUtil;
import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.rest.server.GagaResponse;
import com.gagaframework.web.rest.server.GagaResponseStatus;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.TscPageRequest;
import com.style24.scm.biz.service.TssPlanService;
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 sowon
 * @since 2021. 05. 03
 */
@Controller
@RequestMapping("/marketing")
@Slf4j
public class TssMarketingController extends TssBaseController {

	@Autowired
	private Environment env;
	
	@Autowired
	private TscMessageByLocale message;
	
	@Autowired
	private TssPlanService planService;
	
	@Autowired
	private TssRendererService rendererService;

	@Autowired
	private TscCouponService coreCouponService;

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

	/**
	 *   기획전 작업 시작 - sowon
	 */

	/**
	 * 기획전 관리
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 2. 3
	 */
	@GetMapping("/planning/form")
	public ModelAndView planListForm() {
		ModelAndView mav = new ModelAndView();
		// 사이트 목록
		String supplyCompCd = TssSession.getInfo().getSupplyCompCd();
		log.info("planListForm supplyCompCd>>",supplyCompCd);
		String selfYn = "N";
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, selfYn));
		
		// 사이트 목록
		mav.addObject("siteCdList", rendererService.getCommonCodeList("G000"));
		
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));
		mav.setViewName("marketing/PlanListForm");
		return mav;
	}
	
	/**
	 * 기획전관리 목록
	 *
	 * @param
	 * @return 기획전 목록
	 * @author sowon
	 * @since 2021. 2. 5
	 */
	@PostMapping("/planning/list")
	@ResponseBody
	public GagaMap getPlanList(@RequestBody Plan param) {
		GagaMap result = new GagaMap();

		// 입점업체담당자는 업체코드 설정
		log.info("getPlanList .getRoleCd()>>"+TssSession.getInfo().getRoleCd());
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			param.setRegNo(TssSession.getInfo().getUserNo());
		}
		// multi row 검색관련 처리
		if (!StringUtils.isBlank(param.getCondition())) {
			param.setConditionList(param.getCondition().replaceAll("\r", "").split("\n"));
		}
		
		param.setPageable(new TscPageRequest(param.getPageNo() - 1, param.getPageSize()));
		param.getPageable().setTotalCount(planService.getPlanListCount(param));

		Collection<Plan> planList = planService.getPlanList(param);

		result.set("pageing", param);
		result.set("planList", planList);

		log.debug("dataList: {}", planList);

		return result;
	}
	
	/**
	 * 기획전 웹 등록/수정 화면
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 05
	 */
	@GetMapping("/planning/detail/form")
	public ModelAndView planDetailForm(Plan param) {
		ModelAndView mav = new ModelAndView();
		param.setSiteCd(TscConstants.Site.STYLE24.value());

		if (param.getMode().equals("N")) { // 신규 일 때
			// 기획전 전체 목록
			//mav.addObject("planList", planService.getPlanAllList(param));

			// 브랜드 목록
			mav.addObject("brandList", rendererService.getSupplyCompanyBrandList(""));

		} 
		else if (param.getMode().equals("U")) { // 상세 일 때
			mav.addObject("planInfo", planService.getPlanDetailInfo(param));

			// 등록했던 브랜드
			mav.addObject("planBrandList", planService.getPlanBrandList(param));

			// 등록했던 카테고리
			mav.addObject("planCateList", planService.getPlanCateList(param));

			mav.addObject("brandList", rendererService.getSupplyCompanyBrandList(""));

		}

		// 사이트 목록
		mav.addObject("siteList", rendererService.getAvailCommonCodeList("G000"));
		
		// 카테고리 리스트
		mav.addObject("cateList", planService.getPlanningCategoryList(param));
		
		// 사용가능 고객등급 조회
		mav.addObject("usableCustGradeList", rendererService.getAvailCommonCodeList("G110"));
		
		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));

		
		String supplyCompCd = TssSession.getInfo().getSupplyCompCd();
		String selfYn = "N";
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, selfYn));

		mav.addObject("mode", param.getMode());
		mav.setViewName("marketing/PlanDetailPopupForm");
		return mav;
	}
	
	/**
	 * 기획전 등록
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 05
	 */
	@PostMapping("/planning/detail/create")
	@ResponseBody
	public GagaResponse createPlanInfo(@RequestBody Plan param) {
		planService.createPlanInfo(param);
		return super.ok(message.getMessage("SUCC_0001"));
	}
	
	/**
	 * 기획전 웹 수정
	 *
	 * @return
	 * @author sowon		
	 * @since 2021. 05. 06
	 */
	@PostMapping("/plan/detail/update")
	@ResponseBody
	public GagaResponse updatePlanInfo(@RequestBody Plan param) {
		planService.updatePlanInfo(param);
		return super.ok(message.getMessage("SUCC_0002"));
	}
	
	/**
	 * 기획전 코너 팝업 화면
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@GetMapping("/planning/corner/list/form")
	public ModelAndView planCornerListForm(Plan param) {
		ModelAndView mav = new ModelAndView();

		// 코너유형목록
		mav.addObject("cornerDispTypeList", rendererService.getCommonCodeList("G045", "Y"));

		// 코너유형
		mav.addObject("planDtlStatList", rendererService.getCommonCodeList("G044", "Y"));

		// 상품상태
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y"));

		// 기획전 상세 정보
		mav.addObject("planInfo", planService.getPlanDetailInfo(param));

		mav.setViewName("marketing/PlanCornerListForm");

		return mav;
	}
	
	/**
	 * 기획전 코너 목록
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/corner/list")
	@ResponseBody
	public Collection<Plan> getPlanCornerList(@RequestBody Plan param) {
		return planService.getPlanCornerList(param);
	}
	
	/**
	 * 기획전 코너 저장
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/corner/save")
	@ResponseBody
	public GagaResponse savePlanCornerInfo(@RequestBody Collection<Plan> paramList) {
		planService.savePlanCornerInfo(paramList);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 기획전 코너 상품 조회
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 2. 16
	 */
	@PostMapping("/planning/corner/goods/list")
	@ResponseBody
	public GagaMap getPlanGoodsList(@RequestBody Plan plan) {
		GagaMap result = new GagaMap();

		if ("Y".equals(plan.getPageYn())) {
			plan.setPageable(new TscPageRequest(plan.getPageNo() - 1, plan.getPageSize()));
			plan.getPageable().setTotalCount(planService.getPlanGoodsListCount(plan));
		}
		result.set("pageing", plan);
		result.set("planGoodsList", planService.getPlanGoodsList(plan));
		return result;
	}
	
	/**
	 * 기획전 코너 상품 엑셀상품추가
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/corner/goods/excelupload")
	@ResponseBody
	public GagaMap createExceluploadGoods(@RequestBody Plan param) throws Exception {
		String targetPath = env.getProperty("upload.excel.target.path") + "/excel/";
		String[] goodsNames = {"planDtlSq", "goodsCd"};

		Collection<GagaMap> ecxelGoodsList = GagaExcelUtil.getList(GagaFileUtil.getConcatenationPath(targetPath, param.getExcelFileNm()), 0, goodsNames, 0);

		try {
			planService.createExceluploadGoods(ecxelGoodsList, param);
		} catch (Exception e) {
			// 파일 삭제
			GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, param.getExcelFileNm()));
			throw new IllegalStateException(e.getMessage());
		}

		// 파일 삭제
		GagaFileUtil.deleteFile(GagaFileUtil.getConcatenationPath(targetPath, param.getExcelFileNm()));

		GagaMap result = new GagaMap();
		result.set("status", GagaResponseStatus.SUCCESS.getCode()); // 200
		result.set("message", message.getMessage("SUCC_0001"));
		return result;
	}
	
	/**
	 * 기획전 코너 상품 추가
	 *
	 * @return
	 * @author sowon
	 * @since  2021. 05. 06
	 */
	@PostMapping("/planning/corner/goods/save")
	@ResponseBody
	public GagaResponse savePlanGoods(@RequestBody Collection<Plan> paramList) {
		planService.savePlanGoods(paramList);
		return super.ok(message.getMessage("SUCC_0001"));
	}
	
	/**
	 * 기획전 코너 삭제
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/corner/delete")
	@ResponseBody
	public GagaResponse deletePlanCornerInfo(@RequestBody Collection<Plan> paramList) {
		planService.deletePlanCornerInfo(paramList);
		return super.ok(message.getMessage("SUCC_0003"));
	}
	
	/**
	 * 기획전 코너 상품 삭제
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/corner/goods/delete")
	@ResponseBody
	public GagaResponse deletePlanCornerGoods(@RequestBody Collection<Plan> paramList) {
		planService.deletePlanCornerGoods(paramList);
		return super.ok(message.getMessage("SUCC_0003"));
	}
	
	 /**
	 * 기획전 템플릿 팝업
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@GetMapping("/planning/detail/template/form")
	public ModelAndView planTemplateForm(Plan param, @RequestParam(value = "planSq") Integer planSq) {
		ModelAndView mav = new ModelAndView();

		// 템플릿 등록이 최조인지 확인
		if (planService.getPlanContentsCount(param) > 0) {
			mav.addObject("mode", "U");

			//리뷰리스트
			param.setPlanSq(planSq);
			param.setTmplType("G082_10");
			mav.addObject("reviewList", planService.getPlanContentReviewList(param));

			//쿠폰리스트
			param.setTmplType("G082_20");
			mav.addObject("couponList", planService.getPlanContentCouponList(param));
			mav.addObject("couponNotice", planService.getPlanContentCouponNotice(param));

			//파일리스트
			param.setTmplType("G082_30");
			mav.addObject("fileList", planService.getPlanContentFileList(param));
			
			//유의사항리스트
			param.setTmplType("G082_60");
			mav.addObject("noticeList", planService.getPlanContentNoticeList(param));

			//html 리스트 - 상단
			param.setFontGb("T");
			mav.addObject("fsrcListTop", planService.getPlanContentFsrcList(param));

			//html 리스트 - 하단
			param.setFontGb("B");
			mav.addObject("fsrcListBtm", planService.getPlanContentFsrcList(param));

			//상품 리스트
			mav.addObject("goodsList", planService.getPlanContentGoodsList(param));

			Collection<Plan> goodsList = planService.getPlanContentGoodsList(param);
			Iterator<Plan> iter = goodsList.iterator();
			int i = 1;
			while (iter.hasNext()) {

				Integer planContSq = iter.next().getPlanContSq();
				param.setPlanContSq(planContSq);
				mav.addObject("goodsDetailList" + i, planService.getPlanContentGoodsDetailList(param));
				i++;
			}

		} else {
			mav.addObject("mode", "C");

		}
		// 상품상태
		String[] exceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", exceptCds));

		mav.addObject("planSq", planSq);
		mav.setViewName("marketing/PlanTemplatePopupForm");
		return mav;
	}

	/**
	 * 기회전템플릿 상품 삭제
	 * @param plan_content - 기획전템플릿 상품삭제
	 * @return
	 * @throws IOException
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/detail/template/goods/delete")
	@ResponseBody
	public GagaMap deletePlanTemplateGoods(@RequestBody Collection<Plan> param) throws IOException {
		GagaMap result = new GagaMap();
		Integer planContSq = null;
		Iterator<Plan> list = param.iterator();
		while (list.hasNext()) {
			planContSq = list.next().getPlanContSq();
		}
		planService.deletePlanContentItemGoods(planContSq);
		planService.deletePlanContentItem(planContSq);
		result.set("status", GagaResponseStatus.SUCCESS.getCode());
		return result;
	}
	
	/**
	 * 기획전 템플릿 저장
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/detail/template/save")
	@ResponseBody
	public GagaResponse planTemplateSave(@RequestBody Plan param) {
		// 기획전 컨텐츠 등록
		planService.createPlanContents(param);
		return super.ok(message.getMessage("SUCC_0001"));
	}
	
	/**
	 * 첨부파일 삭제
	 * @param plan_content - 기획전템플릿 첨부파일
	 * @return
	 * @throws IOException
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/detail/template/file/delete")
	@ResponseBody
	public GagaResponse deletePlanTemplateFile(@RequestBody Plan plan) throws IOException {
		// 파일 삭제
		String fileName = GagaFileUtil.getConcatenationPath(uploadTargetPath, "planning", plan.getFileItemVal());

		GagaFileUtil.deleteFile(fileName);

		// 삭제된 파일 DB 처리
		planService.deletePlanTemplateFile(plan);

		return super.ok(message.getMessage("SUCC_0003"));
	}
	
	/**
	 * 기획전 조회 팝업
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@GetMapping("/planning/list/popup")
	public ModelAndView planPopup(Plan plan) {
		ModelAndView mav = new ModelAndView();

		// 사이트 목록
		String supplyCompCd = TssSession.getInfo().getSupplyCompCd();
		String selfYn = "N";
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(supplyCompCd, selfYn));
		// 웹/모바일 구분
		mav.addObject("wmGbList", rendererService.getCommonCodeList("G093", "Y"));

		// 사이트 목록
		mav.addObject("siteList", rendererService.getCommonCodeList("G000", "Y"));

		// 사용여부
		mav.addObject("useYnList", rendererService.getAvailCommonCodeList("G002"));

		// 파라메터
		mav.addObject("params", plan);

		mav.setViewName("marketing/PlanPopupForm");

		return mav;
	}
	
	/**
	 * 기획전관리 목록
	 *
	 * @param
	 * @return 기획전 팝업 목록
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/list/detail/popup")
	@ResponseBody
	public Collection<Plan> getPlanListPop(@RequestBody Plan param) {
		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			param.setRegNo(TssSession.getInfo().getUserNo());
		}
		// multi row 검색관련 처리
		if (!StringUtils.isBlank(param.getCondition())) {
			param.setConditionList(param.getCondition().replaceAll("\r", "").split("\n"));
		}
		
		Collection<Plan> planList = planService.getPlanList(param);
		return planList;
	}
	
	/**
	 * 기획전 등록 화면 기획전 복사
	 *
	 * @return
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/copy")
	@ResponseBody
	public Plan copyPlan(@RequestBody Plan param) {
		return planService.copyPlan(param);
	}
	

	/**
	 * 기획전관리 목록
	 *
	 * @param
	 * @return 기획전 삭제
	 * @author sowon
	 * @since 2021. 05. 06
	 */
	@PostMapping("/planning/delete")
	@ResponseBody
	public GagaResponse deletePlan(@RequestBody Collection<Plan> paramList) {
		planService.deletePlan(paramList);
		return super.ok(message.getMessage("SUCC_0003"));
	}


    /**
     * 쿠폰목록 화면
     *
     * @return
     * @author bin2107
     * @since 2021. 5. 2
     */
    @GetMapping("/coupon/form")
    public ModelAndView couponListForm() {
        ModelAndView mav = new ModelAndView();
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			log.info("couponListForm getSupplyCompCd::::{}",TssSession.getInfo().getSupplyCompCd());
		}
        // 쿠폰상태 목록
        String[] exceptCds = {"G232_14"};
        mav.addObject("cpnStatList", rendererService.getCommonCodeList("G232", "Y", exceptCds));
        // 쿠폰 유형 조회
        mav.addObject("cpnTypeList", rendererService.getCommonCodeList("G230", "Y"));
        // 할인 유형 조회
        mav.addObject("dcWayList", rendererService.getCommonCodeList("G240"));

        mav.setViewName("marketing/CouponListForm");
        return mav;
    }

    /**
     * 쿠폰목록 리스트 조회
     *
     * @return
     * @author bin2107
     * @since 2021. 5. 2
     */
    @PostMapping("/coupon/list")
    @ResponseBody
    public GagaMap getCouponList(@RequestBody Coupon param) {
        GagaMap result = new GagaMap();

        // 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			log.info("getCouponList getSupplyCompCd::::{}",TssSession.getInfo().getSupplyCompCd());
			param.setRegNo(TssSession.getInfo().getUserNo());
		}

        param.setPageable(new TscPageRequest(param.getPageNo() - 1, param.getPageSize()));
        param.getPageable().setTotalCount(coreCouponService.getCouponListCnt(param));

        result.set("pageing", param);
        result.set("cpnList", coreCouponService.getCouponList(param));

        return result;
    }

	/**
	 * 쿠폰목록 리스트 조회
	 * @return
	 * @author bin2107
	 * @since 2021. 5. 17
	 */
	@GetMapping("/coupon/popup/form")
	@ResponseBody
	public ModelAndView couponCreatePopup(@RequestParam(value = "mode") String mode, @RequestParam(value = "cpnId", required = false) Integer cpnId) {
		ModelAndView mav = new ModelAndView();
		log.info("[couponCreatePopup]",cpnId);
		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
//			param.setRegNo(TssSession.getInfo().getUserNo());
		}
		String num = "";
		int issueCnt = 0;

		// 일시 시 리스트 세팅
		Collection<CommonCode> hhList = new ArrayList<CommonCode>();
		for (int i = 0; i < 24; i++) {
			num = "";
			CommonCode temp = new CommonCode();
			if (i < 10) {
				num = "0" + i;
			} else {
				num = String.valueOf(i);
			}

			temp.setCd(num);
			temp.setCdNm(num + "시");

			hhList.add(temp);
		}
		// 일시 분 리스트 세팅
		Collection<CommonCode> mmList = new ArrayList<CommonCode>();
		for (int i = 0; i < 60; i++) {
			num = "";
			CommonCode temp = new CommonCode();
			if (i < 10) {
				num = "0" + i;
			} else {
				num = String.valueOf(i);
			}
			temp.setCd(num);
			temp.setCdNm(num + "분");

			mmList.add(temp);
		}
		// 시간 분 리스트 세팅
		mav.addObject("mmList", mmList);
		// 시간 시 리스트 세팅
		mav.addObject("hhList", hhList);
		// 상품상태
		String[] exceptCds = {"G008_00"};
		mav.addObject("goodsStatList", rendererService.getCommonCodeList("G008", "Y", exceptCds));
		// 입점업체 조회
		mav.addObject("ibSupplyCompList", rendererService.getSupplyCompanyList(TssSession.getInfo().getSupplyCompCd()));
		// 할인 쿠폰 코드 조회
//		mav.addObject("dcCdList", rendererService.getCommonCodeList("G233", "Y"));
		// 정상/이월 조회
		mav.addObject("formalGbList", rendererService.getCommonCodeList("G009"));
		// 카테고리 구분 조회
		mav.addObject("cateGbList", rendererService.getCommonCodeList("G032"));
		// 자사 브랜드 조회
		mav.addObject("selfBrandList", rendererService.getSelfBrandList());
		// 사이트코드 조회
		mav.addObject("siteCdList", rendererService.getCommonCodeList("G000"));
		// 쿠폰상태 조회
		String[] exceptStat = {"G232_14"};
		mav.addObject("cpnStatList", rendererService.getCommonCodeList("G232", "Y", exceptStat));
		// 쿠폰 유형 조회
		String[] exceptCpnType = {"G230_20","G230_30"};
		mav.addObject("cpnTypeList", rendererService.getCommonCodeList("G230", "Y", exceptCpnType));
		// 사용가능 고객구분 조회
//		String[] exceptCds1 = {"G100_00"};
//		mav.addObject("usableCustGbList", rendererService.getCommonCodeList("G100", "Y", exceptCds1));
//		 사용가능 고객등급 조회
//		mav.addObject("usableCustGradeList", rendererService.getCommonCodeList("G110"));
		// 재발급 여부 조회
//		mav.addObject("reissuanceList", rendererService.getCommonCodeList("G231"));
		// 할인방식 조회
		mav.addObject("dcWayList", rendererService.getCommonCodeList("G240"));
		// 쿠폰다운로드 방식 조회
//		mav.addObject("dnGbList", rendererService.getCommonCodeList("G058"));
		// 결제수단 조회
//		String[] exceptCds2 = {"INICIS","ISTYLE","NAVER_ORDER","NICE"};
//		mav.addObject("payTypeList", rendererService.getCommonCodeList("G015", "Y", exceptCds2));
		// 상위제휴채널 조회
//		mav.addObject("upperAfLinkCdList", rendererService.getCommonCodeList("G053"));
		// 선착순쿠폰 조회
//		mav.addObject("limitedTimeCpnList", new Coupon());
		// 제휴채널 조회
//		mav.addObject("channelList", rendererService.getCommonCodeList("G053", "Y"));
		// 이미 쿠폰 아이디가 있으면 적용대상 조회
		if (mode.equals("U")) {
			issueCnt = coreCouponService.getCouponIssueCnt(cpnId);
			// 쿠폰상세조회
			mav.addObject("cpnDetail", coreCouponService.getCouponDetail(cpnId));
			// 쿠폰적용대상 - 공급업체 조회
			mav.addObject("cpnDtlRefvalSupplyCompList", coreCouponService.getCouponRefvalSupplyCompList(cpnId));
			// 쿠폰적용대상 - 적용상품 조회
			mav.addObject("cpnDtlRefvalApplyGoodsList", coreCouponService.getCouponRefvalGoodsList(cpnId, "G260_10"));
			// 쿠폰적용대상 - 카테고리 조회
			mav.addObject("cpnDtlRefvalCateList", coreCouponService.getCouponRefvalCategoryList(cpnId));
			// 쿠폰적용대상 - 브랜드 조회
			mav.addObject("cpnDtlRefvalBrandList", coreCouponService.getCouponRefvalBrandList(cpnId));
			// 쿠폰적용대상 - 제외상품 조회
			mav.addObject("cpnDtlRefvalExceptGoodsList", coreCouponService.getCouponRefvalGoodsList(cpnId, "G260_14"));
			// 쿠폰 입점업체분담율 조회
			mav.addObject("cpnDtlBurdenList", coreCouponService.getCouponBurdenList(cpnId));
			// 시리얼 및 난수 쿠폰 조회
//			mav.addObject("randomCpnList", coreCouponService.getRandomCouponInfo(cpnId));
			// 쿠폰사용가능고객구분 조회
//			mav.addObject("cpnCustGbList", coreCouponService.getCouponCustGbList(cpnId));
			// 쿠폰사용가능고객등급 조회
//			mav.addObject("cpnCustGradeList", coreCouponService.getCouponCustGradeList(cpnId));
			// 쿠폰사용가능결제수단 조회
//			mav.addObject("cpnPayTypeList", coreCouponService.getCouponPayTypeList(cpnId));
			// 선착순쿠폰 조회
//			mav.addObject("limitedTimeCpnList", coreCouponService.getLimitedTimeCouponList(cpnId));
			// 등록했던 제휴채널
//			mav.addObject("afChannelList", coreCouponService.getCouponAfChannelList(cpnId));
		}

		//issueCnt = 3;

		mav.addObject("mode", mode);
		mav.addObject("issueCnt", issueCnt);

		mav.setViewName("marketing/CouponPopupForm");
		return mav;
	}

	/**
	 * 쿠폰 저장
	 * @param coupon - 쿠폰 정보
	 * @return
	 * @author xyzp1539
	 * @since 2021. 1. 11
	 */
	@PostMapping("/coupon/save")
	@ResponseBody
	public GagaResponse saveCoupon(@RequestBody Coupon coupon) {
		log.info("couponSave : {}", coupon);
		coupon.setRegNo(TssSession.getInfo().getUserNo());
		coupon.setUpdNo(TssSession.getInfo().getUserNo());
		String result = coreCouponService.saveCoupon(coupon);
		if (!"SUCCESS".equals(result)) {
			return super.error(message.getMessage(result));
		}

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

	/**
	 * 쿠폰발급받은 회원리스트 팝업
	 * @param
	 * @return
	 * @author bin2107
	 * @since 2021-02-03
	 */
	@GetMapping("/coupon/pubCust/popup/form")
	@ResponseBody
	public ModelAndView couponPubCustListPopup(@RequestParam(value = "cpnId", required = true) Integer cpnId) {
		ModelAndView mav = new ModelAndView();

		mav.addObject("cpnPubCustList", coreCouponService.getCpnPubCustList(cpnId));

		mav.setViewName("marketing/CouponPubCustListPopupForm");
		return mav;
	}

	/**
	 * 브랜드 팝업
	 * @param
	 * @return
	 * @author bin2107
	 * @since 2021-05-21
	 */
	@PostMapping("/brand/popup")
	@ResponseBody
	public Collection<Brand> getBrandListPop(@RequestBody Brand param) {
		// 입점업체담당자는 업체코드 설정
		if ("G001_B000".equals(TssSession.getInfo().getRoleCd())) {
			param.setRegNo(TssSession.getInfo().getUserNo());
		}

		// multi row 검색관련 처리
		if (!StringUtils.isBlank(param.getSearchBrandCd())) {
			param.setMultiBrandCd(param.getSearchBrandCd().replaceAll("\r", "").split("\n"));
		}

		if (!StringUtils.isBlank(param.getSearchBrandNm())) {
			param.setMultiBrandNm(param.getSearchBrandNm().replaceAll("\r", "").split("\n"));
		}

		Collection<Brand> brandList = businessService.getBrandList(param);
		return brandList;
	}

	/**
	 * 쿠폰조회 팝업
	 * @param returnCode - 반환할코드. 필수
	 * @param returnName - 반환할명칭. 필수
	 * @param cpnNm - 쿠폰명. 옵션
	 * @return
	 * @author gagamel
	 * @since 2021. 1. 8
	 */
	@GetMapping("/coupon/retrieve/form")
	@ResponseBody
	public ModelAndView couponRetrieveForm(@RequestParam(value = "returnCode") String returnCode, @RequestParam(value = "returnName") String returnName, @RequestParam(value = "cpnNm", required = false) String cpnNm) {
		ModelAndView mav = new ModelAndView();

		mav.addObject("returnCode", returnCode);
		mav.addObject("returnName", returnName);
		mav.addObject("cpnNm", StringUtils.defaultString(cpnNm, ""));

		// 사이트 목록
		mav.addObject("siteList", rendererService.getAvailCommonCodeList("G000"));

		// 사용가능고객구분 목록
		mav.addObject("usableCustGbList", rendererService.getAvailCommonCodeList("G100"));

		// 쿠폰유형 목록
		mav.addObject("cpnTypeList", rendererService.getAvailCommonCodeList("G230"));

		// 할인방식 목록
		mav.addObject("dcWayList", rendererService.getAvailCommonCodeList("G240"));
		// 쿠폰상태 목록
		mav.addObject("cpnStatList", rendererService.getAvailCommonCodeList("G232"));
		mav.setViewName("marketing/CouponRetrievePopupForm");

		return mav;
	}

	/**
	 * 쿠폰조회 목록
	 * @param coupon - 쿠폰 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 1. 8
	 */
	@PostMapping("/coupon/retrieve/list")
	@ResponseBody
	public Collection<Coupon> getCouponRetrieveList(@RequestBody Coupon coupon) {
		return coreCouponService.getCouponRetrieveList(coupon);
	}
}
