package com.ruoyi.blockchain.service.impl;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.blockchain.domain.ContractMonitor;
import com.ruoyi.blockchain.domain.SmartContract;
import com.ruoyi.blockchain.mapper.ContractMonitorMapper;
import com.ruoyi.blockchain.mapper.SmartContractMapper;
import com.ruoyi.blockchain.service.BlockchainIntegrator;
import com.ruoyi.blockchain.service.OracleService;
import com.ruoyi.blockchain.service.SmartContractService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;

/**
 * 智能合约服务实现类
 * 
 * @author ruoyi
 */
@Service
public class SmartContractServiceImpl implements SmartContractService {
    
    private static final Logger log = LoggerFactory.getLogger(SmartContractServiceImpl.class);
    
    @Autowired
    private SmartContractMapper smartContractMapper;
    
    @Autowired
    private ContractMonitorMapper contractMonitorMapper;
    
    @Autowired
    private BlockchainIntegrator blockchainIntegrator;
    
    @Autowired
    private OracleService oracleService;
    
    // 合约监控调度器
    private final ScheduledExecutorService contractMonitorScheduler = Executors.newScheduledThreadPool(3);
    
    // 合约权限缓存
    private final Map<String, Map<String, List<String>>> contractPermissions = new ConcurrentHashMap<>();
    
    // Gas优化缓存
    private final Map<String, Map<String, Object>> gasOptimizationCache = new ConcurrentHashMap<>();
    
    // 安全随机数生成器
    private final SecureRandom secureRandom = new SecureRandom();
    
    @Override
    public String deployContract(String contractName, String contractCode, String contractAbi, Object... constructorParams) {
        try {
            log.info("开始部署智能合约: {}", contractName);
            
            // 1. 安全审计
            Map<String, Object> auditResult = auditContractSecurity(contractCode, contractAbi);
            if (!"PASSED".equals(auditResult.get("status"))) {
                throw new ServiceException("合约安全审计未通过: " + auditResult.get("message"));
            }
            
            // 2. 检查合约名称唯一性
            SmartContract existingContract = smartContractMapper.checkContractNameUnique(contractName);
            if (existingContract != null) {
                throw new ServiceException("合约名称已存在: " + contractName);
            }
            
            // 3. 部署合约到区块链
            String contractAddress = blockchainIntegrator.deploySmartContract(contractCode, constructorParams);
            
            // 4. 保存合约信息
            SmartContract contract = new SmartContract();
            contract.setContractName(contractName);
            contract.setContractAddress(contractAddress);
            contract.setContractVersion("1.0.0");
            contract.setContractType("FUND_ALLOCATION");
            contract.setContractStatus("ACTIVE");
            contract.setDeployTime(DateUtils.getNowDate());
            contract.setDeployerAddress("0x" + calculateHash(contractName + System.currentTimeMillis()).substring(0, 40));
            contract.setContractAbi(contractAbi);
            contract.setContractBytecode(contractCode);
            contract.setDescription("智能合约: " + contractName);
            
            smartContractMapper.insertSmartContract(contract);
            
            // 5. 启动合约监控
            startContractMonitoring(contractAddress, createDefaultMonitorConfig());
            
            log.info("智能合约部署成功: {} -> {}", contractName, contractAddress);
            return contractAddress;
            
        } catch (Exception e) {
            log.error("智能合约部署失败: {}", contractName, e);
            throw new ServiceException("智能合约部署失败: " + e.getMessage());
        }
    }
    @Override
    public String upgradeContract(String contractAddress, String newContractCode, String newContractAbi, Map<String, Object> migrationData) {
        try {
            log.info("开始升级智能合约: {}", contractAddress);
            
            // 1. 验证原合约存在
            SmartContract originalContract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (originalContract == null) {
                throw new ServiceException("原合约不存在: " + contractAddress);
            }
            
            // 2. 安全审计新合约
            Map<String, Object> auditResult = auditContractSecurity(newContractCode, newContractAbi);
            if (!"PASSED".equals(auditResult.get("status"))) {
                throw new ServiceException("新合约安全审计未通过: " + auditResult.get("message"));
            }
            
            // 3. 暂停原合约
            pauseContract(contractAddress, "合约升级");
            
            // 4. 部署新合约
            String newContractAddress = blockchainIntegrator.deploySmartContract(newContractCode);
            
            // 5. 数据迁移
            if (migrationData != null && !migrationData.isEmpty()) {
                performDataMigration(contractAddress, newContractAddress, migrationData);
            }
            
            // 6. 更新合约信息
            String newVersion = incrementVersion(originalContract.getContractVersion());
            SmartContract newContract = new SmartContract();
            newContract.setContractName(originalContract.getContractName() + "_v" + newVersion);
            newContract.setContractAddress(newContractAddress);
            newContract.setContractVersion(newVersion);
            newContract.setContractType(originalContract.getContractType());
            newContract.setContractStatus("ACTIVE");
            newContract.setDeployTime(DateUtils.getNowDate());
            newContract.setDeployerAddress(originalContract.getDeployerAddress());
            newContract.setContractAbi(newContractAbi);
            newContract.setContractBytecode(newContractCode);
            newContract.setDescription("升级合约: " + originalContract.getContractName());
            
            smartContractMapper.insertSmartContract(newContract);
            
            // 7. 标记原合约为已升级
            smartContractMapper.updateContractStatus(originalContract.getContractId(), "UPGRADED");
            
            // 8. 启动新合约监控
            startContractMonitoring(newContractAddress, createDefaultMonitorConfig());
            
            log.info("智能合约升级成功: {} -> {}", contractAddress, newContractAddress);
            return newContractAddress;
            
        } catch (ServiceException e) {
            log.error("智能合约升级失败: {}", contractAddress, e);
            throw new ServiceException("智能合约升级失败: " + e.getMessage());
        }
    }
    
