package com.cku.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cku.core.BaseDAOMapper;
import com.cku.core.BaseService;
import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.dao.CkuDogMapper;
import com.cku.dao.CkuShowChildMapper;
import com.cku.dao.ShowApplyDiscountMapper;
import com.cku.model.CkuDog;
import com.cku.model.CkuShowsBaoMing;
import com.cku.model.ShowApplyDiscount;
import com.cku.model.ShowChild;

@Service("ShowApplyDiscountService")
public class ShowApplyDiscountServiceImpl extends BaseService<ShowApplyDiscount> {

	@Autowired
	public ShowApplyDiscountMapper showApplyDiscountMapper;

	@Override
	protected BaseDAOMapper<ShowApplyDiscount> getDAO() {
		return this.showApplyDiscountMapper;
	}

	@Autowired
	public CkuShowChildMapper ckuShowChildMapper;

	@Autowired
	public CkuDogMapper ckuDogMapper;

	/**
	 * 主赛事下所有参与优惠的子赛事
	 * @param mainShowId
	 * @return
	 */
	public Set<String> getDiscountChildShowsId(String mainShowId) {
		List<ShowChild> childShowsList = ckuShowChildMapper.getShowChildByMainId(mainShowId);
		Set<String> set = childShowsList.stream().filter(a -> Objects.equals("0", a.getIsDiscount()))
				.map(a -> a.getId()).collect(Collectors.toSet());// 所有参与优惠的子赛事
		return set;

	}
	
	/**
	 * 找到主赛事ID
	 * @param childShowsId
	 * @return
	 * @throws Exception
	 */
	public String getMainShowId(String childShowsId) throws Exception {
		ShowChild childShows = ckuShowChildMapper.get(childShowsId);
		if (childShows == null) {
			throw new ZAException(ZAErrorCode.ZA_ERC_UNKNOWN, "所提交的赛事ID没有查到！");
		}
		return childShows.getMainShowId();
	}
	
	/**
	 * 是否满足进入满减周期的条件
	 * @param pedigreeCertified
	 * @param ageGroups
	 * @return
	 * @throws Exception
	 */
	public boolean isCycleSign(String pedigreeCertified, String ageGroups) throws Exception {
		if (StringUtils.isBlank(ageGroups)) {
			throw new ZAException(ZAErrorCode.ZA_ERC_UNKNOWN, "报名子赛事信息为空");
		}
		Map<String, String> showIdAgeGroups = new HashMap<String, String>();// 处理请求参数
		for (String ageGroup : ageGroups.split(",")) {
			showIdAgeGroups.put(ageGroup.split("=")[0], ageGroup.split("=")[1]);
		}
		String showId = showIdAgeGroups.keySet().iterator().next();// 子赛事ID
		String mainShowId = getMainShowId(showId);
		Set<String> set = getDiscountChildShowsId(mainShowId);// 所有参与优惠的子赛事
		if (set.size() == 0) {// 没有设置满减优惠
			return false;
		}
		if (!showIdAgeGroups.keySet().containsAll(set)) {// 每只犬需报名满所有参与优惠的场次
			return false;
		}
		for (String a : set) {// 参赛犬只报名组别，特幼公、特幼母、幼小公、幼小母不参与优惠；
			if (Integer.valueOf(showIdAgeGroups.get(a)) < 5) {
				return false;
			}
		}
		CkuDog dog = getDog(pedigreeCertified);
		Integer countDogOwnerChange = showApplyDiscountMapper
				.countDogOwnerChangeByReviewTime(new SimpleDateFormat("yyyy-MM-dd").parse("2022-08-15"), dog.getId());
		if (countDogOwnerChange > 0) {// 参赛犬只8月15日后办理过犬主变更的不参与优惠（判断条件：时间用审核通过时间，审核通过计算为办理完成）
			return false;
		}

		return true;//提前全部通过 则进入周期计数
	}
	
	private CkuDog getDog(String pedigreeCertified){
		return ckuDogMapper.getByPedigreeCertifiedCode(pedigreeCertified);
	}
	
