package com.style24.front.biz.service;

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

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.gagaframework.web.util.GagaDateUtil;
import com.gagaframework.web.util.GagaFileUtil;
import com.style24.core.biz.dao.TscPointDao;
import com.style24.core.biz.service.TscEnvsetService;
import com.style24.core.support.env.TscConstants;
import com.style24.front.biz.dao.TsfReviewDao;
import com.style24.front.support.security.session.TsfSession;
import com.style24.persistence.domain.Goods;
import com.style24.persistence.domain.Point;
import com.style24.persistence.domain.Review;
import com.style24.persistence.domain.ReviewAttach;
import com.vdurmont.emoji.EmojiParser;

import lombok.extern.slf4j.Slf4j;

/**
 * 상품평 Service
 *
 * @author gagamel
 * @since 2020. 12. 29
 */
@Service
@Slf4j
public class TsfReviewService {

	@Autowired
	private TsfReviewDao reviewDao;
	
	@Autowired
	private TscPointDao pointDao;
	
	
	@Autowired
	private Environment env;
	
	@Autowired
	private TscEnvsetService envsetService;

	/**
	 * 상품 리뷰 목록 건수
	 * @param review
	 * @return 
	 * @author eskim
	 * @since 2021. 3. 16
	 */
	public int  getReviewTotalCount(Review review) {
		return reviewDao.getReviewTotalCount(review);
	}
	
	/**
	 * 상품 리뷰 목록
	 * @param review
	 * @return 
	 * @author eskim
	 * @since 2021. 3. 15
	 */
	public Collection<Review> getReviewList(Review review) {
		Collection<Review> reviewList = reviewDao.getReviewList(review);

		// 첨부파일
		for(Review loopReview : reviewList) {
			loopReview.setReviewAttachList(reviewDao.getReviewAttachList(loopReview));
			loopReview.setGoodsOptionList(reviewDao.getReviewGoodsOptionList(loopReview));

			// 이모티콘 제거
			loopReview.setReviewContent(EmojiParser.removeAllEmojis(loopReview.getReviewContent()));
		}

		return reviewList;
	}
	
	/**
	 * 상품평 옵션 목록
	 * @param review
	 * @return 
	 * @author eskim
	 * @since 2021. 3. 19
	 */
	public Collection<Goods> getReviewOptionList(Goods goods) {
		Collection<Goods> result = new ArrayList<Goods>();
		if ("Y".equals(goods.getSelfGoodsYn())) {
			result = reviewDao.getReviewOption2List(goods.getGoodsCd());
		}else {
			result = reviewDao.getReviewOption1List(goods.getGoodsCd());
		}
		 return result;
	}
	
	/**
	 * 마이페이지 작성가능한 리뷰 건수
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 25
	 */
	public int getCompleteReviewCount(Review review) {
		return reviewDao.getCompleteReviewCount(review);
	}
	
	/**
	 * 마이페이지 작성가능한 리뷰 목록
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 25
	 */
	public Collection<Review> getCompleteReviewList(Review review){
		Collection<Review> reviewList = new ArrayList<>();
		
		for (Review tmpReview : reviewDao.getCompleteReviewList(review)) {
			// 세트상품 옵션별 배열로 담기
			if (tmpReview.getItemNm().contains("!@!")) {
				tmpReview.setItemNmArr(tmpReview.getItemNm().split("!@!"));
				tmpReview.setColorNmArr(tmpReview.getColorNm().split(","));
				tmpReview.setOptCd1Arr(tmpReview.getOptCd1().split(","));
				tmpReview.setOptCd2Arr(tmpReview.getOptCd2().split(","));
			} else {
				String[] arr = {tmpReview.getItemNm()}, arr2 = {tmpReview.getColorNm()}, arr3 = {tmpReview.getOptCd1()}, arr4 = {tmpReview.getOptCd2()};
				tmpReview.setItemNmArr(arr);
				tmpReview.setColorNmArr(arr2);
				tmpReview.setOptCd1Arr(arr3);
				tmpReview.setOptCd2Arr(arr4);
			}
			reviewList.add(tmpReview);
		}
		
		return reviewList;
	}
	
