package com.admanager;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jjt.JjtApplication;
import com.jjt.ad.domain.AdUserInfo;
import com.jjt.ad.service.IAdSyncService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * AdTest$
 *
 * @author wukai
 * @date 2025/5/6 17:51
 */
@SpringBootTest(classes = JjtApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class AdTest {
    @Resource
    private IAdSyncService adSyncService;

    public static void main(String[] args) {
        String uri = "http://admserver.tlct.com.cn:8080/RestAPI/SearchUser";
        Map<String, Object> map = new HashMap<>(16);
        map.put("domainName", "tlct.com.cn");
        map.put("startIndex", "1");
        map.put("range", "10000");
        map.put("AuthToken", "a21d15fa-58ee-4181-9fca-5f5dbc83dbd2");
        HttpRequest request = HttpUtil.createPost(uri);
        request.setMethod(Method.GET);
        request.form(map);
        request.setConnectionTimeout(5000);
        String success = "SUCCESS";
        try (HttpResponse res = request.execute()) {
            if (!res.isOk()) {
                throw new RuntimeException(res.body());
            }
            String result = new String(res.body().getBytes(), StandardCharsets.UTF_8);
            System.err.println(result);
            JSONObject jsonObject = JSONUtil.parseObj(result, true);
            if (success.equals(jsonObject.getStr("status"))) {
                JSONArray userList = jsonObject.getJSONArray("UsersList");
                for (int i = 0; i < userList.size(); i++) {
                    JSONObject user = userList.getJSONObject(i);
                    try {
                        AdUserInfo userInfo = user.toBean(AdUserInfo.class);
                        System.out.println("Converted Java object: " + userInfo);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Test
    void test() {
        adSyncService.sync();
    }
}
