package com.cku.service;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
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.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.cab.dao.CabMymessageMapper;
import com.cab.model.CabMymessage;
import com.cab.service.UtilServiceImpl;
import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.dao.CkuDogClassMapper;
import com.cku.dao.CkuDogMapper;
import com.cku.dao.CkuDogTypeShowMapper;
import com.cku.dao.CkuDvUserMapper;
import com.cku.dao.CkuMatchSignMapper;
import com.cku.dao.CkuMemberBalanMapper;
import com.cku.dao.CkuShowChildMapper;
import com.cku.dao.CkuShowsBaoMingMapper;
import com.cku.dao.CkuUserMapper;
import com.cku.dao.CkuUserPayListMapper;
import com.cku.dao.CkuUserPayTypeMapper;
import com.cku.dao.EventRelatedMapper;
import com.cku.dao.FrequentlyUsedUsersMapper;
import com.cku.dao.SPCartsMapper;
import com.cku.dao.SPOrderInfoMapper;
import com.cku.dao.SaFinanceSubjectMappingMapper;
import com.cku.dao.ShowApplyDiscountMapper;
import com.cku.jpush.PushUtils;
import com.cku.model.CkuDog;
import com.cku.model.CkuDogClass;
import com.cku.model.CkuDogTypeShow;
import com.cku.model.CkuDvUserModel;
import com.cku.model.CkuMatchSign;
import com.cku.model.CkuMemberBalance;
import com.cku.model.CkuOrder;
import com.cku.model.CkuShowsBaoMing;
import com.cku.model.CkuUser;
import com.cku.model.CkuUserPayList;
import com.cku.model.CkuUserPayType;
import com.cku.model.EventRelatedModel;
import com.cku.model.SPCarts;
import com.cku.model.SPOrderInfo;
import com.cku.model.SaFinanceSubjectMapping;
import com.cku.model.ShowChild;
import com.cku.model.ShowCouponInfoVO;
import com.cku.model.ShowMain;
import com.cku.sms.ZtSmsUtil;
import com.cku.util.DateUtils;
import com.cku.util.Debugger;
import com.cku.util.HttpClientUtil;
import com.cku.util.HttpResult;
import com.cku.util.SysConfig;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.sys.model.MultiUserProfile;

@Service("ckuDogEnteredService")
public class CkuDogEnteredServiceImpl {

	private static Logger logger = LoggerFactory.getLogger(CkuDogEnteredServiceImpl.class);
	@Autowired
	public EventRelatedMapper eventRelatedMapper;

	@Autowired
	public CkuDogMapper ckuDogMapper;

	@Autowired
	public CkuShowsBaoMingMapper ckuShowsBaoMingMapper;

	@Autowired
	public CkuShowChildMapper ckuShowChildMapper;

	@Autowired
	public SPOrderInfoMapper sPOrderInfoMapper;

	@Autowired
	public SPCartsMapper sPCartsMapper;

	@Autowired
	public CkuDvUserMapper ckuDvUserMapper;

	@Autowired
	public CkuMemberBalanMapper ckuMemberBalanMapper;

	@Autowired
	public CkuUserPayListMapper ckuUserPayListMapper;

	@Autowired
	public CkuUserMapper ckuUserMapper;

	@Autowired
	public FrequentlyUsedUsersMapper frequentlyUsedUsersMapper;

	@Autowired
	public PublicService publicService;

	@Autowired
	public CkuMatchSignMapper ckuMatchSignMapper;

	@Autowired
	public UtilServiceImpl utilService;
	@Autowired
	public CabMymessageMapper cabMymessageMapper;
	@Autowired
	public CkuUserPayTypeMapper ckuUserPayTypeMapper;
	@Autowired
	public CkuDogClassMapper ckuDogClassMapper;
	@Autowired
	public CkuDogTypeShowMapper ckuDogTypeShowMapper;
	@Autowired
	public SaFinanceSubjectMappingMapper saFinanceSubjectMappingMapper;
	@Autowired
	public ShowApplyDiscountMapper showApplyDiscountMapper;
	@Autowired
	public ShowApplyDiscountServiceImpl showApplyDiscountService;
	
	

	// 该规则到2019-04-01
	private static final ImmutableMap<String, Double> SHOW_ID_PRICE_MAP = ImmutableMap.<String, Double>builder()
			.put("e5c9d88210db411a8fcc5d1a20be0058", new Double(420))
			.put("b2f9ce081cdb48c181caa259f0d75e51", new Double(350))
			.put("37383f374eea492faba0fea1943736ff", new Double(420))
			.put("de1e0e55e32f4ce3a436779b3a44c929", new Double(350))
			.put("cdf441091ba24de6ab55123aec0cc748", new Double(540))
			.put("a4faf6ecffba413d9eb69ce864c00c21", new Double(540)).build();
	private static final ImmutableList<String> DISCOUNTS_AGE_GROUPS = ImmutableList.<String>builder().add("1").add("2")
			.add("3").add("4").build();
	public static Long DISCOUNTS_END_DATE_TIME_MILLIS = null;
	
	private static final String DOG_SHOW_COUPON = "sys_coupon@show";
	
	private static final String PAYMENT_CHARGING_ITEM_BJZB = "犬只参赛费（北京自办）";
	
	private static final String PAYMENT_CHARGING_ITEM_DWWL = "单位往来";
	
	private static final String CAC_TYPE_CAC = "0";//赛事CAC类型(0:CAC;1CACIB)
	
	private static final String CAC_TYPE_CACIB= "1";
	
	private static final double CAC_TYPE_CAC_FEE= 40;
	
	private static final double CAC_TYPE_CACIB_FEE= 55;
	
	private static final String COUPON_BJ_SHOW_NAME = "sys_coupon@show_bj";
	
	private static final String COUPON_DWWL_SHOW_NAME = "sys_coupon@show_dwwl";
	

	@Value("${TYZYXZBMF_DATA_TIME}")
	public String TYZYXZBMF_START_DATE_TIME_MILLIS;

	static {
		try {
			String data = SysConfig.getInstance().getProperty("SJBYQJG_DATE");
			if (StringUtils.isBlank(data))
				data = "2019-04-02";
			DISCOUNTS_END_DATE_TIME_MILLIS = new SimpleDateFormat("yyyy-MM-dd").parse(data).getTime();
		} catch (ParseException e) {
			System.out.println("判断新旧业务记录格式化时间出错");
		}
	}

	private static String VIP_CHONGAIBAO = "";

	static {
		VIP_CHONGAIBAO = SysConfig.getInstance().getProperty("vipurl");
	}

	// 查询犬只代数借口
	private static final String DOG_GENERATION_URL = VIP_CHONGAIBAO + "/api/v1/open/getDogGeneration?dogCode=";
	// 该规则到2019-04-01

