package com.backendsys.modules;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.backendsys.aspect.RateLimiting;
import com.backendsys.aspect.QueuingPoll;
import com.backendsys.modules.common.config.security.utils.HttpRequestUtil;
import com.backendsys.modules.common.utils.Result;
import com.backendsys.modules.sdk.baidu.yunapp.entity.ExecuteScriptParams;
import com.backendsys.modules.sdk.baidu.yunapp.service.YunappService;
import com.backendsys.modules.sdk.volcengine.entity.VisualFaceSwapV2;
import com.backendsys.modules.sdk.volcengine.service.VolcengineService;
import com.backendsys.modules.system.entity.SysUser;
import com.backendsys.service.TestService;
import com.backendsys.utils.ResourceUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.backendsys.utils.MD5Util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;
import com.tencentcloudapi.common.Credential;
//import io.github.pigmesh.ai.deepseek.core.DeepSeekClientImpl;
//import io.github.pigmesh.ai.deepseek.core.OpenAiHttpException;
//import io.github.pigmesh.ai.deepseek.core.chat.ChatCompletionResponse;
import com.volcengine.service.visual.IVisualService;
import com.volcengine.service.visual.impl.VisualServiceImpl;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.ServletContext;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.redisson.api.*;
import org.springframework.amqp.core.*;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import com.tencentcloudapi.common.CommonClient;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;


@RestController
@RequestMapping("/api/test")
@SuppressWarnings({"rawtypes", "unchecked"})
public class TestController {


    @Value("${tencent.facefusion.secret-id}")
    private String SECRET_ID;
    @Value("${tencent.facefusion.secret-key}")
    private String SECRET_KEY;

//    @Autowired
//    private AmqpAdmin amqpAdmin;
    @Autowired
    private RabbitTemplate rabbitTemplate;

//    private void initRabbitMQ() {
//        System.out.println("-- initRabbitMQ. --");
//
//        // 交换机
//        amqpAdmin.declareExchange(new DirectExchange("demo.exchange", true, false));
//
//        // 队列 (TTL + 死信)
//        Map<String, Object> args = new HashMap<>();
//        args.put("x-message-ttl", 5000);                // 消息 TTL：60 秒（单位毫秒）
//        amqpAdmin.declareQueue(new Queue("demo.queue", true, false, false, args));
//
////        // 队列
////        amqpAdmin.declareQueue(new Queue("demo.queue", true));
//
//        // 把队列 demo.queue 绑定到交换机 demo.exchange，路由键设置为 order.create
//        amqpAdmin.declareBinding(
//                BindingBuilder.bind(new Queue("demo.queue"))
//                        .to(new DirectExchange("demo.exchange"))
//                        .with("order.create")
//        );

//        // 单队列 (无死信)
//        amqpAdmin.declareQueue(new Queue("demo.queue", true));
//    }

    @GetMapping("/testRabbitMQ/send")
    public String send() {

//        initRabbitMQ();
//        rabbitTemplate.convertAndSend("demo.exchange", "order.create", "Hello RabbitMQ!");
//        rabbitTemplate.convertAndSend("", "demo.queue", "Hello RabbitMQ!");

        SysUser sysUser = new SysUser();
        sysUser.setUsername(UUID.randomUUID().toString());
        System.out.println("[Demo][RabbitMQ-发送]：" + sysUser);
//        rabbitTemplate.convertAndSend("", "demo.queue", sysUser);
        rabbitTemplate.convertAndSend("demo.exchange", "demo.create", sysUser);

        return "ok";
    }