	/**
	 * 마이페이지 리뷰작성 상품 데이타
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 25
	 */
	public Review getReviewGoodsInfo(Review review){
		Review tmpReview = reviewDao.getReviewGoodsInfo(review);
		// 세트상품 옵션별 배열로 담기
		if (tmpReview.getItemNm().contains("!@!")) {
			tmpReview.setItemNmArr(tmpReview.getItemNm().split("!@!"));
			tmpReview.setColorNmArr(tmpReview.getColorNm().split(","));
			tmpReview.setOptCd1Arr(tmpReview.getOptCd1().split(","));
			tmpReview.setOptCd2Arr(tmpReview.getOptCd2().split(","));
		} else {
			String[] arr = {tmpReview.getItemNm()}, arr2 = {tmpReview.getColorNm()}, arr3 = {tmpReview.getOptCd1()}, arr4 = {tmpReview.getOptCd2()};
			tmpReview.setItemNmArr(arr);
			tmpReview.setColorNmArr(arr2);
			tmpReview.setOptCd1Arr(arr3);
			tmpReview.setOptCd2Arr(arr4);
		}
		return tmpReview;
	}
	
	/**
	 * 마이페이지 리뷰 등록
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 25
	 */
	@Transactional("shopTxnManager")
	public String saveMypageReview(Review review) {
		
		String resultStr = "SUCESS";
		
		review.setDispYn("Y");
		review.setDelYn("N");
		review.setConfirmYn("Y");
		review.setRegNo(TsfSession.getInfo().getCustNo());
		review.setUpdNo(TsfSession.getInfo().getCustNo());
		
		if (review.getKufKeyArr() == null && review.getOrgFileNmArr() == null) {
			review.setPntGiveStat("G043_30");
			review.setReviewGb("R");
		}else if(review.getKufKeyArr() == null && review.getOrgFileNmArr() != null) {
			review.setPntGiveStat("G043_30");
			review.setReviewGb("P");
		}else {
			review.setPntGiveStat("G043_10");
			review.setReviewGb("P");
		}
		
		reviewDao.saveMypageReview(review);
		
		//이미지등록
		if(review.getOrgFileNmArr() != null) {
			review.setConfirmYn("Y");
			ReviewAttach fileReview = new ReviewAttach();
			fileReview.setRegNo(TsfSession.getInfo().getCustNo());
			fileReview.setUpdNo(TsfSession.getInfo().getCustNo());
			fileReview.setReviewSq(review.getReviewSq());
			fileReview.setFileGb("I");
			fileReview.setDelYn("N");
			//파일아이템 등록
			String[] fileItemVal1 = review.getOrgFileNmArr();
			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, "/review");
				File newFile = new File(GagaFileUtil.getConcatenationPath(planUploadPath, fileItemVal1[j]));
				planUploadPath = GagaFileUtil.getConcatenationPath(planUploadPath, yearMonth);
				String newFilename = "REVIEW_" + 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);
				fileReview.setOrgFileNm("/review/" + yearMonth + "/" + newFilename);
				fileReview.setSysFileNm("/review/" + yearMonth + "/" + newFilename);
				reviewDao.saveReviewAttach(fileReview);
				ind++;
			}
		}
		
		if(review.getKufKeyArr() != null) {
			review.setConfirmYn("N");
			ReviewAttach fileReview = new ReviewAttach();
			fileReview.setRegNo(TsfSession.getInfo().getCustNo());
			fileReview.setUpdNo(TsfSession.getInfo().getCustNo());
			fileReview.setReviewSq(review.getReviewSq());
			fileReview.setFileGb("M");
			fileReview.setDelYn("N");
			String[] fileItemVal1 = review.getKufKeyArr();
			for (int j = 0; j < fileItemVal1.length; j++) {
				fileReview.setKufKey(fileItemVal1[j]);
				reviewDao.saveReviewAttach(fileReview);
			}
		}
		
		// 2021.08.11 
		// @ 1달에 10번만 포인트 지급
		int monthCount = reviewDao.getReviewPointGiveMonthCount(review);
		if (monthCount < 10) {
			
			// @ 한가지상품을 여러번 주문을 했어도 포인트 지급은 한번으로 수정
			int goodsCount = reviewDao.getReviewPointGiveCount(review);
			if (goodsCount < 1) {
				int textReviewPnt = envsetService.getTextReviewPoint(TscConstants.Site.STYLE24.value());
				int photoReviewPnt = envsetService.getPhotoReviewPoint(TscConstants.Site.STYLE24.value());
				
				Point point = new Point();
				point.setCustNo(TsfSession.getInfo().getCustNo());
				point.setOccurGb(TscConstants.PointOccurGb.REVIEW_POINT.value());
				point.setOccurDtlDesc("상품평포인트 지급");
				point.setPntUploadStat(TscConstants.PntUploadStat.APPLY_COMPLETE.value());
				point.setOrdNo(review.getOrdNo());
				point.setOrdDtlNo(review.getOrdDtlNo());
				
				if (review.getKufKeyArr() == null && review.getOrgFileNmArr() == null) {
					// 상품평만 적었을 경우
					point.setGvPntAmt(textReviewPnt);
					point.setRmPntAmt(textReviewPnt);
					reviewDao.createReviewPoint(point);
					point.setPntAmt(textReviewPnt);
					point.setReviewSq(review.getReviewSq());
					reviewDao.createReviewPointHst(point);
				} else if(review.getKufKeyArr() == null && review.getOrgFileNmArr() != null) {
					// 상품평 + 사진
					point.setCustNo(TsfSession.getInfo().getCustNo());
					point.setGvPntAmt(photoReviewPnt);
					point.setRmPntAmt(photoReviewPnt);
					reviewDao.createReviewPoint(point);
					point.setPntAmt(photoReviewPnt);
					point.setReviewSq(review.getReviewSq());
					reviewDao.createReviewPointHst(point);
				}
				
				reviewDao.updateMypageReviewConfimYn(review);
			} else {
				resultStr = "FAIL";
			}
		} else {
			resultStr = "FAIL";
		}
		
		return resultStr;
	}
		
	/**
	 * 상품 리뷰 목록
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 5. 18
	 */
	public Collection<Review> getMypageReviewList(Review review) {
		Collection<Review> reviewList = reviewDao.getReviewList(review);
		
		// 첨부파일
		for(Review loopReview : reviewList) {
			/* loopReview.setRvAtcSq(review.getRvAtcSq()); */
			loopReview.setReviewAttachList(reviewDao.getReviewAttachList(loopReview));
			loopReview.setGoodsOptionList(reviewDao.getReviewGoodsOptionList(loopReview));
		}
		//log.info("getReviewList {}", reviewList);
		
		return reviewList;
	}
	
	
	/**
	 * 마이페이지 리뷰 업데이트
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 25
	 */
	@Transactional("shopTxnManager")
	public void updateMypageReview(Review review) {
		review.setRegNo(TsfSession.getInfo().getCustNo());
		review.setUpdNo(TsfSession.getInfo().getCustNo());		
		//review.setConfirmYn("Y");
		review.setReviewGb("R");
		reviewDao.updateMypageReview(review);
		reviewDao.reviewAttachDelete(review);
		
		//이미지등록
		if(!StringUtils.isAllEmpty(review.getOrgFileNmArr())) {
			//review.setConfirmYn("Y");
			review.setReviewGb("P");
			ReviewAttach fileReview = new ReviewAttach();
			fileReview.setRegNo(TsfSession.getInfo().getCustNo());
			fileReview.setUpdNo(TsfSession.getInfo().getCustNo());
			fileReview.setReviewSq(review.getReviewSq());
			fileReview.setFileGb("I");
			fileReview.setDelYn("N");
			//파일아이템 등록
			String[] fileItemVal1 = review.getOrgFileNmArr();
			int ind = 1;
			for (int j = 0; j < fileItemVal1.length; j++) {
				String imgInd = String.valueOf(ind);
				if (ind < 10) {
					imgInd = "0" + imgInd;
				}
				if (!fileItemVal1[j].contains("REVIEW_")) {
					String planUploadPath = env.getProperty("upload.default.target.path");
					String yearMonth = GagaDateUtil.getToday().substring(0, 6);
					planUploadPath = GagaFileUtil.getConcatenationPath(planUploadPath, "/review");
					File newFile = new File(GagaFileUtil.getConcatenationPath(planUploadPath, fileItemVal1[j]));
					planUploadPath = GagaFileUtil.getConcatenationPath(planUploadPath, yearMonth);
					String newFilename = "REVIEW_" + 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);
					fileReview.setOrgFileNm("/review/" + yearMonth + "/" + newFilename);
					fileReview.setSysFileNm("/review/" + yearMonth + "/" + newFilename);
					reviewDao.saveReviewAttach(fileReview);
				}else {
					fileReview.setOrgFileNm(fileItemVal1[j]);
					fileReview.setSysFileNm(fileItemVal1[j]);
					reviewDao.saveReviewAttach(fileReview);
				}
				
				ind++;
			}
		}
		
		if(!StringUtils.isAllEmpty(review.getKufKeyArr())) {
			//review.setConfirmYn("Y");
			ReviewAttach fileReview = new ReviewAttach();
			fileReview.setRegNo(TsfSession.getInfo().getCustNo());
			fileReview.setUpdNo(TsfSession.getInfo().getCustNo());
			fileReview.setReviewSq(review.getReviewSq());
			fileReview.setFileGb("M");
			fileReview.setDelYn("N");
			String[] fileItemVal1 = review.getKufKeyArr();
			String[] fileItemVal2 = review.getKmcKeyArr();
			for (int j = 0; j < fileItemVal1.length; j++) {
				fileReview.setKufKey(fileItemVal1[j]);
				fileReview.setKmcKey(fileItemVal2[j]);
				reviewDao.saveReviewAttach(fileReview);
			}
			
		}
		//reviewDao.updateMypageReviewConfimYn(review);
	}
	
	/**
	 * 마이페이지 작성한 리뷰 건수
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 26
	 */
	public int getAlreadyReviewCount(Review review) {
		return reviewDao.getAlreadyReviewCount(review);
	}
	
	/**
	 * 마이페이지 작성한 리뷰 목록
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 26
	 */
	public Collection<Review> getAlreadyReviewList(Review review){
		Collection<Review> reviewList = new ArrayList<>();
		
		for (Review tmpReview : reviewDao.getAlreadyReviewList(review)) {
			// 세트상품 옵션별 배열로 담기
			if (tmpReview.getItemNm().contains("!@!")) {
				tmpReview.setItemNmArr(tmpReview.getItemNm().split("!@!"));
				tmpReview.setColorNmArr(tmpReview.getColorNm().split(","));
				tmpReview.setOptCd1Arr(tmpReview.getOptCd1().split(","));
				tmpReview.setOptCd2Arr(tmpReview.getOptCd2().split(","));
			} else {
				String[] arr = {tmpReview.getItemNm()}, arr2 = {tmpReview.getColorNm()}, arr3 = {tmpReview.getOptCd1()}, arr4 = {tmpReview.getOptCd2()};
				tmpReview.setItemNmArr(arr);
				tmpReview.setColorNmArr(arr2);
				tmpReview.setOptCd1Arr(arr3);
				tmpReview.setOptCd2Arr(arr4);
			}
			reviewList.add(tmpReview);
		}
		
		return reviewList;
	}
	
	/**
	 * 마이페이지 작성한 리뷰 이미지 목록
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 26
	 */
	public Collection<Review> getReviewAttach(Review review){
		return reviewDao.getReviewAttach(review);
	}
	
	/**
	 * 마이페이지 어드민이 댓글 단 리뷰 건수
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 26
	 */
	public Review getAdminConfirmCount(Review review) {
		return reviewDao.getAdminConfirmCount(review);
	}
	
	
	/**
	 * 마이페이지 댓글 삭제
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 26
	 */
	@Transactional("shopTxnManager")
	public void reviewDelete(Review review) {
		review.setCustNo(TsfSession.getInfo().getCustNo());
		reviewDao.reviewDelete(review);
		//관련 파일 삭제 처리
		reviewAttachDelete(review);
	}
	
	/**
	 * 마이페이지 댓글 관련 첨부파일 삭제
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 26
	 */
	@Transactional("shopTxnManager")
	public void reviewAttachDelete(Review review) {
		reviewDao.reviewAttachDelete(review);
	}
	
	/**
	 * 마이페이지 댓글 삭제건이 있는지 확인
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 3. 28
	 */
	public Review reviewDeleteConfirm(Review review) {
		return reviewDao.reviewDeleteConfirm(review);
	}
	
	/**
	 * 마이페이지 어드민댓글 확인
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 4. 15
	 */
	public void reviewCustomerConfirm(Review review) {
		review.setCustNo(TsfSession.getInfo().getCustNo());
		reviewDao.reviewCustomerConfirm(review);
	}
	
	/**
	 * 리뷰 포인트 지급 확인
	 * @param review
	 * @return 
	 * @author sowon
	 * @since 2021. 4. 28
	 */
	
	public int getReviewPointGiveCount(Review review) {
		return reviewDao.getReviewPointGiveCount(review);
	}
	
	/**
	 * 상품평 첨부파일 목록
	 * @param review
	 * @return 
	 * @author eskim
	 * @since 2021. 3. 15
	 */
	public Collection<ReviewAttach> getReviewAttachList(Review review){
		return reviewDao.getReviewAttachList(review);
	}
	
	
}
