package com.usky.fire.service.api.mhWater;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.usky.common.core.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;

/**
 * 一网通卡api
 *
 * @author yq
 * @date 2021/11/4 11:24
 */
@Component
@ConfigurationProperties(prefix = "mhwater")
@Slf4j
public class OneCardApi {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * token
     */
    private static final String ACCESS_TOKEN = "3kqxQdFCS5tcXPrEYZHlLeIgBUm0MDWi";

    /**
     * 内网地址
     */
    @Value("${mhwater.path}")
    private String path;

    /**
     * SHA256 加密方法
     *
     * @param str 参数：明文密码
     * @return 密文
     */
    public static String getSHA256StrJava(String str) {
        try {
            if (StringUtils.isBlank(str)) {
                return null;
            }

            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes("UTF-8"));
            byte[] bytes = messageDigest.digest();

            StringBuffer stringBuffer = new StringBuffer();
            String temp;
            for (int i = 0; i < bytes.length; i++) {
                temp = Integer.toHexString(bytes[i] & 0xFF);
                if (temp.length() == 1) {
                    // 1得到一位的进行补0操作
                    stringBuffer.append("0");
                }
                stringBuffer.append(temp);
            }
            return stringBuffer.toString();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取token
     *
     * @return
     */
    public Map<String, String> getAccessToken() {
        //系统当前时间戳
        Long timestamp = System.currentTimeMillis();
        //进行明文加密
        String token = getSHA256StrJava(ACCESS_TOKEN + timestamp);
        token = token + "&" + timestamp;
        Map<String, String> headMaps = new HashMap<>();
        headMaps.put("AccessToken", token);
        return headMaps;
    }

    /**
     * 统一的解析数据
     *
     * @param url
     * @param param
     * @return
     */
    public void sendApiBase(String url, Object param, Consumer<String> consumer) {
        try {
            String result = HttpUtils.postJson(url, param, getAccessToken());
            JsonNode arrNode = MAPPER.readTree(result);
            if ("0".equals(arrNode.get("status").asText())) {
                JsonNode data = arrNode.get("data");
                consumer.accept(data.asText());
            } else {
                log.error("闵行水系统接口-----调用异常:" + arrNode.get("msg").asText());
            }
        } catch (Exception e) {
            log.error("系统异常:" + e.getMessage());
        }
    }

    /**
     * 调用心跳接口
     */
    public void callInfoApi(Object param) {
        sendApiBase(String.format("%s%s", path, "/iot/bomb/yt"), param, data -> log.info("获取到的数据" + data));
    }


    /**
     * 调用告警接口
     */
    public void callAlarmApi(Object param) {
        sendApiBase(String.format("%s%s", path, "/iot/alarm/yt"), param, data -> log.info("获取到的数据" + data));
    }

}
