package com.zksy.controller.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zksy.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author Administrator
 * @version 1.0
 * @project enterprise-assets-service
 * @description 用户权限
 * @date 2025/8/11 10:26:24
 */
@RestController
@Api(tags = "用户权限", description = "用户权限")
@RequestMapping("/userPermissions")
@Slf4j
public class UserPermissionsController {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    @Autowired
    private OkHttpClient httpClient;
    @ApiOperation(value = "用户权限查询")
    @PostMapping("/queryUserPermissions")
    public AjaxResult queryUserPermissions(@RequestParam String appToken, @RequestParam String appId){

        // 拼接URL参数
        String url = "http://183.215.203.75:9010/minto/extTask/findUsers?appToken=" + appToken + "&appId=" + appId;

        // 构建POST请求（空body）
        Request requestHttp = new Request.Builder()
                .url(url)
                .post(RequestBody.create("", null)) // 空body
                .build();

        // 发送请求
        try (Response response = httpClient.newCall(requestHttp).execute()) {
            if (!response.isSuccessful()) {
                return AjaxResult.error("请求失败");
            }
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                String responseString = responseBody.string();
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(responseString);
                JsonNode success = rootNode.path("success");
                if("true".equals(success.asText())) {
                    JsonNode dataNode = rootNode.path("data");
                    if (dataNode != null) {
                        return AjaxResult.success(dataNode);
                    } else {
                        return AjaxResult.success(null);
                    }
                }else {
                    return AjaxResult.error("用户权限查询失败");
                }
            }
        } catch (IOException e) {
            log.error("请求失败: {}", e);
        }
        return AjaxResult.error("请求失败");
    }
}
