package com.cyksj.service.mange.usermirror.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.mirrorshop.*;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.DistributeApplyMoneyReq;
import com.cyksj.model.request.UserMirrorShopInfoApplyReq;
import com.cyksj.redis.RedisService;
import com.cyksj.service.mange.usermirror.UserMirrorCommonService;
import com.cyksj.service.order.OrderRefundService;
import com.cyksj.service.user.UserBenefitsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 项目名: yhlxj2
 * 文件名: UserMirrorCommonServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/10/23 15:25
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserMirrorCommonServiceImpl implements UserMirrorCommonService {

	private final UserMirrorShopDistributeMoneyApplyMapper moneyApplyMapper;

	private final UserMirrorShopMapper userMirrorShopMapper;

	private final UserMirrorShopApplyRecordMapper userMirrorShopApplyRecordMapper;

	private final RedisService redisService;

	private final UserBenefitsService userBenefitsService;

	private final UserMirrorShopFeeOrderDonMapper userMirrorShopFeeOrderDonMapper;

	private final OrderRefundService orderRefundService;

	private final UserMirrorShopDistributeWaitingSendPointsMapper waitingSendPointsMapper;

	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void verifyApplyMoney(DistributeApplyMoneyReq distributeApplyMoneyReq) {
		UserMirrorShopDistributeMoneyApply.Status status = UserMirrorShopDistributeMoneyApply.Status.checkStatus(distributeApplyMoneyReq.getVerifyStatus());
		if (status == null || status == UserMirrorShopDistributeMoneyApply.Status.verifying) {
			throw BusinessRuntimeException.getInstance("审核状态错误");
		}
		UserMirrorShopDistributeMoneyApply distributeMoneyApply = moneyApplyMapper.selectById(distributeApplyMoneyReq.getId());
		if (distributeMoneyApply == null) {
			throw BusinessRuntimeException.getInstance("提现记录不存在");
		}
		if (distributeMoneyApply.getVerifyStatus() != UserMirrorShopDistributeMoneyApply.Status.verifying) {
			throw BusinessRuntimeException.getInstance("该提现记录已处理,无法再进行审核");
		}
		distributeMoneyApply.setVerifyStatus(status);
		if (YhShopDistributeMoneyApply.Status.fail.name().equals(distributeApplyMoneyReq.getVerifyStatus()) && StrUtil.isEmpty(distributeApplyMoneyReq.getReason())) {
			throw BusinessRuntimeException.getInstance("拒绝原因为空");
		}
		if (YhShopDistributeMoneyApply.Status.fail.name().equals(distributeApplyMoneyReq.getVerifyStatus())) {
			distributeMoneyApply.setReason(distributeApplyMoneyReq.getReason());
			Long userId = distributeMoneyApply.getUserId();
			userBenefitsService.addMpMoney(userId, distributeMoneyApply.getMoney());
			log.info("镜像店铺提现审核失败,归还申请提现金额:{}至用户{}结束", distributeMoneyApply.getMoney().divide(BigDecimal.valueOf(100)), userId);
		}
		if (YhShopDistributeMoneyApply.Status.success.name().equals(distributeApplyMoneyReq.getVerifyStatus())) {
			distributeMoneyApply.setImg(distributeApplyMoneyReq.getImg());
		}
		moneyApplyMapper.updateById(distributeMoneyApply);

		if (distributeMoneyApply.getVerifyStatus() == UserMirrorShopDistributeMoneyApply.Status.fail) {
			String type = "mirrorShop";
			String key = String.format(RedisService.key.APPLY_MONEY_DAY_LIMIT_KEY.getName(), distributeMoneyApply.getUserId().toString(), type, distributeMoneyApply.getUserId());
			redisService.del(key);
		}
	}


	@Override
	public void updateVerifyImg(DistributeApplyMoneyReq distributeApplyMoneyReq) {
		Long id = distributeApplyMoneyReq.getId();
		String img = distributeApplyMoneyReq.getImg();
		if (id == null) {
			throw BusinessRuntimeException.getInstance("请选择对应的申请提现记录");
		}
		UserMirrorShopDistributeMoneyApply mirrorShopDistributeMoneyApply = moneyApplyMapper.selectById(id);
		if (mirrorShopDistributeMoneyApply == null) {
			throw BusinessRuntimeException.getInstance("请选择对应的申请提现记录");
		}
		if (StrUtil.isEmpty(img)) {
			throw BusinessRuntimeException.getInstance("请传入对应的审核图片");
		}
		if (mirrorShopDistributeMoneyApply.getVerifyStatus() != UserMirrorShopDistributeMoneyApply.Status.success) {
			throw BusinessRuntimeException.getInstance("该申请提现记录未审核成功");
		}
		mirrorShopDistributeMoneyApply.setImg(img);
		moneyApplyMapper.updateById(mirrorShopDistributeMoneyApply);
	}

	@Override
	public void refundUserMirrorShopFee(Long orderId) throws Exception {
		UserMirrorShopFeeOrderDon orderDon = userMirrorShopFeeOrderDonMapper.selectById(orderId);
		if (orderDon == null) {
			throw BusinessRuntimeException.getInstance("订单不存在");
		}
		if (orderDon.getStatus() != UserMirrorShopFeeOrderDon.Status.hasPayment) {
			throw BusinessRuntimeException.getInstance("订单状态错误");
		}
		String outRefundNo = orderRefundService.refundUserMirrorShopFee(orderDon);
		orderDon.setOutRefundNo(outRefundNo);
		orderDon.setStatus(UserMirrorShopFeeOrderDon.Status.refund);
		orderDon.setRefundMoney(orderDon.getMoney());

		UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getUserId, orderDon.getUserId())
				.last("limit 1"));
		if (userMirrorShop != null) {
			userMirrorShop.setStatus(false);
			userMirrorShopMapper.updateById(userMirrorShop);
		}
		userMirrorShopFeeOrderDonMapper.updateById(orderDon);

		//扣除提成
		UserMirrorShopDistributeWaitingSendPoints waitingSendPoints = waitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopDistributeWaitingSendPoints.class)
				.eq(UserMirrorShopDistributeWaitingSendPoints::getUserId, orderDon.getUserId())
				.eq(UserMirrorShopDistributeWaitingSendPoints::getType, 2)
				.last("limit 1"));
		if (waitingSendPoints != null) {
			if (waitingSendPoints.getSendStatus() == UserMirrorShopDistributeWaitingSendPoints.Status.waiting) {
				waitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.close);
				waitingSendPointsMapper.updateById(waitingSendPoints);
			} else if (waitingSendPoints.getSendStatus() == UserMirrorShopDistributeWaitingSendPoints.Status.success) {
				waitingSendPoints.setRefundMoney(waitingSendPoints.getMoney());
				userBenefitsService.deductUserMirrorShopTakeMoney(waitingSendPoints.getOrderId(), waitingSendPoints.getShopUserId(), waitingSendPoints.getMoney());
				waitingSendPointsMapper.updateById(waitingSendPoints);
			}
		}
	}

	@Override
	public void verifyUserMIrrorShopApply(UserMirrorShopInfoApplyReq applyReq) {
		UserMirrorShopApplyRecord userMirrorShopApplyRecord = userMirrorShopApplyRecordMapper.selectById(applyReq.getId());

		UserMirrorShopApplyRecord.Status status = applyReq.getVerifyStatus();
		if (status == UserMirrorShopApplyRecord.Status.fail && StrUtil.isEmpty(applyReq.getReason())) {
			throw BusinessRuntimeException.getInstance("请输入审核失败原因");
		}

		if (status == UserMirrorShopApplyRecord.Status.success) {
			UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
					.eq(UserMirrorShop::getUserId, userMirrorShopApplyRecord.getUserId())
					.last("limit 1"));

			userMirrorShop.setName(userMirrorShopApplyRecord.getName());
			userMirrorShop.setLogo(userMirrorShopApplyRecord.getLogo());
			userMirrorShopMapper.updateById(userMirrorShop);
		}
		userMirrorShopApplyRecord.setVerifyStatus(applyReq.getVerifyStatus());
		userMirrorShopApplyRecord.setReason(applyReq.getReason());
		userMirrorShopApplyRecordMapper.updateById(userMirrorShopApplyRecord);
	}
}
