package com.style24.front.biz.service;

import java.io.File;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.lang3.StringUtils;
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.style24.front.biz.dao.TsfCommonDao;
import com.style24.front.biz.dao.TsfPlanningDao;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.Coupon;
import com.style24.persistence.domain.CustDeliveryAddr;
import com.style24.persistence.domain.Plan;
import com.style24.persistence.domain.Poll;
import com.style24.persistence.domain.Review;

import lombok.extern.slf4j.Slf4j;

import com.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;

/**
 * 기획전 Service
 *
 * @author gagamel
 * @since 2020. 12. 29
 */
@Service
@Slf4j
public class TsfPlanningService {

	@Autowired
	private TsfPlanningDao planningDao;

	@Autowired
	private TsfCouponService couponService;

	@Autowired
	private TsfCommonDao commonDao;

	@Autowired
	private Environment env;

	/**
	 * 기획전 카테고리 목록
	 * @param plan - 기획전 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 29
	 */
	public Collection<Plan> getPlanningCategoryList(Plan plan) {
		return planningDao.getPlanningCategoryList(plan);
	}

	/**
	 * 기획전 메인 목록
	 * @param plan - 기획전 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 29
	 */
	public Collection<Plan> getPlanningMainList(Plan plan) {
		// 기획전 목록
		Collection<Plan> planningList = planningDao.getPlanningList(plan);

		for (Plan tPlan : planningList) {
			plan.setPlanSq(tPlan.getPlanSq());

			// 기획전 상품 목록
			tPlan.setPlanningGoodsList(planningDao.getPlanningGoodsList(plan));
		}

		return planningList;
	}

	/**
	 * 기획전 갯수 조회
	 * 
	 * @param Plan
	 * @author sowon
	 * @since 2021.03.05
	 */
	public int getPlanAllCount(Plan plan) {
		return planningDao.getPlanAllCount(plan);
	}

	/**
	 * 기획전 목록
	 * @param plan - 기획전 정보
	 * @return
	 * @author gagamel
	 * @since 2021. 3. 29
	 */
	public Collection<Plan> getPlanningList(Plan plan) {
		return planningDao.getPlanningList(plan);
	}

	/**
	 * 기획전 코너 상품 목록
	 * @param plan - 기획전 정보
	 * @return
	 * @author sowon
	 * @since 2021. 3. 31
	 */
	public Collection<Plan> getPlanningCornerGoodsList(Plan plan) {
		return planningDao.getPlanningCornerGoodsList(plan);
	}

	/**
	 * 접근 불가능한 기획전 메시지 조회
	 * @param plan
	 * @return 접근 불가능 사유 메시지
	 * @author gagamel
	 * @since 2021. 3. 30
	 */
	public String getInaccessiblePlanningMessage(Plan plan) {
		// 유효한 기획전 여부 조회
		if ("N".equals(planningDao.getAvailPlanningYn(plan))) {
			return "진행중인 기획전/이벤트가 아닙니다.";
		}

		// 디바이스접근가능여부 조회
		plan.setFrontGb(TsfSession.getFrontGb());
		if ("N".equals(planningDao.getDeviceAccessibleYn(plan))) {
			String frontGb = planningDao.getFrontAccessibleList(plan);
			if ("M".equals(TsfSession.getFrontGb())) {
				return frontGb + "에서만 접근이 가능합니다.";
			} else if ("A".equals(TsfSession.getFrontGb())) {
				return frontGb + "에서만 접근이 가능합니다.";
			}
		}

		if (!TsfSession.isLogin()) {
			plan.setCustGrade("G110_60");
			if ("N".equals(planningDao.getCustomerGradeAccessibleYn(plan))) {
				return "로그인 후 이용 가능합니다.";
			}
		}

		if (TsfSession.isLogin()) {
			// 신규회원접근가능여부 조회
			plan.setCustNo(TsfSession.getInfo().getCustNo());
			if ("N".equals(planningDao.getNewCustomerAccessibleYn(plan))) {
				return "신규회원만 접근 가능합니다.";
			}

			// 고객구분접근가능여부 조회
			plan.setCustGb(TsfSession.getCustGb());
			if ("N".equals(planningDao.getCustomerGubunAccessibleYn(plan))) {
				return planningDao.getCustomerGubunAccessibleList(plan).getCustGb() + "만 접근이 가능합니다.";
			}

			String custGrade = "";
			// 고객등급접근가능여부 조회
			plan.setCustGrade(TsfSession.getInfo().getCustGrade());
			if ("N".equals(planningDao.getCustomerGradeAccessibleYn(plan))) {
				Iterator<Plan> iter = planningDao.getCustomerGradeAccessibleList(plan).iterator();
				while (iter.hasNext()) {
					custGrade += iter.next().getCustGrade();

					if (iter.hasNext()) {
						custGrade += ", ";
					}
				}
				return custGrade + " 회원만 접근 가능합니다.";
			}
		}

		if (StringUtils.isNotBlank(TsfSession.getAttribute("afLinkCd"))) {
			// 웹제휴채널접근가능여부 조회
			plan.setAfLinkCd(TsfSession.getAttribute("afLinkCd"));
			if ("N".equals(planningDao.getAfLinkAccessibleYn(plan))) {
//				return commonDao.getAfLinkName(TsfSession.getAttribute("afLinkCd")) + " 채널만 접근 가능합니다.";
				return "제휴 채널을 통해서만 접근 가능합니다.";
			}
		}

		return "";
	}