    @GetMapping("/testRabbitMQ/poll")
    public String poll() throws Exception {

        // 1. 拿到连接和 channel（不要每次 new）
        Connection connection = rabbitTemplate.getConnectionFactory().createConnection();
        Channel channel = connection.createChannel(false);

        // 2. 手动拉消息，第二个参数传 false 表示“不要自动 ack”
//        GetResponse resp = channel.basicGet("demo.queue", false);
        GetResponse resp = channel.basicGet("demo.queue", false);
        if (resp == null) {
            channel.close();
            connection.close();
            return "no message";
        }

        String body = new String(resp.getBody(), StandardCharsets.UTF_8);
        System.out.println("[Demo][RabbitMQ-手动处理]：" + body);

        // 3. 用同一个 channel 去 ack
        channel.basicAck(resp.getEnvelope().getDeliveryTag(), false);
        channel.close();
        connection.close();
        return "acked: " + body;


//        try {
//            channel.basicAck(msg.getMessageProperties().getDeliveryTag(), false);
//        } finally {
//            channel.close();
//        }
//        return "acked: " + body;
    }






//    @Autowired
//    private DeepSeekClientImpl deepSeekClient;
//
//    // https://javaai.pig4cloud.com/deepseek/quickstart
//    // sse 流式返回
//    @GetMapping(value = "/deepseek/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ChatCompletionResponse> chat(String prompt) {
//        try {
//            Flux<ChatCompletionResponse> flux = deepSeekClient.chatFluxCompletion(prompt);
//            return flux;
//        } catch (OpenAiHttpException e) {
//            throw new CustException(e.getMessage());
//        }
//    }

//    // 进阶配置（多轮对话）
//    @GetMapping(value = "/chat/advanced", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<ChatCompletionResponse> advancedChat(String prompt) {
//        ChatCompletionRequest request = ChatCompletionRequest.builder()
//                .model(ChatCompletionModel.DEEPSEEK_REASONER)  // 指定推理模型
//                .addUserMessage(prompt)                       // 用户当前问题
//                .addAssistantMessage("上轮对话结果")            // 历史助手回复
//                .addSystemMessage("你是一名AI助理")            // 系统角色设定
//                .maxTokens(1000)                              // 最大生成 token 数
//                .temperature(0.7)                             // 生成多样性控制
//                .tools(yourFunctionTools)                     // Function Calling 工具
//                .responseFormat(ChatResponseFormat.JSON)       // 结构化响应
//                .build();
//
//        return deepSeekClient.chatFluxCompletion(request);
//    }

    @Autowired
    private ServletContext servletContext;

    @GetMapping("/tomcat-version")
    public String getTomcatVersion() {
        String serverInfo = servletContext.getServerInfo();
        return "当前Tomcat版本: " + serverInfo;
    }

    /*
        // SubmitMediaModeration 提交审核任务
        // DescribeMediaModeration 查询审核结果
        // SubmitLongVideoFaceFusionJobPro 视频人脸融合异步处理任务，成功提交任务后返回任务的Job id 、预计完成时间以及目前队列长度。
        // QueryVideoFaceFusionJob 通过Job Id查询视频人脸融合任务的进度和状态
    */

    /**
     * [腾讯云-人脸融合] 提交审核任务 (视频)
     */
    @PostMapping("SubmitMediaModeration")
    public String SubmitMediaModeration(@RequestBody Map<String, Object> requestBody) throws TencentCloudSDKException {

        String videoUrl = (String) requestBody.get("videoUrl");
//        String videoUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/video/3.mp4";

        Credential cred = new Credential(SECRET_ID, SECRET_KEY);
        CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");

        String param = "{\"VideoUrl\":\"" + videoUrl + "\"}";
        String resp = client.call("SubmitMediaModeration", param);
        System.out.println(resp);
        return resp;
    }

    /**
     * [腾讯云-人脸融合] 查询审核结果
     */
    @GetMapping("DescribeMediaModeration")
    public String DescribeMediaModeration(String JobId) throws TencentCloudSDKException {
        Credential cred = new Credential(SECRET_ID, SECRET_KEY);
        CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");

        String param = "{\"JobId\":\"" + JobId + "\"}";
        String resp = client.call("DescribeMediaModeration", param);
        System.out.println(resp);
        return resp;
    }

