package com.kingdee.eas.custom.synctask.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingdee.eas.utils.ExpiringMapCache;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.DigestUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description IOT平台接口工具类
 * @Date 2024/11/4 19:49
 * @Created by Heyuan
 */
public class IOTApiUtil {
    private static ExpiringMapCache<String, String> cache = new ExpiringMapCache();

    /**
     * 获取token
     * 本地缓存token，有效时长6.5小时
     *
     * @return
     */
    public static String getToken() {
        String token = cache.get("token");
        if (StringUtils.isBlank(token)) {
            token = getTokenByRemote();
            cache.put("token", token, 27000000);//6.5小时
        }
        return token;
    }


    public void syncOrg() {
        Response response = null;
        Map result = null;
        try {
            String url = "http://10.0.3.87/api/open/enterpriseright/org-manage/v1/external/org/batch";
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\r\n  \"data\": [\r\n    {\r\n      \"id\": \"2\",\r\n      \"name\": \"深圳总公司\",\r\n      \"code\": \"szzgs\",\r\n      \"type\": 2,\r\n      \"description\": \"\",\r\n      \"params\": {\r\n        \"status\": \"1\"\r\n      }\r\n    }\r\n  ],\r\n  \"dataSyncRule\": 1\r\n}");
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .addHeader("Authorization", getToken())
                    .addHeader("Content-Type", "application/json")
                    .build();
            response = client.newCall(request).execute();
            String string = response.body().string();
            ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.readValue(string, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("同步IOT平台组织失败: " + e.getMessage());
        }
        if (response.isSuccessful()) {
            //return (String) result.get("token");
        } else {
            throw new RuntimeException((String) result.get("msg"));
        }
    }


    /**
     * 远程获取Token
     *
     * @return
     */
    private static String getTokenByRemote() {
        Response response = null;
        Map result = null;
        try {
            long now = System.currentTimeMillis();
            Map<String, String> params = new HashMap<>();
            String secret = "c0fd314792e6bd6f329f86b8a46a7dd1d335136a";
            String url = "http://10.0.3.87/api/justauth/generate/v1/visitor/token";
            params.put("appid", "vS5LOofb");
            params.put("sign_method", "md5");
            params.put("timestamp", now + secret);
            //生成签名
            String sign = DigestUtils.md5DigestAsHex((appendUrl(null, params)).getBytes());
            params.put("timestamp", String.valueOf(now));
            params.put("sign", sign);
            String requestUrl = appendUrl(url, params);
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            Request request = new Request.Builder()
                    .url(requestUrl)
                    .get()
                    .build();
            response = client.newCall(request).execute();
            String string = response.body().string();
            ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.readValue(string, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("远程获取IOT平台token失败: " + e.getMessage());
        }
        if (response.isSuccessful()) {
            return (String) result.get("token");
        } else {
            throw new RuntimeException((String) result.get("msg"));
        }
    }

    /**
     * 拼接地址参数
     */
    private static String appendUrl(String url, Map<String, String> data) {
        StringBuilder paramStr = new StringBuilder();
        for (String key : data.keySet()) {
            paramStr.append(key).append("=").append(data.get(key)).append("&");
        }
        paramStr.deleteCharAt(paramStr.lastIndexOf("&"));
        if (!StringUtils.isEmpty(url)) {
            return url.contains("?") ? (url + "&" + paramStr) : (url + "?" + paramStr);
        }
        return paramStr.toString();
    }
}
