package com.style24.admin.biz.service;

import com.gagaframework.web.parameter.GagaMap;
import com.gagaframework.web.security.GagaPasswordEncoder;
import com.style24.admin.biz.dao.TsaCustomerDao;
import com.style24.admin.support.security.session.TsaSession;
import com.style24.core.biz.service.TscCustomerService;
import com.style24.core.biz.service.TscKakaotalkService;
import com.style24.core.biz.service.TscMailService;
import com.style24.core.support.env.TscConstants;
import com.style24.persistence.domain.Counsel;
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 com.style24.persistence.domain.Order;
import com.style24.persistence.domain.Point;
import com.style24.persistence.domain.Review;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * 회원 Service
 *
 * @author jsshin
 * @since 2020. 01. 12
 */
@Service
@Slf4j
public class TsaCustomerService {

	@Autowired
	private TsaCustomerDao customerDao;

	@Autowired
	private TscCustomerService coreCustomerService;

	@Autowired
	private GagaPasswordEncoder passwordEncoder;

	@Autowired
	private TscKakaotalkService kakaotalkService;

	@Autowired
	private TscMailService mailService;

	/**
	 * 활동회원 건수
	 * @param customerSearch - 검색조건
	 * @return int
	 * @author jsshin
	 * @since 2021. 2. 01
	 */
	public int getCustomerActiveListCount(CustomerSearch customerSearch) {
		return  customerDao.getCustomerActiveListCount(customerSearch);
	}

	/**
	 * 활동회원 목록
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2021. 1. 12
	 */
	public Collection<Customer> getCustomerActiveList(CustomerSearch customerSearch) {
		return customerDao.getCustomerActiveList(customerSearch);
	}

	/**
	 * 회원 정보
	 * @param custNo - 고객번호
	 * @return Customer
	 * @author jsshin
	 * @since 2021. 1. 18
	 */
	public Customer getCustomerInfo(Integer custNo) {
		Customer customer = new Customer();
		customer.setSiteCd(TscConstants.Site.STYLE24.value());
		customer.setCustNo(custNo);
		customer.setCustStat(TscConstants.CustStat.ACTIVE.value());
		return coreCustomerService.getCustomerInfo(customer);
	}

	/**
	 * 회원정보 수정
	 * @param customer - 고객정보
	 * @author jsshin
	 * @since 2021. 1. 20
	 */
	@Transactional("shopTxnManager")
	public void saveCustomerInfo(Customer customer) {
		boolean isDupEmail = false;

		// 이메일 변경시 유효성 체크
		if ("Y".equals(customer.getEmailModifyYn())) {
			isDupEmail = getCustomerByEmail(customer.getCustNo(), customer.getEmail());
		}

		if (isDupEmail) {
			throw new IllegalStateException("이미 사용중인 이메일 입니다.");
		}

		Integer userNo = TsaSession.getInfo().getUserNo();
		customer.setRegNo(userNo);
		customer.setUpdNo(userNo);
		customer.initBirthMm();
		customer.encryptData();  // 암호화 처리

		// 1.고객 이력 생성
		coreCustomerService.createCustomerHistory(customer);

		// 2.마케팅수신동의 이력
		if (StringUtils.isNotBlank(customer.getSmsAgreeYn()) || StringUtils.isNotBlank(customer.getEmailAgreeYn())) {
			coreCustomerService.createCustomerMarketHst(customer);
		}

		// 3.고객정보 수정
		customerDao.updateCustomerInfo(customer);

	}

	/**
	 * 이메일 유효성 확인
	 * @param custNo - 고객번호
	 * @param email - 이메일
	 * @return boolean - 결과 사용중인 이메일 있으면 1 없으면 0
	 * @author jsshin
	 * @since 2021. 03. 15
	 */
	private boolean getCustomerByEmail(Integer custNo, String email) {
		Customer customer = new Customer();
		customer.setSiteCd(TscConstants.Site.STYLE24.value());
		customer.setCustNo(custNo);
		customer.setEmail(email);
		customer.encryptData();
		int result = coreCustomerService.getCustomerByEmail(customer);
		return result > 0;
	}

