package com.cyksj.service.shop.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.mapper.GoodsDonMapper;
import com.cyksj.mapper.manage.distribute.UserDistributeSharedMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopUserDistributeSharedMapper;
import com.cyksj.mapper.shop.*;
import com.cyksj.model.entity.*;
import com.cyksj.service.distribute.UserBusinessFrontService;
import com.cyksj.service.shop.YhShopDistributeService;
import com.cyksj.service.user.UserBenefitsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/*
 *项目名: yhlxj
 *文件名: YhShopDistributeServiceImpl
 *创建者: JavaZou
 *创建时间:2023/9/20 15:30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class YhShopDistributeServiceImpl implements YhShopDistributeService {
	private final YhShopUserDistributeSharedMapper yhShopUserDistributeSharedMapper;

	private final YhShopMapper yhShopMapper;

	private final YhShopUserPlatDistributeRateMapper yhShopUserPlatDistributeRateMapper;

	private final YhShopDistributeWaitingSendPointsMapper yhShopDistributeWaitingSendPointsMapper;

	private final UserBusinessFrontService userBusinessFrontService;

	private final UserBenefitsService userBenefitsService;

	private final GoodsDonMapper goodsDonMapper;

	private final UserDistributeSharedMapper userDistributeSharedMapper;

	private final UserMirrorShopMapper userMirrorShopMapper;

	private final UserMirrorShopUserDistributeSharedMapper userMirrorShopUserDistributeSharedMapper;
	@Override
	public void distributeWaitingSendPointsRecord(OrderDon order) {
		BigDecimal orderMoney = order.getMoney();
		if (orderMoney.compareTo(BigDecimal.ZERO) == 0) {
			return;
		}
		BigDecimal returnMoney;
		Long businessId;
		YhShop yhShop = yhShopMapper.selectById(order.getYhsId());
		if (yhShop == null) {
			log.info("订单orderId:{}店铺yhs_id:{}对应的店铺不存在", order.getId(), order.getYhsId());
			return;
		}
		if (order.getUserId().equals(yhShop.getUserId())) {
			log.info("店主:{}自购订单orderId:{}不产生提成", order.getYhsId(), order.getId());
			return;
		}
		GoodsDon goodsDon = goodsDonMapper.selectOne(Wrappers.lambdaQuery(GoodsDon.class)
				.eq(GoodsDon::getId, order.getGoodsId()).last("limit 1"));
		if (goodsDon == null || !goodsDon.getIsDistribute()) {
			log.info("店铺订单orderId:{}对应平台goodsId:{}不存在或已不参与分成比例", order.getId(), order.getGoodsId());
			return;
		}
		Long shopUserId = yhShop.getUserId();
		YhShopDistributeWaitingSendPoints distributeWaitingSendPoints = new YhShopDistributeWaitingSendPoints();
		distributeWaitingSendPoints.setOrderId(order.getId());
		distributeWaitingSendPoints.setUserId(order.getUserId());

		distributeWaitingSendPoints.setShopUserId(shopUserId);
		//是否配置了对应平台比例
		YhShopUserPlatDistributeRate yhShopUserPlatDistributeRate = yhShopUserPlatDistributeRateMapper.selectOne(Wrappers.lambdaQuery(YhShopUserPlatDistributeRate.class)
				.eq(YhShopUserPlatDistributeRate::getUserId, shopUserId)
				.eq(YhShopUserPlatDistributeRate::getGoodsId, order.getGoodsId()).last("limit 1"));
		Integer rate = null;
		if (yhShopUserPlatDistributeRate == null) {
			log.info("未配置店铺主userId:{}对应平台goodsId:{}的比例,走商品通用比例", shopUserId, order.getGoodsId());
		} else {
			rate = yhShopUserPlatDistributeRate.getRate();
		}
		if (rate == null) {
			//未配置比例 默认使用 平台的分销比例
			rate = goodsDon.getRate();
		}
		if (rate == null || rate <= 0) {
			log.info("配置店铺主userId:{}对应平台goodsId:{}的比例为0", shopUserId, order.getGoodsId());
			return;
		}
		returnMoney = orderMoney.multiply(BigDecimal.valueOf(rate)).divide(BigDecimal.valueOf(100));
		distributeWaitingSendPoints.setMoney(returnMoney);
		distributeWaitingSendPoints.setSendStatus(YhShopDistributeWaitingSendPoints.Status.waiting);
		distributeWaitingSendPoints.setSendTime(DateUtil.offsetDay(order.getPayTime(), 3));
		distributeWaitingSendPoints.setRate(rate);
		distributeWaitingSendPoints.setSkuId(order.getSkuId());
		yhShopDistributeWaitingSendPointsMapper.insert(distributeWaitingSendPoints);

		//对应商务
		businessId = yhShop.getBusinessId();
		if (businessId != null) {
			userBusinessFrontService.taskYhShopDistributeRateBenefits(shopUserId, businessId, 1, order, rate);
		}
	}

	@Override
	public void deductDsMoney(OrderDon orderDon) {
		if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
			YhShopDistributeWaitingSendPoints distributeWaitingSendPoints = yhShopDistributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(YhShopDistributeWaitingSendPoints.class).eq(YhShopDistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
			if (distributeWaitingSendPoints != null) {
				BigDecimal money = orderDon.getMoney();
				BigDecimal refundMoney = orderDon.getRefundMoney();
				//已发送 发送中 部分 全额退款
				YhShopDistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
				BigDecimal take_money = distributeWaitingSendPoints.getMoney();
				if (sendStatus == YhShopDistributeWaitingSendPoints.Status.waiting) {
					if (refundMoney.compareTo(money) == 0) {
						//待发送状态 全额退款
						distributeWaitingSendPoints.setSendStatus(YhShopDistributeWaitingSendPoints.Status.close);
						distributeWaitingSendPoints.setRefundMoney(take_money);
						distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
						yhShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
						return;
					}
					Integer rate = distributeWaitingSendPoints.getRate();
					if (rate > 0) {
						BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
						distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
						//剩余积分
						distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
						yhShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
					}
				} else if (sendStatus == YhShopDistributeWaitingSendPoints.Status.success) {
					//已发送的提成 部分退款 全额退款 需要扣除用户积分
					//扣除固定推广者积分
					if (refundMoney.compareTo(money) == 0) {
						//扣除店铺主 已有的提成金额
						userBenefitsService.deductYhShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), take_money);
						distributeWaitingSendPoints.setRefundMoney(take_money);
						distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
						distributeWaitingSendPoints.setSendStatus(YhShopDistributeWaitingSendPoints.Status.close);
						yhShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
						return;
					}
					Integer rate = distributeWaitingSendPoints.getRate();
					if (rate > 0) {
						BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
						//扣除店铺主 已有的提成金额
						userBenefitsService.deductYhShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), needDeductMoney);
						//部分退款
						distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
						distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
						yhShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
					}

				}
			}
		}
	}

	@Override
	public void saveDistributionInvitation(String customId, Long userId, Integer cmt) {
		customId = customId.trim();
		if (cmt != null && cmt == 2) {
			UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
					.eq(UserMirrorShop::getCustomId, customId)
					.last("limit 1"));
			if (userMirrorShop != null && userMirrorShop.getStatus()) {
				log.info("用户镜像店铺shopUserId:{}新用户uid:{}注册关联上下级", userMirrorShop.getUserId(), userId);
				UserMirrorShopUserDistributeShared shopUserDistributeShared = new UserMirrorShopUserDistributeShared();
				shopUserDistributeShared.setShopUserId(userMirrorShop.getUserId());
				shopUserDistributeShared.setUserId(userId);
				userMirrorShopUserDistributeSharedMapper.insert(shopUserDistributeShared);
			}
			return;
		}

		YhShop yhShop = yhShopMapper.selectOne(Wrappers.lambdaQuery(YhShop.class).eq(YhShop::getCustomId, customId).last("limit 1"));
		if (yhShop.getVerifyStatus() != YhShop.Status.success) {
			return;
		}
		if (!yhShop.getStatus()) {
			return;
		}
		try {
			Long shopUserId = yhShop.getUserId();
			YhShopUserDistributeShared yhShopUserDistributeShared = new YhShopUserDistributeShared();
			yhShopUserDistributeShared.setShopUserId(shopUserId);
			yhShopUserDistributeShared.setUserId(userId);
			yhShopUserDistributeSharedMapper.insert(yhShopUserDistributeShared);

			//同步用户邀请关联 待优化 TODO
			UserDistributeShared userDistributeShared = new UserDistributeShared();
			userDistributeShared.setUserId(userId);
			userDistributeShared.setSharedId(shopUserId);
			userDistributeShared.setRemark("小店同步");
			userDistributeSharedMapper.insert(userDistributeShared);
		} catch (DuplicateKeyException e) {
		}
	}
}
