package cn.hanghui.outapi.platform.ldrk.api;

import cn.hanghui.outapi.platform.common.exception.CommonException;
import cn.hanghui.outapi.platform.ldrk.constant.LdrkApiUrl;
import cn.hanghui.outapi.platform.ldrk.constant.LdrkBaseParam;
import cn.hanghui.outapi.platform.ldrk.constant.LdrkRespCode;
import cn.hanghui.outapi.platform.ldrk.entity.param.LdrkApiResp;
import cn.hanghui.outapi.platform.ldrk.entity.param.LdrkHeaderParam;
import cn.hanghui.outapi.platform.ldrk.entity.param.LdrkReportParam;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
@AllArgsConstructor(onConstructor_ = @Autowired)
public class LdrkApi {

    private final LdrkBaseParam ldrkBaseParam;

    /**
     * 流动人口自主申报
     *
     * @param ldrkReportParam LdrkReportParam
     */
    public void reportPersonInfo(LdrkReportParam ldrkReportParam) {
        SM2 sm2 = SmUtil.sm2(null, ldrkBaseParam.getPublicKey());
        // 部分参数加密
        ldrkReportParam.setXm(sm2.encryptHex(ldrkReportParam.getXm(), KeyType.PublicKey));
        ldrkReportParam.setLxdh(sm2.encryptHex(ldrkReportParam.getLxdh(), KeyType.PublicKey));
        ldrkReportParam.setSfzh(sm2.encryptHex(ldrkReportParam.getSfzh(), KeyType.PublicKey));
        // 请求头参数
        LdrkHeaderParam ldrkHeaderParam = new LdrkHeaderParam();
        ldrkHeaderParam.setAppKey(ldrkBaseParam.getAppKey());
        ldrkHeaderParam.setTimestamp(System.currentTimeMillis());
        ldrkHeaderParam.setSecret(sm2.encryptHex(ldrkHeaderParam.getAppKey() + ldrkHeaderParam.getTimestamp(), KeyType.PublicKey));
        Map<String, Object> headers = BeanUtil.beanToMap(ldrkHeaderParam);
        Map<String, String> strHeaders = new HashMap<>();
        for (String key: headers.keySet()) {
            strHeaders.put(key, headers.get(key).toString());
        }
        HttpResponse response = HttpRequest.post(ldrkBaseParam.getBaseUrl() + LdrkApiUrl.LDRKSB.url)
                .addHeaders(strHeaders).body(JSON.toJSONString(ldrkReportParam)).execute();
        String result = response.body();
        LdrkApiResp<String> ldrkApiResp = JSON.parseObject(result, new TypeReference<LdrkApiResp<String>>() {});
        if (!LdrkRespCode.SUCCESS.code.equals(ldrkApiResp.getResultCode())) {
            throw new CommonException("调用流动人口自主申报失败：" + ldrkApiResp.getMessage() + ldrkApiResp.getData());
        }
    }
}
