package com.ycwl.basic.task;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpUtil;
import com.ycwl.basic.utils.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import cn.hutool.http.HttpResponse;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
@EnableScheduling
public class N9eSyncTask {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Scheduled(fixedRate = 1000 * 60L)
    public void syncN9e() {
        // 构建Basic认证头
        String auth = "Basic " + Base64.encode("user001:ccc26da7b9aba533cbb263a36c07dcc4");

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        List<Map<String, Object>> queries = new ArrayList<>();
        Map<String, Object> query = new HashMap<>();
        query.put("key", "group_ids");
        query.put("op", "==");
        List<Integer> values = new ArrayList<>();
        values.add(4);
        query.put("values", values);
        queries.add(query);
        requestBody.put("queries", queries);

        // 发送POST请求
        Map<String, Object> respData;
        try (HttpResponse response = HttpUtil.createPost("https://n9e.jerryyan.top/v1/n9e/target/list")
                .header("Authorization", auth)
                .header("Content-Type", "application/json")
                .body(JacksonUtil.toJSONString(requestBody))
                .execute()) {
            respData = JacksonUtil.parseObject(response.body(), Map.class);
        } catch (Exception e) {
            log.warn("N9E信息获取失败");
            return;
        }
        String err = (String) respData.get("err");
        if (StringUtils.isNotBlank(err)) {
            log.warn("N9E信息获取失败");
            return;
        }
        @SuppressWarnings("unchecked")
        Map<String, Object> data = (Map<String, Object>) respData.get("dat");
        Integer total = (Integer) data.get("total");
        if (total == null || total <= 0) {
            log.warn("N9E信息为空");
            return;
        }
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> list = (List<Map<String, Object>>) data.get("list");
        list.forEach(item -> {
            String ident = (String) item.get("ident");
            Number updateAtNum = (Number) item.get("update_at");
            long updateAt = updateAtNum != null ? updateAtNum.longValue() : 0L;
            redisTemplate.opsForValue().set("ext_device:online:" + ident, Long.toString(updateAt), 1, TimeUnit.DAYS);
        });
    }
}
