package com.slodon.bbc.starter.thirdParty.client;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayOpenAppQrcodeCreateModel;
import com.alipay.api.request.AlipayOpenAppQrcodeCreateRequest;
import com.alipay.api.response.AlipayOpenAppQrcodeCreateResponse;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.bbc.starter.thirdParty.entity.SlodonThirdPartyQrCodeRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 支付宝
 *
 */
@Slf4j
public class AliClient implements ThirdPartyBaseClient {

    /**
     * 获取二维码
     * https://opendocs.alipay.com/apis/009zva
     *
     * @param stringRedisTemplate redis操作工具
     * @param qrCodeRequest       业务参数
     * @return 二维码图片
     */
    @Override
    public BufferedImage getQrCode(StringRedisTemplate stringRedisTemplate, SlodonThirdPartyQrCodeRequest qrCodeRequest) throws Exception{
        String appId = stringRedisTemplate.opsForValue().get("third_party_ali_appid");
        String privateKey = stringRedisTemplate.opsForValue().get("third_party_ali_privatekey");
        String publicKey = stringRedisTemplate.opsForValue().get("third_party_ali_publickey");
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,privateKey,
                "json","utf-8",publicKey,"RSA2");
        AlipayOpenAppQrcodeCreateRequest request = new AlipayOpenAppQrcodeCreateRequest();
        AlipayOpenAppQrcodeCreateModel model = new AlipayOpenAppQrcodeCreateModel();
        model.setUrlParam(qrCodeRequest.getPage());
        if (!CollectionUtils.isEmpty(qrCodeRequest.getParams())) {
            StringBuilder params = new StringBuilder();
            qrCodeRequest.getParams().forEach((k,v) ->{
                params.append(",").append(v);
            });
            model.setQueryParam(params.toString().substring(1));
        }
        model.setDescribe("小程序二维码");
        request.setBizModel(model);
        AlipayOpenAppQrcodeCreateResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            return ImageIO.read(readFile(response.getQrCodeUrl()));
        }
        //请求失败
        log.error("生成支付宝二维码失败：" + response.getMsg() + "," + response.getSubMsg());
        throw new MallException("小程序维护中，请稍后再试");
    }

    /**
     * 获取图片流
     *
     * @param fileUrl http://url:port/store/lesson/qrcode/2018/07/12909064255321.jpg
     * @return InputStream
     */
    private InputStream readFile(String fileUrl) throws Exception{
        URL url = new URL(fileUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(6000);
        urlCon.setReadTimeout(6000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        return urlCon.getInputStream();
    }
}