	/**
	 * 기획전 상세 정보
	 *
	 * @param
	 * @return
	 * @author sowon	
	 * @since 2021. 3. 8
	 */
	public Plan getPlanDetailInfo(Plan plan) {
		return planningDao.getPlanDetailInfo(plan);
	}

	/**
	 * 기획전 상세 프론트소스
	 *
	 * @param
	 * @return
	 * @author sowon	
	 * @since 2021. 3. 22
	 */
	public Plan getPlanFsrcInfo(Plan plan) {
		return planningDao.getPlanFsrcInfo(plan);
	}

	/**
	 * 기획전 템플릿 순서
	 *
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 3. 22
	 */
	public Collection<Plan> templateDispOrdInfo(Plan plan) {
		return planningDao.templateDispOrdInfo(plan);
	}

	/**
	 * 기획전 템플릿 리뷰
	 *
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 3. 22
	 */
	public Collection<Plan> getPlanReviewInfo(Review review) {
		return planningDao.getPlanReviewInfo(review);
	}

	/**
	 * 기획전 템플릿 쿠폰
	 *
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 3. 22
	 */
	public Collection<Plan> getPlanCouponInfo(Coupon coupon) {
		if (TsfSession.isLogin()) {
			coupon.setCustNo(TsfSession.getInfo().getCustNo());
		}

		return planningDao.getPlanCouponInfo(coupon);
	}

	/**
	 * 기획전 템플릿 이미지
	 *
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 3. 22
	 */
	public Collection<Plan> getPlanImageInfo(Plan plan) {
		return planningDao.getPlanImageInfo(plan);
	}

	/**
	 * 기획전 템플릿 유의사항
	 *
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 5. 26
	 */
	public Collection<Plan> getPlanNoticeInfo(Plan plan) {
		return planningDao.getPlanNoticeInfo(plan);
	}

	/**
	 * 기획전 템플릿 상품
	 *
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 3. 22
	 */
	public Collection<Plan> getPlanGoodsDisplayList(Plan plan) {
		return planningDao.getPlanGoodsDisplayList(plan);
	}

	/**
	 * 기획전 코너 리스트
	 *
	 * @param 기획전 번호
	 * @return
	 * @author sowon
	 * @date 2021. 3. 30
	 */
	public Collection<Plan> getPlanCornerList(Plan plan) {
		return planningDao.getPlanCornerList(plan);
	}

	/**
	 * 상품 쿠폰 다운 처리
	 *
	 * @param coupon
	 * @return 
	 * @author sowon
	 * @since 2021.03.24
	 */
	@Transactional("shopTxnManager")
	public String getPlanCouponDownInfo(Coupon coupon) {
		return couponService.getPlanCouponInfo(coupon);
	}

	/**
	 * 이벤트 갯수 조회
	 * 
	 * @param Plan
	 * @author sowon
	 * @since 2021.03.08
	 */
	public int getEvnetAllCount(Plan plan) {
		return planningDao.getEventAllCount(plan);
	}

