package ink.wgink.module.wechat.request.pay.v3.certificates;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ink.wgink.exceptions.base.SystemException;
import ink.wgink.module.wechat.pojo.pay.v3.PayErrorResponse;
import ink.wgink.module.wechat.pojo.pay.v3.certificates.Certificate;
import ink.wgink.module.wechat.request.pay.v3.AbstractPayRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: CertificatesPayRequest
 * @Description: 获取平台证书
 * @Author: wanggeng
 * @Date: 2021/8/26 2:13 下午
 * @Version: 1.0
 */
public class CertificatePayRequestImpl extends AbstractPayRequest<JSONObject, JSONObject, List<Certificate>> {

    @Override
    public JSONObject bodyJson(JSONObject jsonObject) {
        return null;
    }

    @Override
    public List<Certificate> response(ResponseEntity<String> responseEntity) {
        JSONObject resultObject = JSONObject.parseObject(responseEntity.getBody());
        List<Certificate> certificateList = new ArrayList<>();
        JSONArray certificatesData = resultObject.getJSONArray("data");
        for (int i = 0; i < certificatesData.size(); i++) {
            JSONObject certificateJsonObject = certificatesData.getJSONObject(i);
            Certificate certificate = new Certificate();
            certificate.setSerialNo(certificateJsonObject.getString("serial_no"));
            certificate.setEffectiveTime(certificateJsonObject.getString("effective_time"));
            certificate.setExpireTime(certificateJsonObject.getString("expire_time"));

            JSONObject encryptCertificateJsonObject = certificateJsonObject.getJSONObject("encrypt_certificate");
            Certificate.EncryptCertificate encryptCertificate = new Certificate.EncryptCertificate();
            encryptCertificate.setAlgorithm(encryptCertificateJsonObject.getString("algorithm"));
            encryptCertificate.setNonce(encryptCertificateJsonObject.getString("nonce"));
            encryptCertificate.setAssociatedData(encryptCertificateJsonObject.getString("associated_data"));
            encryptCertificate.setCiphertext(encryptCertificateJsonObject.getString("ciphertext"));

            certificate.setEncryptCertificate(encryptCertificate);
            certificateList.add(certificate);
        }
        return certificateList;
    }

    @Override
    public void error(HttpClientErrorException e) {
        LOG.debug("Response error status code：{}", e.getStatusCode());
        PayErrorResponse payErrorResponse = JSONObject.parseObject(e.getResponseBodyAsString(), PayErrorResponse.class);
        LOG.debug("Response error detail: {}", payErrorResponse.getDetail());
        throw new SystemException(payErrorResponse.getMessage());
    }
}