	/**
	 * 회원 비밀번호 수정
	 * @param customer - 고객정보
	 * @author jsshin
	 * @since 2021. 1. 20
	 */
	@Transactional("shopTxnManager")
	public void saveCustomerPassword(Customer customer) {
		Integer userNo = TsaSession.getInfo().getUserNo();

		String tempPasswd = getTemporaryPassword(10);
		customer.setPasswd(tempPasswd);
		customer.setEncodedPasswd(passwordEncoder.encodeSha256(tempPasswd));

		log.info("tempPasswd  ====> {}", tempPasswd);

		customer.setRegNo(userNo);
		customer.setUpdNo(userNo);
		customer.setTempPasswdYn("Y");
		coreCustomerService.saveCustomerPassword(customer);

		if (StringUtils.isNotBlank(customer.getCellPhnno())) {
			kakaotalkService.sendCustomerTempPassword(customer, userNo);
		}

		if (StringUtils.isNotBlank(customer.getEmail())) {
			mailService.sendCustomerTempPassword(customer, userNo);
		}

	}

	/**
	 * 회원 휴대전화번호 수정
	 * @param customer - 고객정보
	 * @author jsshin
	 * @since 2021. 1. 25
	 */
	@Transactional("shopTxnManager")
	public void updateCustomerCellphnno(Customer customer) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		customer.setRegNo(userNo);
		customer.setUpdNo(userNo);
		customer.encryptData();
		coreCustomerService.createCustomerHistory(customer);
		customerDao.updateCustomerCellPhnno(customer);
	}

	/**
	 * 회원 탈퇴처리
	 * @param customer - 고객정보
	 * @return GagaMap - 결과 정보(메시지)
	 * @author jsshin
	 * @since 2021. 1. 26
	 */
	@Transactional("shopTxnManager")
	public GagaMap saveCustomerSecede(Customer customer) {
		customer.setSiteCd(TscConstants.Site.STYLE24.value());
		return coreCustomerService.saveCustomerSecede(customer);
	}

	/**
	 * 회원 주문내역 총 목록
	 * @param customerSearch - 고객번호, 페이징
	 * @return Collection<Order>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public int getCustomerOrderListCount(CustomerSearch customerSearch) {
		return customerDao.getCustomerOrderListCount(customerSearch);
	}

	/**
	 * 회원 주문내역
	 * @param customerSearch - 고객번호, 페이징
	 * @return Collection<Order>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<Order> getCustomerOrderList(CustomerSearch customerSearch) {
		return customerDao.getCustomerOrderList(customerSearch);
	}

	/**
	 * 회원상세-주소정보
	 *
	 * @param custNo - 고객번호
	 * @return Collection<Delivery>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<CustDeliveryAddr> getCustomerDeliveryAddrList(Integer custNo) {
		CustDeliveryAddr custDeliveryAddr = new CustDeliveryAddr();
		custDeliveryAddr.setCustNo(custNo);
		return coreCustomerService.getCustomerDeliveryAddrList(custDeliveryAddr);
	}

	/**
	 * 회원상세-주소정보 수정
	 *
	 * @param custDeliveryAddr - 배송지정보
	 * @author jsshin
	 * @since 2021. 1 21.
	 */
	@Transactional("shopTxnManager")
	public void saveCustomerDeliveryAddr(CustDeliveryAddr custDeliveryAddr) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		custDeliveryAddr.setRegNo(userNo);
		custDeliveryAddr.setUpdNo(userNo);
		coreCustomerService.saveCustomerDeliveryAddr(custDeliveryAddr);
	}

	/**
	 * 회원상세-쿠폰내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Coupon>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<Coupon> getCustomerCouponList(Integer custNo) {
		return customerDao.getCustomerCouponList(custNo);
	}

	/**
	 * 회원상세-포인트
	 *
	 * @param custNo -고객일련번호
	 * @return Point
	 * @author jsshin
	 * @since 2021. 1. 25
	 */
	public Point getCustomerPoint(Integer custNo){
		return customerDao.getCustomerPoint(custNo);
	}

	/**
	 * 회원상세-포인트내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Coupon>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<Point> getCustomerPointList(Integer custNo) {
		return customerDao.getCustomerPointList(custNo);
	}

	/**
	 * 회원상세-상품권내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<GiftCard>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<GiftCard> getCustomerGiftCardList(Integer custNo) {
		return customerDao.getCustomerGiftCardList(custNo);
	}

	/**
	 * 회원상세-상품평내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Review>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<Review> getCustomerReviewList(Integer custNo) {
		return customerDao.getCustomerReviewList(custNo);
	}

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

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

	/**
	 * 회원상세- 등급변경 내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Counsel>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<CustGrade> getCustomerChangeGradeList(Integer custNo) {
		return customerDao.getCustomerChangeGradeList(custNo);
	}

	/**
	 * 회원상세- 접촉내역
	 *
	 * @param custNo -고객일련번호
	 * @return Collection<Counsel>
	 * @author jsshin
	 * @since 2021. 1. 21
	 */
	public Collection<CustContactHst> getCustomerContactList(Integer custNo) {
		return customerDao.getCustomerContactList(custNo);
	}

	/**
	 * 회원상세-회원접촉이력 생성
	 *
	 * @param custContactHst -고객정보
	 * @return void
	 * @author jsshin
	 * @since 2021. 1. 25
	 */
	@Transactional("shopTxnManager")
	public void createCustomerContactHistory(CustContactHst custContactHst) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		custContactHst.setRegNo(userNo);
		custContactHst.setUpdNo(userNo);
		custContactHst.setSenderNo(userNo);
		custContactHst.setReceiverNo(custContactHst.getCustNo());
		coreCustomerService.createCustomerContactHistory(custContactHst);
	}

	/**
	 * 탈퇴회원 목록 건수
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2021. 02. 01
	 */
	public int getCustomerSecedeListCount(CustomerSearch customerSearch) {
		return customerDao.getCustomerSecedeListCount(customerSearch);
	}

	/**
	 * 탈퇴회원 목록
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2020. 0. 14
	 */
	public Collection<Customer> getCustomerSecedeList(CustomerSearch customerSearch) {
		return customerDao.getCustomerSecedeList(customerSearch);
	}

	/**
	 * 휴면회원 목록 건수
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2021. 02. 01
	 */
	public int getCustomerDormantListCount(CustomerSearch customerSearch) {
		return customerDao.getCustomerDormantListCount(customerSearch);
	}

	/**
	 * 휴면회원 목록
	 * @param customerSearch - 검색조건
	 * @return Collection<Customer>
	 * @author jsshin
	 * @since 2020. 1. 14
	 */
	public Collection<Customer> getCustomerDormantList(CustomerSearch customerSearch) {
		return customerDao.getCustomerDormantList(customerSearch);
	}

	/**
	 * 임시비밀번호 조회
	 * @param length - 비밀번호 자릿수
	 * @return 임시비밀번호
	 * @author jsshin
	 * @since 2021. 02. 15
	 */
	public String getTemporaryPassword(int length) {
		return coreCustomerService.getTemporaryPassword(length);
	}

	/**
	 * 휴대전화 번호 조회
	 * @param  cellPhnno - 고객 번호
	 * @return int - 고객 수
	 * @author jsshin
	 * @since 2021. 02. 23
	 */
	public int getCustomerFindByCellPhone(String cellPhnno) {
		CustomerSearch customerSearch = new CustomerSearch();
		customerSearch.setSiteCd(TscConstants.Site.STYLE24.value());
		customerSearch.setCellPhnno(cellPhnno);
		customerSearch.encryptData();
		return customerDao.getCustomerFindByCellPhone(customerSearch);
	}

	/**
	 * 휴면해제 처리
	 *
	 * @param customer - 고객정보
	 * @return boolean 성공하면 true
	 * @author jsshin
	 * @since 2021. 03. 30
	 */
	@Transactional("shopTxnManager")
	public boolean releaseDormantCustomer(Customer customer) {
		Integer userNo = TsaSession.getInfo().getUserNo();
		customer.setRegNo(userNo);
		customer.setUpdNo(userNo);
		return coreCustomerService.saveDormantCustomerRelease(customer);
	}

	/**
	 * 회원 정보 조회
	 * @param custId - 고객 아이디
	 * @return Customer
	 * @author jsshin
	 * @since 2021. 05. 13
	 */
	public Customer getCustomerInfoByCustId(String custId) {
		Customer customer = new Customer();
		customer.setSiteCd(TscConstants.Site.STYLE24.value());
		customer.setCustId(custId);
		customer.setCustStat(TscConstants.CustStat.ACTIVE.value());
		return coreCustomerService.getCustomerInfo(customer);
	}

	/**
	 * 탈퇴처리
	 *
	 * @param custNo - 고객번호
	 * @return GagaMap - 결과정보
	 * @author jsshin
	 * @since 2021. 03. 08
	 */
	@Transactional("shopTxnManager")
	public boolean deleteSecedeCustomer(Integer custNo) {
		return coreCustomerService.deleteSecedeCustomer(custNo);
	}



}