	/**
	 * @param phone
	 * @param name
	 * @Description：犬只赛事报名
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 上午10:01:22
	 * @throws Exception 
	 */
	@Transactional(readOnly = false)
	@SuppressWarnings("all")
	public synchronized CkuOrder dogEventEntered(MultiUserProfile userProfile, String showNum, String pedigreeNum,
			String detil, String ageGroup, String bbeFlag, String couponNum, String stickerFlag, String isOwner)
			throws Exception {
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		List<CkuDog> dogList = ckuDogMapper.getMatchCost(pedigreeNum, null);
		// 根据CKU账号id查询出CKU账号信息
		CkuDvUserModel ckuDvUserModel = ckuDvUserMapper.getckuMemberByUserId(userProfile.getCurrentClubUserId());
		List<CkuUser> list = ckuUserMapper.getUserMessage(ckuDvUserModel.getCkuId());
		Date date = new Date();
		String payPid = "";
		int max = 99;
		int min = 10;
		double bmFei = 0;
		double couponFei = 0;
		String chargingItemName = "";
		BigDecimal money = new BigDecimal(0);
		String random = String.valueOf((int) Math.floor(Math.random() * (max - min + 1) + min));
		String orderID = df.format(date) + random + "@" + ckuDvUserModel.getCkuId();
		String[] strs = showNum.split(",");
		EventRelatedModel eventRelatedModel = new EventRelatedModel();
		// 该规则到2019-04-01
		List<String> discountsChildShowIdList = Lists.newArrayList();
		if (System.currentTimeMillis() < DISCOUNTS_END_DATE_TIME_MILLIS) {//2019-04-02
			String[] array = ageGroup.split(",");
			for (String s : array) {
				String[] a = s.split("=");
				// 年龄组别在1,2,3,4里且在特定的子赛事里，优惠
				if (DISCOUNTS_AGE_GROUPS.contains(a[1]) && SHOW_ID_PRICE_MAP.containsKey(a[0])) {
					discountsChildShowIdList.add(a[0]);
				}
			}
		}

		char ageGroupFlag = '0';
		String bmFeiPrice = "150.00";
		double bmFeiPrices = 0;
		String[] showIdAgeGroup = ageGroup.split(",");
		String[] showIdAgeGroupValue;
		List<BigDecimal> canUseCouponPriceList = new ArrayList<BigDecimal>();
		
		// 本次报名是否满减优惠
		if(showApplyDiscountService.isUnpaidShowApply(pedigreeNum)) {
			throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "当前犬主名下犬只已有未缴费的犬展订单，请先处理。");
		}
		boolean isDiscount = showApplyDiscountService.isDiscount(pedigreeNum, ageGroup);
		boolean isCycleSign = showApplyDiscountService.isCycleSign(pedigreeNum, ageGroup);
		ShowChild showChild = ckuShowChildMapper.getByShowCode(strs[0]);
		Set<String> set = showApplyDiscountService.getDiscountChildShowsId(showChild.getMainShowId());// 所有参与优惠的子赛事
		
		double cacPrice = 0;
		double cacibPrice = 0;
		
	    List<ShowCouponInfoVO> canUseCouponList = Lists.newArrayList();
		
		// 该规则到2019-04-01
		for (int i = 0; i < strs.length; i++) {
			// 判断参赛组别是否是特幼组、幼小组。开始时间在2019-10-25日及以后的赛事，CAC及CACIB的特幼组、幼小组的犬只报名费变为150元。
			/*
			 * 增加逻辑： showIdAgeGroupValue[0]是赛事编号，依据该赛事编号到ckuoa数据库的show_main表中查询，得到start_time
			 */
			ageGroupFlag = '0';
			showIdAgeGroupValue = showIdAgeGroup[i].split("=");
			if (showIdAgeGroupValue != null && showIdAgeGroupValue.length > 0) {
				ShowMain showMain = ckuShowChildMapper.getShowMainById(showIdAgeGroupValue[0]);
				if (showMain.getStartTime()
						.compareTo(DateUtils.strToDateFormat(TYZYXZBMF_START_DATE_TIME_MILLIS)) >= 0) {//2019-10-25
					// UPDATE BY ZJW 2021-07-01 单独展，幼小组（6-9月龄） 收费标准调整，不在优惠为 150
					// TAPD  【ID1003980】关于更改单独展4-6月龄报名费
					if("1".equals(showMain.getShowRules()) && (showIdAgeGroupValue[1].equals("3") || showIdAgeGroupValue[1].equals("4"))) {
						//如果是单独展，幼小组不做处理
					}else if ((showIdAgeGroupValue[1].equals("1")) || (showIdAgeGroupValue[1].equals("2"))
							|| (showIdAgeGroupValue[1].equals("3")) || (showIdAgeGroupValue[1].equals("4"))) {
						ageGroupFlag = '1';
					}
				}
			}
			// 赛事金额
			BigDecimal showChildPrice = BigDecimal.ZERO;

			if (ageGroupFlag == '1') {
				bmFeiPrices = Double.parseDouble(bmFeiPrice.substring(0, bmFeiPrice.length()));
				showChildPrice = new BigDecimal(bmFeiPrices);
			}
			eventRelatedModel = eventRelatedMapper.getSpecificEventByShowNum(strs[i].trim());
			//FCI正式品种formal报名规则不变，FCI临时认可品种temp、FCI国家级认可品种country仅限报名CAC赛事，FCI不认可品种:unauth不能报名比赛
			if("unauth".equals(dogList.get(0).getBreedClass())){
				throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "FCI不认可品种不能报名犬展！");
			}else if(("temp".equals(dogList.get(0).getBreedClass())||"country".equals(dogList.get(0).getBreedClass()))
					&&!"0".equals(eventRelatedModel.getCacType())) {
				//CacType赛事CAC类型(0:CAC;1CACIB)
				throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "FCI临时认可/国家级认可品种不能报名非CAC犬展活动！");
			}
			
			if(!(isDiscount && set.contains(eventRelatedModel.getId()))) {
				if (discountsChildShowIdList.contains(eventRelatedModel.getId())) {//到2019-04-02结束
					bmFei += money.add(new BigDecimal(SHOW_ID_PRICE_MAP.get(eventRelatedModel.getId()))).doubleValue();
				} else {
					if (ageGroupFlag == '1') {
						bmFei += bmFeiPrices;
					} else {
						bmFei += money.add(eventRelatedModel.getBmFei()).doubleValue();
						showChildPrice = eventRelatedModel.getBmFei();
						// showChildPrice拆分为每次的北京自办金额、单位往来金额
						//合办新模式2025 收费项固定为北京自办、单位往来
						if ("3".equals(eventRelatedModel.getGameType())) {
							if(CAC_TYPE_CAC.equals(eventRelatedModel.getCacType())) {
								cacPrice = cacPrice + CAC_TYPE_CAC_FEE;
							}else if(CAC_TYPE_CACIB.equals(eventRelatedModel.getCacType())){
								cacibPrice = cacibPrice + CAC_TYPE_CACIB_FEE;
							}
						}
					}
				}
			}
			
			// 判断该自赛事是否能使用优惠券，如可以使用优惠券，将金额放进 自赛事金额集合
			if (showIdAgeGroupValue != null && showIdAgeGroupValue.length > 0) {
				String useCoupon = ckuShowChildMapper.getCanUseCouponByShowChildId(showIdAgeGroupValue[0]);
				if (StringUtils.isNotBlank(useCoupon) && Integer.valueOf(useCoupon) == 0
						&& showChildPrice.compareTo(BigDecimal.ZERO) > 0) {
					// 增加 犬主人组优惠券最高抵扣金额为 150
					if ("21".equals(showIdAgeGroupValue[1])) {
						canUseCouponPriceList.add(new BigDecimal(150));
						if ("3".equals(eventRelatedModel.getGameType())) {
							ShowCouponInfoVO vo = new ShowCouponInfoVO();
							vo.setAgeGroupFlag(String.valueOf(ageGroupFlag) );
							vo.setCacType(eventRelatedModel.getCacType());
							vo.setShowChildPrice(new BigDecimal(150));
							vo.setShowCode(eventRelatedModel.getShow_num());
							canUseCouponList.add(vo);
						}
					} else {
						canUseCouponPriceList.add(showChildPrice);
						if ("3".equals(eventRelatedModel.getGameType())) {
							ShowCouponInfoVO vo = new ShowCouponInfoVO();
							vo.setAgeGroupFlag(String.valueOf(ageGroupFlag) );
							vo.setCacType(eventRelatedModel.getCacType());
							vo.setShowChildPrice(showChildPrice);
							vo.setShowCode(eventRelatedModel.getShow_num());
							canUseCouponList.add(vo);
						}
					}
				}
			}

			eventRelatedModel.getGameType();// 举办类型（自办or合办）
			eventRelatedModel.getOrganizer();// 举办方
			if (eventRelatedModel.getShowSystem().equals("0") && StringUtils.isNotBlank(eventRelatedModel.getCacType())
					&& eventRelatedModel.getCacType().equals("1")) {
				int generation = getGeneration(pedigreeNum);
				if (generation < 3) {
					throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "全犬种CACIB犬展仅限3代及以上血统犬只报名");
				} else {
					if (!pedigreeNum.toUpperCase().startsWith("CKU")) {
						throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "单独展CAC犬展仅限血统证书以CKU开头的犬只报名");
					}
				}
			}
			// ID: 1006817 修改犬展报名上限
			int cnt = getCntByShowCode(strs[i]);//子赛事当前报名总数
			if(cnt >= eventRelatedModel.getChildDogNumMax()) {
				throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "慢了一步，"+eventRelatedModel.getShow_name()
													+"("+eventRelatedModel.getShow_num()+")"+"已达到犬只报名上限！");
			}
		}

		// 生成订单时校验犬只是否达到报名上限