	/**
	 * 이벤트 목록
	 *
	 * @param
	 * @return
	 * @author sowon
	 * @since 2021. 3. 9
	 */
	public Collection<Plan> getPlanEventList(Plan plan) {
		return planningDao.getPlanEventList(plan);
	}

	/**
	 * 총알배송 상단 html 소스 
	 *
	 * @param plan
	 * @return Collection<Plan>
	 * @author sowon
	 * @date 2021. 3. 30
	 */
	public Plan getShotDeliveryHtmlTop(Plan plan) {
		return planningDao.getShotDeliveryHtmlTop(plan);
	}

	/**
	 * 총알배송 하단 html 소스 
	 *
	 * @param plan
	 * @return Collection<Plan>
	 * @author sowon
	 * @date 2021. 3. 30
	 */
	public Plan getShotDeliveryHtmlBtm(Plan plan) {
		return planningDao.getShotDeliveryHtmlBtm(plan);
	}

	/**
	 * 설문조사 정보
	 *
	 * @param plan
	 * @return poll
	 * @author sowon
	 * @date 2021. 4. 3
	 */
	public Poll getPollQuestionInfo(Plan plan) {
		return planningDao.getPollQuestionInfo(plan);
	}

	/**
	 * 설문조사 질문내용
	 *
	 * @param plan
	 * @return poll
	 * @author sowon
	 * @date 2021. 4. 3
	 */
	public Collection<Poll> getPollQuestionList(Plan plan) {
		return planningDao.getPollQuestionList(plan);
	}

	/**
	 * 설문조사 등록
	 *
	 * @param poll
	 * @return 
	 * @author sowon
	 * @date 2021. 4. 3
	 */
	@Transactional("shopTxnManager")
	public void savePollCustAnswer(Poll poll) {
		poll.setCustNo(TsfSession.getInfo().getCustNo());
		// 단수형
		int ansIndex = planningDao.getPollCustAnswerIndex();
		if (poll.getPollQsq_10() != null && poll.getPollQsq_10() != "") {
			String[] pollQsq_10 = poll.getPollQsq_10().split("/");
			for (int i = 0; i < pollQsq_10.length; i++) {
				String[] temp = pollQsq_10[i].split("-");
				for (int j = 0; j < temp.length; j++) {
					String pollQsq = temp[j].toString();
					poll.setPollQsq(Integer.parseInt(pollQsq));
					String dummy = temp[j + 1].toString();
					poll.setDummy(dummy);
					poll.setAnsIndex(ansIndex);
					planningDao.savePollCustAnswer(poll);
					j++;
				}
			}
		}

		//복수형
		if (poll.getPollQsq_20() != null && poll.getPollQsq_20() != "") {
			String[] pollQsq_20 = poll.getPollQsq_20().split("/");
			for (int i = 0; i < pollQsq_20.length; i++) {
				String[] temp = pollQsq_20[i].split("-");
				for (int j = 0; j < temp.length; j++) {
					String pollQsq = temp[j].toString();
					poll.setPollQsq(Integer.parseInt(pollQsq));
					String dummy = temp[j + 1].toString().replaceAll("[,]", "|");
					poll.setDummy(dummy);
					poll.setAnsIndex(ansIndex);
					planningDao.savePollCustAnswer(poll);

					j++;
				}
			}
		}

		//단답형
		if (poll.getPollQsq_30() != null && poll.getPollQsq_30() != "") {
			String[] pollQsq_30 = poll.getPollQsq_30().split("/");
			for (int i = 0; i < pollQsq_30.length; i++) {
				String[] temp = pollQsq_30[i].split("-");
				for (int j = 0; j < temp.length; j++) {
					String pollQsq = temp[j].toString();
					poll.setPollQsq(Integer.parseInt(pollQsq));
					String dummy = temp[j + 1].toString();
					poll.setDummy(dummy);
					poll.setAnsIndex(ansIndex);
					planningDao.savePollCustAnswer(poll);
					j++;
				}
			}
		}

		//서룰형
		if (poll.getPollQsq_40() != null && poll.getPollQsq_40() != "") {
			String[] pollQsq_40 = poll.getPollQsq_40().split("/");
			for (int i = 0; i < pollQsq_40.length; i++) {
				String[] temp = pollQsq_40[i].split("-");
				for (int j = 0; j < temp.length; j++) {
					String pollQsq = temp[j].toString();
					poll.setPollQsq(Integer.parseInt(pollQsq));
					String dummy = temp[j + 1].toString();
					poll.setDummy(dummy);
					poll.setAnsIndex(ansIndex);
					planningDao.savePollCustAnswer(poll);
					j++;
				}
			}
		}
	}

