package com.hr.repository.service;

import com.hr.repository.domain.Demo1Entity;
import com.hr.repository.jpa.Demo1Jpa;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

/**
 * @author AAA
 * @createTime 2025/9/25 09:28
 **/
@Component
@Slf4j
public class DemoAsyncServer {
    @Autowired
    private Demo1Jpa demo1Jpa;
    @Async("asyncExecutor")
    @GlobalTransactional
    public CompletableFuture<String> inserttest1(String name,int i){

        Demo1Entity e = new Demo1Entity();
        e.setFname(name+i);
        demo1Jpa.save(e);

        return CompletableFuture.completedFuture(String.valueOf(i));
    }

//    @GlobalTransactional
    @Transactional
    @Async("asyncExecutor")
    public CompletableFuture<String> testAsyncThread(int i){
        try {
            log.info("开始计算: " + i + " + " + i);

//            String currentThreadName = Thread.currentThread().getName();
//            System.out.println("当前虚拟线程名称: " + currentThreadName);

            java.util.Random random = new java.util.Random();
            Thread.sleep(4900); // 模拟计算时间
//            Thread.sleep(random.nextInt(500));

            int result = i + i;
            log.info("计算完成: " + result);
            return CompletableFuture.completedFuture(String.valueOf(result));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return CompletableFuture.failedFuture(e);
        }
    }
}
