package com.cyksj.service.distribute.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.UserDistributeSpecialMapper;
import com.cyksj.mapper.UserRenewChangeTicketRecordMapper;
import com.cyksj.mapper.manage.distribute.UserBusinessDefaultRateConfigMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeBusinessOrderDonRecordMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeBusinessRateMapper;
import com.cyksj.mapper.shop.YhShopUserDistributeBusinessOrderDonRecordMapper;
import com.cyksj.model.entity.*;
import com.cyksj.redis.RedisService;
import com.cyksj.service.distribute.UserBusinessFrontService;
import com.ejlchina.searcher.BeanSearcher;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/*
 *项目名: netflix
 *文件名: UserBusinessFrontServiceImpl
 *创建者: JavaZou
 *创建时间:2023/3/23 14:20
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserBusinessFrontServiceImpl implements UserBusinessFrontService {
	private final BeanSearcher beanSearcher;

	private final UserDistributeBusinessRateMapper userDistributeBusinessRateMapper;

	private final OrderDonMapper orderDonMapper;

	private final UserDistributeBusinessOrderDonRecordMapper businessOrderDonRecordMapper;

	private final UserRenewChangeTicketRecordMapper renewChangeTicketRecordMapper;

	private final RedisService redisService;

	private final UserBusinessDefaultRateConfigMapper defaultRateConfigMapper;

	private final UserDistributeSpecialMapper userDistributeSpecialMapper;

	private final YhShopUserDistributeBusinessOrderDonRecordMapper yhShopBusinessOrderDonRecordMapper;

	@Override
	public void taskDistributeRateBenefits(Long sharedId, Long businessId, Integer goodsType, OrderDon order, Integer distributeRate) {
		LambdaQueryWrapper<UserDistributeBusinessRate> wrapper = Wrappers.lambdaQuery(UserDistributeBusinessRate.class)
				.eq(UserDistributeBusinessRate::getBusinessId, businessId)
				.eq(UserDistributeBusinessRate::getGoodsId, order.getGoodsId())
				.last("limit 1");
		if (goodsType == 1) {
			wrapper.eq(UserDistributeBusinessRate::getSkuId, order.getSkuId());
		}
		UserDistributeBusinessRate businessRate = userDistributeBusinessRateMapper.selectOne(wrapper);
		if (businessRate == null) {
			businessRate = new UserDistributeBusinessRate();
			//未配置默认 商务默认首单5
			businessRate.setFirstOrderRate(5);
		}
		//06-21 奈飞平台商务比例特殊处理
		UserDistributeSpecial userDistributeSpecial = userDistributeSpecialMapper.selectOne(Wrappers.lambdaQuery(UserDistributeSpecial.class)
				.eq(UserDistributeSpecial::getSkuId, order.getSkuId())
				.eq(UserDistributeSpecial::getSharedId, sharedId)
				.eq(UserDistributeSpecial::getBusinessId, businessId)
				.last("limit 1"));
		if (userDistributeSpecial != null) {
			businessRate.setFirstOrderRate(userDistributeSpecial.getFirstRate());
			businessRate.setRenewOrderRate(userDistributeSpecial.getRenewRate());
		}
		if (businessRate != null) {
			if (order.getOrderType() == 1) {
				//实物商务分销提成 无首单
				if (goodsType != 1) {
					UserDistributeBusinessOrderDonRecord record = saveBusinessTakeMoneyRecord(order, businessId, sharedId, businessRate.getFirstOrderRate(), null, distributeRate);
					if (record == null) {
						return;
					}
					businessOrderDonRecordMapper.insert(record);
					log.info("开始给商务人员:{}分配分销人:{}分销的用户:{}实物:{}提成", businessId, sharedId, order.getUserId(), order.getId());
					return;
				}
				//首单
				log.info("商务首单orderId:{}分销分配提成开始", order.getId());
				//用户之前是否下过单
				Integer count = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
						.eq(OrderDon::getUserId, order.getUserId())
						.ne(OrderDon::getId, order.getId()).notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
				if (count == 0) {
					//是否享受过该用户带来的首单 提成
					UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
							.eq(UserDistributeBusinessOrderDonRecord::getBusinessId, businessId)
							.eq(UserDistributeBusinessOrderDonRecord::getUserId, order.getUserId())
							.eq(UserDistributeBusinessOrderDonRecord::getOrderType, 1)
							.eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
							.last("limit 1"));
					if (record == null) {
						try {
							boolean isSuccess = redisService.setNx(RedisService.key.BUSINESS_FIRST_ORDER_USER_KEY.getNameFormat(order.getUserId()), businessId, RedisService.key.BUSINESS_FIRST_ORDER_USER_KEY.getTimeout());
							if (isSuccess) {
								//首单虚物规格 提成
								record = saveBusinessTakeMoneyRecord(order, businessId, sharedId, businessRate.getFirstOrderRate(), null, distributeRate);
								if (record == null) {
									return;
								}
								if (record.getTakeMoney().compareTo(BigDecimal.ZERO) == 0) {
									return;
								}
								businessOrderDonRecordMapper.insert(record);
								log.info("开始给商务人员:{}分配分销人:{}分销的用户:{}首单:{}提成", businessId, sharedId, order.getUserId(), order.getId());
								redisService.del(RedisService.key.BUSINESS_FIRST_ORDER_USER_KEY.getNameFormat(order.getUserId()));
							}
						} catch (DuplicateKeyException e) {
							log.error("商务:{}重复获取分销人:{}分销的用户:{}首单:{}提成", businessId, businessId, order.getUserId(), order.getId());
						}
					}
				}
			}
			//续费
//			if (order.getOrderType() == 2) {
//				log.info("商务首单续费分销分配提成开始");
//				//是否享受过该用户首单 提成
//				UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
//						.eq(UserDistributeBusinessOrderDonRecord::getBusinessId, businessId)
//						.eq(UserDistributeBusinessOrderDonRecord::getUserId, order.getUserId())
//						.eq(UserDistributeBusinessOrderDonRecord::getOrderType, 1)
//						.eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
//						.last("limit 1"));
//				if (record != null) {
//					log.info("开始给商务人员:{}分配用户:{}首单续费提成", businessId, order.getUserId());
//					//是否更换过车票规格座位号
//					Long preRelationId = record.getPreRelationId();
//					Long relationId = order.getRelationId();
//					if (relationId.equals(preRelationId)) {
//						try {
//							//分配首单续费提成
//							record = saveBusinessTakeMoneyRecord(order, businessId, sharedId, null, businessRate.getRenewOrderRate(), distributeRate);
//							if (record == null) {
//								return;
//							}
//							businessOrderDonRecordMapper.insert(record);
//							log.info("开始给商务人员:{}分配分销人:{}分销的用户:{}续费首单:{}提成", businessId, sharedId, order.getUserId(), order.getId());
//						} catch (DuplicateKeyException e) {
//							log.error("商务:{}重复获取分销人:{}分销的用户:{}续费首单:{}提成", businessId, businessId, order.getUserId(), order.getId());
//						}
//					} else {
//						UserRenewChangeTicketRecord renewChangeTicketRecord = renewChangeTicketRecordMapper.selectOne(Wrappers.lambdaQuery(UserRenewChangeTicketRecord.class)
//								.eq(UserRenewChangeTicketRecord::getUserId, order.getUserId())
//								.eq(UserRenewChangeTicketRecord::getAfterRelationId, relationId)
//								.last("limit 1"));
//						if (renewChangeTicketRecord != null && renewChangeTicketRecord.getPreRelationId().equals(preRelationId)) {
//							try {
//								//分配首单续费更换车位后提成
//								record = saveBusinessTakeMoneyRecord(order, businessId, sharedId, null, businessRate.getRenewOrderRate(), distributeRate);
//								if (record == null) {
//									return;
//								}
//								businessOrderDonRecordMapper.insert(record);
//								log.info("开始给商务人员:{}分配分销人:{}分销的用户:{}续费首单:{}更换后车位提成", businessId, sharedId, order.getUserId(), order.getId());
//							} catch (DuplicateKeyException e) {
//								log.error("商务:{}重复获取分销人:{}分销的用户:{}续费首单:{}更换后车位提成", businessId, businessId, order.getUserId(), order.getId());
//							}
//						}
//					}
//
//				}
//			}
		}
	}

	/**
	 * 店铺商务提成
	 */
	@Override
	public void taskYhShopDistributeRateBenefits(Long shopUserId, Long businessId, Integer goodsType, OrderDon order, Integer distributeRate) {
		LambdaQueryWrapper<UserDistributeBusinessRate> wrapper = Wrappers.lambdaQuery(UserDistributeBusinessRate.class)
				.eq(UserDistributeBusinessRate::getBusinessId, businessId)
				.eq(UserDistributeBusinessRate::getGoodsId, order.getGoodsId())
				.last("limit 1");
		if (goodsType == 1) {
			wrapper.eq(UserDistributeBusinessRate::getSkuId, order.getSkuId());
		}
		//和渠道商务用一套提成比例
		UserDistributeBusinessRate businessRate = userDistributeBusinessRateMapper.selectOne(wrapper);
		//06-21 奈飞平台商务比例特殊处理
		UserDistributeSpecial userDistributeSpecial = userDistributeSpecialMapper.selectOne(Wrappers.lambdaQuery(UserDistributeSpecial.class)
				.eq(UserDistributeSpecial::getSkuId, order.getSkuId())
				.eq(UserDistributeSpecial::getSharedId, shopUserId)
				.eq(UserDistributeSpecial::getBusinessId, businessId)
				.last("limit 1"));
		if (userDistributeSpecial != null) {
			businessRate.setFirstOrderRate(userDistributeSpecial.getFirstRate());
			businessRate.setRenewOrderRate(userDistributeSpecial.getRenewRate());
		}
		if (businessRate != null) {
			if (order.getOrderType() == 1) {
				//实物商务分销提成 无首单
				if (goodsType != 1) {
					YhShopUserDistributeBusinessOrderDonRecord record = saveYhShopBusinessTakeMoneyRecord(order, businessId, shopUserId, businessRate.getFirstOrderRate(), null, distributeRate);
					if (record == null) {
						return;
					}
					yhShopBusinessOrderDonRecordMapper.insert(record);
					log.info("开始给店铺商务人员:{}分配分销人:{}分销的用户:{}实物:{}提成", businessId, shopUserId, order.getUserId(), order.getId());
					return;
				}
				//首单
				log.info("店铺商务首单orderId:{}分销分配提成开始", order.getId());
				//用户之前是否下过单
				Integer count = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
						.eq(OrderDon::getUserId, order.getUserId())
						.ne(OrderDon::getId, order.getId()).notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
				if (count == 0) {
					//是否享受过该用户带来的首单 提成
					YhShopUserDistributeBusinessOrderDonRecord record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
							.eq(YhShopUserDistributeBusinessOrderDonRecord::getBusinessId, businessId)
							.eq(YhShopUserDistributeBusinessOrderDonRecord::getUserId, order.getUserId())
							.eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderType, 1)
							.eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
							.last("limit 1"));
					if (record == null) {
						try {
							boolean isSuccess = redisService.setNx(RedisService.key.BUSINESS_FIRST_ORDER_USER_KEY.getNameFormat(order.getUserId()), businessId, RedisService.key.BUSINESS_FIRST_ORDER_USER_KEY.getTimeout());
							if (isSuccess) {
								//首单虚物规格 提成
								record = saveYhShopBusinessTakeMoneyRecord(order, businessId, shopUserId, businessRate.getFirstOrderRate(), null, distributeRate);
								if (record == null) {
									return;
								}
								yhShopBusinessOrderDonRecordMapper.insert(record);
								log.info("开始给店铺商务人员:{}分配分销人:{}分销的用户:{}首单:{}提成", businessId, shopUserId, order.getUserId(), order.getId());
								redisService.del(RedisService.key.BUSINESS_FIRST_ORDER_USER_KEY.getNameFormat(order.getUserId()));
							}
						} catch (DuplicateKeyException e) {
							log.error("店铺商务:{}重复获取分销人:{}分销的用户:{}首单:{}提成", businessId, businessId, order.getUserId(), order.getId());
						}
					}
				}
			}
			//续费
			if (order.getOrderType() == 2) {
				log.info("店铺商务首单续费分销分配提成开始");
				//是否享受过该用户首单 提成
				YhShopUserDistributeBusinessOrderDonRecord record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
						.eq(YhShopUserDistributeBusinessOrderDonRecord::getBusinessId, businessId)
						.eq(YhShopUserDistributeBusinessOrderDonRecord::getUserId, order.getUserId())
						.eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderType, 1)
						.eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
						.last("limit 1"));
				if (record != null) {
					log.info("开始给店铺商务人员:{}分配用户:{}首单续费提成", businessId, order.getUserId());
					//是否更换过车票规格座位号
					Long preRelationId = record.getPreRelationId();
					Long relationId = order.getRelationId();
					if (relationId.equals(preRelationId)) {
						try {
							//分配首单续费提成
							record = saveYhShopBusinessTakeMoneyRecord(order, businessId, shopUserId, null, businessRate.getRenewOrderRate(), distributeRate);
							if (record == null) {
								return;
							}
							yhShopBusinessOrderDonRecordMapper.insert(record);
							log.info("开始给店铺商务人员:{}分配分销人:{}分销的用户:{}续费首单:{}提成", businessId, shopUserId, order.getUserId(), order.getId());
						} catch (DuplicateKeyException e) {
							log.error("店铺商务:{}重复获取分销人:{}分销的用户:{}续费首单:{}提成", businessId, businessId, order.getUserId(), order.getId());
						}
					} else {
						UserRenewChangeTicketRecord renewChangeTicketRecord = renewChangeTicketRecordMapper.selectOne(Wrappers.lambdaQuery(UserRenewChangeTicketRecord.class)
								.eq(UserRenewChangeTicketRecord::getUserId, order.getUserId())
								.eq(UserRenewChangeTicketRecord::getAfterRelationId, relationId)
								.last("limit 1"));
						if (renewChangeTicketRecord != null && renewChangeTicketRecord.getPreRelationId().equals(preRelationId)) {
							try {
								//分配首单续费更换车位后提成
								record = saveYhShopBusinessTakeMoneyRecord(order, businessId, shopUserId, null, businessRate.getRenewOrderRate(), distributeRate);
								if (record == null) {
									return;
								}
								yhShopBusinessOrderDonRecordMapper.insert(record);
								log.info("开始给店铺商务人员:{}分配分销人:{}分销的用户:{}续费首单:{}更换后车位提成", businessId, shopUserId, order.getUserId(), order.getId());
							} catch (DuplicateKeyException e) {
								log.error("店铺商务:{}重复获取分销人:{}分销的用户:{}续费首单:{}更换后车位提成", businessId, businessId, order.getUserId(), order.getId());
							}
						}
					}

				}
			}
		}
	}


	/**
	 * 保存商务分配提成记录
	 */
	public UserDistributeBusinessOrderDonRecord saveBusinessTakeMoneyRecord(OrderDon order, Long businessId, Long sharedId, Integer firstOrderRate, Integer renewOrderRate, Integer distributeRate) {
		UserBusinessDefaultRateConfig defaultGoodsRateConfig = defaultRateConfigMapper.selectOne(Wrappers.lambdaQuery(UserBusinessDefaultRateConfig.class)
				.eq(UserBusinessDefaultRateConfig::getGoodsId, order.getGoodsId()).last("limit 1"));
		if (defaultGoodsRateConfig == null) {
			log.info("系统默认商务分销配置未配置,businessId:{},orderId:{}", businessId, order.getId());
			return null;
		}
		UserDistributeBusinessOrderDonRecord record = new UserDistributeBusinessOrderDonRecord();
		record.setBusinessId(businessId);
		record.setUserId(order.getUserId());
		record.setSharedId(sharedId);
		record.setOrderType(order.getOrderType());
		record.setOrderCreatedTime(order.getCreatedTime());
		record.setOrderId(order.getId());
		record.setPreRelationId(order.getRelationId());
		//是否超过默认配置平台比例
		Integer defaultGoodsRate = defaultGoodsRateConfig.getRate();
		//首单提成比例
		BigDecimal orderMoney = order.getDsMoney();
		BigDecimal takeMoney = BigDecimal.ZERO;
		if (firstOrderRate != null) {
			if (distributeRate > defaultGoodsRate) {
				if (defaultGoodsRateConfig.getIsPlatPay()) {
					log.info("首单,平台承担商务businessId:{}配置分销者sharedId:{}超过平台goodsId:{}标准分销比例:{}", businessId, sharedId, order.getGoodsId(), defaultGoodsRate);
				} else {
					firstOrderRate -= distributeRate - defaultGoodsRate;
					log.info("商务businessId:{}配置分销者sharedId:{}比例超过标准比例,可获取首单提成比例为:{}", businessId, sharedId, firstOrderRate);
					if (firstOrderRate <= 0) {
						log.info("商务businessId:{}获得分销者sharedId:{}首单提成比例不大于0", businessId, sharedId);
						return null;
					}
				}
			}
			record.setRate(firstOrderRate);
			BigDecimal firstRate = BigDecimal.valueOf(firstOrderRate).divide(BigDecimal.valueOf(100));
			takeMoney = orderMoney.multiply(firstRate);
		}
		if (renewOrderRate != null) {
			if (distributeRate > defaultGoodsRate) {
				if (defaultGoodsRateConfig.getIsPlatPay()) {
					log.info("首单续费,平台承担商务businessId:{}配置分销者sharedId:{}超过平台goodsId:{}标准分销比例:{}", businessId, sharedId, order.getGoodsId(), defaultGoodsRate);
				} else {
					renewOrderRate -= distributeRate - defaultGoodsRate;
					log.info("商务businessId:{}配置分销者sharedId:{}比例超过标准比例,可获取首单续费提成比例为:{}", businessId, sharedId, renewOrderRate);
					if (renewOrderRate <= 0) {
						log.info("商务businessId:{}获得分销者sharedId:{}首单续费提成比例不大于0", businessId, sharedId);
						return null;
					}
				}
			}
			record.setRate(renewOrderRate);
			BigDecimal renewRate = BigDecimal.valueOf(renewOrderRate).divide(BigDecimal.valueOf(100));
			takeMoney = orderMoney.multiply(renewRate);
		}
		record.setTakeMoney(takeMoney);
		return record;
	}

	/**
	 * 保存店铺商务分配提成记录
	 */
	public YhShopUserDistributeBusinessOrderDonRecord saveYhShopBusinessTakeMoneyRecord(OrderDon order, Long businessId, Long shopUserId, Integer firstOrderRate, Integer renewOrderRate, Integer distributeRate) {
		UserBusinessDefaultRateConfig defaultGoodsRateConfig = defaultRateConfigMapper.selectOne(Wrappers.lambdaQuery(UserBusinessDefaultRateConfig.class)
				.eq(UserBusinessDefaultRateConfig::getGoodsId, order.getGoodsId()).last("limit 1"));
		if (defaultGoodsRateConfig == null) {
			log.info("系统默认商务分销配置未配置,businessId:{},orderId:{}", businessId, order.getId());
			return null;
		}
		YhShopUserDistributeBusinessOrderDonRecord record = new YhShopUserDistributeBusinessOrderDonRecord();
		record.setBusinessId(businessId);
		record.setUserId(order.getUserId());
		record.setShopUserId(shopUserId);
		record.setOrderType(order.getOrderType());
		record.setOrderCreatedTime(order.getCreatedTime());
		record.setOrderId(order.getId());
		record.setPreRelationId(order.getRelationId());
		//是否超过默认配置平台比例
		Integer defaultGoodsRate = defaultGoodsRateConfig.getRate();
		//首单提成比例
		BigDecimal orderMoney = order.getMoney();
		BigDecimal takeMoney = BigDecimal.ZERO;
		if (firstOrderRate != null) {
			if (distributeRate > defaultGoodsRate) {
				if (defaultGoodsRateConfig.getIsPlatPay()) {
					log.info("首单,平台承担商务businessId:{}配置分销者sharedId:{}超过平台goodsId:{}标准分销比例:{}", businessId, shopUserId, order.getGoodsId(), defaultGoodsRate);
				} else {
					firstOrderRate -= distributeRate - defaultGoodsRate;
					log.info("商务businessId:{}配置分销者sharedId:{}比例超过标准比例,可获取首单提成比例为:{}", businessId, shopUserId, firstOrderRate);
					if (firstOrderRate <= 0) {
						log.info("商务businessId:{}获得分销者sharedId:{}首单提成比例不大于0", businessId, shopUserId);
						return null;
					}
				}
			}
			record.setRate(firstOrderRate);
			BigDecimal firstRate = BigDecimal.valueOf(firstOrderRate).divide(BigDecimal.valueOf(100));
			takeMoney = orderMoney.multiply(firstRate);
		}
		if (renewOrderRate != null) {
			if (distributeRate > defaultGoodsRate) {
				if (defaultGoodsRateConfig.getIsPlatPay()) {
					log.info("首单续费,平台承担商务businessId:{}配置分销者sharedId:{}超过平台goodsId:{}标准分销比例:{}", businessId, shopUserId, order.getGoodsId(), defaultGoodsRate);
				} else {
					renewOrderRate -= distributeRate - defaultGoodsRate;
					log.info("商务businessId:{}配置分销者sharedId:{}比例超过标准比例,可获取首单续费提成比例为:{}", businessId, shopUserId, renewOrderRate);
					if (renewOrderRate <= 0) {
						log.info("商务businessId:{}获得分销者sharedId:{}首单续费提成比例不大于0", businessId, shopUserId);
						return null;
					}
				}
			}
			record.setRate(renewOrderRate);
			BigDecimal renewRate = BigDecimal.valueOf(renewOrderRate).divide(BigDecimal.valueOf(100));
			takeMoney = orderMoney.multiply(renewRate);
		}
		record.setTakeMoney(takeMoney);
		return record;
	}
}
