package ink.wgink.module.wechat.pay.service.v3.certificates.impl;

import com.alibaba.fastjson.JSONObject;
import ink.wgink.exceptions.base.SystemException;
import ink.wgink.module.wechat.pay.enums.PayAuthorizationTypeEnum;
import ink.wgink.module.wechat.pay.pojo.v3.certificates.Certificate;
import ink.wgink.module.wechat.pay.remote.v3.IPayRemoteService;
import ink.wgink.module.wechat.pay.service.BasePayService;
import ink.wgink.module.wechat.pay.service.v3.certificates.ICertificateService;
import ink.wgink.module.wechat.pay.utils.v3.PayAesUtil;
import ink.wgink.util.date.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName: ICertificatesService
 * @Description: 平台证书业务
 * @Author: wanggeng
 * @Date: 2021/8/26 2:40 下午
 * @Version: 1.0
 */
@Service
public class CertificateServiceImpl extends BasePayService implements ICertificateService {

    @Autowired
    private IPayRemoteService payRemoteService;

    @Override
    public String getNewestPlatformCertificate() throws Exception {
        String urlSuffix = "/v3/certificates";

        LOG.debug("获得证书序列号");
        String serialNumber = getSerialNumber();
        String authorization = getAuthorization(RequestMethod.GET, urlSuffix, serialNumber, payProperties, "", PayAuthorizationTypeEnum.WECHATPAY2_SHA256_RSA2048);
        JSONObject resultJsonObject = payRemoteService.getCertificates(getPayBaseUrl(), authorization, serialNumber);
        List<Certificate> certificates = resultJsonObject.getJSONArray("data").toJavaList(Certificate.class);
        LOG.debug("获取最新的平台证书");
        Certificate newestCertificate = certificates.get(certificates.size() - 1);
        LOG.debug("解析密文");
        PayAesUtil aesUtil = new PayAesUtil(payProperties.getApiV3Secretkey().getBytes(StandardCharsets.UTF_8));
        Certificate.EncryptCertificate encryptCertificate = newestCertificate.getEncryptCertificate();
        String ciphertext = aesUtil.decryptToString(encryptCertificate.getAssociatedData().getBytes(StandardCharsets.UTF_8), encryptCertificate.getNonce().getBytes(StandardCharsets.UTF_8), encryptCertificate.getCiphertext());
        String certificateFilePath = payProperties.getCertificatePath() + File.separator + DateUtil.getDays()+ "_wxp_pub.pem";
        LOG.debug("新证书文件路径：{}", certificateFilePath);
        try (FileWriter fileWriter = new FileWriter(certificateFilePath)) {
            fileWriter.write(ciphertext);
            fileWriter.flush();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            throw new SystemException("证书生成异常");
        }
        LOG.debug("保存新平台证书成功");
        return certificateFilePath;
    }

}
