package com.cyksj.service.order.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.constant.Constant;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.snowflake.Sequence;
import com.cyksj.common.util.Codec;
import com.cyksj.common.util.Jsons;
import com.cyksj.config.zfb.BaseZfbConfig;
import com.cyksj.mapper.UserMapper;
import com.cyksj.mapper.channel.ShopConfigMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopDistributeWaitingSendPointsMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopFeeOrderDonMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopSubUserMapper;
import com.cyksj.mapper.sys.SysConfigMapper;
import com.cyksj.model.dto.AliPayParams;
import com.cyksj.model.dto.UserMirrorShopDistributeConfigDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.AlipayOrderDonReq;
import com.cyksj.model.request.OrderAttach;
import com.cyksj.model.request.UserMirrorShopSubmitReq;
import com.cyksj.service.order.UserMirrorShopOrderService;
import com.cyksj.service.pay.AliPayCommonService;
import com.cyksj.service.sys.SysConfigService;
import com.cyksj.service.user.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * 项目名: yhlxj2
 * 文件名: UserMirrorShopOrderServiceImpl
 * 创建者: JavaZou
 * 创建时间:2024/10/25 17:08
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserMirrorShopOrderServiceImpl implements UserMirrorShopOrderService {
	private final SysConfigMapper sysConfigMapper;

	private final UserMirrorShopFeeOrderDonMapper feeOrderDonMapper;

	private final UserMapper userMapper;

	private final AliPayCommonService aliPayCommonService;

	private final ShopConfigMapper shopConfigMapper;

	private final UserMirrorShopMapper userMirrorShopMapper;

	private final UserService userService;

	private final static Sequence SEQUENCE = new Sequence(0);

	private final SysConfigService sysConfigService;

	private final UserMirrorShopDistributeWaitingSendPointsMapper userMirrorShopDistributeWaitingSendPointsMapper;

	private final UserMirrorShopSubUserMapper subUserMapper;

	@Override
	public UserMirrorShopFeeOrderDon submitOpenShop(UserMirrorShopSubmitReq shopSubmitReq) throws Exception {
		Long userId = shopSubmitReq.getUserId();
		String customId = shopSubmitReq.getCustomId();
		User user = userMapper.selectById(userId);
		Integer selectCount = feeOrderDonMapper.selectCount(Wrappers.lambdaQuery(UserMirrorShopFeeOrderDon.class)
				.eq(UserMirrorShopFeeOrderDon::getUserId, userId)
				.eq(UserMirrorShopFeeOrderDon::getStatus, UserMirrorShopFeeOrderDon.Status.hasPayment));
		if (selectCount > 0) {
			throw BusinessRuntimeException.getInstance("您已支付开店加盟费");
		}
		UserMirrorShopFeeOrderDon userMirrorShopFeeOrderDon = Optional.ofNullable(feeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopFeeOrderDon.class).eq(UserMirrorShopFeeOrderDon::getUserId, userId)
				.eq(UserMirrorShopFeeOrderDon::getStatus, UserMirrorShopFeeOrderDon.Status.noPayment)
				.last("limit 1"))).orElse(new UserMirrorShopFeeOrderDon());
		SysConfig sysConfig = sysConfigMapper.selectOne(Wrappers.lambdaQuery(SysConfig.class)
				.eq(SysConfig::getSysKey, Constant.MIRROR_SHOP_COMMISSION)
				.last("limit 1"));
		UserMirrorShopDistributeConfigDto userMirrorShopDistributeConfigDto = Jsons.parseObject(sysConfig.getSysValue(), UserMirrorShopDistributeConfigDto.class);
		BigDecimal fee = userMirrorShopDistributeConfigDto.getShopFee();
		if (userMirrorShopFeeOrderDon.getId() == null) {
			userMirrorShopFeeOrderDon = new UserMirrorShopFeeOrderDon();
			userMirrorShopFeeOrderDon.setOrderNo(SEQUENCE.nextId().toString());
			userMirrorShopFeeOrderDon.setStatus(UserMirrorShopFeeOrderDon.Status.noPayment);
			userMirrorShopFeeOrderDon.setUserId(userId);
			userMirrorShopFeeOrderDon.setType(UserMirrorShopFeeOrderDon.Type.ALI_PAY);
			userMirrorShopFeeOrderDon.setOpenId(user.getOpenId());
			feeOrderDonMapper.insert(userMirrorShopFeeOrderDon);
		}
		UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
				.eq(UserMirrorShop::getCustomId, customId)
				.last("limit 1"));
		if (userMirrorShop != null) {
			userMirrorShopFeeOrderDon.setMpId(userMirrorShop.getId());
		}
		userMirrorShopFeeOrderDon.setMoney(fee);
		feeOrderDonMapper.updateById(userMirrorShopFeeOrderDon);
		return userMirrorShopFeeOrderDon;
	}

	@Override
	public AliPayParams aliPay(AlipayOrderDonReq re, String productCode, String qrPayMode) throws Exception {
		return aliPayCommonService.openShopAliPay(re,productCode, qrPayMode);
	}

	@Override
	public void aliPayNotify(Map<String, String> params) throws Exception {
		//调用SDK验证签名
		String body = Codec.DoBase64.custom().setData(params.get("body")).decodeAsText();
		OrderAttach orderAttach = Jsons.parseObject(body, OrderAttach.class);
		Long oderId = orderAttach.getO();
		UserMirrorShopFeeOrderDon orderDon = feeOrderDonMapper.selectById(oderId);
		if (null == orderDon) {
			throw BusinessRuntimeException.getInstance("订单不存在.");
		}
		String appId = params.get("app_id");
		boolean signVerified = AlipaySignature.rsaCheckV1(params, shopConfigMapper.getByAppId(appId).getPublicKey(), BaseZfbConfig.charset, BaseZfbConfig.signType);
		if (!signVerified) {
			log.error("开店押金支付宝回调校验签名错误,自定义入参:{}", params.get("body"));
			throw BusinessRuntimeException.getInstance("开店押金支付宝回调校验签名错误");
		}
		String transactionId = params.get("trade_no");
		String payTimeStr = params.get("gmt_payment");
		//买家支付宝账号
		String buyerId = Optional.ofNullable(params.get("buyer_id")).orElse(params.get("buyer_open_id"));
		log.info("开店押金支付宝回调信息:{}", Jsons.toJson(params));
		if (!orderDon.getStatus().equals(UserMirrorShopFeeOrderDon.Status.noPayment) && !orderDon.getStatus().equals(UserMirrorShopFeeOrderDon.Status.close)) {
			log.info("开店押金支付宝已回调，重复修改状态 id:{}", orderDon.getId());
			return;
		}
		Date payTime = DateTime.now();
		if (StringUtils.isNotBlank(payTimeStr)) {
			payTime = DateUtil.parse(payTimeStr, "yyyy-MM-dd HH:mm:ss");
		}
		// 更改订单状态
		orderDon.setTransactionId(transactionId);
		orderDon.setPayTime(payTime);
		orderDon.setShopId(appId);
		orderDon.setType(UserMirrorShopFeeOrderDon.Type.ALI_PAY);
		orderDon.setBuyerId(buyerId);
		orderDon.setStatus(UserMirrorShopFeeOrderDon.Status.hasPayment);
		feeOrderDonMapper.updateById(orderDon);

		try {
			UserMirrorShop userMirrorShop = userMirrorShopMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShop.class)
					.eq(UserMirrorShop::getUserId, orderDon.getUserId())
					.last("limit 1"));
			if (userMirrorShop == null) {
				userMirrorShop = new UserMirrorShop();
				userMirrorShop.setUserId(orderDon.getUserId());
				userMirrorShop.setStatus(true);
				userMirrorShop.setLogo(Constant.USER_MIRROR_SHOP_DEFAULT_LOGO);
				userMirrorShopMapper.insert(userMirrorShop);
				//获取customId
				userService.getUserMirrorShopId(orderDon.getUserId());
			} else {
				if (!userMirrorShop.getStatus()) {
					userMirrorShop.setStatus(true);
					userMirrorShopMapper.updateById(userMirrorShop);
				}
			}
		} catch (DuplicateKeyException e) {

		}

		if (orderDon.getMpId() != null) {
			UserMirrorShop masterShop = userMirrorShopMapper.selectById(orderDon.getMpId());
			if (masterShop == null) {
				return;
			}
			log.info("用户：{}加盟店铺:{}订单:{}分销，发放提成", orderDon.getUserId(), masterShop.getName(), orderDon.getId());
			SysConfig config = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class)
					.eq(SysConfig::getSysKey, Constant.MIRROR_SHOP_COMMISSION)
					.last("limit 1"));
			UserMirrorShopDistributeConfigDto shopDistributeConfigDto = Jsons.parseObject(config.getSysValue(), UserMirrorShopDistributeConfigDto.class);
			Integer feeRate = shopDistributeConfigDto.getFeeRate();
			UserMirrorShopDistributeWaitingSendPoints waitingSendPoints = new UserMirrorShopDistributeWaitingSendPoints();
			waitingSendPoints.setOrderId(orderDon.getId());
			waitingSendPoints.setShopUserId(masterShop.getUserId());
			waitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.waiting);
			waitingSendPoints.setMoney(BigDecimal.valueOf(feeRate).divide(BigDecimal.valueOf(100)).multiply(orderDon.getMoney()));
			waitingSendPoints.setRate(feeRate);
			waitingSendPoints.setUserId(orderDon.getUserId());
			waitingSendPoints.setSendTime(DateUtil.offsetDay(orderDon.getPayTime(), 3));
			waitingSendPoints.setType(2);
			userMirrorShopDistributeWaitingSendPointsMapper.insert(waitingSendPoints);

			UserMirrorShopSubUser shopSubUser = new UserMirrorShopSubUser();
			shopSubUser.setUserId(masterShop.getUserId());
			shopSubUser.setSubUserId(orderDon.getUserId());
			shopSubUser.setOrderId(orderDon.getId());
			subUserMapper.insert(shopSubUser);
		}
	}
}
