package com.style24.admin.biz.web;

import java.util.Collection;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.util.GagaStringUtil;
import com.style24.admin.biz.service.TsaCustomerService;
import com.style24.admin.support.util.TsitUtil;
import com.style24.core.biz.service.TscKakaotalkService;
import com.style24.core.biz.service.TscMailService;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.session.TscSession;
import com.style24.core.support.util.CryptoUtils;
import com.style24.persistence.TscPageRequest;
import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.CustContactHst;
import com.style24.persistence.domain.CustDeliveryAddr;
import com.style24.persistence.domain.CustGrade;
import com.style24.persistence.domain.Customer;
import com.style24.persistence.domain.CustomerSearch;
import com.style24.persistence.domain.GiftCard;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 com.style24.admin.biz.service.TsaCounselService;
import com.style24.admin.biz.service.TsaRendererService;
import com.style24.admin.support.controller.TsaBaseController;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.biz.service.TscAnswerPhaseService;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.AnswerPhase;
import com.style24.persistence.domain.Counsel;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.rest.server.GagaResponse;
import com.style24.persistence.domain.Order;
import com.style24.persistence.domain.Plan;
import com.style24.persistence.domain.Point;
import com.style24.persistence.domain.Review;

/**
 * 고객 Controller
 *
 * @author gagamel
 * @since 2020. 12. 28
 */
@Controller
@RequestMapping("/customer")
@Slf4j
public class TsaCustomerController extends TsaBaseController {

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private TsaCounselService counselService;

	@Autowired
	private TsaRendererService rendererService;

	@Autowired
	private TscAnswerPhaseService ansPhaseService;

	@Autowired
	private TsaCustomerService customerService;

	@Autowired
	private TscKakaotalkService kakaotalkService;

	@Autowired
	private TscMailService mailService;