    @Override
    public String executeContract(String contractAddress, String methodName, Object... params) {
        try {
            log.info("执行智能合约方法: {} -> {}", contractAddress, methodName);
            
            // 1. 验证合约存在且活跃
            SmartContract contract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (contract == null || !"ACTIVE".equals(contract.getContractStatus())) {
                throw new ServiceException("合约不存在或不可用: " + contractAddress);
            }
            
            // 2. Gas优化检查
            Map<String, Object> gasOptimization = optimizeGasUsage(contractAddress, methodName, params);
            if ((Boolean) gasOptimization.get("needOptimization")) {
                log.warn("Gas使用可能过高: {}", gasOptimization.get("suggestion"));
            }
            
            // 3. 执行合约方法
            String result = blockchainIntegrator.executeSmartContract(contractAddress, methodName, params);
            
            // 4. 记录执行日志
            recordContractExecution(contractAddress, methodName, params, result);
            
            log.info("智能合约执行成功: {} -> {} = {}", contractAddress, methodName, result);
            return result;
            
        } catch (Exception e) {
            log.error("智能合约执行失败: {} -> {}", contractAddress, methodName, e);
            throw new ServiceException("智能合约执行失败: " + e.getMessage());
        }
    }
    
    @Override
    public Object queryContract(String contractAddress, String methodName, Object... params) {
        try {
            log.debug("查询智能合约: {} -> {}", contractAddress, methodName);
            
            // 验证合约存在
            SmartContract contract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (contract == null) {
                throw new ServiceException("合约不存在: " + contractAddress);
            }
            
            // 执行查询
            Map<String, Object> queryParams = new HashMap<>();
            queryParams.put("contractAddress", contractAddress);
            queryParams.put("methodName", methodName);
            queryParams.put("params", params);
            
            Map<String, Object> result = blockchainIntegrator.queryChainData(queryParams);
            
            log.debug("智能合约查询完成: {} -> {}", contractAddress, methodName);
            return result;
            
        } catch (Exception e) {
            log.error("智能合约查询失败: {} -> {}", contractAddress, methodName, e);
            throw new ServiceException("智能合约查询失败: " + e.getMessage());
        }
    }
    
    @Override
    public String createFundAllocationContract(Long escrowAccountId, BigDecimal totalAmount, Map<String, Object> priorityRules) {
        try {
            log.info("创建资金分配合约: escrowAccountId={}, totalAmount={}", escrowAccountId, totalAmount);
            
            // 1. 构建合约代码
            String contractCode = generateFundAllocationContractCode(escrowAccountId, totalAmount, priorityRules);
            String contractAbi = generateFundAllocationContractAbi();
            
            // 2. 部署合约
            String contractName = "FundAllocation_" + escrowAccountId + "_" + System.currentTimeMillis();
            String contractAddress = deployContract(contractName, contractCode, contractAbi, escrowAccountId, totalAmount);
            
            // 3. 初始化优先级规则
            for (Map.Entry<String, Object> rule : priorityRules.entrySet()) {
                setPaymentPriority(contractAddress, 
                    Integer.valueOf(rule.getKey()), 
                    (String) ((Map<?, ?>) rule.getValue()).get("recipient"),
                    new BigDecimal(((Map<?, ?>) rule.getValue()).get("amount").toString()));
            }
            
            log.info("资金分配合约创建成功: {}", contractAddress);
            return contractAddress;
            
        } catch (Exception e) {
            log.error("创建资金分配合约失败", e);
            throw new ServiceException("创建资金分配合约失败: " + e.getMessage());
        }
    }
    
