package com.style24.core.biz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gagaframework.web.parameter.GagaMap;
import com.style24.core.biz.dao.TscCustomerDao;
import com.style24.core.support.env.TscConstants;
import com.style24.core.support.util.CryptoUtils;
import com.style24.persistence.domain.CustAccount;
import com.style24.persistence.domain.CustContactHst;
import com.style24.persistence.domain.CustDeliveryAddr;
import com.style24.persistence.domain.Customer;
import com.style24.persistence.domain.Order;

import lombok.extern.slf4j.Slf4j;

import java.util.Collection;

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

	@Autowired
	private TscCustomerDao customerDao;

	@Autowired
	private TscOrderService coreOrderService;

	@Autowired
	private TscEnvsetService envsetService;

	@Autowired
	private Environment env;


	/**
	 * 회원 정보
	 * @param customer - 고객정보
	 * @return Customer
	 * @author jsshin
	 * @since 2021. 1. 18
	 */
	public Customer getCustomerInfo(Customer customer) {
		return customerDao.getCustomerInfo(customer);
	}


	/**
	 * 회원접촉이력 생성
	 *
	 * @param custContactHst - 고객접촉이력
	 * @author jsshin
	 * @since 2020. 01. 20
	 */
	@Transactional("shopTxnManager")
	public void createCustomerContactHistory(CustContactHst custContactHst) {
		customerDao.createCustomerContactHistory(custContactHst);
	}

	/**
	 * 고객이력 생성
	 *
	 * @param customer - 고객번호/사용자번호
	 * @author jsshin
	 * @since 2021. 1. 20
	 */
	@Transactional("shopTxnManager")
	public void createCustomerHistory(Customer customer) {
		customerDao.createCustomerHistory(customer);
	}


	/**
	 * 회원 비밀번호 수정
	 *
	 * @param customer - 고객정보
	 * @author jsshin
	 * @since 2020. 01. 20
	 */
	@Transactional("shopTxnManager")
	public void saveCustomerPassword(Customer customer) {
		customerDao.createCustomerHistory(customer);
		customerDao.updateCustomerPassword(customer);
	}

	/**
	 * 회원 탈퇴처리
	 *
	 * @param customer - 고객정보
	 * @author jsshin
	 * @since 2020. 01. 26
	 */
	@Transactional("shopTxnManager")
	public GagaMap saveCustomerSecede(Customer customer) {
		GagaMap result = new GagaMap();

		// 1. 이미 탈퇴처리 되었는지 확인
		Customer customerInfo = customerDao.getCustomerInfo(customer);
		if (TscConstants.CustStat.SECEDE.value().equals(customerInfo.getCustStat())) {
			result.setBoolean("isSuccess", false);
			result.setString("resultType", "ALREADY_SECEDE");
			return result;
		}

		// 2. 진행중인 주문건 있는지 확인
		boolean progressOrder = getOrderProgress(customer.getCustNo());
		if (progressOrder) {
			result.setBoolean("isSuccess", false);
			result.setString("resultType", "PROGRESS_ORDER");
			return result;
		}
		customer.setCustStat(TscConstants.CustStat.SECEDE.value());
		customer.setEncodedCustNm(CryptoUtils.encryptAES("탈퇴"));

		// 3.고객정보 이력 생성
		customerDao.createCustomerHistory(customer);

		// 4.탈퇴정보생성
		int custSecedeCnt = customerDao.createCustomerSecede(customer);

		// 5.고객테이블 탈퇴처리
		customerDao.updateCustomerSecedeInfo(customer);

		// 6.위시테이블 삭제
		customerDao.deleteWishList(customer.getCustNo());

		// 7. 장바구니상세테이블 삭제
		customerDao.deleteCustomerCartDetail(customer.getCustNo());

		// 8. 장바구니테이블 삭제
		customerDao.deleteCustomerCart(customer.getCustNo());

		if (custSecedeCnt > 0) {
			int rejoinRejectDay = envsetService.getRejoinRejectDays(TscConstants.Site.STYLE24.value());
			Customer custSecede = customerDao.getSecedeDt(customer.getCustNo());
			result.setInt("rejoinRejectDay", rejoinRejectDay);
			result.setString("secedeDt", custSecede.getSecedeDt());
			result.setString("snsType", custSecede.getSnsType());
			result.setBoolean("isSuccess", true);
		} else {
			result.setBoolean("isSuccess", false);
			result.setString("resultType", "ERROR");
		}

		return result;
	}

	/**
	 * 회원 탈퇴처리
	 *
	 * @param custNo - 고객번호
	 * @return boolean - 진행중 주문 건 , 취소진행/교환진행/반품진행 건 있으면 true / false
	 * @author jsshin
	 * @since 2020. 03. 24
	 */
	public boolean getOrderProgress(Integer custNo) {
		Order order = new Order();
		order.setCustNo(custNo);
		Order orderStatInfo = coreOrderService.getOrderStatCount(order);
		// 진행중인 주문
		int proOrdCnt = orderStatInfo.getDepositWaitingCount() + orderStatInfo.getWaitingAddPaymentCount()
					+ orderStatInfo.getPaymentCompleteCount() + orderStatInfo.getGoodsPrepareCount()
					+ orderStatInfo.getShipPrepareCount() + orderStatInfo.getShippingCount();
		// 진행중인 취소
		int cnclOrdCnt = orderStatInfo.getCancelCount();
		// 진행중인 반품
		int returnCount = orderStatInfo.getReturnCount();
		// 진행중인 교환
		int exchangeCount = orderStatInfo.getExchangeCount();

		return proOrdCnt + cnclOrdCnt + returnCount + exchangeCount > 0;
	}

	/**
	 * 회원정보 마케팅수신동의이력
	 *
	 * @param customer - 고객정보
	 * @author jsshin
	 * @since 2020. 01. 26
	 */
	@Transactional("shopTxnManager")
	public void createCustomerMarketHst(Customer customer) {
		customerDao.createCustomerMarketHst(customer);
	}


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


	/**
	 * 휴면해제 처리
	 *
	 * @param customer - 고객정보
	 * @return int - 성공하면 1 이기때문에 true
	 * @author jsshin
	 * @since 2021. 03. 08
	 */
	@Transactional("shopTxnManager")
	public boolean saveDormantCustomerRelease(Customer customer) {
		// 1. 고객정보 이력 생성
		customerDao.createCustomerHistory(customer);

		// 2. 휴면해제처리 - 등급 WELCOME 추가
		customer.setCustGrade(TscConstants.CustGrade.WELCOME.value());
		int resultCnt = customerDao.updateDormantCustomerRelease(customer);

		// 3. 휴면 테이블 삭제
		customerDao.deleteDormantCustomer(customer.getCustNo());

		// 4. 주문정보 휴면해제
		customerDao.updateDormantOrderRelease(customer);

		// 5. 휴면주문정보 삭제
		customerDao.deleteDormantOrder(customer.getCustNo());

		return resultCnt > 0;
	}

	/**
	 * 고객계좌 정보
	 *
	 * @param  custNo - 고객번호
	 * @return CustAccount - 고객계과 정보
	 * @author jsshin
	 * @since 2021. 03. 18
	 */
	public CustAccount getCustomerAccuontInfo(Integer custNo) {
		CustAccount custAccount = new CustAccount();
		custAccount.setCustNo(custNo);
		return customerDao.getCustomerAccuontInfo(custAccount);
	}

	/**
	 * 고객계좌 정보
	 *
	 * @param  custAccount - 고객계좌정보
	 * @return boolean - 성공여부
	 * @author jsshin
	 * @since 2021. 03. 22
	 */
	@Transactional("shopTxnManager")
	public boolean saveCustomerAccountInfo(CustAccount custAccount) {
		CustAccount custAcc = customerDao.getCustomerAccuontInfo(custAccount);
		customerDao.updateAccountDefaultInit(custAccount);
		custAccount.setDelYn("N");
		custAccount.setDefaultYn("Y");
		custAccount.encryptData(); // 계좌번호 암호화

		int resultCnt;

		// 1. 없으면 INSERT / 있으면 UPDATE
		if (custAcc != null) {
			resultCnt = customerDao.updateAccountInfo(custAccount);
		} else {
			resultCnt = customerDao.createAccountInfo(custAccount);
		}


		return resultCnt > 0;
	}

	/**
	 * 이메일 유효성 확인
	 * @param customer - 고객정보
	 * @return int - 결과
	 * @author jsshin
	 * @since 2021. 03. 15
	 */
	public int getCustomerByEmail(Customer customer) {
		return customerDao.getCustomerByEmail(customer);
	}

	/**
	 * 고객 주소정보
	 *
	 * @param custDeliveryAddr - 고객번호
	 * @return Collection<CustDeliveryAddr>
	 * @author jsshin
	 * @since 2021. 04. 02
	 */
	public Collection<CustDeliveryAddr> getCustomerDeliveryAddrList(CustDeliveryAddr custDeliveryAddr) {
		return customerDao.getCustomerDeliveryAddrList(custDeliveryAddr);
	}

	/**
	 * 고객배송지 정보 저장
	 *
	 * @param custDeliveryAddr - 배송지정보
	 * @author jsshin
	 * @since 2021. 04. 02
	 */
	@Transactional("shopTxnManager")
	public void saveCustomerDeliveryAddr(CustDeliveryAddr custDeliveryAddr) {
		if ("Y".equals(custDeliveryAddr.getDefaultYn())) {
			customerDao.updateCustomerDeliveryAddrDefaultInit(custDeliveryAddr);
		}
		customerDao.saveCustomerDeliveryAddr(custDeliveryAddr);
	}

	/**
	 * 고객배송지 정보 삭제
	 *
	 * @param custDeliveryAddr - 배송지정보
	 * @return int - 결과
	 * @author jsshin
	 * @since 2021. 04. 02
	 */
	@Transactional("shopTxnManager")
	public int deleteCustDeliveryAddr(CustDeliveryAddr custDeliveryAddr) {
		return customerDao.deleteCustDeliveryAddr(custDeliveryAddr);
	}

	/**
	 * 탈퇴처리
	 *
	 * @param custNo - 고객번호
	 * @author jsshin
	 * @since 2021. 06. 30
	 */
	@Transactional("shopTxnManager")
	public boolean deleteSecedeCustomer(Integer custNo) {
		customerDao.deleteCustomerHst(custNo);
		customerDao.deleteCustomerSns(custNo);
		int resultCnt = customerDao.deleteSecedeCustomer(custNo);
		return resultCnt > 0;
	}

}