    /**
     * 视频人脸融合异步处理任务，成功提交任务后返回任务的Job id 、预计完成时间以及目前队列长度。
     */
    @PostMapping("/SubmitLongVideoFaceFusionJobPro")
    public String SubmitLongVideoFaceFusionJobPro(@RequestBody Map<String, Object> requestBody) {
        try {
            // 从Map中获取参数
            List<Map<String, Object>> TemplateInfos = (List<Map<String, Object>>) requestBody.get("TemplateInfos");
            List<Map<String, Object>> MergeInfos = (List<Map<String, Object>>) requestBody.get("MergeInfos");
            String VideoUrl = (String) requestBody.get("VideoUrl");
            Integer SwapModelType = (Integer) requestBody.get("SwapModelType");
            /*
            https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-1.png
            https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-2.jpg
            https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/m-1.png
            https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/m-2.png
             */
            //        String imgUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/face/fe-2.jpg";
            //        String videoUrl = "https://guangzhou-1320301544.cos-website.ap-guangzhou.myqcloud.com/test/ai-face/video/3.mp4";

            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
            //        FacefusionClient client = new FacefusionClient(cred, "ap-guangzhou");
            CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");

            JSONObject param = new JSONObject();
            JSONArray paramMergeInfos = JSONUtil.parseArray(MergeInfos);
            JSONArray paramTemplateInfos = JSONUtil.parseArray(TemplateInfos);

            System.out.println("paramMergeInfos:");
            System.out.println(paramMergeInfos);
            System.out.println("paramTemplateInfos:");
            System.out.println(paramTemplateInfos);

            param.set("MergeInfos", MergeInfos);
            param.set("TemplateInfos", TemplateInfos);
            param.set("VideoUrl", VideoUrl);
            param.set("SwapModelType", SwapModelType);

            System.out.println("param:");
            System.out.println(param);

            String resp = client.call("SubmitLongVideoFaceFusionJobPro", JSONUtil.toJsonStr(param));
            System.out.println(resp);
            return resp;
        } catch (TencentCloudSDKException e) {
            System.out.println(e);
            System.out.println(e.getMessage());
            return e.getMessage();
        }
    }

    /**
     *  通过Job Id查询视频人脸融合任务的进度和状态
     */
    @GetMapping("QueryVideoFaceFusionJob")
    public String QueryVideoFaceFusionJob(String JobId) throws TencentCloudSDKException {
        Credential cred = new Credential(SECRET_ID, SECRET_KEY);
        CommonClient client = new CommonClient("facefusion", "2022-09-27", cred, "ap-guangzhou");

        String param = "{\"JobId\":\"" + JobId + "\"}";
        String resp = client.call("QueryVideoFaceFusionJob", param);
        System.out.println(resp);
        return resp;
    }


    @Value("${file.upload.directory}") // 配置保存文件的目录
    private String uploadDirectory;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    // @Autowired
    // private HttpExchangeService httpExchangeService;


//    @PostMapping("testWebHook")
//    public Result testWebHook(@RequestBody Map<String, Object> requestBody, HttpServletRequest request) {
//        System.out.println("------- testWebHook --------");
////        try {
////            String requestBody = StreamUtils.copyToString(request.getInputStream(), StandardCharsets.UTF_8);
////            System.out.println(requestBody);
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
//        System.out.println("===========================================");
//        System.out.println("requestBody:");
//        System.out.println(requestBody);
//        System.out.println("----------------------------");
//        System.out.println("requestBody (JSON):");
//        System.out.println(JSONUtil.parseObj(requestBody));
//        System.out.println("----------------------------");
//        String token = request.getHeader("X-Codeup-Token");
//        System.out.println("X-Codeup-Token: " + token);
//        System.out.println("===========================================");
//        return null;
//    }
//

    @Autowired
    private TestService testService;

    @GetMapping("testThreadPool")
    public String testThreadPool() throws ExecutionException, InterruptedException {
        testService.testThreadPool();
        return "ok";
    }


    @RateLimiting(key = "test", limit = 5, duration = 10)
    @GetMapping("testSemaphore")
    public String testSemaphore() {

//        Semaphore semaphore = new Semaphore(2);
//        try {
//            // 尝试获取一个许可
//            semaphore.acquire();
//            // 模拟服务操作
//            System.out.println("服务被访问，当前活跃线程数：" + semaphore.availablePermits());
//            // 假设服务操作需要一些时间
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            Thread.currentThread().interrupt();
//            System.out.println("线程被中断");
//        } finally {
//            // 释放许可
//            semaphore.release();
//            System.out.println("服务访问结束，释放许可，当前活跃线程数：" + semaphore.availablePermits());
//        }

        return "ok";
    }

//    @Autowired
//    private SysResourceService sysResourceService;
//
//    @GetMapping("testConsumptionPoint")
//    public Result testConsumptionPoint(String resource_type, String resource_tag) throws IOException {
//        sysResourceService.consumptionPoint(resource_type, resource_tag, null);
//        return Result.success("扣除成功");
//    }





//    @Autowired
//    private SDKTencentCOSService sdkTencentCOSService;
//
//    @PostMapping("testUploadOrigin")
//    public Result testUploadOrigin(@RequestBody UploadOriginDTO uploadOriginDTO) throws IOException {
//        return Result.success(sdkTencentCOSService.uploadOrigin(uploadOriginDTO));
//    }