	/**
	 * 설문조사 중복카운트
	 *
	 * @param plan
	 * @return int
	 * @author sowon
	 * @date 2021. 4. 4
	 */
	public int getCustAnswerCount(Plan plan) {
		return planningDao.getCustAnswerCount(plan);
	}

	/**
	 * 설문조사 중복카운트
	 *
	 * @param plan
	 * @return int
	 * @author sowon
	 * @date 2021. 4. 5
	 */
	public int getCustAnswerPartiCount(Poll poll) {
		return planningDao.getCustAnswerPartiCount(poll);
	}

	/**
	 * 총알배송 조회할 기본 주소
	 *
	 * @param CustDeliveryAddr
	 * @return CustDeliveryAddr
	 * @author sowon
	 * @date 2021. 4. 5
	 */
	public CustDeliveryAddr getCustAddrInfo(CustDeliveryAddr addr) {
		return planningDao.getCustAddrInfo(addr);
	}

	/**
	 * 총알배송 가능여부
	 *
	 * @param CustDeliveryAddr
	 * @return CustDeliveryAddr
	 * @author sowon
	 * @date 2021. 4. 5
	 */
	public CustDeliveryAddr getCustAddrShotConfirm(String recipZipcode) {
		return planningDao.getCustAddrShotConfirm(recipZipcode);
	}

	/**
	 * 출석체크 달력 출력
	 *
	 * @param Plan
	 * @return Plan
	 * @author sowon
	 * @date 2021. 4. 6
	 */
	public Collection<Plan> getAttendMonth(Plan plan) {
		return planningDao.getAttendMonth(plan);
	}

	/**
	 * 출석체크 
	 *
	 * @param Plan
	 * @return 
	 * @author sowon
	 * @date 2021. 4. 7
	 */
	@Transactional("shopTxnManager")
	public void saveAttendEntry(Plan plan) {
		int custNo = TsfSession.getInfo().getCustNo();
		plan.setCustNo(custNo);
		plan.setEntryCustNo(custNo);
		plan.setEntryVal2("Y");
		planningDao.saveAttendEntry(plan);
	}

	/**
	 * 출석체크 확인
	 *
	 * @param Plan
	 * @return int
	 * @author sowon
	 * @date 2021. 4. 7
	 */
	public int getAttendEntryCount(Plan plan) {
		plan.setCustNo(TsfSession.getInfo().getCustNo());
		return planningDao.getAttendEntryCount(plan);
	}

	/**
	 * 고객이 출석한 일 리스트
	 *
	 * @param Plan
	 * @return Collection<Plan>
	 * @author sowon
	 * @date 2021. 4. 7
	 */
	public Collection<Plan> getCustAttendEntryList(Plan plan) {
		plan.setCustNo(TsfSession.getInfo().getCustNo());
		return planningDao.getCustAttendEntryList(plan);
	}

	/**
	 * 출석체크 혜택 리스트
	 *
	 * @param Plan
	 * @return Collection<Plan>
	 * @author sowon
	 * @date 2021. 4. 14
	 */
	public Collection<Plan> getAttendBenefitList(Plan plan) {
		plan.setFrontGb(TsfSession.getFrontGb());
		return planningDao.getAttendBenefitList(plan);
	}

	/**
	 * 기획전/이벤트 댓글
	 *
	 * @param Plan
	 * @return Collection<Plan>
	 * @author sowon
	 * @date 2021. 4. 8
	 */
	public Collection<Plan> getReplyList(Plan plan) {
		return planningDao.getReplyList(plan);
	}

