package cn.hanghui.outapi.platform.tenant.service.impl;

import cn.hanghui.outapi.platform.tenant.entity.dto.open.RpRequestDTO;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @author shisl
 * @package cn.hanghui.outapi.platform.tenant.service.impl
 * @class RecurrentPopulationServer
 * @date 2024/3/1 上午9:34
 * @description
 */
@Slf4j
@Service
public class RecurrentPopulationServer {

    //流动人口自主申报
    @Value("${recurrent.population.accessKey}")
    private String rpAccessKey;
    @Value("${recurrent.population.secretKey}")
    private String rpSecretKey;
    @Value("${recurrent.population.url}")
    private String rpUrl;
    @Value("${recurrent.population.method}")
    private String rpMethod;

    /**
     * 流动人口自主申报
     *
     * @param data
     * @return
     */
    public String recurrentPopulationPush(String data) {
        try {
//            rpAccessKey = "test";
//            rpSecretKey = "zjjc@sjwg#test#2024";
//            rpUrl = "http://121.199.30.109:42008/api/open/v1";
//            rpMethod = "zzsb_ldrk";
            SymmetricCrypto sm4 = SmUtil.sm4(rpSecretKey.substring(0, 16).getBytes(StandardCharsets.UTF_8));
            data = sm4.encryptHex(data);
            Long timestamp = System.currentTimeMillis();
            String nonce = RandomUtil.randomString(32);
            String rawData = rpSecretKey + "accessKey=" + rpAccessKey + "&data=" + data + "&method=" + rpMethod + "&nonce="
                    + nonce + "&timestamp=" + timestamp + rpSecretKey;
            String sign = DigestUtils.sha256Hex(rawData.toLowerCase());
            RpRequestDTO openApiRequestDTO = new RpRequestDTO();
            openApiRequestDTO.setAccessKey(rpAccessKey);
            openApiRequestDTO.setNonce(nonce);
            openApiRequestDTO.setSign(sign);
            openApiRequestDTO.setTimestamp(timestamp);
            openApiRequestDTO.setData(data);
            openApiRequestDTO.setMethod(rpMethod);
            String jsonBody = JSONObject.toJSONString(openApiRequestDTO);
            log.info("--->流动人口自主申报请求参数：{}", jsonBody);
            String response = HttpUtil.createPost(rpUrl).body(jsonBody, "application/json").execute().body();
            log.info("--->流动人口自主申报响应参数：{}", response);
            return response;
        } catch (Exception e) {
            log.error("--->流动人口自主申报响应异常");
            e.printStackTrace();
        }
        return null;
    }



}
