package com.hzs.third.pay.service.impl;

import cn.hutool.json.JSONUtil;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.text.CharsetKit;
import com.hzs.common.domain.third.pay.TOnlinePayment;
import com.hzs.third.pay.config.BaoFuPayConfig;
import com.hzs.third.pay.config.WeChatConfig;
import com.hzs.third.pay.constants.PayRedisConstants;
import com.hzs.third.pay.dto.WechatStateDTO;
import com.hzs.third.pay.service.IBaoFuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 宝付支付服务
 * @Author: jiang chao
 * @Time: 2023/3/17 15:20
 * @Classname: BaoFuServiceImpl
 * @PackageName: com.hzs.third.pay.service.impl
 */
@Slf4j
@Service
public class BaoFuServiceImpl implements IBaoFuService {

    @Autowired
    private BaoFuPayConfig baoFuPayConfig;
    @Autowired
    private WeChatConfig weChatConfig;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R<String> createUrl(TOnlinePayment onlinePayment) {
        try {
            if (onlinePayment.getPayMoney().compareTo(new BigDecimal("20000")) >= 0) {
                return R.fail("当前支付方式单笔金额不能超过20000");
            }
            // 创建缓存对象
            this.createCache(onlinePayment);

            StringBuilder url = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize");
            // 公众号appId
            url.append("?appid=").append(weChatConfig.getPublicAppId());
            // 重写向的URL -- https://new.hzs413.com/#/login
            url.append("&redirect_uri=").append(URLEncoder.encode(baoFuPayConfig.getRedirectUri(), CharsetKit.UTF_8));
            url.append("&response_type=code");
            // 默认授权，只拿openId
            url.append("&scope=snsapi_base");
            // 重定向后会带上 state 参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
            url.append("&state=").append(onlinePayment.getBusinessCode());
            url.append("#wechat_redirect");

            log.info("宝付生成公众号跳转URL：{}", url);

            return R.ok(url.toString());
        } catch (Exception e) {
            log.error("宝付扫码支付返回异常", e);
        }
        return R.fail("宝付扫码支付返回失败");
    }


    @Override
    public R<String> createCode(TOnlinePayment onlinePayment) {
        try {
            if (onlinePayment.getPayMoney().compareTo(new BigDecimal("20000")) >= 0) {
                return R.fail("当前支付方式单笔金额不能超过20000");
            }
            // 创建缓存对象
            this.createCache(onlinePayment);

            log.info("宝付小程序支付订单：{}", onlinePayment.getBusinessCode());

            return R.ok(onlinePayment.getBusinessCode());
        } catch (Exception e) {
            log.error("宝付小程序支付返回异常", e);
        }
        return R.fail("宝付小程序支付返回失败");
    }

    /**
     * 封装订单缓存
     *
     * @param onlinePayment 支付信息
     */
    private void createCache(TOnlinePayment onlinePayment) {
        // 缓存对象
        WechatStateDTO wechatStateDTO = new WechatStateDTO();
        wechatStateDTO.setType(onlinePayment.getBusinessType());
        wechatStateDTO.setOrderCode(onlinePayment.getBusinessCode());
        wechatStateDTO.setPkMember(onlinePayment.getPkModified());
        // redis 缓存KEY
        String stateKey = String.format(PayRedisConstants.BAOFU_STATE_KEY, onlinePayment.getBusinessCode());
        // 放到redis中缓存（有效期24小时）
        redisTemplate.opsForValue().set(stateKey, JSONUtil.toJsonStr(wechatStateDTO), 24, TimeUnit.HOURS);
    }

}
