package com.cool.store.service.iot.impl;

import com.alibaba.fastjson.JSONObject;
import com.cool.store.mq.util.HttpRestTemplateService;
import com.cool.store.service.iot.ThirdIotService;
import com.cool.store.utils.Md5Utils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 第三方Iot 服务类
 * </p>
 *
 * @author wangff
 * @since 2025/10/20
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ThirdIotServiceImpl implements ThirdIotService {
    private final HttpRestTemplateService restTemplateService;

    @Value("${zx.iot.appId}")
    private String appId;
    @Value("${zx.iot.appSecret}")
    private String appSecret;

    public static final String BASE_URL = "https://zhengxin.ks.osvlabs.com:31310/api";

    @Override
    public Map<String, Object> getToken() {
        String url = BASE_URL + "/system/third-party/auth?timestamp={0}&appId={1}&sign={2}";
        Long timestamp = System.currentTimeMillis() / 1000;
        HashMap<String, Object> params = new HashMap<>();
        params.put("appId", appId);
        params.put("timestamp", timestamp);
        String sign = sign(params, appSecret);
        log.info("send request");
        Map result = restTemplateService.postForObject(MessageFormat.format(url, String.valueOf(timestamp), appId, sign), null, Map.class);
        log.info("response:{}", JSONObject.toJSONString(result));
        return result;
    }

    private static String sign(Map<String, Object> param, String appSecret) {
        String paramStr = param.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&"));
        return Md5Utils.md5(paramStr + appSecret).toUpperCase();
    }
}