//		Map<String, Integer> map = publicService.enrollStatus(strs[0]);
//		Integer topDog = 0;
//		if (eventRelatedModel.getTop_dog() != null && !"".equals(eventRelatedModel.getTop_dog())) {
//			topDog = new Integer(eventRelatedModel.getTop_dog());
//		} else {
//			topDog = 0;
//		}
//		Debugger.doAssert(!(map.get("enrollNumber") >= topDog), ZAErrorCode.ZA_ERC_DOG_LIMITED, "慢了一步，该场犬展已达到犬只报名上限！");
		// ---------------------
		// 生成订单时赛事报名截止时间校验
		Date now = new Date();
		Date expiryTime = eventRelatedModel.getExpiry_time();
		boolean flag = expiryTime.before(now);
		Debugger.doAssert(!flag, ZAErrorCode.ZA_ERC_ENDING, "慢了一步，该场犬展活动已结束报名！");
		String orderId = UUID.randomUUID().toString().replaceAll("-", "");
		// ---------------------
		synchronized (this) {
			// 校验犬只是否报名过此赛事
			List<CkuMatchSign> ckuMatchSign = ckuMatchSignMapper.getSignByStudbookNum(strs[0].substring(0, 7),
					pedigreeNum);
			Debugger.doAssert(!(ckuMatchSign.size() > 0), ZAErrorCode.ZA_ERC_REPEAT, "该犬只已报名此犬展！");
			// ---------------------
			String businessStr = "";
			String gameType = "";
			String organizer = "";
			String couponItemId = DOG_SHOW_COUPON;
			if ("1".equals(eventRelatedModel.getGameType())) {
				gameType = "自办";
			}
			if ("0".equals(eventRelatedModel.getGameType())) {
				gameType = "合办";
			}

			if ("1".equals(eventRelatedModel.getBusinessModelFlag())) {
				businessStr = "新";
			}
			if ("0".equals(eventRelatedModel.getBusinessModelFlag())) {
				businessStr = "";
			}

			if ("1".equals(eventRelatedModel.getOrganizer())) {
				organizer = "北京";
				couponItemId += "_bj";
			}
			if ("2".equals(eventRelatedModel.getOrganizer())) {
				organizer = "杭州";
				couponItemId += "_hz";
			}
			if ("3".equals(eventRelatedModel.getOrganizer())) {
				organizer = "长春";
				couponItemId += "_cc";
			}
			if ("4".equals(eventRelatedModel.getOrganizer())) {
				organizer = "重庆";
				couponItemId += "_cq";
			}
			if ("5".equals(eventRelatedModel.getOrganizer())) {
				organizer = "长沙";
				couponItemId += "_cs";
			}
			if ("6".equals(eventRelatedModel.getOrganizer())) {
				organizer = "郑州";
				couponItemId += "_zz";
			}
			if ("7".equals(eventRelatedModel.getOrganizer())) {
				organizer = "南方区";
				couponItemId += "_nf";
			}
			if ("8".equals(eventRelatedModel.getOrganizer())) {
				organizer = "北方区";
				couponItemId += "_bf";
			}
			
			ShowCouponInfoVO couponShow = null;
			
			// 是否使用了优惠券
			CkuUserPayType coupon = new CkuUserPayType();
			if (Integer.parseInt(couponNum) > 0) {
				// 如果APP使用了优惠券，但没有可使用优惠券的自赛事，则抛出异常
				if (CollectionUtils.isEmpty(canUseCouponPriceList)) {
					throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "该犬展不能使用优惠券");
				}
				// 修改优惠券抵扣按最高金额抵扣
				Collections.sort(canUseCouponPriceList);
				Collections.reverse(canUseCouponPriceList);
				couponFei = 0 - canUseCouponPriceList.stream().findFirst().get().doubleValue();
				//找出抵扣的哪场赛事
				for(ShowCouponInfoVO vo : canUseCouponList){
					if(vo.getShowChildPrice().compareTo(BigDecimal.valueOf(-couponFei))==0) {
						couponShow = vo;
					}
				};
				coupon = ckuUserPayTypeMapper.getPaymentCodeByShortName(couponItemId);
				/*
				 * coupon = ckuUserPayTypeMapper.getPaymentCodeByShortName(couponItemId); String
				 * price = coupon.getPrice(); if (ageFlag == '1' && notAgeFlag == '0') price =
				 * "-150.00"; Double prices = 0 - Double.parseDouble(price.substring(1,
				 * price.length())); couponFei = Integer.parseInt(couponNum) * prices;
				 */
			}
			//合办新模式2025 收费项固定为北京自办、单位往来
			String bjzbPaymentCode = null;
			//单位往来
			CkuUserPayType dwwl = ckuUserPayTypeMapper.getPaymentCode(PAYMENT_CHARGING_ITEM_DWWL);
			String dwwlPaymentCode = dwwl.getId();
			if ("3".equals(eventRelatedModel.getGameType())) {
				if(cacPrice+cacibPrice>0) {//有可能没有北京自办，比如只报了一场特幼组
					//北京自办
					CkuUserPayType bjzb = ckuUserPayTypeMapper.getPaymentCode(PAYMENT_CHARGING_ITEM_BJZB);
					bjzbPaymentCode =  bjzb.getId();
				}
				
				payPid = StringUtils.isNotBlank(bjzbPaymentCode)?  bjzbPaymentCode+","+dwwlPaymentCode:dwwlPaymentCode;//用于在show_apply中记录收费项ID
			}else if ("4".equals(eventRelatedModel.getGameType())) {
				//合办新模式（统一管理费）
				payPid = dwwlPaymentCode;//用于在show_apply中记录收费项ID
				chargingItemName = PAYMENT_CHARGING_ITEM_DWWL;
			}else {
				String paymentCode = getPaymentCode(organizer + businessStr + gameType);
				if (!"".equals(paymentCode)) {
					payPid = paymentCode;
					chargingItemName = "犬只参展费（" + organizer + businessStr + gameType + "）";
				}
			}
			
			// 对赛事编号和年龄组别进行排序
			showNum = sortShowNum(showNum);
			ageGroup = sortAgeGroup(ageGroup);
			CkuShowsBaoMing ckuShowsBaoMing =insertEntered(dogList, showNum, (bmFei + couponFei), orderID, date, ckuDvUserModel.getCkuId(),
					payPid, detil, ageGroup, list.get(0), eventRelatedModel, bbeFlag, stickerFlag, isOwner);
			String uuid = ckuShowsBaoMing.getId();
			insertSPOrderInfo(ckuDvUserModel, (bmFei + couponFei), orderID, date, orderId, userProfile.getLoginType());
			String businessOrderCode = UUID.randomUUID().toString().replaceAll("-", "");
			
			//合办新模式2025 收费项固定为北京自办、单位往来
			if ("3".equals(eventRelatedModel.getGameType())) {
				//三种拆分方式：CAC 北京自办40 单位往来 总额-40
				//CACIB 北京自办55 单位往来 总额-55
				//全犬种特幼组和幼小组参赛费、单独展特幼组 单位往来 总额

				//累加cac金额 累计cacib金额
				if(cacPrice+cacibPrice>0) {
					insertSPCarts(ckuDvUserModel, orderID, cacPrice+cacibPrice, date, bjzbPaymentCode, (uuid + "#" + pedigreeNum), PAYMENT_CHARGING_ITEM_BJZB,
								eventRelatedModel.getOrganizer(), businessOrderCode);
				}
				insertSPCarts(ckuDvUserModel, orderID, bmFei-cacibPrice-cacPrice, date, dwwlPaymentCode, (uuid + "#" + pedigreeNum), PAYMENT_CHARGING_ITEM_DWWL,
							eventRelatedModel.getOrganizer(), businessOrderCode);
			}else {
				insertSPCarts(ckuDvUserModel, orderID, bmFei, date, payPid, (uuid + "#" + pedigreeNum), chargingItemName,
						eventRelatedModel.getOrganizer(), businessOrderCode);
			}
			
			// 优惠券
			if (Integer.parseInt(couponNum) > 0) {
				//合办新模式2025 收费项为CAC赛事免费参赛卷（单位往来） sys_coupon@show_dwwl、CAC赛事免费参赛券   sys_coupon@show_bj
				CkuUserPayType couponDwwl = ckuUserPayTypeMapper.getPaymentCodeByShortName(COUPON_DWWL_SHOW_NAME);
				if ("3".equals(eventRelatedModel.getGameType())) {
					if("1".equals(couponShow.getAgeGroupFlag())) {
						insertSPCarts(ckuDvUserModel, orderID, couponFei, date, couponDwwl.getId(), (uuid + "#" + pedigreeNum),
								couponDwwl.getName(), eventRelatedModel.getOrganizer(), businessOrderCode);
					}else {
						CkuUserPayType couponBj = ckuUserPayTypeMapper.getPaymentCodeByShortName(COUPON_BJ_SHOW_NAME);
						// 赛事CAC类型(0:CAC;1CACIB)
						if("0".equals(couponShow.getCacType())) {
							insertSPCarts(ckuDvUserModel, orderID, -CAC_TYPE_CAC_FEE, date, couponBj.getId(), (uuid + "#" + pedigreeNum),
									couponBj.getName(), eventRelatedModel.getOrganizer(), businessOrderCode);
							couponFei -= -CAC_TYPE_CAC_FEE;
						}else {
							insertSPCarts(ckuDvUserModel, orderID, -CAC_TYPE_CACIB_FEE, date, couponBj.getId(), (uuid + "#" + pedigreeNum),
									couponBj.getName(), eventRelatedModel.getOrganizer(), businessOrderCode);
							couponFei -= -CAC_TYPE_CACIB_FEE;
						}
						insertSPCarts(ckuDvUserModel, orderID, couponFei, date, couponDwwl.getId(), (uuid + "#" + pedigreeNum),
								couponDwwl.getName(), eventRelatedModel.getOrganizer(), businessOrderCode);
						
					}
				}else if ("4".equals(eventRelatedModel.getGameType())) {
					insertSPCarts(ckuDvUserModel, orderID, couponFei, date, couponDwwl.getId(), (uuid + "#" + pedigreeNum),
							couponDwwl.getName(), eventRelatedModel.getOrganizer(), businessOrderCode);
				}else {
					insertSPCarts(ckuDvUserModel, orderID, couponFei, date, coupon.getId(), (uuid + "#" + pedigreeNum),
							coupon.getName(), eventRelatedModel.getOrganizer(), businessOrderCode);
				}
				ckuUserPayTypeMapper.updateCouponBy(pedigreeNum, ckuDvUserModel.getCkuId(), new Date(),
						(uuid + "#" + pedigreeNum));
			}
			if(isCycleSign) {
				//记录满减优惠
				showApplyDiscountService.saveNewRecord( ckuDvUserModel.getCkuId(),isDiscount?"0":"1",ckuShowsBaoMing);//0减免 1不减免
			}
		}
		// 更新犬只代数
		String generation = getGeneration(pedigreeNum) + "";
		ckuDogMapper.updateDogGeneration(generation, pedigreeNum);

		String[] locations = eventRelatedModel.getShow_num().split("-");
		String notification = "尊敬的会员，您于" + new SimpleDateFormat("yyyy年MM月dd日  HH时mm分").format(new Date()) + ""
				+ "报名CKU犬展-" + (locations.length > 1 ? locations[1] + "-" : "") + eventRelatedModel.getMain_game_name()
				+ "，参展犬只证书号为" + pedigreeNum + "。本次参展费" + (bmFei + couponFei) + "元整，" + "请您务必于当日24时前完成犬展缴费，以免耽误正常参展。";
		// ZtSmsCode.sendNoteYX(notification, user.getPhone());
		ZtSmsUtil.sendNote(notification, userProfile.getMobile());
		// 手机推送
		PushUtils.push_alias_notification(PushUtils.getShowId(userProfile.getUserId().toString()), notification);
		// 入库，我的消息
		System.out.println("============================================================" + cabMymessageMapper
				+ "=============================================================================");
		CabMymessage cabMymessage = new CabMymessage();
		cabMymessage.setUserId(userProfile.getUserId());
		cabMymessage.setIsread(0);
		cabMymessage.setType(1);
		cabMymessage.setTitle("【宠爱王国】业务办理");
		cabMymessage.setContent(notification.replace("拒收请回复R", ""));
		cabMymessage.setCreateTime(new Date());
		int i = cabMymessageMapper.insertSelective(cabMymessage);
		System.out.println("============================================================" + i
				+ "=============================================================================");

		CkuOrder ckuOrder = new CkuOrder();
		ckuOrder.setOrderID(orderID);
		ckuOrder.setTypeId(payPid);
		ckuOrder.setId(orderId);
		return ckuOrder;
	}

	private int getGeneration(String pedigreeNum) {
		HttpResult hr = null;
		try {
			hr = HttpClientUtil.get(null, DOG_GENERATION_URL + pedigreeNum, null);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!"".equals(hr.getResponseBody()) && hr.getResponseBody() != null) {
			JSONObject obj = JSONObject.parseObject(hr.getResponseBody());
			if (obj != null && !"".equals(obj)) {
				return obj.getInteger("dogGeneration").intValue();
			}
		}
		return 0;
	}

	/**
	 * @param phone
	 * @param name
	 * @Description：赛事报名表生成未支付报名信息
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 下午4:39:03
	 */
	@Transactional(readOnly = false)
	public CkuShowsBaoMing insertEntered(List<CkuDog> dogList, String showNum, double bmFei, String orderID, Date date,
			String ckuId, String payPid, String detil, String ageGroup, CkuUser ckuUser,
			EventRelatedModel eventRelatedModel, String bbeFlag, String stickerFlag, String isOwner)
			throws ZAException {
		CkuShowsBaoMing ckuShowsBaoMing = new CkuShowsBaoMing();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		// update by zjw 2023-02-07 工单号：ID1005116 取消宠爱护照发放
//		ckuShowsBaoMing.setStickerFlag(stickerFlag);
		ckuShowsBaoMing.setStickerFlag("0");
		// 主键
		ckuShowsBaoMing.setId(uuid);
		// 订单生成来源
		ckuShowsBaoMing.setEntryNo("CAB");
		// 犬主人
		ckuShowsBaoMing.setDogOwner(dogList.get(0).getDogOwner());
		List<CkuUser> list = ckuUserMapper.getUserMessage(dogList.get(0).getMemberNum());
		// 犬主英文名
		if (list.size() > 0) {
			ckuShowsBaoMing.setDogOwnerE(list.get(0).getNameSpelling());
		}
		// 会员号
		ckuShowsBaoMing.setUserNo(list.get(0).getMemberNum());
		//增加记录第二犬主
		ckuShowsBaoMing.setSecondDogOwner(dogList.get(0).getDogSecondOwenr());
		ckuShowsBaoMing.setSecondOwnerMember(dogList.get(0).getSecondOwenrMemberNum());
		// 赛事编号
		ckuShowsBaoMing.setShowNum(showNum);
		// 根据牵犬师会员号，查询牵犬师电话并替换牵犬师信息里的带*号的电话号码
		List<CkuUser> handler = ckuUserMapper.getUserMessageByMemberCodeOrPhoneNumber(detil.split(",")[0]);
		if (list.size() > 0) {
			CkuUser handlerMember = handler.get(0);
			detil = handlerMember.getMemberNum() + "," + handlerMember.getName() + "," + handlerMember.getMobilePhone();
		}
		String[] remark = detil.split(",", -1);
		// 备注
		ckuShowsBaoMing.setRemark(remark[1] + " " + remark[2]);
		// 报名费
		ckuShowsBaoMing.setEntryFee(String.valueOf(bmFei));
		// 请假及取消
		ckuShowsBaoMing.setLeaveCancel("0");
		// 赛场请假
		ckuShowsBaoMing.setShowLeave("0");

		String dogBreed = dogList.get(0).getShowDogBreed();
		String breedName = "";
		String breedNameE = "";
		String breedGroup = "";
		if (StringUtils.isBlank(dogBreed)) {
			dogBreed = dogList.get(0).getDogType();
			List<CkuDogClass> ckuDogClassList = ckuDogClassMapper.getByDogBreed(dogBreed);
			Debugger.doAssert(ckuDogClassList.size() > 0, ZAErrorCode.ZA_ERC_SHOWAPPLY,
					"该犬只的犬种" + dogBreed + "无效,请修改犬只犬种后提交。");
			CkuDogClass ckuDogClass = ckuDogClassList.get(0);
			breedName = ckuDogClass.getDogChinaName();
			breedNameE = ckuDogClass.getDogEnglishName();
			breedGroup = ckuDogClass.getTypeGroup();
		} else {
			List<CkuDogTypeShow> ckuDogTypeShowList = ckuDogTypeShowMapper.getByDogShowCode(dogBreed);
			Debugger.doAssert(ckuDogTypeShowList.size() > 0, ZAErrorCode.ZA_ERC_SHOWAPPLY,
					"该犬只的犬种" + dogBreed + "无效,请修改犬只犬种后提交。");
			CkuDogTypeShow ckuDogTypeShow = ckuDogTypeShowList.get(0);
			breedName = ckuDogTypeShow.getShowCnName();
			breedNameE = ckuDogTypeShow.getShowEnName();
			breedGroup = ckuDogTypeShow.getTypeGroup();
		}
		// 犬种中文名
		ckuShowsBaoMing.setBreedName(breedName);
		// 犬种英文名
		ckuShowsBaoMing.setBreedNameE(breedNameE);
		// FCI代码
		ckuShowsBaoMing.setFciCode(dogBreed);
		// 犬种类组
		ckuShowsBaoMing.setBreedGroup(breedGroup);
		// 犬名
		ckuShowsBaoMing.setDogName(dogList.get(0).getDogEgName());
		// 犬性别
		String gender = "";
		if ("公".equals(dogList.get(0).getDogGender())) {
			gender = "1";
		}
		if ("母".equals(dogList.get(0).getDogGender())) {
			gender = "2";
		}
		ckuShowsBaoMing.setGender(gender);
		// 出生日期
		ckuShowsBaoMing.setBirth(dogList.get(0).getDogBirthday());
		// 年龄组别
		ckuShowsBaoMing.setAgeGroup(ageGroup);
		// 是否报名犬主人组
		ckuShowsBaoMing.setIsOwner(isOwner);
		// CKU血统证书号
		ckuShowsBaoMing.setCkuStudbookNum(dogList.get(0).getPedigreeNum());
		// 国外血统证书号
		ckuShowsBaoMing.setForeignStudbookNum(dogList.get(0).getOverseasRegCertifi());
		// 芯片号
		ckuShowsBaoMing.setMicrochipNo(dogList.get(0).getIdentifiSign());
		// 父犬血统证号
		ckuShowsBaoMing.setFstudbookNum(dogList.get(0).getfPedigreeNum());
		if (dogList.size() > 0) {
			if (StringUtils.isNotBlank(dogList.get(0).getfPedigreeNum())) {
				List<CkuDog> fList = ckuDogMapper.getMatchCost(dogList.get(0).getfPedigreeNum(), null);
				if (fList.size() > 0) {
					// 父犬名
					ckuShowsBaoMing.setFdogName(fList.get(0).getDogEgName());
				}
			}
			if (StringUtils.isNotBlank(dogList.get(0).getmPedigreeNum())) {
				List<CkuDog> mList = ckuDogMapper.getMatchCost(dogList.get(0).getmPedigreeNum(), null);
				if (mList.size() > 0) {
					// 母犬名
					ckuShowsBaoMing.setMdogName(mList.get(0).getDogEgName());
				}
			}
			dogList.get(0).getmPedigreeNum();
		}
		// 母犬血统证号
		ckuShowsBaoMing.setMstudbookNum(dogList.get(0).getmPedigreeNum());
		// 繁殖人
		ckuShowsBaoMing.setBreeder(dogList.get(0).getBreeder());
		// 操作人员
		ckuShowsBaoMing.setOptUser(ckuId.trim() + ":" + sdf.format(new Date()));
		// 项目类型(根据gameType、organizer来判断)
		ckuShowsBaoMing.setPayPid(payPid);
		// 订单金额
		ckuShowsBaoMing.setOrderPrice(new BigDecimal(bmFei));
		// 订单号
		ckuShowsBaoMing.setRunningNumber(orderID);
		// 订单生成时间
		ckuShowsBaoMing.setAddTime(date);
		// 支付状态
		ckuShowsBaoMing.setPayout("1");
		// 支付会员号
		ckuShowsBaoMing.setPayCkuid(ckuId);
		// 添加牵犬师信息
		ckuShowsBaoMing.setSponsorDetil(detil);
		// 牵犬师头像校验
		if ("1".equals(eventRelatedModel.getHandlerPhotoFlag())) {
			if (list.size() > 0) {
				String avatar = handler.get(0).getAvatar();
				Debugger.doAssert(StringUtils.isNotBlank(avatar), ZAErrorCode.ZA_ERC_SHOWAPPLY,
						"您选择的牵犬师还没有上传证件照，无法报名赛事.会员中心添加照片请前往“个人中心”页面，点击“证件照上传”按钮即可添加");
			}
		}
		// 比赛报名牵犬师项添加“禁赛”校验
		if (handler.get(0).getSsJstime() != null
				&& eventRelatedModel.getMainShowStartTime().getTime() < handler.get(0).getSsJstime().getTime()) {
			throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "牵犬师会员在禁赛期中");
		}
		ckuShowsBaoMing.setDelTag("0");
		ckuShowsBaoMing.setInfoConfirm("0");
		// 犬只代数
		// 犬只代数校验
		int i = 0;
		int fDogGeneration = publicService.getDogGeneration("fu", dogList.get(0).getPedigreeNum(), 0, 0);
		int mDogGeneration = publicService.getDogGeneration("mu", dogList.get(0).getPedigreeNum(), 0, 0);
		if (fDogGeneration > mDogGeneration) {
			i = mDogGeneration;
		} else {
			i = fDogGeneration;
		}
		boolean generation3 = false;
		List<CkuDog> dog2f = StringUtils.isBlank(dogList.get(0).getfPedigreeNum()) ? new ArrayList<CkuDog>(0)
				: ckuDogMapper.getMatchCost(dogList.get(0).getfPedigreeNum(), null);
		List<CkuDog> dog2m = StringUtils.isBlank(dogList.get(0).getmPedigreeNum()) ? new ArrayList<CkuDog>(0)
				: ckuDogMapper.getMatchCost(dogList.get(0).getmPedigreeNum(), null);
		if (dog2f.size() > 0 && validateParentsPedigreeCertifiedCode(dog2f) && dog2m.size() > 0
				&& validateParentsPedigreeCertifiedCode(dog2m)) {
			List<CkuDog> dog3ff = StringUtils.isBlank(dog2f.get(0).getfPedigreeNum()) ? new ArrayList<CkuDog>(0)
					: ckuDogMapper.getMatchCost(dog2f.get(0).getfPedigreeNum(), null);
			List<CkuDog> dog3fm = StringUtils.isBlank(dog2f.get(0).getmPedigreeNum()) ? new ArrayList<CkuDog>(0)
					: ckuDogMapper.getMatchCost(dog2f.get(0).getmPedigreeNum(), null);
			List<CkuDog> dog3mf = StringUtils.isBlank(dog2m.get(0).getfPedigreeNum()) ? new ArrayList<CkuDog>(0)
					: ckuDogMapper.getMatchCost(dog2m.get(0).getfPedigreeNum(), null);
			List<CkuDog> dog3mm = StringUtils.isBlank(dog2m.get(0).getmPedigreeNum()) ? new ArrayList<CkuDog>(0)
					: ckuDogMapper.getMatchCost(dog2m.get(0).getmPedigreeNum(), null);
			if (dog3ff.size() > 0 && validateParentsPedigreeCertifiedCode(dog3ff) && dog3fm.size() > 0
					&& validateParentsPedigreeCertifiedCode(dog3fm) && dog3mf.size() > 0
					&& validateParentsPedigreeCertifiedCode(dog3mf) && dog3mm.size() > 0
					&& validateParentsPedigreeCertifiedCode(dog3mm)) {
				generation3 = true;
			}
		}
		// CKU-NB不校验代数
		if (!dogList.get(0).getPedigreeNum().toUpperCase().startsWith("CKU-NB") && !generation3) {
			if (eventRelatedModel.getShowSystem().equals("0") && StringUtils.isNotBlank(eventRelatedModel.getCacType())
					&& eventRelatedModel.getCacType().equals("1")) {
				throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "犬只参赛仅限3代及以上血统犬只报名，如有疑问致电协会400-660-7000咨询");
			}
		}
		ckuShowsBaoMing.setDogGenertions(i + "");
		// 失格次数校验
		if (StringUtils.isNotBlank(dogList.get(0).getDisqualificationNumber())
				&& StringUtils.isNumeric(dogList.get(0).getDisqualificationNumber())
				&& Integer.parseInt(dogList.get(0).getDisqualificationNumber()) >= 3) {
			throw new ZAException(ZAErrorCode.ZA_ERC_SHOWAPPLY, "该犬因失格限定已被禁止报名参赛");
		}
		// 主办方
		ckuShowsBaoMing.setOrganizer(eventRelatedModel.getOrganizer());
		// 主赛事id
		ckuShowsBaoMing.setMainShowId(eventRelatedModel.getMainShowId());
		ckuShowsBaoMing.setBbe(bbeFlag);
		StringBuffer isOwnerT = new StringBuffer("");
		
		// add by zjw 2021-05-25 如报名犬主人组标识为1，增加年龄限制：比赛当日犬只月龄大于等于9月龄才增加犬主人组
		List<String> showNums = Arrays.asList(ckuShowsBaoMing.getShowNum().split(",")).stream().map(num->num.trim()).collect(Collectors.toList());
		List<ShowChild> showChilds = ckuShowChildMapper.getShowChildByMainId(ckuShowsBaoMing.getMainShowId());
		if(Objects.isNull(showChilds)) {
			throw new ZAException(ZAErrorCode.ZA_ERC_UNKNOWN, "子赛事记录为空");
		}
		//根据用户所选子赛事，过滤出子赛事对象信息
		Map<String,ShowChild> showChildMap = showChilds.stream().filter(child->showNums.contains(child.getShowCode().trim()) && Objects.nonNull(child.getStartTime())).collect(Collectors.toMap(ShowChild::getShowCode,Function.identity()));
		// 判断 子赛事最小开始日期，犬只是否大于等于9月龄
		String[] showNumArr = ckuShowsBaoMing.getShowNum().split(",");
		for (int j = 0; j < showNumArr.length; j++) {
			ShowChild child = showChildMap.get(showNumArr[j]);
			if("1".equals(isOwner) && Objects.nonNull(child) && !DateUtils.isInXMounth(ckuShowsBaoMing.getBirth(),child.getStartTime(),9)) {
				isOwnerT.append("1");
			}else {
				isOwnerT.append("0");
			}
			if (j != ckuShowsBaoMing.getShowNum().split(",").length - 1) {
				isOwnerT.append(",");
			}
		}
		ckuShowsBaoMing.setIsOwner(isOwnerT.toString());
		ckuShowsBaoMingMapper.insertSelective(ckuShowsBaoMing);
		return ckuShowsBaoMing;
	}

	/**
	 * @param loginType
	 * @Description：订单表生成未支付订单信息
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 下午4:59:30
	 */
	public void insertSPOrderInfo(CkuDvUserModel ckuDvUserModel, double bmFei, String orderID, Date date, String uuid,
			String loginType) {
		SPOrderInfo record = new SPOrderInfo();
		record.setId(uuid);
		record.setCkuId(ckuDvUserModel.getCkuId());
		record.setUsername(ckuDvUserModel.getMemberName());
		record.setOrderid(orderID);
		record.setSpPrices(new BigDecimal(bmFei));
		record.setPayconfirm("1");
		record.setAddTime(date);
		record.setLoginType(loginType);
		// record.setSpIntegral(1); 业务数量
		record.setDelFlag("0");
		sPOrderInfoMapper.insertSelective(record);
	}

	/**
	 * @Description：购物车表生成未支付订单信息
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 下午5:11:30
	 * @throws ZAException
	 */
	public void insertSPCarts(CkuDvUserModel ckuDvUserModel, String orderID, double bmFei, Date date, String payPid,
			String businessId, String chargingItemName, String organizer, String businessOrderCode) throws ZAException {
		SPCarts sPCarts = new SPCarts();
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		sPCarts.setId(uuid);
		sPCarts.setOrderid(orderID);
		sPCarts.setCkuId(ckuDvUserModel.getCkuId());
		sPCarts.setPid(payPid);// 增加项目类型
		sPCarts.setPcount(1);
		sPCarts.setTotalPrice(new BigDecimal(bmFei));
		sPCarts.setAddTime(date);
		sPCarts.setSpPrice(new BigDecimal(bmFei));
		sPCarts.setDelFlag("0");
		sPCarts.setBusinessIds(businessId);// 订单详情表插入业务主键 2016年11月3日15:47:49
		sPCarts.setBusinessTable("show_apply");// 订单详情表插入业务表明 2016年11月3日15:47:52
		sPCarts.setBusinessOrderCode(businessOrderCode);
		this.addBusinessManage(sPCarts, getBusinessIdByShowApply(organizer));
		sPCarts.setCreateBy(ckuDvUserModel.getCkuId());
		sPCarts.setUpdateBy(ckuDvUserModel.getCkuId());
		sPCarts.setChargingItemName(chargingItemName);
		sPCartsMapper.insertSelective(sPCarts);
	}

	public SPCarts addBusinessManage(SPCarts pc, String id) throws ZAException {
		if (pc == null) {
			return pc;
		}
		if (StringUtils.isBlank(id)) {
			logger.info("购物车收费项所属业务id为空");
			// 没有id不能加入购物车
			throw new ZAException(ZAErrorCode.ZA_ERC_INVALID_PARAMETER, id + "业务名字不存在");
		}
		// 修改为使用映射表 by GYH
		SaFinanceSubjectMapping bizId = saFinanceSubjectMappingMapper.findByPrimarykey(id);
		if (bizId == null)
			throw new ZAException(ZAErrorCode.ZA_ERC_INVALID_PARAMETER, id + "业务名字不存在");
		pc.setBusinessName(bizId.getSubjectName());
		pc.setBusinessId(bizId.getId());
		pc.setBusinessRefund(bizId.getBusinessRefund());
		return pc;
	}

	private String getBusinessIdByShowApply(String organizer) throws ZAException {
		int organizerInt = 0;
		try {
			organizerInt = Integer.valueOf(organizer);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		switch (organizerInt) {
		// 北京
		case 1:
			return "1027";
		// 杭州
		case 2:
			return "1036";
		// 长春
		case 3:
			return "1030";
		// 重庆
		case 4:
			return "1039";
		// 长沙
		case 5:
			return "1033";
		// 郑州
		case 6:
			return "1042";
		// 南方
		case 7:
			return "1070";
		// 北方
		case 8:
			return "1073";
		default:
			throw new ZAException(ZAErrorCode.ZA_ERC_INVALID_PARAMETER, "举办城市错误，请联系管理员");
		}

	}

	/**
	 * @throws Exception
	 * @Description：余额支付赛事费用
	 * @author: zhuoHeng
	 * @version: 2016年4月20日 上午10:21:24
	 */
	@Transactional
	public void eventBalancePayment(MultiUserProfile userProfile, String orderID, String pid, String payPsw,
			String dynamic) throws Exception {

		// byte[] content = Base64.getDecoder().decode(user.getPayPassWord());
		// String realPassword = new String(AESUtils.decrypt(content));
		// String md5 = MD5Generator.generate(realPassword + dynamic);
		// Debugger.doAssert(payPsw.equalsIgnoreCase(md5),
		// ZAErrorCode.ZA_ERC_INVALID_PAYPASSWORD, "支付密码错误");

		String ckuUserId = "-1";
		// 根据CKU账号id查询出CKU账号信息
		CkuDvUserModel ckuDvUserModel = ckuDvUserMapper.getckuMemberByUserId(userProfile.getCurrentClubUserId());
		if (ckuDvUserModel != null) {
			ckuUserId = ckuDvUserModel.getCkuId();
		}
		// 根据CKU会员号查询出对应用户的余额信息
		CkuMemberBalance ckuMemberBalance = ckuMemberBalanMapper.getCkuMemberBalance(ckuUserId);

		if (ckuMemberBalance == null) {
			ckuMemberBalance = new CkuMemberBalance();
			String str = "0.0000";
			ckuMemberBalance.setMoneyAmount(str);
		}
		// 获取CKU账户余额
		BigDecimal money = new BigDecimal(ckuMemberBalance.getMoneyAmount());
		double amount = 0;
		String[] orderIds;
		String[] pids;
		// 合并支付订单
		if (orderID.contains(",")) {
			orderIds = orderID.split(",");
			pids = pid.split(",");
			for (int i = 0; i < orderIds.length; i++) {
				// 根据订单号查询出该订单应支付金额
				SPOrderInfo sPOrderInfo = sPOrderInfoMapper.selectByOrderID(orderIds[i], ckuUserId);
				amount = money.subtract(sPOrderInfo.getSpPrices()).doubleValue();
				Debugger.doAssert(amount >= 0, ZAErrorCode.ZA_BALANCE_ENOUGH, "账户余额不足");

				// ckuMemberBalanMapper.updateMemberBalance(new BigDecimal(amount),ckuUserId);
				ckuMemberBalanMapper.updateMemberBalance(amount, ckuUserId);
				ckuShowsBaoMingMapper.updateShowBaomingPayOut(orderIds[i]);
				sPOrderInfoMapper.updateOrderPayConfim(orderIds[i]);
				sPCartsMapper.updateSPCartsPayConfirm(orderIds[i]);
				CkuUserPayList ckuUserPayList = new CkuUserPayList();
				ckuUserPayList.setUserId(ckuUserId);
				// 余额支付赛事费用，money_type为69业务订单支付（余额支付）
				ckuUserPayList.setMoneyType("69");
				ckuUserPayList.setMoneyAmount(sPOrderInfo.getSpPrices());
				ckuUserPayList.setMoneyWay("cku.org");
				ckuUserPayList.setRunningNumber(orderIds[i]);
				ckuUserPayList.setPayState("1");
				ckuUserPayList.setOutTradeNo(orderIds[i]);
				ckuUserPayList.setAlipayS("www_mycku");
				ckuUserPayList.setAddTime(new Date());
				ckuUserPayList.setOperater(ckuUserId);
				ckuUserPayList.setDelTag("0");
				ckuUserPayListMapper.insertSelective(ckuUserPayList);
			}
		} else {// 单独支付订单
			// 根据订单号查询出该订单应支付金额
			SPOrderInfo sPOrderInfo = sPOrderInfoMapper.selectByOrderID(orderID, ckuUserId);
			Debugger.doAssert(sPOrderInfo != null, ZAErrorCode.ZA_ERC_UNKNOWN, "订单信息错误");
			if ("2".equals(sPOrderInfo.getPayconfirm())) {
				throw new ZAException(ZAErrorCode.ZA_ERC_UNKNOWN, "该订单已支付");
			}
			if (!"1".equals(sPOrderInfo.getPayconfirm())) {
				throw new ZAException(ZAErrorCode.ZA_ERC_UNKNOWN, "订单信息错误");
			}
			amount = money.subtract(sPOrderInfo.getSpPrices()).doubleValue();
			Debugger.doAssert(amount >= 0, ZAErrorCode.ZA_BALANCE_ENOUGH, "账户余额不足");
			ckuMemberBalanMapper.updateMemberBalance(amount, ckuUserId);
			ckuShowsBaoMingMapper.updateShowBaomingPayOut(orderID);
			sPOrderInfoMapper.updateOrderPayConfim(orderID);
			// sPCartsMapper.updateSPCartsPayConfirm(orderID);//如今购物车表设计中不存在支付状态的标识
			CkuUserPayList ckuUserPayList = new CkuUserPayList();
			ckuUserPayList.setUserId(ckuUserId);
			// 余额支付赛事费用，money_type为69业务订单支付（余额支付）
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			ckuUserPayList.setId(uuid);
			ckuUserPayList.setMoneyType("69");
			ckuUserPayList.setMoneyDate(new Date());
			ckuUserPayList.setMoneyAmount(sPOrderInfo.getSpPrices());
			ckuUserPayList.setMoneyWay("cku.org");
			ckuUserPayList.setRunningNumber(orderID);
			ckuUserPayList.setPayState("2");
			ckuUserPayList.setOutTradeNo(orderID);
			ckuUserPayList.setAlipayS("www_mycku");
			ckuUserPayList.setAddTime(new Date());
			ckuUserPayList.setOperater(ckuUserId);
			ckuUserPayList.setDelTag("0");
			ckuUserPayList.setCreateBy(ckuUserId);
			ckuUserPayList.setUpdateBy(ckuUserId);
			ckuUserPayListMapper.insertSelective(ckuUserPayList);
			String notification = "您于" + new SimpleDateFormat("yyyy年MM月dd日  HH时mm分").format(new Date()) + "成功报名,订单号:"
					+ orderID + "请妥善安排行程，CKU与您不见不散。";
			// 【缴费成功】尊敬的会员，您已成功报名CKU赛事-“赛事主名”，参赛犬只为“芯片号/证书号”。请于妥善安排行程，2016年7月15日杭州CKU与您不见散。
			PushUtils.push_alias_notification(PushUtils.getShowId(userProfile.getUserId().toString()), notification);
			// ZtSmsCode.sendNote(notification, user.getPhone());
			logger.info("========= notification:" + notification);
			ZtSmsUtil.sendNoteYX(notification, userProfile.getMobile());

			// 入库，我的消息
			CabMymessage cabMymessage = new CabMymessage();
			cabMymessage.setUserId(userProfile.getUserId());
			cabMymessage.setIsread(0);
			cabMymessage.setType(1);
			cabMymessage.setTitle("【宠爱王国】业务办理");
			cabMymessage.setContent(notification);
			cabMymessage.setCreateTime(new Date());
			cabMymessageMapper.insertSelective(cabMymessage);
		}
		// 订单支付完成,添加赛事报名积分
		utilService.addPoints(userProfile.getUserId(), 4);
		// TODO 推送直送成功短信
	}

	/**
	 * @Description：赛事报名取消订单
	 * @author: zhuoHeng
	 * @version: 2016年4月21日 下午1:10:37
	 */
	@Transactional
	public void cancelTheOrder(MultiUserProfile userProfile, String orderID) {
		ckuShowsBaoMingMapper.deleteByOrderId(userProfile.getUserId(), orderID);
		sPCartsMapper.deleteByOrderId(userProfile.getUserId(), orderID);
		sPOrderInfoMapper.deleteByOrderId(userProfile.getUserId(), orderID);
		String notification = "您于" + new SimpleDateFormat("yyyy年MM月dd日  HH时mm分").format(new Date()) + "已取消了订单号为:"
				+ orderID + "的订单。如非您本人操作，请尽快登录CKU会员中心进行重新报名，以免耽误您的参赛安排。";
		// 取消报名】尊敬的会员，您与2016年6月24日09时40分已取消了CKU赛事-“赛事主名”，参赛犬只为“芯片号/证书号”。如非您本人操作，请尽快登录CKU会员中心进行重新报名，以免耽误您的参赛安排

		PushUtils.push_alias_notification(PushUtils.getShowId(userProfile.getUserId().toString()), notification);
		// ZtSmsCode.sendNote(notification, user.getPhone());
		logger.info("========= notification:" + notification);
		ZtSmsUtil.sendNoteYX(notification, userProfile.getMobile());
		// 入库，我的消息
		CabMymessage cabMymessage = new CabMymessage();
		cabMymessage.setUserId(userProfile.getUserId());
		cabMymessage.setIsread(0);
		cabMymessage.setType(1);
		cabMymessage.setTitle("【宠爱王国】业务办理");
		cabMymessage.setContent(notification);
		cabMymessage.setCreateTime(new Date());
		cabMymessageMapper.insertSelective(cabMymessage);
	}

	/**
	 * @Description：根据收费项目名称获取收费项目编号
	 * @author: zhuoHeng
	 * @version: 2016年9月13日 上午10:10:54
	 */
	public String getPaymentCode(String name) {

		String id;
		CkuUserPayType ckuUserPayType = new CkuUserPayType();
		StringBuffer sb = new StringBuffer();
		sb.append("犬只参赛费（");
		sb.append(name + "）");
		ckuUserPayType = ckuUserPayTypeMapper.getPaymentCode(sb.toString());
		id = ckuUserPayType.getId();

		return id;
	}

	/**
	 * @Description：赛事编号排序
	 * @author: laiguanglong
	 * @version: 2017年7月27日 上午10:10:54
	 */
	private String sortShowNum(String showNum) {
		String[] strs = showNum.split(",");
		Arrays.sort(strs);
		StringBuilder sb = new StringBuilder();
		for (String str : strs) {
			sb.append(str.trim()).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}

	/**
	 * @Description：年龄组别排序
	 * @author: laiguanglong
	 * @version: 2017年7月27日 上午10:10:54
	 */
	private String sortAgeGroup(String ageGroup) {
		if (!ageGroup.contains("=")) {
			return ageGroup;
		}
		String[] strs = ageGroup.split(",");
		String[] showNums = new String[strs.length];
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0, len = strs.length; i < len; i++) {
			String[] s = strs[i].split("=");
			showNums[i] = ckuShowChildMapper.getShowCodeByShowChildId(s[0]);
			map.put(showNums[i], s[1]);
		}
		Arrays.sort(showNums);
		StringBuilder sb = new StringBuilder();
		for (String showNum : showNums) {
			sb.append(map.get(showNum)).append(",");
		}
		sb.deleteCharAt(sb.length() - 1);
		return sb.toString();
	}

	/**
	 * @description: 校验该犬只父母犬的血统证书号是否有值, 返回true表示有值
	 * @author: laiguanglong
	 * @date: 2016年8月12日 上午10:21:23
	 */
	private boolean validateParentsPedigreeCertifiedCode(List<CkuDog> list) {
		CkuDog dog = list.get(0);
		if (StringUtils.isBlank(dog.getfPedigreeNum()) || "-".equals(dog.getfPedigreeNum())) {
			return false;
		}
		if (StringUtils.isBlank(dog.getmPedigreeNum()) || "-".equals(dog.getmPedigreeNum())) {
			return false;
		}
		return true;
	}

	// public static void main(String[] args) {
	// Date date1 = DateUtils.strToDateFormat("2019-10-26 00:00:00");
	// Date date2 = DateUtils.strToDateFormat("2019-10-25 00:00:00");
	//
	// if(date1.compareTo(date2) >= 0) {
	// System.out.println("1");
	// }else {
	// System.out.println("2");
	// }
	//
	//
	// }
	
	public int getCntByShowCode(String showCode) {
		return ckuShowChildMapper.getCntByShowCode(showCode);
	}

}
