package io.common.utils;


import lombok.Data;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.security.SecureRandom;
import java.util.HexFormat;
import java.util.List;

/**
 *
 * 1.在主方法加@EnableScheduling
 */
//
//@Component
//@Slf4j
public class MyScheduledTask {
//    @Autowired
//    ContractsDao contractsService;
//
//    // 每5秒执行一次
//    @Scheduled(fixedRate = 5000)
//    public void runEveryFiveSeconds() {
//        System.out.println("⏰ 定时任务执行时间: " + java.time.LocalDateTime.now());
//        //需要检测的hex字段
//        List<Contracts> list = contractsService.selectList(null);
//        for (Contracts itemEntity : list) {
//            if (!isValidEthereumHexId(itemEntity.getHexId(),64)){
//                itemEntity.setHexId(sendSetRequest(itemEntity.getId().toString(),itemEntity.toString()));
//                //更新数据
//                contractsService.updateById(itemEntity);
//            }
//        }
//    }
    public static String sendSetRequest(String key, String value) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String url = "http://localhost:8080/set?key=" + key + "&value=" + value;
            // 发送 GET 请求并解析返回 JSON 为 SetResponse 对象
            ResponseEntity<SetResponse> response = restTemplate.getForEntity(url, SetResponse.class);
            return response.getBody().data;
        }catch (Exception e){
            SetResponse setRequestService = new SetResponse();
            setRequestService.setData(generate(40));
            return setRequestService.data;
        }
    }
    /**
     * 判断是否为合法的以太坊Hex ID（例如：交易哈希、区块哈希、地址）
     * @param hexId 要校验的字符串
     * @param length 字符长度（40 = 钱包地址，64 = 交易哈希/区块哈希）
     * @return true 表示合法，否则 false
     */
    public static boolean isValidEthereumHexId(String hexId, int length) {
        if (hexId == null || !hexId.startsWith("0x")) {
            return false;
        }
        String hexBody = hexId.substring(2);
        String pattern = "^[0-9a-fA-F]{" + length + "}$";
        return hexBody.matches(pattern);
    }


    // 内嵌的SetResponse类
    @Data
    public static class SetResponse {
        private String msg;
        private String data;
    }

    private static final SecureRandom secureRandom = new SecureRandom();
    private static final HexFormat hexFormat = HexFormat.of();

    public static String generate(int byteLength) {
        byte[] randomBytes = new byte[byteLength];
        secureRandom.nextBytes(randomBytes);
        return "0x" + hexFormat.formatHex(randomBytes);
    }
}