package com.miaxis.common.config;

import com.miaxis.common.utils.uuid.CommonUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import org.apache.http.client.HttpClient;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;


@Configuration
public class BeanConfig {

    @Value("${cos.secretId}")
    private String secretId;
    @Value("${cos.secretKey}")
    private String secretKey;
    @Value("${cos.bucket}")
    private String bucket;
    @Value("${cos.bucketName}")
    private String bucketName;
    @Value("${cos.path}")
    private String path;
    @Value("${cos.preffix}")
    private String preffix;

    @Autowired
    private  WxpayConfig wxpayConfig;
    @Autowired
    private AutoUpdateCertificatesVerifier verifier;

    /**
     * 腾讯云 COS
     * @return
     */

    @Bean
    public COSClient  COSClientconfigBean() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        String secretId = this.secretId;
        String secretKey = this.secretKey;
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(this.bucket);
        ClientConfig clientConfig = new ClientConfig(region);
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     * 腾讯云 VODClient
     * @return
     */

    @Bean
    public VodClient  VODClientconfigBean() {
        Credential cred = new Credential(secretId, secretKey);

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("vod.tencentcloudapi.com");

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        VodClient client = new VodClient(cred, "", clientProfile);
        return client;

    }

//    @Bean
//    public VodUploadClient vodUploadClienConfigBean() {
//        VodUploadClient client = new VodUploadClient(secretId, secretKey);
//        return client;
//    }


    /**
     * 微信支付 httpclient 对象
     * @return
     * @throws Exception
     */
    @Bean
    public HttpClient wxpayConfigBean() throws Exception{
        File file = new ClassPathResource("wechatpay/apiclient_key.pem").getFile();
        String realPath =file.getAbsolutePath();
        PrivateKey privateKey = CommonUtils.getPrivateKey(realPath);
        // 初始化httpClient
        HttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(wxpayConfig.getMerchantId(), wxpayConfig.getSerialNumber(), privateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
        return httpClient;

    }

    /**
     * 创建微信公钥 对象
     * @return
     * @throws Exception
     */
    @Bean
    public RSAPublicKey readPublicKey() throws Exception {
        KeyFactory factory = KeyFactory.getInstance("RSA");

        File file = new ClassPathResource("wechatpay/public.pem").getFile();
        try (FileReader keyReader = new FileReader(file);
             PemReader pemReader = new PemReader(keyReader)) {

            PemObject pemObject = pemReader.readPemObject();
            byte[] content = pemObject.getContent();
            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
            return (RSAPublicKey) factory.generatePublic(pubKeySpec);
        }
    }




}