	/**
	 * 1:1문의관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@GetMapping("/onetoone/qna/form")
	public ModelAndView oneToOneQnaForm() {
		ModelAndView mav = new ModelAndView();

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

		// 상담분류
		mav.addObject("counselClsfList", rendererService.getCommonCodeList("G059", "Y", new String[] {"G596"}));

		// 상담상태 목록
		mav.addObject("ansStatList", rendererService.getAvailCommonCodeList("G060"));

		mav.setViewName("customer/OneToOneQnaForm");

		return mav;
	}

	/**
	 * 1:1문의 목록
	 * @param counsel - 상담정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@PostMapping("/onetoone/qna/list")
	@ResponseBody
	public GagaMap getOneToOneQnaList(@RequestBody Counsel counsel) {
		GagaMap result = new GagaMap();
		
		counsel.setPageable(new TscPageRequest(counsel.getPageNo() - 1, counsel.getPageSize()));
		counsel.getPageable().setTotalCount(counselService.getOneToOneQnaListCount(counsel));
		
		Collection<Counsel> counselList = counselService.getOneToOneQnaList(counsel);
		
		result.set("pageing", counsel);
		result.set("counselList", counselList);
		
		return result;
	}

	/**
	 * 1:1문의상세 화면
	 * @param counselSq -상담일련번호
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@GetMapping("/onetoone/qna/detail/form/{counselSq}")
	public ModelAndView oneToOneQnaDetailForm(@PathVariable Integer counselSq) {
		ModelAndView mav = new ModelAndView();

		// 1:1문의 상세 정보
		mav.addObject("counselInfo", counselService.getOneToOneQna(counselSq));

		// 문의용 답변문구
		mav.addObject("ansPhaseList", rendererService.getQnaAnswerPhaseList("G061_20"));

		mav.setViewName("customer/OneToOneQnaDetailForm");

		return mav;
	}

	/**
	 * 문의용 답변문구 조회
	 * @param ansSq - 답변일련번호
	 * @param ansClsf - 답변종류
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@GetMapping("/qna/answerphase/{ansSq}/{ansClsf}")
	@ResponseBody
	public AnswerPhase getQnaAnswerPhase(@PathVariable Integer ansSq, @PathVariable String ansClsf) {
		AnswerPhase ansPhase = new AnswerPhase();
		ansPhase.setAnsSq(ansSq);
		ansPhase.setAnsClsf(ansClsf);
		return ansPhaseService.getQnaAnswerPhase(ansPhase);
	}

	/**
	 * 문의 답변 저장
	 * @param counsel -상담정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@PostMapping("/qna/answer/save")
	@ResponseBody
	public GagaResponse saveQnaAnswer(@RequestBody Counsel counsel) {
		counsel.setAnsNo(TsaSession.getInfo().getUserNo());
		counsel.setUpdNo(TsaSession.getInfo().getUserNo());

		counselService.updateQnaAnswer(counsel);

		// TODO. 고객이 SMS답변수신을 요청했을 때
		if (counsel.getSmsReqYn().equals("Y")) {
			try {
				if (counsel.getCounselType().equals("C")) {
					// 일대일문의상세 조회
					Counsel tCounsel = counselService.getOneToOneQna(counsel.getCounselSq());
					// 1:1문의답변완료안내 카카오알림톡 발송
					kakaotalkService.sendOneToOneAnswerNotify(tCounsel,tCounsel.getCustNo());
				}else if (counsel.getCounselType().equals("G")) {
					// 상품문의상세 조회
					Counsel tCounsel = counselService.getGoodsQna(counsel.getCounselSq());
					// 상품문의답변완료안내 카카오알림톡 발송
					kakaotalkService.sendGoodsAskNotify(tCounsel,tCounsel.getCustNo());					
				}
				
			} catch (Exception e) {
				// Do nothing
			}
		}
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 상품문의관리 화면
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@GetMapping("/goods/qna/form")
	public ModelAndView goodsQnaForm() {
		ModelAndView mav = new ModelAndView();

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

		// 답변의뢰업체 목록
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd(), "N"));

		// 상담상태 목록
		mav.addObject("ansStatList", rendererService.getAvailCommonCodeList("G060"));

		mav.setViewName("customer/GoodsQnaForm");

		return mav;
	}

	/**
	 * 상품문의 목록
	 * @param counsel - 상담정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@PostMapping("/goods/qna/list")
	@ResponseBody
	public GagaMap getGoodsQnaList(@RequestBody Counsel counsel) {
		
		GagaMap result = new GagaMap();
		
		counsel.setPageable(new TscPageRequest(counsel.getPageNo() - 1, counsel.getPageSize()));
		counsel.getPageable().setTotalCount(counselService.getGoodsQnaListCount(counsel));
		
		Collection<Counsel> counselList = counselService.getGoodsQnaList(counsel);
		
		result.set("pageing", counsel);
		result.set("counselList", counselList);
		
		
		return result;
	}

	/**
	 * 상품문의상세 화면
	 * @param counselSq -상담일련번호
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@GetMapping("/goods/qna/detail/form/{counselSq}")
	public ModelAndView goodsQnaDetailForm(@PathVariable Integer counselSq) {
		ModelAndView mav = new ModelAndView();

		// 답변의뢰업체
		mav.addObject("supplyCompList", rendererService.getSupplyCompanyList(TsaSession.getInfo().getSupplyCompCd(), "N"));

		// 상품문의 상세
		mav.addObject("counselInfo", counselService.getGoodsQna(counselSq));

		// 문의용 답변문구
		mav.addObject("ansPhaseList", rendererService.getQnaAnswerPhaseList("G061_20"));

		mav.setViewName("customer/GoodsQnaDetailForm");

		return mav;
	}

	/**
	 * 상품문의 입점업체에 답변의뢰 (입점상품일 경우)
	 * @param counsel -상담정보
	 * @return
	 * @author gagamel
	 * @since 2020. 12. 24
	 */
	@PostMapping("/goods/qna/answer/transfer/save")
	@ResponseBody
	public GagaResponse saveGoodsQnaAnswerTransfer(@RequestBody Counsel counsel) {
		counsel.setAnsTransNo(TsaSession.getInfo().getUserNo());
		counsel.setUpdNo(TsaSession.getInfo().getUserNo());

		counselService.updateGoodsQnaAnswerTransfer(counsel);

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

	/**
	 * 활동회원
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2021. 01. 12
	 */
	@GetMapping("/active/list/form")
	public ModelAndView customerActiveListForm() {
		ModelAndView mav = new ModelAndView();

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

		// 성별
		mav.addObject("genderGbList", rendererService.getCommonCodeList("G007", "Y"));

		// 회원 구분
		mav.addObject("custGbList", rendererService.getCommonCodeList("G100", "Y"));

		// 회원 등급
		mav.addObject("custGradeList", rendererService.getCommonCodeList("G110", "Y"));

		// 관리대상
		mav.addObject("managedRsnList", rendererService.getCommonCodeList("G103", "Y"));

		// 간편가입유형
		mav.addObject("snsTypeList", rendererService.getCommonCodeList("G105","Y"));

		mav.setViewName("customer/CustomerActiveListForm");

		return mav;
	}

	/**
	 * 활동회원 목록
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2021. 01. 12
	 */
	@PostMapping("/active/list")
	@ResponseBody
	public GagaMap getCustomerActiveList(@RequestBody CustomerSearch customerSearch) {
		GagaMap result = new GagaMap();
		// multi row 검색관련 처리
		if (!StringUtils.isBlank(customerSearch.getCondition())) {
			if(customerSearch.getSearch().equals("custNm") || customerSearch.getSearch().equals("email")){
				String[] multiParams = customerSearch.getCondition().replaceAll("\r", "").split("\n");
				for (int i = 0; i < multiParams.length; i++) {
					multiParams[i] = CryptoUtils.encryptAES(multiParams[i]);
				}

				customerSearch.setConditions(multiParams);
			}else{
				customerSearch.setConditions(customerSearch.getCondition().replaceAll("\r", "").split("\n"));
			}
		}

		// 회원명, 이메일 암호화
		if ("custNm".equals(customerSearch.getSearchGb()) || "email".equals(customerSearch.getSearchGb())) {
			customerSearch.setSearchTxt(CryptoUtils.encryptAES(customerSearch.getSearchTxt()));
		}
		if(!"Y".equals(customerSearch.getCpnPubPopYn())){
			customerSearch.setCpnPubPopYn("N");
		}
		customerSearch.encryptData();	//데이터 암호화 필요
		customerSearch.setRegNo(TsaSession.getInfo().getUserNo());
		customerSearch.setPageable(new TscPageRequest(customerSearch.getPageNo()-1, customerSearch.getPageSize()));
		customerSearch.getPageable().setTotalCount(customerService.getCustomerActiveListCount(customerSearch));
		TscSession.setAttribute("maskingYn", TsaSession.getInfo().getMaskingYn());

		result.set("pageing", customerSearch);
		result.set("custList", customerService.getCustomerActiveList(customerSearch));
		return result;
	}

	/**
	 * 회원상세 목록
	 * @param custNo - 고객번호
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2021. 01. 14
	 */
	@GetMapping("/detail/form/{custNo}")
	public ModelAndView getCustomerDetailForm(@PathVariable Integer custNo) {
		ModelAndView mav = new ModelAndView();

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

		// 몰구분
		mav.addObject("mallGbList", rendererService.getCommonCodeList("G011"));

		// 성별
		mav.addObject("genderGbList", rendererService.getCommonCodeList("G007"));

		// 회원 구분
		mav.addObject("custGbList", rendererService.getCommonCodeList("G100","Y"));

		// 회원 등급
		mav.addObject("custGradeList", rendererService.getCommonCodeList("G110"));

		// 관리대상
		mav.addObject("managedRsnList", rendererService.getCommonCodeList("G103"));

		// 전화번호국번
		mav.addObject("nationalNumberList", rendererService.getCommonCodeList("G095"));

		// 휴대폰번호국번
		mav.addObject("nationalHpNumberList", rendererService.getCommonCodeList("G096"));

		// 이메일도메인
		mav.addObject("emailDomainList", rendererService.getCommonCodeList("G097"));

		// 상담분류
		mav.addObject("counselClsfList", rendererService.getCommonCodeList("G059"));

		// 회원접촉유형 목록
		mav.addObject("contactTypeList", rendererService.getCommonCodeList("G054"));

		// 회원접촉방법 목록
		mav.addObject("contactMethodList", rendererService.getCommonCodeList("G055"));

		// 주문상태
		mav.addObject("orderStatList", rendererService.getCommonCodeList("G012"));

		// 주문상세상태
		mav.addObject("orderDtlStatList", rendererService.getCommonCodeList("G013"));

		// 쿠폰유형
		mav.addObject("cpnType", rendererService.getCommonCodeList("G230", "Y"));

		// 쿠폰할인방식
		//mav.addObject("dcWayList", rendererService.getCommonCodeList("G240"));

		// 쿠폰발행사유
		mav.addObject("pubReasonList", rendererService.getCommonCodeList("G068"));

		// 포인트반영상태
		mav.addObject("pntOccurGbList", rendererService.getCommonCodeList("G069"));

		// 포인트반영상태
		mav.addObject("pntUploadStatList", rendererService.getCommonCodeList("G070"));
		
		// 상품평포인트반영상태
		mav.addObject("reviewPntStatList", rendererService.getCommonCodeList("G043"));

		// 상품권유형
		mav.addObject("giftCardOccurGbList", rendererService.getCommonCodeList("G074"));

		mav.addObject("custNo", custNo);

		mav.setViewName("customer/CustomerDetailForm");

		return mav;
	}

	/**
	 * 회원정보
	 * @param custNo - 고객번호
	 * @return Customer
	 * @author jsshin
	 * @since 2021. 01. 18
	 */
	@GetMapping("/info/{custNo}")
	@ResponseBody
	public Customer getCustomerInfo(@PathVariable Integer custNo) {
		TscSession.setAttribute("maskingYn", TsaSession.getInfo().getMaskingYn());
		return customerService.getCustomerInfo(custNo);
	}

	/**
	 * 회원정보 수정
	 * @param customer - 고객정보
	 * @return Customer
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/info/save")
	@ResponseBody
	public GagaResponse saveCustomerInfo(@RequestBody Customer customer) {
		customerService.saveCustomerInfo(customer);
		return ok(message.getMessage("SUCC_0002"));
	}

	/**
	 * 회원비밀번호초기화
	 *
	 * @param customer -고객정보
	 * @return GagaResponse
	 * @throws Exception
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/password/reset")
	@ResponseBody
	public GagaResponse resetCustomerPassword(@RequestBody Customer customer) {

		Customer custInfo = customerService.getCustomerInfo(customer.getCustNo());

		// 비밀번호 수정
		customerService.saveCustomerPassword(custInfo);

		return ok(message.getMessage("SUCC_0005"));
	}

	/**
	 * 메시지 발송 팝업 화면
	 *
	 * @param elementCellPhnno - 휴대폰
	 * @param elementCustNo - 고객일련번호
	 * @param maskingCellPhnno - 마스킹된 휴대폰
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/lms/popup/form")
	public ModelAndView lmsPopupForm(@RequestParam(value = "elementCellPhnno", required = false) String elementCellPhnno
									, @RequestParam(value = "elementCustNo") String elementCustNo
									, @RequestParam(value = "elementMaskingCellPhnno", required = false) String maskingCellPhnno
									, @RequestParam(value = "pageGb", required = false) String pageGb) {
		ModelAndView mav = new ModelAndView();
		// 휴대폰 번호
		mav.addObject("elementCellPhnno", elementCellPhnno);


		// 휴대폰 번호
		mav.addObject("maskingCellPhnno", StringUtils.defaultString(maskingCellPhnno,""));

		// 고객 아이디
		mav.addObject("elementCustNo", elementCustNo);

		mav.addObject("callBack", TscConstants.CALLCENTER_TEL_NO);

		mav.addObject("pageGb", StringUtils.defaultString(pageGb, ""));

		mav.setViewName("customer/LmsPopupForm");

		return mav;
	}

	/**
	 * 메시지 발송
	 *
	 * @param customer -고객정보
	 * @return GagaResponse
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/message/send")
	@ResponseBody
	public GagaResponse sendMessage(@RequestBody Customer customer) {
		Customer custInfo = customerService.getCustomerInfo(customer.getCustNo());
		customer.setCustNm(custInfo.getCustNm());
		customer.setCustNo(custInfo.getCustNo());

		if (StringUtils.isNotBlank(customer.getCellPhnno())) {
			Integer userNo = TsaSession.getInfo().getUserNo();
			kakaotalkService.sendCustomerBasicLms(customer, userNo);
		}

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

	/**
	 * 메시지 발송 팝업 화면
	 *
	 * @param elementCellPhnno - 휴대폰
	 * @param elementCustNo - 고객일련번호
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2021. 01. 25
	 */
	@GetMapping("/cellphone/change/popup/form")
	public ModelAndView cellphoneChangePopupForm(@RequestParam(value = "elementCellPhnno", required = false) String elementCellPhnno
			, @RequestParam(value = "elementCustNo") String elementCustNo) {
		ModelAndView mav = new ModelAndView();
		// 휴대폰 번호
		mav.addObject("elementCellPhnno", elementCellPhnno);

		// 고객 아이디
		mav.addObject("elementCustNo", elementCustNo);

		mav.addObject("callBack", TscConstants.CALLCENTER_TEL_NO);

		mav.setViewName("customer/CellphoneChangePopupForm");

		return mav;
	}

	/**
	 * 인증번호 발송
	 *
	 * @param customer -고객정보
	 * @return GagaResponse
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/certno/send")
	@ResponseBody
	public GagaResponse sendCustomerCertNo(@RequestBody Customer customer) {

		// 1.기존 사용하고 있는 고객이 있는지 확인
		int custCnt = customerService.getCustomerFindByCellPhone(customer.getCellPhnno());

		if (custCnt > 0) {
			throw new IllegalStateException("해당 휴대전화번호로 사용하고 있는 고객이 있습니다.");
		}

		String certNo = GagaStringUtil.getRandomNumber(6);
		TsaSession.setAttribute("certNo", certNo);
		TsaSession.setAttribute("cellPhnno", customer.getCellPhnno());


		Customer custInfo = customerService.getCustomerInfo(customer.getCustNo());
		customer.setCustNm(custInfo.getCustNm());
		customer.setCertNo(certNo);
		log.info("certNo {}", certNo);

		// 카카오알림톡 발송(카카오 템플릿 문구검수 후 변경 해야함)
		// 광고가 아니므로 SMS수신동의여부 체크할 필요 없음. 무조건 발송해야 함
		if (StringUtils.isNotBlank(customer.getCellPhnno())) {
			Integer userNo = TsaSession.getInfo().getUserNo();
			kakaotalkService.sendCustomerCertNo(customer, userNo);
		}

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

	/**
	 * 인증번호 확인
	 *
	 * @param customer -고객정보
	 * @return GagaMap
	 * @author jsshin
	 * @since 2021. 01. 25
	 */
	@PostMapping("/certno/confirm")
	@ResponseBody
	public GagaMap confirmCustomerCertNo(@RequestBody Customer customer) {
		String certNo = TsaSession.getAttribute("certNo");
		String cellPhnno = TsaSession.getAttribute("cellPhnno");
		String crtfdNoYn = "N";

		if (certNo.equals(customer.getCertNo())) {
			customer.setCellPhnno(cellPhnno);
			if (StringUtils.isNotBlank(cellPhnno)) {
				customerService.updateCustomerCellphnno(customer);
			}
			crtfdNoYn = "Y";
		}

		GagaMap result = new GagaMap();
		result.setString("crtfdNoYn", crtfdNoYn);
		return result;
	}

	/**
	 * 메일 발송 팝업 화면
	 *
	 * @param elementEmail  - 이메일
	 * @param elementCustNo - 고객일련번호
	 * @param elementMaskingEmail - 마스킹 이메일
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/email/popup/form")
	public ModelAndView emailPopupForm(@RequestParam(value = "elementEmail") String elementEmail
									, @RequestParam(value = "elementCustNo") String elementCustNo
									, @RequestParam(value = "elementMaskingEmail", required = false) String elementMaskingEmail) {

		ModelAndView mav = new ModelAndView();

		// 받는사람 이메일
		mav.addObject("elementEmail", elementEmail);

		// 마스킹된 이메일
		mav.addObject("elementMaskingEmail", StringUtils.defaultString(elementMaskingEmail,""));

		// 고객 번호
		mav.addObject("elementCustNo", elementCustNo);

		mav.addObject("sendEmail", TscConstants.REP_EMAIL);

		mav.setViewName("customer/EmailPopupForm");

		return mav;
	}

	/**
	 * 이메일 발송
	 *
	 * @param customer -고객정보
	 * @return GagaResponse
	 * @throws Exception
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/email/send")
	@ResponseBody
	public GagaResponse sendEmail(@RequestBody Customer customer) throws Exception {
		Customer custInfo = customerService.getCustomerInfo(customer.getCustNo());
		customer.setCustNm(custInfo.getCustNm());

		// 메일 발송
		if (StringUtils.isNotBlank(customer.getEmail())) {
			mailService.sendBasicMail(customer, TsaSession.getInfo().getUserNo());
		}

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

	/**
	 * 회원탈퇴처리 화면
	 *
	 * @param elementCustNo - 고객일련번호
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/secede/popup/form")
	public ModelAndView emailPopupForm( @RequestParam(value = "elementCustNo") String elementCustNo) {

		ModelAndView mav = new ModelAndView();

		// 고객일련번호
		mav.addObject("elementCustNo", elementCustNo);

		// 탈퇴 구분
		mav.addObject("secedeRsnList", rendererService.getCommonCodeList("G102", "Y"));

		mav.setViewName("customer/CustomerSecedePopupForm");

		return mav;
	}

	/**
	 * 회원탈퇴처리
	 *
	 * @param customer - 고객일련번호
	 * @return GagaMap
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/secede/save")
	@ResponseBody
	public GagaMap saveCustomerSecede(@RequestBody Customer customer) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		customer.setRegNo(userNo);
		customer.setUpdNo(userNo);
		return customerService.saveCustomerSecede(customer);
	}

	/**
	 * 회원상세-주문내역목록
	 *
	 * @param customerSearch -고객일련번호, 페이징
	 * @return Collection<Order>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/order/list")
	@ResponseBody
	public GagaMap getCustomerOrderList(@RequestBody CustomerSearch customerSearch) {
		GagaMap result = new GagaMap();
		customerSearch.setRegNo(TsaSession.getInfo().getUserNo());
		customerSearch.setPageable(new TscPageRequest(customerSearch.getPageNo()-1, customerSearch.getPageSize()));
		customerSearch.getPageable().setTotalCount(customerService.getCustomerOrderListCount(customerSearch));
		result.set("pageing", customerSearch);
		result.set("custOrderList", customerService.getCustomerOrderList(customerSearch));
		return result;
	}

	/**
	 * 회원상세-주소정보
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Delivery>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/delivery/list/{custNo}")
	@ResponseBody
	public Collection<CustDeliveryAddr> getCustomerDeliveryList(@PathVariable Integer custNo) {
		return customerService.getCustomerDeliveryAddrList(custNo);
	}

	/**
	 * 회원상세 - 주소지 저장
	 *
	 * @param custDeliveryAddr - 고객배송지정보
	 * @return GagaResponse
	 * @author jsshin
	 * @since 2021. 1. 21.
	 */
	@PostMapping("/delivery/addr/save")
	@ResponseBody
	public GagaResponse saveCustomerDeliveryAddr(@RequestBody CustDeliveryAddr custDeliveryAddr) {
		customerService.saveCustomerDeliveryAddr(custDeliveryAddr);
		return super.ok(message.getMessage("SUCC_0001"));
	}

	/**
	 * 회원상세-쿠폰내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Coupon>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/coupon/list/{custNo}")
	@ResponseBody
	public Collection<Coupon> getCustomerCouponList(@PathVariable Integer custNo) {
		return customerService.getCustomerCouponList(custNo);
	}

	/**
	 * 회원상세-포인트
	 *
	 * @param custNo -고객일련번호
	 * @return Point
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/point/{custNo}")
	@ResponseBody
	public Point getCustomerPoint(@PathVariable Integer custNo) {
		return customerService.getCustomerPoint(custNo);
	}

	/**
	 * 회원상세-포인트내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<TsaPoint>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/point/list/{custNo}")
	@ResponseBody
	public Collection<Point> getCustomerPointList(@PathVariable Integer custNo) {
		return customerService.getCustomerPointList(custNo);
	}

	/**
	 * 회원상세-1:1문의내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Counsel>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/giftcard/list/{custNo}")
	@ResponseBody
	public Collection<GiftCard> getCustomerGiftCardList(@PathVariable Integer custNo) {
		return customerService.getCustomerGiftCardList(custNo);
	}

	/**
	 * 회원상세-1:1문의내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Counsel>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/counsel/list/{custNo}")
	@ResponseBody
	public Collection<Counsel> getCustomerCounselList(@PathVariable Integer custNo) {
		return customerService.getCustomerCounselList(custNo);
	}

	/**
	 * 회원상세-상품문의내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Counsel>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/goodsQna/list/{custNo}")
	@ResponseBody
	public Collection<Counsel> getCustomerGoodsQnaList(@PathVariable Integer custNo) {
		return customerService.getCustomerGoodsQnaList(custNo);
	}

	/**
	 * 회원상세-상품평내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<TsaReview>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
		@GetMapping("/review/list/{custNo}")
		@ResponseBody
		public Collection<Review> getCustomerReviewList(@PathVariable Integer custNo) {
			return customerService.getCustomerReviewList(custNo);
		}

	/**
	 * 회원상세-회원등급변경이력
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<TsaCustomer>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
		@GetMapping("/change/grade/list/{custNo}")
		@ResponseBody
		public Collection<CustGrade> getCustomerChageGradeList(@PathVariable Integer custNo) {
			return customerService.getCustomerChangeGradeList(custNo);
		}

	/**
	 * 회원상세-회원접촉이력
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@GetMapping("/contact/list/{custNo}")
	@ResponseBody
	public Collection<CustContactHst> getCustomerContactList(@PathVariable Integer custNo) {
		return customerService.getCustomerContactList(custNo);
	}

	/**
	 * 회원상세-회원접촉이력 생성
	 *
	 * @param custContactHst -고객정보
	 * @return GagaResponse
	 * @author jsshin
	 * @since 2021. 01. 21
	 */
	@PostMapping("/contact/create")
	@ResponseBody
	public GagaResponse createCustomerContactHistory(@RequestBody CustContactHst custContactHst) {
		customerService.createCustomerContactHistory(custContactHst);
		return super.ok(message.getMessage("SUCC_0001"));
	}


	/**
	 * 탈퇴회원
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2020. 01. 14
	 */
	@GetMapping("/secede/list/form")
	public ModelAndView customerSecedeListForm() {
		ModelAndView mav = new ModelAndView();

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

		// 탈퇴 구분
		mav.addObject("secedeRsnList", rendererService.getCommonCodeList("G102", "Y"));

		mav.setViewName("customer/CustomerSecedeListForm");

		return mav;
	}

	/**
	 * 탈퇴회원 목록
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2020. 01. 14
	 */
	@PostMapping("/secede/list")
	@ResponseBody
	public GagaMap getCustomerSecedeList(@RequestBody CustomerSearch customerSearch) {
		GagaMap result = new GagaMap();
		// 회원명, 이메일 암호화
		if ("custNm".equals(customerSearch.getSearchGb()) || "email".equals(customerSearch.getSearchGb())) {
			customerSearch.setSearchTxt(CryptoUtils.encryptAES(customerSearch.getSearchTxt()));
		}
		customerSearch.encryptData();	//데이터 암호화 필요
		customerSearch.setRegNo(TsaSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		customerSearch.setPageable(new TscPageRequest(customerSearch.getPageNo() - 1, customerSearch.getPageSize()));
		customerSearch.getPageable().setTotalCount(customerService.getCustomerSecedeListCount(customerSearch));

		TscSession.setAttribute("maskingYn", TsaSession.getInfo().getMaskingYn());
		result.set("pageing", customerSearch);
		result.set("custList", customerService.getCustomerSecedeList(customerSearch));

		return result;
	}

	/**
	 * 휴면회원
	 * @return ModelAndView
	 * @author jsshin
	 * @since 2020. 01. 14
	 */
	@GetMapping("/dormant/list/form")
	public ModelAndView customerDormantListForm() {
		ModelAndView mav = new ModelAndView();

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

		mav.setViewName("customer/CustomerDormantListForm");

		return mav;
	}

	/**
	 * 휴면회원 목록
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2020. 01. 14
	 */
	@PostMapping("/dormant/list")
	@ResponseBody
	public GagaMap getCustomerDormantList(@RequestBody CustomerSearch customerSearch) {
		GagaMap result = new GagaMap();
		// 회원명, 이메일 암호화
		if ("custNm".equals(customerSearch.getSearchGb()) || "email".equals(customerSearch.getSearchGb())) {
			customerSearch.setSearchTxt(CryptoUtils.encryptAES(customerSearch.getSearchTxt()));
		}
		customerSearch.encryptData();	//데이터 암호화 필요
		customerSearch.setRegNo(TsaSession.getInfo().getUserNo()); // 엑셀조회시 로그인 사용자의 엑셀 상품조회시 사용
		customerSearch.setPageable(new TscPageRequest(customerSearch.getPageNo() - 1, customerSearch.getPageSize()));
		customerSearch.getPageable().setTotalCount(customerService.getCustomerDormantListCount(customerSearch));
		TscSession.setAttribute("maskingYn", TsaSession.getInfo().getMaskingYn());

		result.set("pageing", customerSearch);
		result.set("custList", customerService.getCustomerDormantList(customerSearch));
		return result;
	}

	/**
	 * 휴면해제 처리
	 * @param  customerCollection - 휴면해제대상목록
	 * @return GagaMap - 결과
	 * @author jsshin
	 * @since 2020. 01. 14
	 */
	@PostMapping("/dormant/release")
	@ResponseBody
	public GagaMap releaseDormantCustomer(@RequestBody Collection<Customer> customerCollection) {
		GagaMap result = new GagaMap();
		int totalCnt = customerCollection.size();
		int succCnt = 0;
		int failCnt = 0;
		for (Customer customer : customerCollection) {
			try {
				boolean isRelase = customerService.releaseDormantCustomer(customer);
				if (isRelase) {
					succCnt ++;
				} else {
					failCnt ++;
				}
			} catch (Exception e) {
				log.error(e.getMessage());
				failCnt ++;
			}
		}
		result.setInt("totalCnt", totalCnt);
		result.setInt("succCnt", succCnt);
		result.setInt("failCnt", failCnt);

		return result;
	}

	/**
	 * 탈퇴이력 삭제
	 *
	 * @param  customerCollection - 탈퇴이력 삭제
	 * @return GagaMap - 결과
	 * @author jsshin
	 * @since 2020. 01. 14
	 */
	@PostMapping("/secede/delete")
	@ResponseBody
	public GagaMap deleteSecedCustomer(@RequestBody Collection<Customer> customerCollection) {
		GagaMap result = new GagaMap();
		int totalCnt = customerCollection.size();
		int succCnt = 0;
		int failCnt = 0;
		for (Customer customer : customerCollection) {
			try {
				customerService.deleteSecedeCustomer(customer.getCustNo());
				succCnt ++;
			} catch (Exception e) {
				log.error(e.getMessage());
				failCnt ++;
			}
		}
		result.setInt("totalCnt", totalCnt);
		result.setInt("succCnt", succCnt);
		result.setInt("failCnt", failCnt);

		return result;
	}


}
