package org.springblade.modules.quartz.task;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ijpay.core.IJPayHttpResponse;
import com.ijpay.core.enums.RequestMethod;
import com.ijpay.wxpay.WxPayApi;
import com.ijpay.wxpay.enums.WxApiType;
import com.ijpay.wxpay.enums.WxDomain;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.finance.pay.entity.WxPayV3Bean;
import org.springblade.modules.finance.service.IWxPayService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * 微信平台证书定时任务
 */
@Slf4j
@Component
public class WxPlatformCertMngTask {

	@Resource
	WxPayV3Bean wxPayV3Bean;
	@Resource
	private IWxPayService wxPayService;


	public void sync() {
		log.info("同步微信平台证书.....");
		try {
			IJPayHttpResponse response = WxPayApi.v3(
				RequestMethod.GET,
				WxDomain.CHINA.toString(),
				WxApiType.GET_CERTIFICATES.toString(),
				wxPayV3Bean.getMchId(),
				wxPayService.getSerialNumber(),
				null,
				wxPayV3Bean.getKeyPath(),
				""
			);

			String serialNumber = response.getHeader("Wechatpay-Serial");

			String body = response.getBody();
			int status = response.getStatus();

			log.info("serialNumber: {}", serialNumber);
			log.info("status: {}", status);
			log.info("body: {}", body);
			int isOk = 200;
			if (status == isOk) {
				JSONObject jsonObject = JSONUtil.parseObj(body);
				JSONArray dataArray = jsonObject.getJSONArray("data");
				// 默认认为只有一个平台证书
				JSONObject encryptObject = dataArray.getJSONObject(0);
				JSONObject encryptCertificate = encryptObject.getJSONObject("encrypt_certificate");
				String associatedData = encryptCertificate.getStr("associated_data");
				String cipherText = encryptCertificate.getStr("ciphertext");
				String nonce = encryptCertificate.getStr("nonce");
				String serialNo = encryptObject.getStr("serial_no");
				final String platSerialNo = wxPayService.savePlatformCert(associatedData, nonce, cipherText, wxPayV3Bean.getPlatformCertPath());
				log.info("平台证书序列号: {} serialNo: {}", platSerialNo, serialNo);
			}
		} catch (Exception e) {
			log.error("同步微信平台证书失败_" + e.getMessage(), e);
		}
	}
}