	/**
	 * 此次报名能不能进行满减
	 * @param pedigreeCertified
	 * @param ageGroups
	 * @return
	 * @throws Exception
	 */
	public boolean isDiscount(String pedigreeCertified, String ageGroups) throws Exception {
		if(!isCycleSign(pedigreeCertified, ageGroups)) {//不满足进入周期的直接返回 
			return false;
		}
		String showId = ageGroups.split("=")[0];// 子赛事ID
		String mainShowId = getMainShowId(showId);
		CkuDog dog = getDog(pedigreeCertified);
		// 犬只需在同一犬主名下,已付款的报名才会计入该表
		String lastCycleSign = showApplyDiscountMapper.getLastCycleSign(mainShowId, dog.getMemberNum());// 当前最后一个周期标志
		int count = Objects.isNull(lastCycleSign) ? 0 : showApplyDiscountMapper.countByCycleSign(lastCycleSign);
		// 情况一：此周期有八条记录，周期结束，进入新周期，当前报名不免费
		// 情况二：此周期符合规定的报名满3免1，满6免1，满7免1，计算符合规则的报名个数即可
		// 增加最大优惠只数限制 6最多1 7最多2 8最多3
    	int countDiscount = showApplyDiscountMapper.countDiscountByCycleSign(lastCycleSign);
    	if((count==3 && countDiscount==0) 
 	    		|| (count==6 && countDiscount <= 1) 
 	    		|| (count==7 && countDiscount <= 2) ) {
			return true;
		}
		return false;

	}
	
	/**
	 * 获得下一条记录的周期标志
	 * @param mainShowId
	 * @param discountSign
	 * @return
	 */
	private CycleSignInfo getNextCycleSign(String mainShowId, String discountSign) {
		String lastCycleSign = showApplyDiscountMapper.getLastCycleSign(mainShowId, discountSign);// 当前最后一个周期标志
		if(StringUtils.isBlank(lastCycleSign)) {
			return  new CycleSignInfo(1, UUID.randomUUID().toString().replaceAll("-", ""));
		}
		int count = showApplyDiscountMapper.countByCycleSign(lastCycleSign);//最后一个周期有几条记录
		return new CycleSignInfo(count < 8 ?count + 1:1,count<8?lastCycleSign:UUID.randomUUID().toString().replaceAll("-", ""));
		
	}
	
	private class CycleSignInfo {
		
		public CycleSignInfo(int cycleSignNo,String cycleSign) {
			this.cycleSign = cycleSign;
			this.cycleSignNo = cycleSignNo;
		}
		
		private int cycleSignNo;// 周期序号
		
		private String cycleSign;		// 周期标志

		public int getCycleSignNo() {
			return cycleSignNo;
		}

		public void setCycleSignNo(int cycleSignNo) {
			this.cycleSignNo = cycleSignNo;
		}

		public String getCycleSign() {
			return cycleSign;
		}

		public void setCycleSign(String cycleSign) {
			this.cycleSign = cycleSign;
		}
		
		
	}
	

	
	public int saveNewRecord(String userId,String isDiscount, CkuShowsBaoMing ckuShowsBaoMing){
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		ShowApplyDiscount ShowApplyDiscount = new ShowApplyDiscount();
		ShowApplyDiscount.setId(uuid);
		ShowApplyDiscount.setCreateDate(new Date());
		ShowApplyDiscount.setUpdateDate(new Date());
		ShowApplyDiscount.setCreateBy(userId);
		ShowApplyDiscount.setUpdateBy(userId);
		ShowApplyDiscount.setShowApplyId(ckuShowsBaoMing.getId());
		ShowApplyDiscount.setShowMainId(ckuShowsBaoMing.getMainShowId());
		ShowApplyDiscount.setRunningNumber(ckuShowsBaoMing.getRunningNumber());
		ShowApplyDiscount.setDiscountSign(ckuShowsBaoMing.getUserNo());
		ShowApplyDiscount.setIsDiscount(isDiscount);
		CycleSignInfo info = getNextCycleSign(ckuShowsBaoMing.getMainShowId(), ckuShowsBaoMing.getUserNo());
		ShowApplyDiscount.setCycleSign(info.getCycleSign());// 周期标志
		ShowApplyDiscount.setCycleSignNo(info.getCycleSignNo());
		ShowApplyDiscount.setDelFlag("0");
		return showApplyDiscountMapper.insert(ShowApplyDiscount);

	}
	
	/**
	 * 当前犬主名下犬只有未缴费的赛事订单
	 * @param pedigreeCertified
	 * @return
	 * @throws Exception
	 */
	public boolean isUnpaidShowApply(String pedigreeCertified) throws Exception {
		CkuDog dog = getDog( pedigreeCertified);
		int count =  showApplyDiscountMapper.countUnpaidShowAppByDogOwnerMemberCode(dog.getMemberNum());
		return count>0;
		
	}
	
}