    @GetMapping("testLocalPath")
    public Path testLocalPath() {
        return Paths.get(".");
    }

    @GetMapping("testDownloadLocal")
    public String testDownloadLocal() {
//        return ResourceUtil.downloadImage("https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/466b5214/20240417/172326_0_2a130824-cffe-4d18-8455-f98c18e4900e.png?Expires=1713432207&OSSAccessKeyId=LTAI5tQZd8AEcZX6KZV4G8qL&Signature=439TeHWxweXDJ%2FE8mAQ3UQJx7XI%3D");
        return ResourceUtil.downloadImage("http://cos.daoguyujiamcn.com/customer-pipline/1/65119e58-9940-458c-8911-750d23f9fbf1/idcard/b.pdf", uploadDirectory);
    }

//
//
//    // 【腾讯云 COS】
//    // 文档中心 > 对象存储 > API 文档 > Object 接口 > 基本操作 > PUT Object
//    // https://cloud.tencent.com/document/product/436/7749
//    // https://github.com/tencentyun/cos-java-sdk-v5/blob/master/src/main/java/com/qcloud/cos/demo/PutObjectDemo.java
//    static COSClient cosClient = createCli();
//
//    static COSClient createCli() {
//        return createCli("ap-hongkong");
//    }
//
//    static COSClient createCli(String region) {
//        // 初始化用户身份信息(secretId, secretKey)
//        COSCredentials cred = new BasicCOSCredentials("AKID3zlNxRjstjnohWFnDUfeVBj3CJH7mFaK","IXgzFKB71rXOCxlS4BTdtCYuJbP8h7Xr");
//        // 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
//        ClientConfig clientConfig = new ClientConfig(new Region(region));
//        // 生成cos客户端
//        return new COSClient(cred, clientConfig);
//    }
//
//    /**
//     * 腾讯云 COS - 上传文件
//     */
//    @GetMapping("testTencentSDK/putObject")
//    public String testTencentSDKPutObject() {
//        String bucketName = "storage-1320301544";
//
//        // 获取当前日期
//        Date currentDate = new Date();
//        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
//        String dateFolder = dateFormat.format(currentDate);
//
//        System.out.println("dateFolder: " + dateFolder);
//
//        String fileName = "README.md";
//        String key = dateFolder + "/" + fileName;
//
//        String localPath = fileName;
//
//        // 计算过期时间为 1 分钟后
//        Date currentTime = new Date();
//        long expiresTime = currentTime.getTime() + 60*1000; // 当前时间毫秒数 + 1分钟的毫秒数
//        ObjectMetadata objectMetadata = new ObjectMetadata();
//        objectMetadata.setHeader("expires", new Date(expiresTime));
//
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new File(localPath));
//        putObjectRequest.withMetadata(objectMetadata);
//
//        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
//
//        System.out.println(putObjectResult.getRequestId());
//
//        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
//        COSObject cosObject = cosClient.getObject(getObjectRequest);
//        System.out.println(cosObject.getObjectMetadata().getRequestId());
//
//        cosClient.shutdown();
//        return "ok";
//    }
//




    // 文档中心 > SDK 中心 > Java
    // https://cloud.tencent.com/document/sdk/Java
    // 【腾讯云-混元大模型】
    // https://cloud.tencent.com/document/api/1729/101843

