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.HuiFuConfig;
import com.hzs.third.pay.constants.PayRedisConstants;
import com.hzs.third.pay.dto.WechatStateDTO;
import com.hzs.third.pay.service.IHuiFuPayService;
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.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * 汇付新支付服务
 */
@Slf4j
@Service
public class HuiFuPayServiceImpl implements IHuiFuPayService {

    @Autowired
    private HuiFuConfig huiFuConfig;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public R<String> prePayScan(TOnlinePayment onlinePayment) {
        try {
            // 缓存对象
            WechatStateDTO wechatStateDTO = new WechatStateDTO();
            wechatStateDTO.setType(onlinePayment.getBusinessType());
            wechatStateDTO.setOrderCode(onlinePayment.getBusinessCode());
            wechatStateDTO.setPkMember(onlinePayment.getPkModified());
            // redis 缓存KEY
            String stateKey = String.format(PayRedisConstants.HUIFU_STATE_KEY, onlinePayment.getBusinessCode());
            // 放到redis中缓存（有效期24小时）
            redisTemplate.opsForValue().set(stateKey, JSONUtil.toJsonStr(wechatStateDTO), 24, TimeUnit.HOURS);

            StringBuilder url = new StringBuilder("https://open.weixin.qq.com/connect/oauth2/authorize");
            // 公众号appId
            url.append("?appid=").append(huiFuConfig.getPublicAppId());
            // 重写向的URL
            url.append("&redirect_uri=").append(URLEncoder.encode(huiFuConfig.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("汇付新扫码支付返回失败");
    }

}
