package com.changhu.task;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


/**
 * @author 20252
 * @createTime 2024/11/27 下午4:59
 * @desc SecurityAssociationDockingServiceTask...
 */
@Slf4j
@Component
public class SecurityAssociationDockingServiceTask {

    private static final String BASE_HOST = "http://baxh.3589hn.cn";

    private static String TOKEN;

    /**
     * 每小时续一次token
     */
    @PostConstruct
    @Scheduled(cron = "0 0 * * * *")
    public void getToken() {
        JSONObject params = new JSONObject();
        params.put("appid", "anfang");
        params.put("appkey", "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCg");
        //创建请求
        HttpRequest request = HttpUtil.createPost(BASE_HOST + "/api/security/get_token");
        //设置参数
        request.body(params.toJSONString());
        try (HttpResponse response = request.execute()) {
            int status = response.getStatus();
            if (!(status == 200)) {
                log.error("保安协会 获取token接口出错 status={} msg={}", status, response.body());
                return;
            }
            String body = response.body();
            log.info("getToken 接收到值:{}", body);
            if (!JSON.isValid(body)) {
                log.warn("返回数据不是json格式");
                return;
            }
            JSONObject jsonObject = JSON.parseObject(body);
            JSONObject data = jsonObject.getJSONObject("data");
            TOKEN = data.getString("token");
            log.info("续期后的 token:{}", TOKEN);
        }
    }

    public JSONObject querySecurityNumberByIdCard(String idCard) {
        HttpRequest request = HttpUtil.createPost(BASE_HOST + "/api/security/query?token=" + TOKEN);
        //请求体参数
        request.body(JSONObject.of("idcard", idCard).toJSONString());
        try (HttpResponse response = request.execute()) {
            int status = response.getStatus();
            if (!(status == 200)) {
                log.error("保安协会 身份证查保安证接口出错 status={} msg={}", status, response.body());
                return null;
            }
            String body = response.body();
            log.info("querySecurityNumberByIdCard 接收到返回值:{}", body);
            if (!JSON.isValid(body)) {
                log.warn("返回数据不是json格式");
                return null;
            }
            JSONObject jsonObject = JSON.parseObject(body);
            return jsonObject.getJSONObject("data");
        }
    }

}