//    private final static Charset UTF8 = StandardCharsets.UTF_8;
////    // 需要设置环境变量 TENCENTCLOUD_SECRET_ID，值为示例的 AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******
////    private final static String SECRET_ID = "AKID3zlNxRjstjnohWFnDUfeVBj3CJH7mFaK";
////    // 需要设置环境变量 TENCENTCLOUD_SECRET_KEY，值为示例的 Gu5t9xGARNpq86cd98joQYCN3*******
////    private final static String SECRET_KEY = "IXgzFKB71rXOCxlS4BTdtCYuJbP8h7Xr";
//
//    @Value("tencent.hunyuan.secret-id")
//    private String SECRET_ID;
//    @Value("tencent.hunyuan.secret-key")
//    private String SECRET_KEY;
//
//
//    private final static String CT_JSON = "application/json; charset=utf-8";
//    public static byte[] hmac256(byte[] key, String msg) throws Exception {
//        Mac mac = Mac.getInstance("HmacSHA256");
//        SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
//        mac.init(secretKeySpec);
//        return mac.doFinal(msg.getBytes(UTF8));
//    }
//    public static String sha256Hex(String s) throws Exception {
//        MessageDigest md = MessageDigest.getInstance("SHA-256");
//        byte[] d = md.digest(s.getBytes(UTF8));
//        return DatatypeConverter.printHexBinary(d).toLowerCase();
//    }

//    @GetMapping("testTencentSDK/hunyuan")
//    public Result testTencentSDKHunyuan() throws Exception {
//
//        try {
//            String result = "";
//            Credential cred = new Credential(SECRET_ID, SECRET_KEY);
//            ClientProfile clientProfile = new ClientProfile();
//            HunyuanClient client = new HunyuanClient(cred, "ap-guangzhou", clientProfile);
//
//            ChatStdRequest req = new ChatStdRequest();
//            Message msg = new Message();
//            msg.setRole("user");
//            msg.setContent("给我一句诗，不超过10个字");
//            req.setMessages(new Message[]{ msg });
//
//            ChatStdResponse resp = client.ChatStd(req);
//
//            Gson gson = new GsonBuilder().create();
//            for (SSEResponseModel.SSE e : resp) {
//
//                System.out.println(e.Data);
//
//                /**
//                 * .Data:
//                 *  {"Note":"以上内容为AI生成，不代表开发者立场，请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":"当然"}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":1,"TotalTokens":8}}
//                 * e.Data:
//                 *  {"Note":"以上内容为AI生成，不代表开发者立场，请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":"可以"}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":2,"TotalTokens":9}}
//                 * e.Data:
//                 *  {"Note":"以上内容为AI生成，不代表开发者立场，请勿删除或修改本标记","Choices":[{"FinishReason":"","Delta":{"Role":"assistant","Content":"，"}}],"Created":1709618061,"Id":"e73c0a71-5c98-4893-ba90-ad5056d5871a","Usage":{"PromptTokens":7,"CompletionTokens":3,"TotalTokens":10}}
//                 * e.Data:
//                 */
//                JSONObject dataObject = JSONUtil.parseObj(e.Data);
//                JSONArray choicesArray = dataObject.getJSONArray("Choices");
//                if (choicesArray != null && choicesArray.size() > 0) {
//                    // 获取第一个元素
//                    JSONObject firstChoice = choicesArray.getJSONObject(0);
//                    System.out.println("firstChoice:");
//                    System.out.println(firstChoice);
//                    // 获取 Delta 对象
//                    JSONObject deltaObject = firstChoice.getJSONObject("Delta");
//                    System.out.println("deltaObject:");
//                    System.out.println(deltaObject);
//                    // 获取 content 的值
//                    String content = deltaObject.getStr("Content");
//                    System.out.println("Content: " + content);
//
//                    result += content;
//                    System.out.println("result: " + result);
//                    System.out.println("---------------------------------------------");
//                }
//            }
//            return Result.success(result);
//
//        } catch (TencentCloudSDKException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }


