package com.cyksj.service.pay.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayRequest;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.EnvCommonService;
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.common.util.StringUtil;
import com.cyksj.config.zfb.AliPayClientFactory;
import com.cyksj.config.zfb.BaseZfbConfig;
import com.cyksj.config.zfb.ZfbProductCode;
import com.cyksj.mapper.*;
import com.cyksj.mapper.channel.ShopConfigMapper;
import com.cyksj.mapper.mirrorshop.UserMirrorShopFeeOrderDonMapper;
import com.cyksj.mapper.order.OrderDonPostMapper;
import com.cyksj.mapper.vip.VipOrderDonMapper;
import com.cyksj.model.dto.AliPayParams;
import com.cyksj.model.dto.OrderPayBuilderDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.request.AlipayOrderDonReq;
import com.cyksj.model.request.OrderAttach;
import com.cyksj.service.pay.AliPayCommonService;
import com.cyksj.service.sys.SysConfigService;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/*
 *项目名: netflix
 *文件名: AliPayCommonServiceImpl
 *创建者: JavaZou
 *创建时间:2023/6/14 15:19
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AliPayCommonServiceImpl implements AliPayCommonService {
	private final RegisterOrderDonMapper registerOrderDonMapper;

	private final OrderDonMapper orderDonMapper;

	private final GoodsDonMapper goodsDonMapper;

	private final GoodsDonCategoryRelateMapper goodsDonCategoryRelateMapper;

	private final ShopConfigMapper shopConfigMapper;

	private final EnvCommonService envCommonService;

	private final SysConfigService sysConfigService;

	private final OrderDonPostMapper orderDonPostMapper;

	private final UpgradeOrderDonMapper	upgradeOrderDonMapper;

	private final UpgradePackageMapper upgradePackageMapper;

	private final GoodsWholesaleOrderDonMapper goodsWholesaleOrderDonMapper;

	private final GoodsWholesaleUserDepositMapper depositMapper;

	private final UserBenefitsOrderRecordMapper userBenefitsOrderRecordMapper;

	private final UserMirrorShopFeeOrderDonMapper feeOrderDonMapper;

	private final ZfbShopOrderDayLimitMapper zfbShopOrderDayLimitMapper;

	private final SpotifyUserUpgradeOrderMapper spotifyUserUpgradeOrderMapper;

	private final VipOrderDonMapper vipOrderDonMapper;

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

	@Override
	public AliPayParams unifiedPayRegister(Long orderId, String productCode, String payMode, String returnUrl) throws Exception {
		RegisterOrderDon orderDon = registerOrderDonMapper.selectById(orderId);
		Assert.notNull(orderDon, "订单不存在");
		if (StrUtil.isEmpty(productCode)) throw BusinessRuntimeException.getInstance("支付异常");
		//获取支付宝默认商户
		String shopId = sysConfigService.getDefaultShopConfigByType("zfb");
		orderDon.setShopId(shopId);
		orderDon.setType(RegisterOrderDon.Type.ALI_PAY);
		if (orderDon.getType() != RegisterOrderDon.Type.ALI_PAY) {
			orderDon.setType(RegisterOrderDon.Type.ALI_PAY);
		}
		registerOrderDonMapper.updateById(orderDon);
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, BaseZfbConfig.zfb_register_notify_url);
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode) && BaseZfbConfig.qrPayMode_redirect.equals(payMode)) {
			returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.zfb_register_login_return_url);
		}
		String subject = "注册服务";
		AliPayParams aliPayParams = builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getCreatedTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
		return aliPayParams;
	}

	@Override
	public AliPayParams unifiedPay(AlipayOrderDonReq re, String productCode, String payMode) throws Exception {
		Long orderId = re.getOrderId();
		String returnUrl = re.getReturnUrl();
		OrderDon orderDon = orderDonMapper.selectById(orderId);
		Boolean isWebPay = orderDon.getIsWebPay();
		if (ZfbProductCode.PC_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(true);
		}
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(false);
		}
		//设备 默认使用益路同行
		if (orderDon.getGoodsId() == 15) {
			orderDon.setShopId(ShopConfig.ZFB_DEFAULT_APP_ID);
		}
		String appId = orderDon.getShopId();
		if (StrUtil.isEmpty(appId)) {
			appId = getZfbDayLimitShopId(orderDon);
		}
		//若切换支付环境
		if (StrUtil.isNotBlank(orderDon.getShopId()) && isWebPay != orderDon.getIsWebPay()) {
			//当前支付宝商户 不支持所有环境 使用默认支付宝
			ZfbShopOrderDayLimit dayLimit = zfbShopOrderDayLimitMapper.selectOne(Wrappers.lambdaQuery(ZfbShopOrderDayLimit.class)
					.eq(ZfbShopOrderDayLimit::getAppId, orderDon.getShopId())
					.last("limit 1"));
			if (dayLimit != null && dayLimit.getScope() != 0) {
				appId = sysConfigService.getDefaultShopConfigByType("zfb");
				//恢复支付宝每日限单数
				zfbShopOrderDayLimitMapper.incrDayLimitRemainOrders(orderDon.getShopId());
				//恢复小时限单数
				zfbShopOrderDayLimitMapper.incrHourLimitRemainOrders(orderDon.getShopId());
			}
		}
		if (OrderDon.Type.ALI_PAY != orderDon.getType()) {
			orderDon.setType(OrderDon.Type.ALI_PAY);
		}
		orderDon.setShopId(appId);
		orderDonMapper.updateById(orderDon);
		String notifyPath = BaseZfbConfig.notifyUrl;
		Boolean isUserBenefits = re.getIsUserBenefits();
		String subject;
		if (isUserBenefits) {
			subject = orderDon.getGoodsId() == 15 ? "套餐权益" : "续费减免";
		} else {
			GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
			subject = goodsDon.getTitle().contains("ChatGPT") ? "AI订阅" : goodsDon.getTitle();
		}
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, notifyPath);
		//手机h5 跳转
		OrderDonPost orderDonPost = orderDonPostMapper.selectOne(Wrappers.lambdaQuery(OrderDonPost.class)
				.eq(OrderDonPost::getOrderId, orderId).last("limit 1"));
		//百度回传 跳转
		Boolean is_bdPost = false;
		if (orderDonPost != null && OrderDonPost.Type.BaiDu == orderDonPost.getType()) {
			is_bdPost = true;
		}
		if (StrUtil.isNotEmpty(returnUrl)) {
			log.info("支付宝支付成功返回地址：{}", returnUrl);
		}
		//是否在微信内支付 微信内支付宝支付后 支付宝回调页面不跳转
		Boolean isWx = Optional.ofNullable(re.getIsWx()).orElse(false);
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode) && !isWx) {
			if (is_bdPost) {
				//页面 拼接订单号,前端从url获取订单id.
				returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.SUCCESS_URL) + orderDon.getId();
			} else {
				if (StrUtil.isEmpty(returnUrl)) {
					//默认跳转页
					returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.DEFAULT_URL);
				}
			}
		}
		if (StrUtil.isNotEmpty(returnUrl)) {
			log.info("支付宝支付成功最终返回地址：{}", returnUrl);
		}
		AliPayParams aliPayParams = builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getCreatedTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
		return aliPayParams;
	}

	private ZfbShopOrderDayLimit getZfbShopOrdersDayLimit(Long goodsId, List<Integer> scope) {
		int hour = DateUtil.hour(DateTime.now(), true);
		//如果是ai订单 不分配给善缘
		Integer aiCount = goodsDonCategoryRelateMapper.selectCount(Wrappers.lambdaQuery(GoodsDonCategoryRelate.class)
				.eq(GoodsDonCategoryRelate::getCategory, 1)
				.eq(GoodsDonCategoryRelate::getGoodsId, goodsId));
		List<ZfbShopOrderDayLimit> orderDayLimits = null;
		//Ai订单 优先分配给崇宇
		if (aiCount > 0) {
			orderDayLimits = zfbShopOrderDayLimitMapper.selectList(Wrappers.lambdaQuery(ZfbShopOrderDayLimit.class)
					.le(ZfbShopOrderDayLimit::getHourStart, hour)
					.ge(ZfbShopOrderDayLimit::getHourEnd, hour)
					.gt(ZfbShopOrderDayLimit::getDayRemainOrders, 0)
					.gt(ZfbShopOrderDayLimit::getHourRemainOrders, 0)
					.eq(ZfbShopOrderDayLimit::getStatus, 1)
					.in(ZfbShopOrderDayLimit::getScope, scope)
					.eq(ZfbShopOrderDayLimit::getAppId, Constant.CY_SHOP_ID));
		}
		if (CollUtil.isEmpty(orderDayLimits)) {
			orderDayLimits = zfbShopOrderDayLimitMapper.selectList(Wrappers.lambdaQuery(ZfbShopOrderDayLimit.class)
					.le(ZfbShopOrderDayLimit::getHourStart, hour)
					.ge(ZfbShopOrderDayLimit::getHourEnd, hour)
					.gt(ZfbShopOrderDayLimit::getDayRemainOrders, 0)
					.gt(ZfbShopOrderDayLimit::getHourRemainOrders, 0)
					.eq(ZfbShopOrderDayLimit::getStatus, 1)
					.in(ZfbShopOrderDayLimit::getScope, scope)
					.ne(aiCount > 0, ZfbShopOrderDayLimit::getAppId, Constant.SY_SHOP_ID));
		}
		if (orderDayLimits.isEmpty()) {
			return null;
		}
		int randomIndex = RandomUtil.randomInt(orderDayLimits.size());
		ZfbShopOrderDayLimit dayLimit = orderDayLimits.get(randomIndex);
		Integer update = zfbShopOrderDayLimitMapper.decrRemainOrdersById(dayLimit.getId());
		if (update == 1) {
			return dayLimit;
		}
		for (ZfbShopOrderDayLimit orderDayLimit : orderDayLimits) {
			update = zfbShopOrderDayLimitMapper.decrRemainOrdersById(orderDayLimit.getId());
			if (update == 1) {
				return orderDayLimit;
			}
		}
		return null;
	}

	public AliPayParams builderPayParams(Long orderId, String orderNo, String shopId, BigDecimal money, Date orderCreatedTime, String subject, String productCode, String payMode, String notifyUrl, String returnUrl) throws Exception {
		OrderPayBuilderDto orderPayBuilderDto = new OrderPayBuilderDto();
		orderPayBuilderDto.setOrderId(orderId);
		orderPayBuilderDto.setMoney(money);
		orderPayBuilderDto.setOrderNo(orderNo);
		orderPayBuilderDto.setSubject(subject);
		orderPayBuilderDto.setOrderCreatedTime(orderCreatedTime);
		orderPayBuilderDto.setProductCode(productCode);
		orderPayBuilderDto.setPayMode(payMode);
		orderPayBuilderDto.setReturnUrl(returnUrl);
		orderPayBuilderDto.setNotifyUrl(notifyUrl);
		orderPayBuilderDto.setShopId(shopId);
		AliPayParams aliPayParams = commonAliPay(orderPayBuilderDto);
		return aliPayParams;
	}

	public AliPayParams commonAliPay(OrderPayBuilderDto orderPayBuilderDto) throws Exception {
		AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderPayBuilderDto.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
		String returnUrl = orderPayBuilderDto.getReturnUrl();
		String notifyUrl = orderPayBuilderDto.getNotifyUrl();
		// 创建API对应的request
		AlipayRequest alipayRequest = getAliAayRequest(orderPayBuilderDto);
		if (alipayRequest == null) {
			throw BusinessRuntimeException.getInstance("支付宝不支持该支付方式:{0}", orderPayBuilderDto.getProductCode());
		}
		if (StrUtil.isNotBlank(returnUrl)) {
			alipayRequest.setReturnUrl(returnUrl);
		}
		alipayRequest.setNotifyUrl(notifyUrl);
		String form = null;
		try {
			//调用SDK生成表单
			//pagePay 统一下单接口
			form = alipayClient.pageExecute(alipayRequest).getBody();
		} catch (AlipayApiException e) {
			log.error("支付宝生成表单错误:{}", StringUtil.getErrorText(e));
		}
		log.info("支付宝返回参数:{}", form);
		return new AliPayParams(form);
	}

	/**
	 * 支付宝获取不同的request
	 */
	private AlipayRequest getAliAayRequest(OrderPayBuilderDto payBuilderDto) throws Exception {
		Long orderId = payBuilderDto.getOrderId();
		BigDecimal money = payBuilderDto.getMoney();
		String orderNo = payBuilderDto.getOrderNo();
		//productCode 销售产品码，与支付宝签约的产品码名称
		String productCode = payBuilderDto.getProductCode();
		String subject = payBuilderDto.getSubject();
		Date orderCreatedTime = payBuilderDto.getOrderCreatedTime();
		//网页支付跳转模式
		String qrPayMode = payBuilderDto.getPayMode();
		OrderAttach attach = new OrderAttach();
		attach.setO(orderId);
		String body = Codec.DoBase64.custom()
				.setData(Jsons.toJson(attach)).encodeAsText();
		String moneyStr = money.divide(new BigDecimal(100), 2, RoundingMode.HALF_EVEN).toString();
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode)) {
			//手机网站支付
			AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();
			//手机网站支付支付参数
			AlipayTradeWapPayModel alipayTradeWapPayModel = new AlipayTradeWapPayModel();
			alipayTradeWapPayModel.setBody(body);
			alipayTradeWapPayModel.setOutTradeNo(orderNo);
			alipayTradeWapPayModel.setTotalAmount(moneyStr);
			alipayTradeWapPayModel.setSubject(subject);
			alipayTradeWapPayModel.setProductCode(productCode);
			//5分钟订单失效时间
			alipayTradeWapPayModel.setTimeExpire(DateUtil.offsetMinute(orderCreatedTime, 5).toString());
			alipayTradeWapPayRequest.setBizModel(alipayTradeWapPayModel);
			return alipayTradeWapPayRequest;
		} else if (ZfbProductCode.PC_WEB.getProductCode().equals(productCode)) {
			//电脑网站支付
			AlipayTradePagePayRequest alipayTradePagePayRequest = new AlipayTradePagePayRequest();
			//电脑网站支付参数
			AlipayTradePagePayModel alipayTradePagePayModel = new AlipayTradePagePayModel();
			alipayTradePagePayModel.setBody(body);
			alipayTradePagePayModel.setOutTradeNo(orderNo);
			alipayTradePagePayModel.setTotalAmount(moneyStr);
			alipayTradePagePayModel.setSubject(subject);
			alipayTradePagePayModel.setProductCode(productCode);
			//5分钟订单失效时间
			alipayTradePagePayModel.setTimeExpire(DateUtil.offsetMinute(orderCreatedTime, 5).toString());
			if (StrUtil.isEmpty(qrPayMode)) {
				qrPayMode = BaseZfbConfig.qrPayMode_orderCode;
			}
			alipayTradePagePayModel.setQrPayMode(qrPayMode);
			alipayTradePagePayRequest.setBizModel(alipayTradePagePayModel);
			return alipayTradePagePayRequest;
		}
		return null;
	}


	@Override
	public AliPayParams unifiedPayUpgrade(AlipayOrderDonReq re, String productCode, String payMode) throws Exception {
		Long orderId = re.getOrderId();
		String returnUrl = re.getReturnUrl();
		UpgradeOrderDon orderDon = upgradeOrderDonMapper.selectById(orderId);
		//获取支付宝默认商户
		String appId = sysConfigService.getDefaultShopConfigByType("zfb");
		if (UpgradeOrderDon.Type.ALI_PAY != orderDon.getType()) {
			orderDon.setType(UpgradeOrderDon.Type.ALI_PAY);
		}
		orderDon.setShopId(appId);
		if (ZfbProductCode.PC_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(true);
		}
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(false);
		}
		upgradeOrderDonMapper.updateById(orderDon);
		UpgradePackage upgradePackage = upgradePackageMapper.selectById(orderDon.getPackageId());
		String subject = upgradePackage.getName();
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, BaseZfbConfig.upgradeNotifyUrl);
		//是否在微信内支付 微信内支付宝支付后 支付宝回调页面不跳转
		Boolean isWx = Optional.ofNullable(re.getIsWx()).orElse(false);
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode) && !isWx) {
			//默认跳转页
			returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.DEFAULT_URL);
		}
        return builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getCreatedTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
	}

	@Override
	public AliPayParams aliPayUnifiedWholesale(AlipayOrderDonReq re, String productCode, String payMode) throws Exception {
		Long orderId = re.getOrderId();
		String returnUrl = re.getReturnUrl();
		GoodsWholesaleOrderDon orderDon = goodsWholesaleOrderDonMapper.selectById(orderId);
		//获取支付宝默认商户
		String appId = sysConfigService.getDefaultShopConfigByType("zfb");
		if (GoodsWholesaleOrderDon.Type.ALI_PAY != orderDon.getType()) {
			orderDon.setType(GoodsWholesaleOrderDon.Type.ALI_PAY);
		}
		orderDon.setShopId(appId);
		if (ZfbProductCode.PC_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(true);
		}
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(false);
		}
		goodsWholesaleOrderDonMapper.updateById(orderDon);
		GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
		String subject = goodsDon.getTitle();
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, BaseZfbConfig.wholesaleNotifyUrl);
		//是否在微信内支付 微信内支付宝支付后 支付宝回调页面不跳转
		Boolean isWx = Optional.ofNullable(re.getIsWx()).orElse(false);
		if (StrUtil.isEmpty(returnUrl) && ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode) && !isWx) {
			//默认跳转页
			returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.DEFAULT_URL);
		}
		return builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getUpdateTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
	}

	@Override
	public AliPayParams aliPayUnifiedWholesaleDeposit(AlipayOrderDonReq re, String productCode, String payMode) throws Exception {
		Long orderId = re.getOrderId();
		String returnUrl = re.getReturnUrl();
		GoodsWholesaleUserDeposit orderDon = depositMapper.selectById(orderId);
		//获取支付宝默认商户
		String appId = sysConfigService.getDefaultShopConfigByType("zfb");
		if (GoodsWholesaleUserDeposit.Type.ALI_PAY != orderDon.getType()) {
			orderDon.setType(GoodsWholesaleUserDeposit.Type.ALI_PAY);
		}
		orderDon.setShopId(appId);
		if (ZfbProductCode.PC_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(true);
		}
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode)) {
			orderDon.setIsWebPay(false);
		}
		depositMapper.updateById(orderDon);
		String subject = "押金";
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, BaseZfbConfig.wholesaleDepositNotifyUrl);
		//是否在微信内支付 微信内支付宝支付后 支付宝回调页面不跳转
		Boolean isWx = Optional.ofNullable(re.getIsWx()).orElse(false);
		if (StrUtil.isEmpty(returnUrl) && ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode) && !isWx) {
			//默认跳转页
			returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.DEFAULT_URL);
		}
		//退款后重新支付
		if (orderDon.getStatus() == GoodsWholesaleUserDeposit.Status.refund) {
			orderDon.setOrderNo(SEQUENCE.nextId().toString());
		}
		return builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getUpdateTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
	}

	@Override
	public AliPayParams openShopAliPay(AlipayOrderDonReq re, String productCode, String payMode) throws Exception {
		Long orderId = re.getOrderId();
		String returnUrl = re.getReturnUrl();
		UserMirrorShopFeeOrderDon orderDon = feeOrderDonMapper.selectById(orderId);
		//获取支付宝默认商户
		String appId = sysConfigService.getDefaultShopConfigByType("zfb");
		if (UserMirrorShopFeeOrderDon.Type.ALI_PAY != orderDon.getType()) {
			orderDon.setType(UserMirrorShopFeeOrderDon.Type.ALI_PAY);
		}
		orderDon.setShopId(appId);
		feeOrderDonMapper.updateById(orderDon);
		String subject = "押金";
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, BaseZfbConfig.userMirrorOpenShopNotifyUrl);
		//退款后重新支付
		if (orderDon.getStatus() == UserMirrorShopFeeOrderDon.Status.refund) {
			orderDon.setOrderNo(SEQUENCE.nextId().toString());
		}
		return builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getUpdateTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
	}

	@Override
	public AliPayParams aliPaySpotifyUpgrade(AlipayOrderDonReq re, String productCode, String payMode) throws Exception {
		Long orderId = re.getOrderId();
		String returnUrl = re.getReturnUrl();
		SpotifyUserUpgradeOrder orderDon = spotifyUserUpgradeOrderMapper.selectById(orderId);
		//获取支付宝默认商户
		String appId = sysConfigService.getDefaultShopConfigByType("zfb");
		if (SpotifyUserUpgradeOrder.Type.ALI_PAY != orderDon.getType()) {
			orderDon.setType(SpotifyUserUpgradeOrder.Type.ALI_PAY);
		}
		orderDon.setShopId(appId);
		spotifyUserUpgradeOrderMapper.updateById(orderDon);
		String subject = "Spotify家庭组升级";
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, BaseZfbConfig.spotifyUpgradeNotifyUrl);
		//是否在微信内支付 微信内支付宝支付后 支付宝回调页面不跳转
		if (StrUtil.isEmpty(returnUrl)) {
			//默认跳转页
			returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.DEFAULT_URL);
		}
		return builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getUpdateTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
	}

	@Override
	public AliPayParams unifiedPayVip(Long orderId, String productCode, String payMode, String returnUrl) throws Exception {
		VipOrderDon orderDon = vipOrderDonMapper.selectById(orderId);
		Assert.notNull(orderDon, "订单不存在");
		if (StrUtil.isEmpty(productCode)) throw BusinessRuntimeException.getInstance("支付异常");
		//获取支付宝默认商户
		String shopId = sysConfigService.getDefaultShopConfigByType("zfb");
		orderDon.setShopId(shopId);
		orderDon.setType(VipOrderDon.Type.ALI_PAY);
		if (orderDon.getType() != VipOrderDon.Type.ALI_PAY) {
			orderDon.setType(VipOrderDon.Type.ALI_PAY);
		}
		vipOrderDonMapper.updateById(orderDon);
		//回调地址
		String host = envCommonService.getNotifyHost();
		String notifyUrl = String.format("%s%s", host, BaseZfbConfig.zfb_vip_notify_url);
		if (ZfbProductCode.MOBILE_WEB.getProductCode().equals(productCode) && BaseZfbConfig.qrPayMode_redirect.equals(payMode)) {
			returnUrl = String.format("%s%s", envCommonService.getDomain(), BaseZfbConfig.zfb_vip_login_return_url);
		}
		String subject = orderDon.getPayTitle();
		AliPayParams aliPayParams = builderPayParams(orderDon.getId(),
				orderDon.getOrderNo(),
				orderDon.getShopId(),
				orderDon.getMoney(),
				orderDon.getCreatedTime(),
				subject,
				productCode,
				payMode,
				notifyUrl,
				returnUrl);
		return aliPayParams;
	}

	public String getZfbDayLimitShopId(OrderDon orderDon) {
		String appId = orderDon.getShopId();
		if (orderDon.getPopularizeId() != null) {
			ShopConfig shopConfig = shopConfigMapper.getByChannelPopularizeId(orderDon.getPopularizeId(), "zfb");
			if (shopConfig != null) {
				appId = shopConfig.getAppId();
			}
		}
		List<Integer> scope = Lists.newArrayList(0);
		//是否是PC的端支付
		if (orderDon.getIsWebPay()) {
			scope.add(1);
		} else scope.add(2);
		//排除推广链接
		if (StrUtil.isEmpty(appId)) {
			//获取每日订单限制 支付宝商户
			ZfbShopOrderDayLimit dayLimit = getZfbShopOrdersDayLimit(orderDon.getGoodsId(), scope);
			if (dayLimit == null) {
				//获取支付宝默认商户
				appId = sysConfigService.getDefaultShopConfigByType("zfb");
			} else {
				appId = dayLimit.getAppId();
			}
		}
		return appId;
	}
}