	/**
	 * 기획전/이벤트 댓글,이미지 저장
	 *
	 * @param Plan
	 * @return 
	 * @author sowon
	 * @date 2021. 4. 13
	 */
	@Transactional("shopTxnManager")
	public void saveEntryReply(Plan plan) {
		int custNo = TsfSession.getInfo().getCustNo();
		plan.setCustNo(custNo);
		planningDao.saveEntryReply(plan);

		//이미지등록
		Plan filePlan = new Plan();
		if (!StringUtils.isAllEmpty(plan.getMultiReplySysFile())) {
			filePlan.setRegNo(custNo);
			filePlan.setPlanEntrySq(plan.getPlanEntrySq());
			//파일아이템 등록
			String[] fileItemVal1 = plan.getMultiReplySysFile();
			int ind = 1;
			for (int j = 0; j < fileItemVal1.length; j++) {
				String imgInd = String.valueOf(ind);
				if (ind < 10) {
					imgInd = "0" + imgInd;
				}
				String planUploadPath = env.getProperty("upload.default.target.path");
				String yearMonth = GagaDateUtil.getToday().substring(0, 6);
				planUploadPath = GagaFileUtil.getConcatenationPath(planUploadPath, "/reply");
				File newFile = new File(GagaFileUtil.getConcatenationPath(planUploadPath, fileItemVal1[j]));
				planUploadPath = GagaFileUtil.getConcatenationPath(planUploadPath, yearMonth);
				String newFilename = "REPLY_" + GagaDateUtil.getTodayDateTime() + "_" + imgInd + "." + org.springframework.util.StringUtils.getFilenameExtension(fileItemVal1[j]);
				File uniqueFile = GagaFileUtil.getUniqueFile(new File(GagaFileUtil.getConcatenationPath(planUploadPath, newFilename)));
				// Rename a file
				File path = new File(planUploadPath);
				if (!path.exists()) {
					path.mkdir();
				}
				newFile.renameTo(uniqueFile);
				filePlan.setOrgFileNm("/reply/" + yearMonth + "/" + newFilename);
				filePlan.setSysFileNm("/reply/" + yearMonth + "/" + newFilename);
				planningDao.saveEntryReplyAttach(filePlan);
				ind++;
			}
		}
	}

	/**
	 * 기획전/이벤트 댓글 카운트
	 *
	 * @param Plan
	 * @return int
	 * @author sowon
	 * @date 2021. 4. 13
	 */
	public int getEntryReplyCount(Plan plan) {
		return planningDao.getEntryReplyCount(plan);
	}

	/**
	 * 기획전/이벤트 댓글, 이미지 삭제
	 *
	 * @param Plan
	 * @return 
	 * @author sowon
	 * @date 2021. 4. 13
	 */
	@Transactional("shopTxnManager")
	public void deleteEntryReply(Plan plan) {
		planningDao.deleteEntryReply(plan);
		planningDao.deleteEntryReplyAttach(plan);
	}

	/**
	 * 기획전/이벤트 댓글 이미지 리스트
	 *
	 * @param Plan
	 * @return Collection<Plan>
	 * @author sowon
	 * @date 2021. 4. 8
	 */
	public Collection<Plan> getEntryReplyAttachList(Plan plan) {
		return planningDao.getEntryReplyAttachList(plan);
	}

	/**
	 * 총알배송 planSq 
	 *
	 * @param 
	 * @return
	 * @author sowon
	 * @date 2021. 5. 10
	 */
	public Integer getShotPlanSq(Plan plan) {
		return planningDao.getShotPlanSq(plan);
	}

	/**
	 * 기획전 컨텐츠 정보 
	 *
	 * @param 기획전 번호
	 * @return
	 * @author sowon
	 * @date 2021. 6. 3
	 */
	public Collection<Plan> getPlanContentInfo(Plan plan) {
		return planningDao.getPlanContentInfo(plan);
	}

	/**
	* 총알배송 브랜드 리스트 
	*
	* @param 
	* @return
	* @author sowon
	* @date 2021. 6. 29
	*/
	public Collection<Plan> getShotBrandList() {
		return planningDao.getShotBrandList();
	}

	/**
	 * 총알배송 브랜드 상품 리스트 
	 *
	 * @param 
	 * @return
	 * @author sowon
	 * @date 2021. 6. 29
	 */
	public Collection<Plan> getShotDeliveryGoodsList(Plan plan) {
		return planningDao.getShotDeliveryGoodsList(plan);
	}

}