//    @GetMapping("testQueue")
//    @QueuingPoll
//    public String testQueue(@RequestParam Integer tenantId, @RequestParam Integer time) throws InterruptedException {
//        Thread currentThread = Thread.currentThread();
//        String threadName = currentThread.getName();
//        System.out.println(threadName + " 开始休眠: " + time);
//        Thread.sleep(time);
//        System.out.println(threadName + " 休眠结束: " + time);
//        return threadName;
//    }

    @GetMapping("testMeitu/login")
    public JSONObject testMeituLogin(String code, String access_key) {

        System.out.println("code: " + code + ", access_key: " + access_key);
        System.out.println("---------------------------------------------------");

        String response = "{\"code\": 0,\"msg\": \"success\", \"data\": {\"id\": \"enjdj328ydhhw3u43yjhdj\", \"name\": \"张三\",\"avatar_url\": \"http://www.**.com/avatar/icon.jpg\"}}";
        JSONObject jsonObject = JSONUtil.parseObj(response);
        return jsonObject;
    }




    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("testQueue")
    @QueuingPoll
    public String testQueue(String taskId) {

        redisTemplate.opsForList().rightPush("demoQueue", taskId);

        Long listSize = redisTemplate.opsForList().size("demoQueue");
        System.out.println("队伍总人数: " + listSize);

        List listData = redisTemplate.opsForList().range("demoQueue", 0, -1);
        System.out.println("队伍信息: " + listData.toString() + ", taskId: " + taskId + ", listData.get(0): " + listData.get(0));

        Integer index = 0;

        if (listData.size() == 0 || (listData.size() > 0 && listData.get(0).toString().equals(taskId))) {

            // 创建一个 CompletableFuture 来执行异步任务
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                // 执行业务逻辑
                System.out.println("开始休眠..");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("休眠结束..");

                //
                Long removeNum = redisTemplate.opsForList().remove("demoQueue", 0, taskId);
                System.out.println("离开队伍: " + removeNum);
                System.out.println("-------------------------------------");
            });

            return "操作成功";

        } else {
            index = listData.indexOf(taskId);
            return "排队中：" + index +  " / " + listSize;
        }

    }






    /**
     * 这里多个key用":" 拼接，后续定时任务踢出队列拆分使用。
     * @param keys
     * @return
     */
    public static String buildResourcesSetValue(String... keys){
        return String.join(":",keys);
    }


//    @GetMapping("testQueue")
//    public String testQueue() throws InterruptedException {
//        // 定义Redis信号量，允许的最大并发数为1
//        RSemaphore semaphore = redissonClient.getSemaphore("demoQueue");
//        int maxConcurrentRequests = 2; // 允许的最大并发请求数
//
//        try {
//            // 尝试获取信号量，设定超时时间为3秒
//            if (!semaphore.tryAcquire(maxConcurrentRequests, 3, TimeUnit.SECONDS)) {
//                // 如果无法获取信号量，说明并发数已满，抛出异常
//                long waitingPosition = getWaitingPosition();
//                throw new CustException("正在排队中，第" + waitingPosition + "位 / 共" + maxConcurrentRequests + "位");
//            }
//            // 执行业务逻辑
//            System.out.println("开始休眠..");
//            Thread.sleep(5000);
//            System.out.println("休眠结束..");
//
//        } catch (InterruptedException e) {
//            // 处理中断异常
//            throw new CustException("处理中断异常");
//
//        } finally {
//            // 释放信号量
////            if (semaphore.isHeldByCurrentThread()) {
//            System.out.println("semaphore:");
//            System.out.println(semaphore);
//            System.out.println(semaphore.isExists());
//            semaphore.release();
////            }
//        }
//
//
//        // 返回结果
//        return "操作成功";
//
//    }
//
//    // 获取当前排队位置的方法
//    private long getWaitingPosition() {
//        RScoredSortedSet<Object> scoreSet = redissonClient.getScoredSortedSet("demoQueue");
////        long queueSize = scoreSet.size();
////        System.out.println("(getWaitingPosition) queueSize: " + queueSize);
//        long waitingPosition = 0;
//        // 遍历有序集合，计算当前请求之前的请求数量
//        Iterator<Object> iterator = scoreSet.iterator(0);
//        while (iterator.hasNext()) {
//            Object obj = iterator.next();
//            Double score = scoreSet.getScore(obj);
//            if (score > System.currentTimeMillis()) {
//                waitingPosition++;
//            }
//        }
//        return waitingPosition;
//    }




    /* 字符串 转 JSONObject */
    @GetMapping("testJSONObject")
    public JSONObject testGson() {
        String jsonString = " {\"Note\":\"以上内容为AI生成，不代表开发者立场，请勿删除或修改本标记\",\"Choices\":[{\"FinishReason\":\"stop\",\"Delta\":{\"Role\":\"assistant\",\"Content\":\"\"}}],\"Created\":1709617106,\"Id\":\"7511d79a-6318-4da1-883a-35c8be97f67f\",\"Usage\":{\"PromptTokens\":7,\"CompletionTokens\":23,\"TotalTokens\":30}}";
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);
        return jsonObject;
    }


    // 【火山引擎】
    // - 公共错误代码
    // https://www.volcengine.com/docs/6369/68677
    // - 获取个性化内容
    // https://www.volcengine.com/docs/6392/75762
    // - 模型广场
    // https://www.volcengine.com/docs/82379/1099503