    @Override
    public Map<String, Object> executeFundAllocation(String contractAddress, Map<String, Object> allocationPlan) {
        try {
            log.info("执行资金分配: {}", contractAddress);
            
            Map<String, Object> result = new HashMap<>();
            
            // 1. 验证分配计划
            validateAllocationPlan(allocationPlan);
            
            // 2. 执行分配
            String executionResult = executeContract(contractAddress, "allocateFunds", allocationPlan);
            
            // 3. 构建返回结果
            result.put("status", "SUCCESS");
            result.put("executionResult", executionResult);
            result.put("allocationPlan", allocationPlan);
            result.put("executionTime", DateUtils.getNowDate());
            
            log.info("资金分配执行成功: {}", contractAddress);
            return result;
            
        } catch (Exception e) {
            log.error("资金分配执行失败: {}", contractAddress, e);
            Map<String, Object> result = new HashMap<>();
            result.put("status", "FAILED");
            result.put("error", e.getMessage());
            return result;
        }
    }
    @Override
    public boolean setPaymentPriority(String contractAddress, Integer priorityLevel, String recipient, BigDecimal amount) {
        try {
            log.info("设置支付优先级: {} -> level={}, recipient={}, amount={}", 
                contractAddress, priorityLevel, recipient, amount);
            
            // 执行合约方法设置优先级
            String result = executeContract(contractAddress, "setPaymentPriority", priorityLevel, recipient, amount);
            
            boolean success = "SUCCESS".equals(result);
            log.info("支付优先级设置{}: {}", success ? "成功" : "失败", contractAddress);
            return success;
            
        } catch (Exception e) {
            log.error("设置支付优先级失败: {}", contractAddress, e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> executePriorityPayment(String contractAddress, BigDecimal availableAmount) {
        try {
            log.info("执行优先级支付: {} -> amount={}", contractAddress, availableAmount);
            
            Map<String, Object> result = new HashMap<>();
            
            // 1. 获取优先级列表
            Object priorityData = queryContract(contractAddress, "getPriorityList");
            
            // 2. 执行优先级支付
            String executionResult = executeContract(contractAddress, "executePriorityPayment", availableAmount);
            
            // 3. 构建返回结果
            result.put("status", "SUCCESS");
            result.put("executionResult", executionResult);
            result.put("availableAmount", availableAmount);
            result.put("priorityData", priorityData);
            result.put("executionTime", DateUtils.getNowDate());
            
            log.info("优先级支付执行成功: {}", contractAddress);
            return result;
            
        } catch (Exception e) {
            log.error("优先级支付执行失败: {}", contractAddress, e);
            Map<String, Object> result = new HashMap<>();
            result.put("status", "FAILED");
            result.put("error", e.getMessage());
            return result;
        }
    }
    
    @Override
    public Map<String, Object> auditContractSecurity(String contractCode, String contractAbi) {
        try {
            log.info("执行合约安全审计");
            
            Map<String, Object> auditResult = new HashMap<>();
            List<String> issues = new ArrayList<>();
            List<String> warnings = new ArrayList<>();
            
            // 1. 代码静态分析
            performStaticAnalysis(contractCode, issues, warnings);
            
            // 2. ABI安全检查
            performAbiSecurityCheck(contractAbi, issues, warnings);
            
            // 3. 常见漏洞检查
            performVulnerabilityCheck(contractCode, issues, warnings);
            
            // 4. Gas优化检查
            performGasOptimizationCheck(contractCode, warnings);
            
            // 5. 确定审计结果
            String status = issues.isEmpty() ? "PASSED" : "FAILED";
            String message = issues.isEmpty() ? "安全审计通过" : "发现安全问题: " + String.join(", ", issues);
            
            auditResult.put("status", status);
            auditResult.put("message", message);
            auditResult.put("issues", issues);
            auditResult.put("warnings", warnings);
            auditResult.put("auditTime", DateUtils.getNowDate());
            
            log.info("合约安全审计完成: status={}, issues={}, warnings={}", status, issues.size(), warnings.size());
            return auditResult;
            
        } catch (Exception e) {
            log.error("合约安全审计失败", e);
            Map<String, Object> auditResult = new HashMap<>();
            auditResult.put("status", "ERROR");
            auditResult.put("message", "审计过程出错: " + e.getMessage());
            return auditResult;
        }
    }
    
    @Override
    public boolean setContractPermissions(String contractAddress, String userAddress, List<String> permissions) {
        try {
            log.info("设置合约权限: {} -> user={}, permissions={}", contractAddress, userAddress, permissions);
            
            // 1. 验证权限列表
            validatePermissions(permissions);
            
            // 2. 更新权限缓存
            contractPermissions.computeIfAbsent(contractAddress, k -> new ConcurrentHashMap<>())
                .put(userAddress, new ArrayList<>(permissions));
            
            // 3. 执行合约方法设置权限
            String result = executeContract(contractAddress, "setPermissions", userAddress, permissions);
            
            boolean success = "SUCCESS".equals(result);
            log.info("合约权限设置{}: {}", success ? "成功" : "失败", contractAddress);
            return success;
            
        } catch (Exception e) {
            log.error("设置合约权限失败: {}", contractAddress, e);
            return false;
        }
    }
    
    @Override
    public boolean checkContractPermission(String contractAddress, String userAddress, String operation) {
        try {
            log.debug("检查合约权限: {} -> user={}, operation={}", contractAddress, userAddress, operation);
            
            // 1. 从缓存检查权限
            Map<String, List<String>> contractPerms = contractPermissions.get(contractAddress);
            if (contractPerms != null) {
                List<String> userPerms = contractPerms.get(userAddress);
                if (userPerms != null && userPerms.contains(operation)) {
                    return true;
                }
            }
            
            // 2. 从合约查询权限
            Object result = queryContract(contractAddress, "checkPermission", userAddress, operation);
            boolean hasPermission = Boolean.TRUE.equals(result);
            
            log.debug("权限检查结果: {} -> user={}, operation={}, hasPermission={}", 
                contractAddress, userAddress, operation, hasPermission);
            return hasPermission;
            
        } catch (Exception e) {
            log.error("检查合约权限失败: {}", contractAddress, e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> optimizeGasUsage(String contractAddress, String methodName, Object... params) {
        try {
            log.debug("优化Gas使用: {} -> {}", contractAddress, methodName);
            
            Map<String, Object> optimization = new HashMap<>();
            
            // 1. 检查缓存
            String cacheKey = contractAddress + ":" + methodName;
            Map<String, Object> cached = gasOptimizationCache.get(cacheKey);
            if (cached != null) {
                return cached;
            }
            
            // 2. 估算Gas使用
            long estimatedGas = estimateGasUsage(contractAddress, methodName, params);
            
            // 3. 分析优化建议
            List<String> suggestions = new ArrayList<>();
            boolean needOptimization = false;
            
            if (estimatedGas > 100000) {
                needOptimization = true;
                suggestions.add("Gas使用量较高，建议优化合约逻辑");
            }
            
            if (params.length > 5) {
                suggestions.add("参数过多，建议使用结构体传参");
            }
            
            // 4. 构建优化结果
            optimization.put("estimatedGas", estimatedGas);
            optimization.put("needOptimization", needOptimization);
            optimization.put("suggestions", suggestions);
            optimization.put("optimizationTime", DateUtils.getNowDate());
            
            // 5. 缓存结果
            gasOptimizationCache.put(cacheKey, optimization);
            
            log.debug("Gas优化分析完成: {} -> estimatedGas={}, needOptimization={}", 
                contractAddress, estimatedGas, needOptimization);
            return optimization;
            
        } catch (Exception e) {
            log.error("Gas优化分析失败: {}", contractAddress, e);
            Map<String, Object> optimization = new HashMap<>();
            optimization.put("error", e.getMessage());
            return optimization;
        }
    }
    @Override
    public boolean registerOracle(String oracleName, String oracleAddress, String dataType, Long updateInterval) {
        try {
            log.info("注册Oracle数据源: name={}, address={}, type={}", oracleName, oracleAddress, dataType);
            
            Map<String, Object> oracleConfig = new HashMap<>();
            oracleConfig.put("oracleName", oracleName);
            oracleConfig.put("oracleAddress", oracleAddress);
            oracleConfig.put("dataType", dataType);
            oracleConfig.put("updateInterval", updateInterval);
            
            boolean result = oracleService.registerOracle(oracleConfig);
            
            log.info("Oracle注册{}: {}", result ? "成功" : "失败", oracleName);
            return result;
            
        } catch (Exception e) {
            log.error("Oracle注册失败: {}", oracleName, e);
            return false;
        }
    }
    
    @Override
    public Object getOracleData(String oracleName, String dataKey) {
        try {
            log.debug("获取Oracle数据: {} -> {}", oracleName, dataKey);
            
            Object data = oracleService.getOracleData(oracleName, dataKey);
            
            log.debug("Oracle数据获取完成: {} -> {} = {}", oracleName, dataKey, data);
            return data;
            
        } catch (Exception e) {
            log.error("获取Oracle数据失败: {} -> {}", oracleName, dataKey, e);
            return null;
        }
    }
    
    @Override
    public boolean validateOracleData(String oracleName, String dataKey, Object expectedValue) {
        try {
            log.debug("验证Oracle数据: {} -> {} = {}", oracleName, dataKey, expectedValue);
            
            boolean result = oracleService.validateOracleData(oracleName, dataKey, expectedValue);
            
            log.debug("Oracle数据验证{}: {} -> {}", result ? "通过" : "失败", oracleName, dataKey);
            return result;
            
        } catch (Exception e) {
            log.error("Oracle数据验证失败: {} -> {}", oracleName, dataKey, e);
            return false;
        }
    }
    
    @Override
    public boolean updateOracleData(String oracleName, String dataKey, Object dataValue, String signature) {
        try {
            log.info("更新Oracle数据: {} -> {} = {}", oracleName, dataKey, dataValue);
            
            Map<String, Object> dataUpdates = new HashMap<>();
            dataUpdates.put(dataKey, dataValue);
            dataUpdates.put("signature", signature);
            
            boolean result = oracleService.updateOracleData(oracleName, dataUpdates);
            
            log.info("Oracle数据更新{}: {} -> {}", result ? "成功" : "失败", oracleName, dataKey);
            return result;
            
        } catch (Exception e) {
            log.error("Oracle数据更新失败: {} -> {}", oracleName, dataKey, e);
            return false;
        }
    }
    
    @Override
    public String startContractMonitoring(String contractAddress, Map<String, Object> monitorConfig) {
        try {
            log.info("启动合约监控: {}", contractAddress);
            
            // 1. 创建监控记录
            ContractMonitor monitor = new ContractMonitor();
            monitor.setContractAddress(contractAddress);
            monitor.setMonitorName("Monitor_" + contractAddress.substring(0, 8) + "_" + System.currentTimeMillis());
            monitor.setMonitorType((String) monitorConfig.getOrDefault("type", "EXECUTION"));
            monitor.setMonitorConfig(serializeMonitorConfig(monitorConfig));
            monitor.setMonitorStatus("ACTIVE");
            monitor.setStartTime(DateUtils.getNowDate());
            monitor.setCheckInterval((Long) monitorConfig.getOrDefault("checkInterval", 60L));
            monitor.setAlertThreshold((String) monitorConfig.getOrDefault("alertThreshold", "ERROR"));
            monitor.setAlertCount(0);
            monitor.setDescription("合约监控: " + contractAddress);
            
            contractMonitorMapper.insertContractMonitor(monitor);
            
            // 2. 启动监控任务
            String monitorId = monitor.getMonitorId().toString();
            startMonitoringTask(monitorId, monitor);
            
            log.info("合约监控启动成功: {} -> {}", contractAddress, monitorId);
            return monitorId;
            
        } catch (Exception e) {
            log.error("启动合约监控失败: {}", contractAddress, e);
            throw new ServiceException("启动合约监控失败: " + e.getMessage());
        }
    }
    
    @Override
    public boolean stopContractMonitoring(String monitorId) {
        try {
            log.info("停止合约监控: {}", monitorId);
            
            Long id = Long.valueOf(monitorId);
            int result = contractMonitorMapper.stopMonitor(id, DateUtils.getNowDate());
            
            boolean success = result > 0;
            log.info("合约监控停止{}: {}", success ? "成功" : "失败", monitorId);
            return success;
            
        } catch (Exception e) {
            log.error("停止合约监控失败: {}", monitorId, e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> getContractExecutionStatus(String contractAddress, String txHash) {
        try {
            log.debug("获取合约执行状态: {} -> {}", contractAddress, txHash);
            
            Map<String, Object> status = new HashMap<>();
            
            // 1. 从区块链获取交易状态
            com.ruoyi.blockchain.domain.BlockchainTransaction transaction = blockchainIntegrator.getTransactionDetails(txHash);
            if (transaction != null) {
                status.put("transactionStatus", transaction.getTransactionStatus());
                status.put("blockNumber", transaction.getBlockNumber());
                status.put("gasUsed", transaction.getGasUsed());
            }
            
            // 2. 获取合约状态
            SmartContract contract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (contract != null) {
                status.put("contractStatus", contract.getContractStatus());
                status.put("contractVersion", contract.getContractVersion());
            }
            
            status.put("queryTime", DateUtils.getNowDate());
            
            log.debug("合约执行状态获取完成: {}", contractAddress);
            return status;
            
        } catch (Exception e) {
            log.error("获取合约执行状态失败: {}", contractAddress, e);
            Map<String, Object> status = new HashMap<>();
            status.put("error", e.getMessage());
            return status;
        }
    }
    
    @Override
    public boolean rollbackContractExecution(String contractAddress, String txHash, String rollbackReason) {
        try {
            log.warn("回滚合约执行: {} -> {}, reason={}", contractAddress, txHash, rollbackReason);
            
            // 1. 验证合约和交易
            SmartContract contract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (contract == null) {
                throw new ServiceException("合约不存在: " + contractAddress);
            }
            
            // 2. 执行回滚逻辑
            String result = executeContract(contractAddress, "rollback", txHash, rollbackReason);
            
            // 3. 记录回滚事件
            recordRollbackEvent(contractAddress, txHash, rollbackReason, result);
            
            boolean success = "SUCCESS".equals(result);
            log.warn("合约执行回滚{}: {} -> {}", success ? "成功" : "失败", contractAddress, txHash);
            return success;
            
        } catch (Exception e) {
            log.error("合约执行回滚失败: {} -> {}", contractAddress, txHash, e);
            return false;
        }
    }
    
    @Override
    public Map<String, Object> handleContractException(String contractAddress, Exception exception, String recoveryAction) {
        try {
            log.error("处理合约异常: {} -> {}, action={}", contractAddress, exception.getMessage(), recoveryAction);
            
            Map<String, Object> result = new HashMap<>();
            
            // 1. 分析异常类型
            String exceptionType = classifyException(exception);
            
            // 2. 执行恢复动作
            boolean recovered = false;
            switch (recoveryAction) {
                case "PAUSE":
                    recovered = pauseContract(contractAddress, "异常暂停: " + exception.getMessage());
                    break;
                case "RETRY":
                    recovered = retryContractOperation(contractAddress, exception);
                    break;
                case "ROLLBACK":
                    recovered = performEmergencyRollback(contractAddress, exception);
                    break;
                default:
                    log.warn("未知的恢复动作: {}", recoveryAction);
            }
            
            // 3. 构建处理结果
            result.put("exceptionType", exceptionType);
            result.put("recoveryAction", recoveryAction);
            result.put("recovered", recovered);
            result.put("handleTime", DateUtils.getNowDate());
            result.put("message", exception.getMessage());
            
            log.error("合约异常处理完成: {} -> recovered={}", contractAddress, recovered);
            return result;
            
        } catch (Exception e) {
            log.error("处理合约异常失败: {}", contractAddress, e);
            Map<String, Object> result = new HashMap<>();
            result.put("error", e.getMessage());
            result.put("recovered", false);
            return result;
        }
    }
    @Override
    public boolean pauseContract(String contractAddress, String reason) {
        try {
            log.warn("暂停合约: {} -> reason={}", contractAddress, reason);
            
            // 1. 更新合约状态
            SmartContract contract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (contract == null) {
                throw new ServiceException("合约不存在: " + contractAddress);
            }
            
            int result = smartContractMapper.updateContractStatus(contract.getContractId(), "PAUSED");
            
            // 2. 执行合约暂停方法
            if (result > 0) {
                executeContract(contractAddress, "pause", reason);
            }
            
            boolean success = result > 0;
            log.warn("合约暂停{}: {}", success ? "成功" : "失败", contractAddress);
            return success;
            
        } catch (Exception e) {
            log.error("暂停合约失败: {}", contractAddress, e);
            return false;
        }
    }
    
    @Override
    public boolean resumeContract(String contractAddress) {
        try {
            log.info("恢复合约: {}", contractAddress);
            
            // 1. 更新合约状态
            SmartContract contract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (contract == null) {
                throw new ServiceException("合约不存在: " + contractAddress);
            }
            
            int result = smartContractMapper.updateContractStatus(contract.getContractId(), "ACTIVE");
            
            // 2. 执行合约恢复方法
            if (result > 0) {
                executeContract(contractAddress, "resume");
            }
            
            boolean success = result > 0;
            log.info("合约恢复{}: {}", success ? "成功" : "失败", contractAddress);
            return success;
            
        } catch (Exception e) {
            log.error("恢复合约失败: {}", contractAddress, e);
            return false;
        }
    }
    
    @Override
    public boolean destroyContract(String contractAddress, String reason) {
        try {
            log.warn("销毁合约: {} -> reason={}", contractAddress, reason);
            
            // 1. 暂停合约
            pauseContract(contractAddress, "准备销毁: " + reason);
            
            // 2. 停止所有监控
            List<ContractMonitor> monitors = contractMonitorMapper.selectContractMonitorByContractAddress(contractAddress);
            for (ContractMonitor monitor : monitors) {
                stopContractMonitoring(monitor.getMonitorId().toString());
            }
            
            // 3. 执行合约销毁方法
            executeContract(contractAddress, "destroy", reason);
            
            // 4. 更新合约状态
            SmartContract contract = smartContractMapper.selectSmartContractByContractAddress(contractAddress);
            if (contract != null) {
                smartContractMapper.updateContractStatus(contract.getContractId(), "DESTROYED");
            }
            
            // 5. 清理权限缓存
            contractPermissions.remove(contractAddress);
            
            log.warn("合约销毁完成: {}", contractAddress);
            return true;
            
        } catch (Exception e) {
            log.error("销毁合约失败: {}", contractAddress, e);
            return false;
        }
    }
    
    @Override
    public SmartContract getContractInfo(String contractAddress) {
        try {
            return smartContractMapper.selectSmartContractByContractAddress(contractAddress);
        } catch (Exception e) {
            log.error("获取合约信息失败: {}", contractAddress, e);
            return null;
        }
    }
    
    @Override
    public List<SmartContract> getContractList(String contractType, String contractStatus) {
        try {
            SmartContract query = new SmartContract();
            query.setContractType(contractType);
            query.setContractStatus(contractStatus);
            
            return smartContractMapper.selectSmartContractList(query);
        } catch (Exception e) {
            log.error("获取合约列表失败: type={}, status={}", contractType, contractStatus, e);
            return new ArrayList<>();
        }
    }
    
    // ==================== 私有辅助方法 ====================
    
    /**
     * 创建默认监控配置
     */
    private Map<String, Object> createDefaultMonitorConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("type", "EXECUTION");
        config.put("checkInterval", 60L);
        config.put("alertThreshold", "ERROR");
        config.put("enableGasMonitoring", true);
        config.put("enablePermissionMonitoring", true);
        return config;
    }
    
    /**
     * 计算哈希值
     */
    private String calculateHash(String data) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(data.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new ServiceException("哈希计算失败: " + e.getMessage());
        }
    }
    
    /**
     * 版本号递增
     */
    private String incrementVersion(String version) {
        try {
            String[] parts = version.split("\\.");
            int major = Integer.parseInt(parts[0]);
            int minor = Integer.parseInt(parts[1]);
            int patch = Integer.parseInt(parts[2]);
            
            patch++;
            if (patch >= 10) {
                patch = 0;
                minor++;
                if (minor >= 10) {
                    minor = 0;
                    major++;
                }
            }
            
            return major + "." + minor + "." + patch;
        } catch (Exception e) {
            return "1.0.1";
        }
    }
    
    /**
     * 执行数据迁移
     */
    private void performDataMigration(String oldAddress, String newAddress, Map<String, Object> migrationData) {
        log.info("执行数据迁移: {} -> {}", oldAddress, newAddress);
        
        // 实现数据迁移逻辑
        for (Map.Entry<String, Object> entry : migrationData.entrySet()) {
            try {
                executeContract(newAddress, "migrateData", entry.getKey(), entry.getValue());
            } catch (Exception e) {
                log.error("数据迁移失败: key={}", entry.getKey(), e);
            }
        }
    }
    
    /**
     * 记录合约执行
     */
    private void recordContractExecution(String contractAddress, String methodName, Object[] params, String result) {
        // 记录执行日志的逻辑
        log.info("记录合约执行: {} -> {} = {}", contractAddress, methodName, result);
    }
    
    /**
     * 验证分配计划
     */
    private void validateAllocationPlan(Map<String, Object> allocationPlan) {
        if (allocationPlan == null || allocationPlan.isEmpty()) {
            throw new ServiceException("分配计划不能为空");
        }
        
        // 验证分配计划的逻辑
        if (!allocationPlan.containsKey("totalAmount")) {
            throw new ServiceException("分配计划必须包含总金额");
        }
    }
    
    /**
     * 生成资金分配合约代码
     */
    private String generateFundAllocationContractCode(Long escrowAccountId, BigDecimal totalAmount, Map<String, Object> priorityRules) {
        // 生成智能合约代码的逻辑
        return "// Fund Allocation Contract Code for account: " + escrowAccountId;
    }
    
    /**
     * 生成资金分配合约ABI
     */
    private String generateFundAllocationContractAbi() {
        // 生成合约ABI的逻辑
        return "[{\"type\":\"function\",\"name\":\"allocateFunds\"}]";
    }
    
    /**
     * 执行静态分析
     */
    private void performStaticAnalysis(String contractCode, List<String> issues, List<String> warnings) {
        // 静态代码分析逻辑
        if (contractCode.contains("selfdestruct")) {
            issues.add("包含危险的selfdestruct调用");
        }
        
        if (contractCode.contains("tx.origin")) {
            warnings.add("使用tx.origin可能存在安全风险");
        }
    }
    
    /**
     * 执行ABI安全检查
     */
    private void performAbiSecurityCheck(String contractAbi, List<String> issues, List<String> warnings) {
        // ABI安全检查逻辑
        if (contractAbi == null || contractAbi.trim().isEmpty()) {
            issues.add("合约ABI不能为空");
        }
    }
    
    /**
     * 执行漏洞检查
     */
    private void performVulnerabilityCheck(String contractCode, List<String> issues, List<String> warnings) {
        // 常见漏洞检查逻辑
        if (contractCode.contains("call.value")) {
            warnings.add("使用call.value可能存在重入攻击风险");
        }
    }
    
    /**
     * 执行Gas优化检查
     */
    private void performGasOptimizationCheck(String contractCode, List<String> warnings) {
        // Gas优化检查逻辑
        if (contractCode.contains("for") && contractCode.contains("array.length")) {
            warnings.add("循环中使用array.length可能消耗过多Gas");
        }
    }
    
    /**
     * 验证权限列表
     */
    private void validatePermissions(List<String> permissions) {
        List<String> validPermissions = Arrays.asList("READ", "WRITE", "EXECUTE", "ADMIN", "DEPLOY", "UPGRADE");
        for (String permission : permissions) {
            if (!validPermissions.contains(permission)) {
                throw new ServiceException("无效的权限: " + permission);
            }
        }
    }
    
    /**
     * 估算Gas使用量
     */
    private long estimateGasUsage(String contractAddress, String methodName, Object[] params) {
        // Gas估算逻辑
        long baseGas = 21000;
        long methodGas = methodName.length() * 100;
        long paramsGas = params.length * 1000;
        
        return baseGas + methodGas + paramsGas;
    }
    
    /**
     * 序列化监控配置
     */
    private String serializeMonitorConfig(Map<String, Object> config) {
        // 简单的JSON序列化
        StringBuilder sb = new StringBuilder("{");
        boolean first = true;
        for (Map.Entry<String, Object> entry : config.entrySet()) {
            if (!first) sb.append(",");
            sb.append("\"").append(entry.getKey()).append("\":\"").append(entry.getValue()).append("\"");
            first = false;
        }
        sb.append("}");
        return sb.toString();
    }
    
    /**
     * 启动监控任务
     */
    private void startMonitoringTask(String monitorId, ContractMonitor monitor) {
        contractMonitorScheduler.scheduleAtFixedRate(() -> {
            try {
                performContractCheck(monitor);
            } catch (Exception e) {
                log.error("合约监控检查失败: monitorId={}", monitorId, e);
            }
        }, 0, monitor.getCheckInterval(), TimeUnit.SECONDS);
    }
    
    /**
     * 执行合约检查
     */
    private void performContractCheck(ContractMonitor monitor) {
        // 合约监控检查逻辑
        log.debug("执行合约检查: {}", monitor.getContractAddress());
        
        // 更新最后检查时间
        contractMonitorMapper.updateLastCheckTime(monitor.getMonitorId(), DateUtils.getNowDate());
    }
    
    /**
     * 记录回滚事件
     */
    private void recordRollbackEvent(String contractAddress, String txHash, String reason, String result) {
        log.warn("记录回滚事件: {} -> {}, reason={}, result={}", contractAddress, txHash, reason, result);
    }
    
    /**
     * 分类异常类型
     */
    private String classifyException(Exception exception) {
        String message = exception.getMessage().toLowerCase();
        if (message.contains("gas")) {
            return "GAS_ERROR";
        } else if (message.contains("revert")) {
            return "REVERT_ERROR";
        } else if (message.contains("timeout")) {
            return "TIMEOUT_ERROR";
        } else {
            return "UNKNOWN_ERROR";
        }
    }
    
    /**
     * 重试合约操作
     */
    private boolean retryContractOperation(String contractAddress, Exception exception) {
        // 重试逻辑
        log.info("重试合约操作: {}", contractAddress);
        return true;
    }
    
    /**
     * 执行紧急回滚
     */
    private boolean performEmergencyRollback(String contractAddress, Exception exception) {
        // 紧急回滚逻辑
        log.warn("执行紧急回滚: {}", contractAddress);
        return pauseContract(contractAddress, "紧急回滚: " + exception.getMessage());
    }
}