package com.cyksj.service.distribute.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.constant.TaskTypeEnum;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.Jsons;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.UserDistributeSharedRelateUnbindMapper;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.manage.coupon.CouponDistributePopularizeMapper;
import com.cyksj.mapper.manage.coupon.CouponMapper;
import com.cyksj.mapper.manage.distribute.*;
import com.cyksj.mapper.manage.distribute.equipment.UserDistributeEquipmentMapper;
import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubMapper;
import com.cyksj.mapper.market.task.TaskTypeMapper;
import com.cyksj.mapper.shop.YhShopMapper;
import com.cyksj.mapper.shop.YhShopUserPlatDistributeRateMapper;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.UserDistributeReq;
import com.cyksj.redis.RedisService;
import com.cyksj.service.claude.ClaudeCodeService;
import com.cyksj.service.distribute.DistributeService;
import com.cyksj.service.market.task.TaskService;
import com.cyksj.service.relation.GroupRelationFrontService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/*
 *项目名: netflix
 *文件名: DistributeServiceImpl
 *创建者: JavaZou
 *创建时间:2022/11/14 12:21
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class DistributeServiceImpl implements DistributeService {
	private final UserDistributeMapper userDistributeMapper;

	private final UserPlatDistributeRateMapper userPlatDistributeRateMapper;

	private final GoodsDonMapper goodsDonMapper;

	private final TaskService taskService;

	private final TaskTypeMapper taskTypeMapper;

	private final UserDistributeSharedMapper userDistributeSharedMapper;

	private final UserBusinessDefaultRateConfigMapper defaultRateConfigMapper;

	private final RedisService redisService;

	private final CouponMapper couponMapper;

	private final CouponDistributePopularizeMapper couponDistributePopularizeMapper;

	private final YhShopUserPlatDistributeRateMapper yhShopUserPlatDistributeRateMapper;

	private final YhShopMapper yhShopMapper;

	private final UserPlatSkuDistributeRateMapper userPlatSkuDistributeRateMapper;

	private final UserDistributeTargetAlertMapper targetAlertMapper;

	private final UserDistributeSharedRelateUnbindMapper userDistributeSharedRelateUnbindMapper;

	private final UserDistributeEquipmentMapper userDistributeEquipmentMapper;

	private final UserDistributeSubMapper userDistributeSubMapper;

	private final DistributeGeneralSkuRateMapper generalSkuRateMapper;

	private final ClaudeCodeService claudeCodeService;

	private final UserMapper userMapper;

	private final GroupRelationFrontService groupRelationFrontService;

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void insertDistribute(UserDistributeReq userDistributeReq) {
		if (!redisService.setNx(RedisService.key.USER_DISTRIBUTE_ADD_KEY.getNameFormat(userDistributeReq.getUserId()), userDistributeReq.getUserId(), 2 * 5l)) {
			return;
		}
		UserDistribute exists = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class).eq(UserDistribute::getUserId, userDistributeReq.getUserId()).eq(UserDistribute::getDeleted, true).last("limit 1"));
		if (exists != null) {
			throw BusinessRuntimeException.getInstance("该推广者已添加");
		}
		Long businessId = userDistributeReq.getBusinessId();
		UserDistribute userDistribute = new UserDistribute();
		userDistribute.setUserId(userDistributeReq.getUserId());
		userDistribute.setRemark(userDistributeReq.getRemark());
		userDistribute.setType(userDistributeReq.getType());
		userDistribute.setBusinessId(businessId);
		if (businessId != null && businessId != 0) {
			userDistribute.setBusinessBindTime(DateTime.now());
		}
		userDistributeMapper.insert(userDistribute);
		for (UserPlatDistributeRate rate : userDistributeReq.getRates()) {
			if (rate.getRate() == null) {
				rate.setRate(0);
			}
			if (rate.getSecondRate() == null) {
				rate.setSecondRate(0);
			}
			if (rate.getRate() < 0 || rate.getRate() > 100) {
				throw new BusinessRuntimeException("比例错误");
			}
			GoodsDon goodsDon = goodsDonMapper.selectById(rate.getGoodsId());
			if (goodsDon == null || !goodsDon.getDeleted() || goodsDon.getType() == 3) {
				throw new BusinessRuntimeException("平台错误");
			}
			//分销者虚物分销比例且配置商务
			if (businessId != null && goodsDon.getType() == 1) {
				checkDistributorAndBusinessRate(rate.getRate(), goodsDon.getId(), goodsDon.getTitle());
			}
			rate.setDistributeId(userDistribute.getId());
			userPlatDistributeRateMapper.insert(rate);
		}
		List<UserPlatSkuDistributeRate> skuRates = userDistributeReq.getSkuRates();
		if (CollUtil.isNotEmpty(skuRates)) {
			Map<Long, GoodsDon> map = new ConcurrentHashMap<>();
			for (UserPlatSkuDistributeRate skuRate : skuRates) {
				if (skuRate.getRate() == null) {
					skuRate.setRate(0);
				}
				if (skuRate.getSecondRate() == null) {
					skuRate.setSecondRate(0);
				}
				if (skuRate.getRate() < 0 || skuRate.getRate() > 100) {
					throw new BusinessRuntimeException("比例错误");
				}
				GoodsDon goodsDon = map.get(skuRate.getGoodsId());
				if (goodsDon == null) {
					goodsDon = goodsDonMapper.selectById(skuRate.getGoodsId());
					map.putIfAbsent(skuRate.getSkuId(), goodsDon);
				}
				try {
					skuRate.setDistributeId(userDistribute.getId());
					if (businessId != null && goodsDon.getType() == 1) {
						checkDistributorAndBusinessRate(skuRate.getRate(), skuRate.getGoodsId(), goodsDon.getTitle());
					}
					userPlatSkuDistributeRateMapper.insert(skuRate);
				} catch (DuplicateKeyException e) {
				}
			}
		}
		//渠道附加功能
		handlerDistributeOtherFunc(userDistribute, userDistributeReq);
		//设置过个人专属推广码 升级为渠道专属优惠码
		setDistributePopularizeCode(userDistribute.getId(), userDistribute.getUserId());
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void editDistribute(UserDistributeReq userDistributeReq) {
		if (userDistributeReq.getId() == null || userDistributeReq.getId() < 1) {
			throw BusinessRuntimeException.getInstance("id错误");
		}
		Long id = userDistributeReq.getId();
		UserDistribute userDistribute = userDistributeMapper.selectById(id);
		if (userDistribute == null || !userDistribute.getDeleted()) {
			return;
		}
		userDistribute.setId(userDistributeReq.getId());
		userDistribute.setRemark(userDistributeReq.getRemark());
		Long businessId = userDistributeReq.getBusinessId();
		if (businessId == null) {
			userDistribute.setBusinessId(0l);
		} else {
			if (userDistribute.getBusinessId() != null && !userDistribute.getBusinessId().equals(businessId)) {
				userDistribute.setBusinessBindTime(DateTime.now());
			}
			userDistribute.setBusinessId(businessId);
		}
		userDistribute.setType(userDistributeReq.getType());
		userDistributeMapper.updateById(userDistribute);
		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class)
				.eq(YhShop::getUserId, userDistribute.getUserId())
				.eq(YhShop::getVerifyStatus, YhShop.Status.success).last("limit 1"));
		for (UserPlatDistributeRate rate : userDistributeReq.getRates()) {
			if (rate.getRate() == null) {
				rate.setRate(0);
			}
			if (rate.getSecondRate() == null) {
				rate.setSecondRate(0);
			}
			if (rate.getRate() < 0 || rate.getRate() > 100) {
				throw new BusinessRuntimeException("比例错误");
			}
			GoodsDon goodsDon = goodsDonMapper.selectById(rate.getGoodsId());
			if (rate.getId() != null && (goodsDon == null || !goodsDon.getDeleted())) {
				userPlatDistributeRateMapper.deleteById(rate.getId());
				continue;
			}
			if (goodsDon == null || !goodsDon.getDeleted() || goodsDon.getType() == 3) {
				throw new BusinessRuntimeException("平台错误");
			}
			//分销者虚物分销比例且配置商务
			if (businessId != null && goodsDon.getType() == 1) {
				checkDistributorAndBusinessRate(rate.getRate(), goodsDon.getId(), goodsDon.getTitle());
			}
			rate.setDistributeId(userDistribute.getId());
			if (rate.getId() == null) {
				try {
					userPlatDistributeRateMapper.insert(rate);
				} catch (DuplicateKeyException e) {
					userPlatDistributeRateMapper.update(null, Wrappers.lambdaUpdate(UserPlatDistributeRate.class)
							.eq(UserPlatDistributeRate::getDistributeId, userDistribute.getId())
							.eq(UserPlatDistributeRate::getGoodsId, rate.getGoodsId())
							.set(UserPlatDistributeRate::getRate, rate.getRate()));
				}
				if (yhShop != null) {
					try {
						YhShopUserPlatDistributeRate yhShopUserPlatDistributeRate = new YhShopUserPlatDistributeRate();
						yhShopUserPlatDistributeRate.setRate(rate.getRate());
						yhShopUserPlatDistributeRate.setGoodsId(rate.getGoodsId());
						yhShopUserPlatDistributeRate.setUserId(userDistribute.getUserId());
						yhShopUserPlatDistributeRateMapper.insert(yhShopUserPlatDistributeRate);
					} catch (DuplicateKeyException e) {
						//同步店铺分销比例
						yhShopUserPlatDistributeRateMapper.update(null, Wrappers.lambdaUpdate(YhShopUserPlatDistributeRate.class)
								.eq(YhShopUserPlatDistributeRate::getUserId, userDistribute.getUserId())
								.eq(YhShopUserPlatDistributeRate::getGoodsId, rate.getGoodsId())
								.set(YhShopUserPlatDistributeRate::getRate, rate.getRate()));
					}
				}
			} else {
				UserPlatDistributeRate dbPlateRate = userPlatDistributeRateMapper.selectById(rate.getId());
				if (dbPlateRate == null) {
					continue;
				}
				if (dbPlateRate.getRate() != rate.getRate() || dbPlateRate.getSecondRate() != rate.getSecondRate()) {
					userPlatDistributeRateMapper.updateById(rate);
					if (yhShop != null && dbPlateRate.getRate() != rate.getRate()) {
						//同步店铺分销比例
						yhShopUserPlatDistributeRateMapper.update(null, Wrappers.lambdaUpdate(YhShopUserPlatDistributeRate.class)
								.eq(YhShopUserPlatDistributeRate::getUserId, userDistribute.getUserId())
								.eq(YhShopUserPlatDistributeRate::getGoodsId, rate.getGoodsId())
								.set(YhShopUserPlatDistributeRate::getRate, rate.getRate()));
					}
				}
			}
		}

		//特殊平台 按规格分销比例
		List<UserPlatSkuDistributeRate> skuRates = userDistributeReq.getSkuRates();
		if (CollUtil.isNotEmpty(skuRates)) {
			List<Long> skuIds = skuRates.stream().map(UserPlatSkuDistributeRate::getSkuId).collect(Collectors.toList());
			userPlatSkuDistributeRateMapper.delete(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
					.notIn(UserPlatSkuDistributeRate::getSkuId, skuIds)
					.eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId()));

			Map<Long, GoodsDon> map = new ConcurrentHashMap<>();
			for (UserPlatSkuDistributeRate skuRate : skuRates) {
				if (skuRate.getRate() == null) {
					skuRate.setRate(0);
				}
				if (skuRate.getSecondRate() == null) {
					skuRate.setSecondRate(0);
				}
				if (skuRate.getRate() < 0 || skuRate.getRate() > 100) {
					throw new BusinessRuntimeException("比例错误");
				}
				GoodsDon goodsDon = map.get(skuRate.getGoodsId());
				if (goodsDon == null) {
					goodsDon = goodsDonMapper.selectById(skuRate.getGoodsId());
					map.putIfAbsent(skuRate.getSkuId(), goodsDon);
				}
				if (businessId != null && goodsDon.getType() == 1) {
					checkDistributorAndBusinessRate(skuRate.getRate(), goodsDon.getId(), goodsDon.getTitle());
				}
				if (skuRate.getId() != null) {
					userPlatSkuDistributeRateMapper.updateById(skuRate);
					continue;
				}
				try {
					skuRate.setDistributeId(userDistribute.getId());
					userPlatSkuDistributeRateMapper.insert(skuRate);
				} catch (DuplicateKeyException e) {
				}
			}
		} else {
			userPlatSkuDistributeRateMapper.delete(Wrappers.lambdaQuery(UserPlatSkuDistributeRate.class)
					.eq(UserPlatSkuDistributeRate::getDistributeId, userDistribute.getId()));
		}
		handlerDistributeOtherFunc(userDistribute, userDistributeReq);
	}

	/**
	 * 渠道附加功能
	 */
	public void handlerDistributeOtherFunc(UserDistribute userDistribute, UserDistributeReq userDistributeReq) {
		//处理优惠券关联
		handlerDistributeCouponRelate(userDistribute.getId(), userDistribute.getUserId(), userDistributeReq.getCouponRelates());

		//渠道目标额配置
		handlerDistributeTargetAlert(userDistribute.getId(), userDistributeReq.getTargets());

		//设备分销
		handlerSpecialEquipmentRate(userDistributeReq.getEpRate(), userDistribute);

		//下级渠道绑定
		handlerDistributeSub(userDistributeReq.getUserDistributeSub(), userDistribute);
	}

	@Override
	public void saveDistributionInvitation(Long sharedId, Long userId, Long dsPopularizeId, Boolean ccGeneralTg) {
		if (sharedId == 0l || sharedId.equals(userId)) {
			return;
		}
		User user = userMapper.selectById(sharedId);
		if (user == null) {
			return;
		}
		UserDistributeShared userDistributeShared = new UserDistributeShared();
		userDistributeShared.setSharedId(sharedId);
		//存在分销
		userDistributeShared.setUserId(userId);
		userDistributeShared.setDsPopularizeId(dsPopularizeId);
		if (ccGeneralTg != null) {
			//普通推广
			Integer selectCount = userDistributeMapper.selectCount(Wrappers.lambdaQuery(UserDistribute.class).eq(UserDistribute::getUserId, sharedId).eq(UserDistribute::getDeleted, Boolean.TRUE));
			if (selectCount == 0) {
				//打上普通cc推广标识
				userDistributeShared.setRemark(Constant.CC_DISTRIBUTE_MARK);
			}
		}
		try {
			userDistributeSharedMapper.insert(userDistributeShared);
			if (Constant.CC_DISTRIBUTE_MARK.equals(userDistributeShared.getRemark())) {
				//若是cc普通推广 发送claude code积分卡
				claudeCodeService.sendCreditCard(null, userDistributeShared.getSharedId(), Constant.CLAUDE_CODE_SUP_QUOTA, Constant.CLAUDE_CODE_CARD_NUMBER + System.currentTimeMillis(), "新用户注册");
				//存在Claude code车票不发送体验卡
				if (!claudeCodeService.checkClaudeCodeUser(userId)) {
					//发送claude code 体验卡
					groupRelationFrontService.getTrialTicketByUserIdAndGoodsId(userId, Constant.DISTRIBUTE_CLAUDE_CODE_TRIAL_SKU_ID, 1);
				}
			}
			TaskType taskType = taskTypeMapper.selectOne(Wrappers.lambdaQuery(TaskType.class)
					.eq(TaskType::getName, TaskTypeEnum.share.getDesc()).last("limit 1"));
			taskService.completeTask(taskType, sharedId);
		} catch (DuplicateKeyException e) {
			log.info("分销被邀请人重复插入");
		}
	}

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void bindPopularizeCode(Long userId, String code) {
		Coupon coupon = couponMapper.getCouponById(Constant.GENERAL_POPULARIZE_COUPON_ID);
		if (!redisService.setNx(RedisService.key.GENERAL_POPULARIZE_CODE.getName() + code, userId, RedisService.key.GENERAL_POPULARIZE_CODE.getTimeout())) {
			throw BusinessRuntimeException.getInstance("该专属推广优惠码已被设置");
		}
		UserDistribute userDistribute = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
				.eq(UserDistribute::getUserId, userId)
				.eq(UserDistribute::getDeleted, true)
				.last("limit 1"));
		if (userDistribute != null) throw BusinessRuntimeException.getInstance("只适用于普通用户进行专属推广");
		CouponDistributePopularize is_exists = couponDistributePopularizeMapper.selectOne(Wrappers.lambdaQuery(CouponDistributePopularize.class)
				.eq(CouponDistributePopularize::getUserId, userId)
				.eq(CouponDistributePopularize::getDeleted, true)
				.last("limit 1"));
		if (is_exists != null) throw BusinessRuntimeException.getInstance("你已设置专属推广优惠码");
		CouponDistributePopularize couponDistributePopularize = new CouponDistributePopularize();
		couponDistributePopularize.setCouponId(coupon.getId());
		couponDistributePopularize.setUserId(userId);
		couponDistributePopularize.setIsGeneral(true);
		CouponDistributePopularize exists = couponDistributePopularizeMapper.selectOne(Wrappers.lambdaQuery(CouponDistributePopularize.class)
				.eq(CouponDistributePopularize::getExCode, code)
				.eq(CouponDistributePopularize::getDeleted, true)
				.select(CouponDistributePopularize::getId)
				.last("limit 1"));
		if (exists != null) {
			throw BusinessRuntimeException.getInstance("该专属推广优惠码已被设置");
		} else {
			Coupon existsCoupon = couponMapper.selectOne(Wrappers.lambdaQuery(Coupon.class)
					.eq(Coupon::getExCode, code)
					.eq(Coupon::getDeleted, true)
					.select(Coupon::getId)
					.last("limit 1"));
			if (existsCoupon != null) {
				throw BusinessRuntimeException.getInstance("该专属推广优惠码已被设置");
			}
		}
		couponDistributePopularize.setExCode(code);
		couponDistributePopularizeMapper.insert(couponDistributePopularize);
	}

	@Override
	public void unbindUserDistributeShared(List<Object> userBind) throws Exception {
		List<Long> save_userIds = new ArrayList<>(500);
		userBind.forEach(e -> {
			Map<String, Object> map = Jsons.toMap(e);
			Object value0 = map.get("0");
			if (value0 != null) {
				Long userId = Long.parseLong(value0.toString());
				save_userIds.add(userId);
				if (save_userIds.size() == 500) {
					userDistributeSharedRelateUnbindMapper.batchInsert(save_userIds);
					save_userIds.clear();
				}
			}
		});
		if (save_userIds.size() > 0) {
			userDistributeSharedRelateUnbindMapper.batchInsert(save_userIds);
			save_userIds.clear();
		}
	}

	@Override
	public void setDistributeCommonSkuRate(List<DistributeGeneralSkuRate> skuRates) {
		List<Long> collect = skuRates.stream().map(DistributeGeneralSkuRate::getSkuId).collect(Collectors.toList());
		if (CollUtil.isNotEmpty(collect)) {
			generalSkuRateMapper.delete(Wrappers.lambdaQuery(DistributeGeneralSkuRate.class)
					.notIn(DistributeGeneralSkuRate::getSkuId, collect));
		}
		skuRates.forEach(e -> {
			Integer rate = e.getRate();
			if (rate == null || rate < 0 || rate > 100) {
				throw BusinessRuntimeException.getInstance("请输入正确的比例");
			}
			if (e.getId() == null) {
				try {
					generalSkuRateMapper.insert(e);
				} catch (DuplicateKeyException ex) {
				}
			} else {
				generalSkuRateMapper.updateById(e);
			}
		});
	}

	public void checkDistributorAndBusinessRate(Integer distributeGoodsRate, Long goodsId, String goodsName) {
		UserBusinessDefaultRateConfig defaultGoodsRateConfig = defaultRateConfigMapper.selectOne(Wrappers.lambdaQuery(UserBusinessDefaultRateConfig.class)
				.eq(UserBusinessDefaultRateConfig::getGoodsId, goodsId)
				.last("limit 1"));
		Optional.ofNullable(defaultGoodsRateConfig).ifPresent(config -> {
			if (distributeGoodsRate > config.getMaxRate()) {
				throw BusinessRuntimeException.getInstance(String.format("该%s平台最高可配置分销比例为%s", goodsName, config.getMaxRate()));
			}
		});
	}

	private void handlerDistributeCouponRelate(Long distributeId, Long userId, List<CouponDistributePopularize> couponRelates) {
		Map<Long, CouponDistributePopularize> map = new ConcurrentHashMap<>();
		couponRelates.forEach(data -> {
			data.setDistributeId(distributeId);
			if (data.getCouponId() == null) {
				throw BusinessRuntimeException.getInstance("优惠券不存在");
			}
			Integer exists = couponMapper.selectCount(Wrappers.lambdaQuery(Coupon.class).eq(Coupon::getId, data.getCouponId()).eq(Coupon::getDeleted, 1));
			if (exists == 0) {
				throw BusinessRuntimeException.getInstance("id为{0}的优惠券不存在", data.getCouponId());
			}
			String exCode = data.getExCode();
			if (StrUtil.isEmpty(exCode)) {
				throw BusinessRuntimeException.getInstance("优惠码为空");
			}
			List<CouponDistributePopularize> popularizeList = couponDistributePopularizeMapper.selectList(Wrappers.lambdaQuery(CouponDistributePopularize.class)
					.eq(CouponDistributePopularize::getDeleted, 1)
					.eq(CouponDistributePopularize::getExCode, exCode));
			//个人渠道
			for (CouponDistributePopularize couponDistributePopularize : popularizeList) {
				Long disId = couponDistributePopularize.getDistributeId();
				if (disId != null) {
					if (!ObjectUtil.equal(disId, distributeId) || !ObjectUtil.equal(couponDistributePopularize.getCouponId(), data.getCouponId())) {
						throw BusinessRuntimeException.getInstance("优惠码:{0}已存在", exCode);
					}
				}
				Long uid = couponDistributePopularize.getUserId();
				if (uid != null) {
					if (!ObjectUtil.equal(uid, userId) || !ObjectUtil.equal(couponDistributePopularize.getCouponId(), data.getCouponId())) {
						throw BusinessRuntimeException.getInstance("优惠码:{0}已存在", exCode);
					}
				}
			}
			Integer count = couponMapper.selectCount(Wrappers.lambdaQuery(Coupon.class).eq(Coupon::getExCode, exCode).eq(Coupon::getDeleted, true));
			if (count > 0) {
				throw BusinessRuntimeException.getInstance("优惠码:{0}已存在", exCode);
			}
			if (data.getId() != null) {
				couponDistributePopularizeMapper.updateById(data);
			} else {
				couponDistributePopularizeMapper.insert(data);
			}
			map.put(data.getId(), data);
		});

		List<CouponDistributePopularize> dbCouponPopularizes = couponDistributePopularizeMapper.selectList(Wrappers.lambdaQuery(CouponDistributePopularize.class)
				.eq(CouponDistributePopularize::getDistributeId, distributeId)
				.eq(CouponDistributePopularize::getDeleted, 1));

		//不存在的删除
		List<Long> delDbCouponPids = new ArrayList<>();
		dbCouponPopularizes.forEach(db -> {
			if (map.get(db.getId()) == null) {
				delDbCouponPids.add(db.getId());
			}
		});

		if (CollUtil.isNotEmpty(delDbCouponPids)) {
			couponDistributePopularizeMapper.update(null, Wrappers.lambdaUpdate(CouponDistributePopularize.class)
					.set(CouponDistributePopularize::getDeleted, 0)
					.in(CouponDistributePopularize::getId, delDbCouponPids)
					.eq(CouponDistributePopularize::getDeleted, 1));
		}
	}


	/**
	 * 渠道目标额 设置
	 */
	private void handlerDistributeTargetAlert(Long distributeId, List<UserDistributeTargetAlert> targets) {
		Map<Long, UserDistributeTargetAlert> map = new ConcurrentHashMap<>();
		for (UserDistributeTargetAlert targetAlert : targets) {
			targetAlert.setDistributeId(distributeId);
			Integer type = targetAlert.getType();
			BigDecimal target = targetAlert.getTarget();
			Assert.notNull(type, "请选择对应目标类型");
			Assert.notNull(target, "请输入对应目标额");
			if (type < 1 || type > 3) {
				throw BusinessRuntimeException.getInstance("请选择正确的目标类型");
			}

			if (target.compareTo(BigDecimal.ZERO) <= 0) {
				throw BusinessRuntimeException.getInstance("请输入正确的目标额值");
			}

			if ((type == 2 || type == 3) && target.compareTo(BigDecimal.ZERO) < 0) {
				throw BusinessRuntimeException.getInstance("请输入正确的变化比例");
			}
			Long id = targetAlert.getId();

			try {
				if (id != null) {
					UserDistributeTargetAlert dbAlert = targetAlertMapper.selectById(id);
					if (dbAlert != null) {
						//目标额 变化 去掉下次提醒时间
						if (dbAlert.getTarget().compareTo(targetAlert.getTarget()) != 0) {
							targetAlert.setNextAlertTime(null);
						}
						//关闭一周内提醒 去掉下次提醒时间
						if (!targetAlert.getIsWeek()) {
							targetAlert.setNextAlertTime(null);
						}
						targetAlertMapper.updateById(targetAlert);
					}
				} else {
					targetAlertMapper.insert(targetAlert);
				}
				map.put(targetAlert.getId(), targetAlert);
			} catch (DuplicateKeyException e) {
			}
		}

		List<UserDistributeTargetAlert> dbTargetAlert = targetAlertMapper.selectList(Wrappers.lambdaQuery(UserDistributeTargetAlert.class)
				.eq(UserDistributeTargetAlert::getDistributeId, distributeId));

		//不存在的删除
		List<Long> delDbTargetAlert = new ArrayList<>();
		dbTargetAlert.forEach(db -> {
			if (map.get(db.getId()) == null) {
				delDbTargetAlert.add(db.getId());
			}
		});

		if (CollUtil.isNotEmpty(delDbTargetAlert)) {
			targetAlertMapper.deleteBatchIds(delDbTargetAlert);
		}
	}

	/**
	 * 设备分销
	 */
	private void handlerSpecialEquipmentRate(UserDistributeEquipment epRate, UserDistribute userDistribute) {
		BigDecimal zero = BigDecimal.ZERO;
		Long userId = userDistribute.getUserId();
		Long distributeId = userDistribute.getId();
		if (epRate != null) {
			epRate.setUserId(userId);
			epRate.setDistributeId(distributeId);
			BigDecimal ep = epRate.getEp();
			BigDecimal apTv = epRate.getApTv();
			BigDecimal combo = epRate.getCombo();
			if (ep == null || apTv == null || combo == null) {
				throw BusinessRuntimeException.getInstance("请填写设备分销必填项..");
			}
			if (ep.compareTo(zero) <= 0 || apTv.compareTo(zero) <= 0 || combo.compareTo(zero) <= 0 || combo.compareTo(BigDecimal.valueOf(100)) >= 0) {
				throw BusinessRuntimeException.getInstance("请输入正确的设备分销设置");
			}
			if (epRate.getId() == null) {
				try {
					userDistributeEquipmentMapper.insert(epRate);
				} catch (DuplicateKeyException e) {
				}
			} else {
				userDistributeEquipmentMapper.updateById(epRate);
			}
			return;
		}
		if (userDistributeEquipmentMapper.selectCount(Wrappers.lambdaQuery(UserDistributeEquipment.class)
				.eq(UserDistributeEquipment::getDistributeId, distributeId)) > 0) {
			userDistributeEquipmentMapper.delete(Wrappers.lambdaQuery(UserDistributeEquipment.class)
					.eq(UserDistributeEquipment::getDistributeId, distributeId));
		}
	}

	/**
	 * 下级渠道
	 */
	private void handlerDistributeSub(UserDistributeSub userDistributeSub, UserDistribute userDistribute) {
		if (userDistributeSub != null) {
			userDistributeSub.setSubUserId(userDistribute.getUserId());
			if (userDistributeSub.getUserId() == null) {
				throw BusinessRuntimeException.getInstance("请选择对应的上级渠道..");
			}
			if (userDistributeSub.getUserId().equals(userDistribute.getUserId())) {
				throw BusinessRuntimeException.getInstance("不能选择自己作为上级渠道");
			}
			UserDistribute superUser = userDistributeMapper.selectOne(Wrappers.lambdaQuery(UserDistribute.class)
					.eq(UserDistribute::getUserId, userDistributeSub.getUserId())
					.eq(UserDistribute::getDeleted, 1)
					.last("limit 1"));
			if (superUser == null) {
				throw BusinessRuntimeException.getInstance("上级渠道不存在");
			}
			userDistributeSub.setDistributeId(superUser.getId());
			userDistributeSub.setSubDistributeId(userDistribute.getId());
			if (userDistributeSub.getId() == null) {
				try {
					userDistributeSubMapper.insert(userDistributeSub);
				} catch (DuplicateKeyException e) {
				}
			} else {
				userDistributeSubMapper.updateById(userDistributeSub);
			}
		}else {
			if (userDistributeSubMapper.selectCount(Wrappers.lambdaQuery(UserDistributeSub.class)
					.eq(UserDistributeSub::getSubUserId, userDistribute.getUserId()))>0) {
				userDistributeSubMapper.delete(Wrappers.lambdaQuery(UserDistributeSub.class)
						.eq(UserDistributeSub::getSubUserId, userDistribute.getUserId()));
			}
		}
	}

	private void setDistributePopularizeCode(Long distributeId, Long userId) {
		CouponDistributePopularize couponDistributePopularize = couponDistributePopularizeMapper.selectOne(Wrappers.lambdaQuery(CouponDistributePopularize.class)
				.eq(CouponDistributePopularize::getCouponId, Constant.GENERAL_POPULARIZE_COUPON_ID)
				.eq(CouponDistributePopularize::getUserId, userId)
				.eq(CouponDistributePopularize::getDeleted, 1)
				.eq(CouponDistributePopularize::getIsGeneral, 1)
				.last("limit 1"));
		if (couponDistributePopularize != null) {
			//先删除
			couponDistributePopularize.setDeleted(false);
			couponDistributePopularizeMapper.updateById(couponDistributePopularize);

			//后升级
			CouponDistributePopularize newPopularizeCode = new CouponDistributePopularize();
			newPopularizeCode.setDistributeId(distributeId);
			newPopularizeCode.setExCode(couponDistributePopularize.getExCode());
			newPopularizeCode.setCouponId(Constant.DISTRIBUTE_POPULARIZE_COUPON_ID);
			couponDistributePopularizeMapper.insert(newPopularizeCode);
		}
	}
}