//    @GetMapping("testHuoshanSDK")
//    public String testHuoShanSDK() throws Exception {
//        // 注意示例代码安全，代码泄漏会导致AK/SK泄漏，有极大的安全风险。
//        String ak = "AKLTMjM2OTNmNTViNGQ3NDM0NmI1YjU4MmU2ZjY5YzEwM2I";
//        String sk = "WlRZMk5qRTJOR1ZrTURnMk5EVmhZVGc1TmpVeE4yUTJNelkzWXpVeU1XVQ==";
//
//        BusinessSecurityService businessSecurityService = BusinessSecurityServiceImpl.getInstance();
//        // call below method if you dont set ak and sk in ～/.volc/config
//
//        businessSecurityService.setAccessKey(ak);
//        businessSecurityService.setSecretKey(sk);
//        // risk detection
//        try {
//            RiskDetectionRequest riskDetectionRequest = new RiskDetectionRequest();
////            riskDetectionRequest.setLimit(3);
//
//            RiskDetectionResponse riskDetectionResponse = businessSecurityService.RiskDetection(riskDetectionRequest);
//            System.out.println(JSON.toJSONString(riskDetectionResponse));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return "1";
//    }


//    @GetMapping("testMeituSDK")
//    public SdkResponseDTO.Result testMeituSDK() throws URISyntaxException {
//        //使用前需提前申请 AccessKey 和 secret，具体获取，请对接商务
//        String accessKey = "306129caf4574016be9c09a5b0ecdcad";
//        String secret = "a202a3f4f0a844109cea84af79ad9b40";
//
//        // 创建AiClient实例
//        AiClient aiClient = new AiClient(accessKey,secret);
//
//        // 【美图AI - 文生图】
//        // https://ai.meitu.com/doc/?id=228&type=api&lang=zh
//
//        //  文生图的请求对象
//        InferenceParamsDTO inferenceParamsDTO = new InferenceParamsDTO();
//        // 推理业务配置中获取中约定的模型平台
//        inferenceParamsDTO.setModelPlatform("diffusers");
//        // 推理业务配置中获取的模型
//        inferenceParamsDTO.setModel("braBeautifulRealistic_V5_diffusers_v0.1.zip");
//        // 提示词
//        inferenceParamsDTO.setPrompt("a girl");
//        // 方向提示词
//        inferenceParamsDTO.setNegativePrompt("easy negative");
//        // 推理业务配置中获取中约定的高
//        inferenceParamsDTO.setHeight(512);
//        // 推理业务配置中获取中约定的宽
//        inferenceParamsDTO.setHeight(512);
//        // 推理提交推理任务，并等待返回推理图片地址
//        SdkResponseDTO.Result result = aiClient.inference(inferenceParamsDTO);
//        return result;
//    }





    @GetMapping("testWordExport")
    public Map<String, Object> SimpleWordExport() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("title", "Easypoi 标题");
        map.put("content", "JueYue 内容，在家也能享受绿色健康美味！用纯天然无添加剂的食材，带给你和家人最纯净的美味。从选购新鲜食材到烘焙出炉，每一步都充满温馨与乐趣。让我们一起回归自然，享受绿色健康的蛋糕时光！");
        try {
            XWPFDocument doc = WordExportUtil.exportWord07("D:/excel/template.docx", map);
            FileOutputStream fos = new FileOutputStream("D:/excel/simple.docx");
            doc.write(fos);
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    @GetMapping("testGetUUID")
    public String testGetUUID() {
        return UUID.randomUUID().toString();
    }

    @GetMapping("testGetShortUUID")
    public String testGetShortUUID(Integer length) {
//        return UUID.randomUUID().toString()
//            .replace("-", "")
//            .substring(0, length);
        return IdUtil.simpleUUID().substring(0, length);
    }

    /**
     * BCrypt算法进行加密
     */
    @GetMapping("testPassword")
    public String testPassword(String value) {
        String password = Optional.ofNullable(value).orElse("123456");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(password);
        boolean matched = encoder.matches(password, encodedPassword);
        return "Value: " + value + "\nencodedPassword: " + encodedPassword + "\nmatched: " + matched;
    }

    /**
     * 使用 MD5Util 工具类
     */
    @GetMapping("testMD5")
    public String testMD5(String value) throws NoSuchAlgorithmException {
        String password = Optional.ofNullable(value).orElse("123456");
        String version = "0.0.48";
        return "Value: " + value + "\n" +
                "MD5: " + MD5Util.encrypt(password) + "\n" +
                "Version: " + version;
    }


    @GetMapping("/testJSON")
    public String testJSON() throws JsonProcessingException {
        Integer[] a = MAPPER.readValue("1,2", Integer[].class);
        System.out.println("a: ");
        System.out.println(a);
        return "1";
    }

    @GetMapping("testFont")
    public String[] testFont() {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String[] fontNames = ge.getAvailableFontFamilyNames();
        for (String fontName : fontNames) {
            System.out.println(fontName);
        }
        return fontNames;
    }


    /**
     * Redisson 加锁
     * @return
     */
    @Lazy
    @Autowired
    RedissonClient redissonClient;

    @GetMapping("testRedisson")
    public String testGetRedisson() throws InterruptedException {
        RLock lock = redissonClient.getLock("my-lock");
        lock.tryLock(3, TimeUnit.SECONDS); // 阻塞式等待。默认加的锁是30s时间
        try {
            // 1、锁的自动续期，运行期间自动给锁续上新的30s，无需担心业务时间长，锁过期会自动被释放
            // 2、加锁的业务只要运行完成，就不会给当前锁续期，即使不手动释放锁，锁默认在30s后自动释放，避免死锁
            System.out.println("加锁成功，执行业务代码..."+Thread.currentThread().getId());
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("释放锁..."+Thread.currentThread().getId());
            lock.unlock();
        }
        return "get lock!";
    }
    /**
     * Redisson 一般用于商品秒杀活动：
     */
    /*
        @Component
        public class DistributedLockExample {

            @Autowired
            private Redisson redisson;

            private RLock distributedLock;

            @PostConstruct
            private void init() {
                distributedLock = redisson.getLock("myDistributedLock");
            }

            public void performOperation() {
                try {
                    // 尝试获取分布式锁，最多等待10秒
                    boolean lockAcquired = distributedLock.tryLock(10, TimeUnit.SECONDS);

                    if (lockAcquired) {
                        // 获取锁成功，执行需要加锁的业务逻辑
                        // ...
                    } else {
                        // 获取锁失败，处理异常情况
                        // ...
                    }
                } catch (InterruptedException e) {
                    // 处理中断异常
                    // ...
                } finally {
                    // 释放分布式锁
                    distributedLock.unlock();
                }
            }
        }
     */

    public static Object resource1 = new Object();
    public static Object resource2 = new Object();

    @GetMapping("testDeadLock")
    public String testDeadLock() {

        RLock lock = redissonClient.getLock("thread-lock");

        // 线程1
        new Thread(() -> {
            //System.out.println("------- lock thread-1 -------");
            lock.lock();
            synchronized (resource2) {
                System.out.println(Thread.currentThread().getName() + "获取了 resource2 锁");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (resource1) {
                    System.out.println(Thread.currentThread().getName() + "获取了 resource1 锁");
                    lock.unlock();
                }
            }
        }).start();

        // 线程2
        new Thread(() -> {
            //System.out.println("------- lock thread-2 -------");
            lock.lock();
            synchronized (resource1) {
                System.out.println(Thread.currentThread().getName() + "获取了 resource1 锁");
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (resource2) {
                    System.out.println(Thread.currentThread().getName() + "获取了 resource2 锁");
                    lock.unlock();
                }
            }
        }).start();

        return "ok";
    }

}
