系统正在处理您的请求.请稍后:DIV的另一种用法.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>拍拍印</title> <style> body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; } /* 新增滑动轮播关键样式 */ .container { overflow: hidden; position: relative; width: 100vw; height: 100vh; } .slide-track { display: flex; width: 100%; height: 100vh; transition: transform 1.5s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑过渡效果 */ } .slide { flex: 1 0 100vw; /* 每张占满视口宽度 */ background-size: cover; background-position: center; } /* 无限循环关键技巧) */ .slide-track::before, .slide-track::after { content: ''; flex: 100vw; /* 复制首尾图片实现无缝 */ background-image: inherit; } .content { position: absolute; top: 35.5%; left: 4.2%; display: flex; flex-direction: column; justify-content: center; align-items: center; margin: 0 auto; } .box { display: grid; grid-template-columns: repeat(2, 1fr); /* 两列 */ gap: 36px; margin-left: 22px; margin-top: -20px; } .box.no-margin { margin-top: 0 !important; } .item { background-color: #B13627; border-radius: 50px; width: 455px; height: 512px; } .item2 { background-color: #B13627; border-radius: 40px; width: 455px; margin-top: 20px; } .topDiv { width: 100%; height: 172px; } .divP { width: 70%; height: 86px; background-color: #00000000; color: #ffffff; font-size: 64px; font-weight: 700; letter-spacing: 2px; margin-left: 25px; } .divP2 { width: 240px; height: 48px; background-color: #ffffff; color: #000; font-size: 24px; letter-spacing: 2px; margin-left: 30px; display: flex; align-items: center; justify-content: center; margin-top: -50px; border-radius: 25px } .bottomDiv { position: relative; /* 使子元素的绝对定位相对于此元素 */ height: 307px; /* 确保容器有确定的高度 */ } .butDiv, .butDiv2 { position: absolute; left: 20px; bottom: 20px; /* 放置在底部 */ width: calc(100% - 40px); /* 宽度减去左右边距 */ z-index: 10; /* 确保它在图片上方 */ margin-top: 0; /* 移除之前的margin-top */ } /* 调整报纸头条部分 */ .item .butDiv { margin-top: 0; top: auto; /* 重置顶部位置 */ bottom: 20px; /* 放置在底部 */ margin-left: 0; /* 移除左外边距 */ } /* 修改斑马日报和自助打印的按钮位置 */ .item2 .butDiv2 { position: absolute; width: calc(100% - 40px); bottom: 20px; top: -80px; margin-top: 0; margin-left: 0; } /* 调整按钮在卡片内的位置 */ .button, .button2 { margin-top: -13px; margin-left: 265px; position: static; /* 按钮使用默认定位 */ } /* 调整顶部区域避免重叠 */ .topDiv { margin-top: -30px; /* 适当上移 */ z-index: 5; /* 确保在butDiv之上 */ } /* 调整斑马日报和自助打印高度 */ .item2 { position: relative; /* 确保绝对定位元素有参考点 */ height: 236px; } .bottomDiv img { width: 100%; height: 100%; } .butDiv { width: 415px; height: 93px; background-color: #ffffff; border-radius: 47px; margin-top: 185px; margin-left: 20px; } .butDiv2 { width: 415px; height: 93px; background-color: #ffffff; border-radius: 47px; margin-top: 0px; margin-left: 20px; } .avaiDiv { width: 220px; height: 73px; margin-top: 16px; margin-left: 8px; } .available { font-size: 38px; margin-left: 30px; align-self: center; color: #303030; font-weight: 700; } .sizelabie { font-size: 20px; color: #606060; } .button { width: 140px; height: 73px; background-color: #000; border-radius: 50px; margin-top: -60px; margin-left: 255px; display: flex; align-items: center; justify-content: center; color: #ffffff; font-size: 25px; } .button2 { width: 140px; height: 73px; background-color: #000; border-radius: 50px; margin-top: -65px; margin-left: 255px; display: flex; align-items: center; justify-content: center; color: #ffffff; font-size: 25px; } /* 弹窗样式 */ #popup { display: none; } #popup-mask { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0, 0, 0, 0.6); z-index: 999; } #popup-content { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 1000; background: white; border-radius: 10px; padding: 40px; text-align: center; width: 70%; } #popup-content img { width: 60%; height: 60%; padding: 40px 0; } .popup-header { display: flex; justify-content: space-between; align-items: center; } #popup-close { font-size: 40px; font-weight: bold; color: #000; cursor: pointer; user-select: none; } #countdown { font-size: 26px; color: #000; text-align: right; } .title { text-align: center; font-size: 40px; color: #000; } /* 新增小项目容器样式 */ .small-items-container { display: flex; flex-direction: column; gap: 10px; width: 100%; margin-top: 20px; } /* 修改小项目宽度为100% */ .item2 { background-color: #B13627; border-radius: 40px; width: 100%; /* 从固定宽度改为100% */ height: 236px; /* 移除原来的margin-bottom */ } </style> </head> <body> <div class="container"> <div class="slide-track"> <div class="slide" style="background-image: url('./assets/bg1.png')"></div> <div class="slide" style="background-image: url('./assets/bg2.png')"></div> <div class="slide" style="background-image: url('./assets/bg1.png')"></div> </div> <div style='background-color:rgba(0, 0, 0, 0);width: 100%;height: 1280px;position: absolute; top: 33.4%;'> <img src="./assets/img.png" style="width: 100%;"> </div> <div class="content"> <div class="box" id="newsContainer"> <!-- <div class="item"> <div class="topDiv"> <p class="divP">报纸头条</p> <p class="divP2">人人都是大明星</p> </div> <div class="bottomDiv"> <img src="./assets/group.png" alt=""> <div class="butDiv"> <span >16/18</span> <div class="button">点击体验 </div> </div> </div> --> <!-- <div style="margin-top: -29px;"> <div class="item2"> <div class="topDiv"> <p class="divP">斑马日报</p> </div> <div> <div class="butDiv2"> <span>16/18</span> <div class="button2">点击体验 </div> </div> </div> </div> <div class="item2"> <div class="topDiv"> <p class="divP">自助打印</p> </div> <div> <div class="butDiv2"> <span>16/18</span> <div class="button2">点击体验 </div> </div> </div> </div> </div> --> </div> </div> </div> <!-- 弹窗结构 --> <div id="popup"> <div id="popup-mask"></div> <div id="popup-content"> <div class="popup-header"> <div id="popup-close">×</div> <div id="countdown">倒计时:120 秒</div> </div> <p class="title">微信扫码解锁自助打印</p> <img src="https://files.vchoo.net/memento/pro/34/webresource/0524893c-b50e-43bf-a0a4-0c4593aa16ac.png" alt="二维码" /> </div> </div> </div> <script> let newspaperData = [] // 获取当前页面的URL参数值 function getQueryParam(paramName) { //(去掉开头的'?') const queryString = window.location.search.substring(1); const params = queryString.split('&'); for (const param of params) { const pair = param.split('='); // 对参数名和值进行URL解码 const name = decodeURIComponent(pair[0]); const value = pair.length > 1 ? decodeURIComponent(pair[1]) : ''; if (name === paramName) { return value; } } // 找不到目标参数返回 return 'C0GSLS'; } // 创建API请求函数 async function fetchNewsData() { const codeValue = getQueryParam('terminalCode'); return fetch(`http://192.168.8.117:5175/api/v1/Common/GetModules?terminalCode=${codeValue}`, { method: "get", headers: { "Content-Type": "application/json" }, }) .then(response => response.json()) .then(res => { if (res.code === 200) { // .slice(0, 4) 截取 return res.data.slice(0, 4).map(module => ({ id: module.id, title: module.moduleName, subtitle: module.moduleDesc, available: module.photoOriginalPrice, size: module.printType == 2 ? "A3报纸" : '6寸照片', image: module.coverImage || "./assets/group.png", moduleUrl: `${module.moduleUrl}?terminalCode=${codeValue}&moduleCode=${module.moduleCode}` })); } else { console.log("请求返回错误:", res.message); return []; } }) .catch(error => { console.error('API请求错误:', error); return []; }); } // 优化初始化函数 async function init() { try { // 等待API返回数据 newspaperData = await fetchNewsData(); console.log("获取到的数据:", newspaperData); // 确保在数据获取后再渲染 renderItems(newspaperData); setupEventListeners(); setupJumpLinks(); // 启动轮播图(新增) setupSlider(); } catch (error) { console.error('初始化失败:', error); // 使用空数组渲染结构 renderItems([]); } } document.addEventListener('touchstart', function (event) { if (event.touches.length > 1) { event.preventDefault(); } }, { passive: false }); let countdownTimer = null; function showPopup() { document.getElementById('popup').style.display = 'block'; let timeLeft = 120; const countdownEl = document.getElementById('countdown'); countdownEl.textContent = `倒计时:${timeLeft} 秒`; countdownTimer = setInterval(() => { timeLeft--; countdownEl.textContent = `倒计时:${timeLeft} 秒`; if (timeLeft <= 0) { hidePopup(); } }, 1000); } // 修改后的渲染函数--判断长度渲染逻辑 function renderItems(data) { const container = document.getElementById('newsContainer'); container.innerHTML = ''; // 获取box元素 const boxElement = container.closest('.box'); if (data.length === 0) { // 没有数据时显示提示 container.innerHTML = `<div class="no-data">数据加载中,稍后...</div>`; return; } // 原有布局渲染逻辑保持不变 if (data.length === 4) { // 当数组长度为4时,添加no-margin类 boxElement.classList.add('no-margin'); // 长度为4时的布局:全部为大盒子(.item) data.forEach(item => { container.appendChild(createItem(item)); }); } else if (data.length === 5) { // 其他情况下移除no-margin类 boxElement.classList.remove('no-margin'); // 长度为5时的布局:前3个大盒子,最后2个小盒子放在第三个大盒子位置上下排列 // 第一列(包含前2个大盒子) const leftCol = document.createElement('div'); leftCol.className = 'layout-column'; leftCol.appendChild(createItem(data[0])); leftCol.appendChild(createItem(data[1])); container.appendChild(leftCol); // 第二列(包含第三个大盒子和小盒子容器) const rightCol = document.createElement('div'); rightCol.className = 'layout-column'; // 添加第三个大项目 rightCol.appendChild(createItem(data[2])); // 创建小项目容器(包含第四和第五个项目) const smallContainer = document.createElement('div'); smallContainer.className = 'small-items-container'; smallContainer.appendChild(createItem2(data[3])); smallContainer.appendChild(createItem2(data[4])); // 添加小项目容器到第二列 rightCol.appendChild(smallContainer); // 将第二列添加到容器 container.appendChild(rightCol); } else { // 通用渲染方案 - 使用网格布局 const gridContainer = document.createElement('div'); gridContainer.className = 'box'; gridContainer.style.display = 'grid'; gridContainer.style.gridTemplateColumns = 'repeat(2, 1fr)'; gridContainer.style.gap = '36px'; data.forEach(item => { // 根据位置决定渲染大项目或小项目 if (gridContainer.childElementCount < 2) { gridContainer.appendChild(createItem(item)); } else { gridContainer.appendChild(createItem2(item)); } }); container.appendChild(gridContainer); } } function hidePopup() { document.getElementById('popup').style.display = 'none'; if (countdownTimer) clearInterval(countdownTimer); } // 为静态数据添加跳转功能 function setupJumpLinks() { // 为所有按钮添加点击事件 document.querySelectorAll('.print-button').forEach(button => { button.addEventListener('click', function (e) { e.stopPropagation(); // 获取所在项目的data-moduleUrl属性 const container = this.closest('[data-module-url]'); if (container) { const url = container.dataset.moduleUrl; if (url && url !== 'undefined') { window.location.href = url; } else { console.error('无效的跳转URL'); } } }); }); } // 创建大项目(报纸头条) function createItem(item) { const itemElement = document.createElement('div'); itemElement.className = 'item'; itemElement.dataset.id = item.id; itemElement.dataset.moduleUrl = item.moduleUrl; // 添加跳转URL itemElement.innerHTML = ` <div class="topDiv print-button"> <p class="divP">${item.title}</p> <p class="divP2">${item.subtitle}</p> </div> <div class="bottomDiv print-button"> <img src="${item.image}" alt="${item.title}"> <div class="butDiv"> <div class='avaiDiv'> <span class="available"> <span class='sizelabie'>¥</span>${item.available}</span> <span class='sizelabie'> / ${item.size}</span> <div> <span class="button print-button">点击体验</span> </div> </div> `; return itemElement; } // 创建小项目(自助打印) function createItem2(item) { const itemElement = document.createElement('div'); itemElement.className = 'item2'; itemElement.dataset.id = item.id; itemElement.dataset.moduleUrl = item.moduleUrl; // 添加跳转URL itemElement.innerHTML = ` <div class="topDiv print-button"> <p class="divP">${item.title}</p> </div> <div class="bottomDiv print-button"> <div class="butDiv2"> <div class='avaiDiv'> <span class="available"> <span class='sizelabie'>¥</span>${item.available}</span> <span class='sizelabie'> / ${item.size}</span> <div> <div class="button2 print-button">点击体验</div> </div> </div> `; return itemElement; } // 事件监听处理 function setupEventListeners() { document.getElementById('newsContainer').addEventListener('click', function (e) { if (e.target.classList.contains('print-button')) { const itemContainer = e.target.closest('[data-id]'); if (itemContainer) { const itemId = itemContainer.dataset.id; showPopup(); } } }); document.getElementById('popup-mask').onclick = hidePopup; document.getElementById('popup-close').onclick = hidePopup; } // 新增轮播图设置函数 function setupSlider() { const track = document.querySelector('.slide-track'); const slides = document.querySelectorAll('.slide'); let currentIndex = 0; const intervalTime = 5000; // 确保至少有2张幻灯片 if (slides.length < 2) return; function nextSlide() { currentIndex = (currentIndex + 1) % slides.length; track.style.transform = `translateX(-${currentIndex * 100}%)`; if (currentIndex === slides.length - 1) { setTimeout(() => { track.style.transition = 'none'; currentIndex = 0; track.style.transform = 'translateX(0)'; setTimeout(() => { track.style.transition = 'transform 1.5s cubic-bezier(0.4, 0, 0.2, 1)'; }, 50); }, 1500); } } let slideInterval = setInterval(nextSlide, intervalTime); track.addEventListener('mouseenter', () => clearInterval(slideInterval)); track.addEventListener('mouseleave', () => { slideInterval = setInterval(nextSlide, intervalTime); }); } // 移除DOMContentLoaded中的测试按钮代码 document.addEventListener('DOMContentLoaded', init); </script> </body> </html> 把class="divP"的字体改为Alimama ShuHeiTi,其他包涵字体的class的样式字体改为 Alibaba PuHuiTi
06-24
# E:\AI_System\web_ui\server.py (完整可运行版) import sys import os import time import logging import json import traceback import threading import platform import psutil import datetime from pathlib import Path from functools import wraps from concurrent.futures import ThreadPoolExecutor import logging.handlers # ========== 关键修复1: 最先执行eventlet猴子补丁 ========== try: import eventlet eventlet.monkey_patch() # 必须在所有导入之前执行 print("✅ Eventlet monkey patch applied at startup") except ImportError: print("⚠️ Eventlet not installed, using threading mode") pass # 修复1:更新依赖包列表 REQUIRED_PACKAGES = [ 'flask', 'flask_socketio', 'flask_limiter', 'psutil', 'waitress' ] def check_dependencies(): """增强依赖检查功能""" missing = [] for package in REQUIRED_PACKAGES: try: __import__(package) except ImportError: missing.append(package) if missing: print(f"❌ 缺少必要的依赖包: {', '.join(missing)}") print("运行以下命令安装依赖:") print(f"pip install {' '.join(missing)}") sys.exit(1) if __name__ == '__main__': check_dependencies() # 在启动前检查依赖 # 现在导入其他模块 from flask import Flask, jsonify, request, render_template, send_from_directory from flask_socketio import SocketIO, emit from flask_limiter import Limiter from flask_limiter.util import get_remote_address # ========== 配置系统 ========== class SystemConfig: def __init__(self): self.BASE_DIR = Path(__file__).resolve().parent.parent self.HOST = '0.0.0.0' self.PORT = 5000 self.LOG_LEVEL = 'DEBUG' self.SECRET_KEY = os.getenv('SECRET_KEY', 'your_secret_key_here') self.DEBUG = True self.USE_GPU = False self.DEFAULT_MODEL = 'gpt-3.5-turbo' self.MAX_WORKERS = 4 # 目录配置 self.LOG_DIR = self.BASE_DIR / 'logs' self.LOG_DIR.mkdir(parents=True, exist_ok=True) self.CONFIG_DIR = self.BASE_DIR / 'config' self.CONFIG_DIR.mkdir(parents=True, exist_ok=True) self.AGENT_PATH = self.BASE_DIR / 'agent' self.MODEL_CACHE_DIR = self.BASE_DIR / 'model_cache' self.MODEL_CACHE_DIR.mkdir(parents=True, exist_ok=True) self.TEMPLATE_DIR = self.BASE_DIR / 'web_ui' / 'templates' self.STATIC_DIR = self.BASE_DIR / 'web_ui' / 'static' def __str__(self): return f"SystemConfig(HOST={self.HOST}, PORT={self.PORT})" config = SystemConfig() # ========== 全局协调器 ========== coordinator = None executor = ThreadPoolExecutor(max_workers=config.MAX_WORKERS) def register_coordinator(coord): global coordinator coordinator = coord if coordinator and hasattr(coordinator, 'connect_to_ui'): coordinator.connect_to_ui(update_ui) def update_ui(event): if 'socketio' in globals(): socketio.emit('system_event', event) # ========== 线程安全装饰器 ========== def synchronized(lock): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): with lock: return func(*args, **kwargs) return wrapper return decorator # ========== 日志系统 ========== def setup_logger(): """优化日志配置""" logger = logging.getLogger('WebServer') logger.setLevel(getattr(logging, config.LOG_LEVEL.upper(), logging.DEBUG)) # 清除所有现有处理器 for handler in logger.handlers[:]: logger.removeHandler(handler) # 日志格式 log_formatter = logging.Formatter( '%(asctime)s [%(levelname)s] %(name)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) # 文件日志处理器 (每天轮换,保留30天) file_handler = logging.handlers.TimedRotatingFileHandler( config.LOG_DIR / 'web_server.log', when='midnight', backupCount=30, encoding='utf-8' ) file_handler.setFormatter(log_formatter) logger.addHandler(file_handler) # 控制台日志处理器 console_handler = logging.StreamHandler() console_handler.setFormatter(log_formatter) logger.addHandler(console_handler) # 设置Flask和SocketIO日志 flask_logger = logging.getLogger('werkzeug') flask_logger.setLevel(logging.WARNING) socketio_logger = logging.getLogger('engineio') socketio_logger.setLevel(logging.WARNING) return logger logger = setup_logger() # ========== 环境管理器 ========== class EnvironmentManager: """独立的环境管理器类""" def __init__(self, config): self.config = config self.state = { 'temperature': 22.5, 'humidity': 45.0, 'light_level': 75, 'objects': [], 'last_updated': datetime.datetime.now().isoformat() } self.healthy = True self.lock = threading.Lock() @synchronized(threading.Lock()) def start(self): logger.info("环境管理器已启动") @synchronized(threading.Lock()) def get_state(self): # 更新模拟数据 self.state['temperature'] = round(20 + 5 * (time.time() % 10) / 10, 1) self.state['humidity'] = round(40 + 10 * (time.time() % 10) / 10, 1) self.state['light_level'] = round(70 + 10 * (time.time() % 10) / 10, 1) self.state['last_updated'] = datetime.datetime.now().isoformat() return self.state @synchronized(threading.Lock()) def execute_action(self, action, params): logger.info(f"执行环境动作: {action} 参数: {params}") if action == "adjust_temperature": self.state['temperature'] = params.get('value', 22.0) return True elif action == "adjust_light": self.state['light_level'] = params.get('level', 70) return True return False def is_healthy(self): return self.healthy # ========== 系统初始化 ========== class SystemInitializer: def __init__(self): self.base_dir = Path(__file__).resolve().parent.parent self.ai_core = None self.hardware_manager = None self.life_scheduler = None self.ai_agent = None self.start_time = time.time() self.environment_manager = None self.life_lock = threading.Lock() def initialize_system_paths(self): sys.path.insert(0, str(self.base_dir)) logger.info(f"项目根目录: {self.base_dir}") sub_dirs = ['agent', 'core', 'utils', 'config', 'cognitive_arch', 'environment'] for sub_dir in sub_dirs: full_path = self.base_dir / sub_dir if full_path.exists(): sys.path.insert(0, str(full_path)) logger.info(f"添加路径: {full_path}") else: logger.warning(f"目录不存在: {full_path} - 已跳过") def initialize_environment_manager(self): try: env_config = {'update_interval': 1.0, 'spatial': {'grid_size': 1.0}} self.environment_manager = EnvironmentManager(env_config) self.environment_manager.start() logger.info("✅ 环境管理器初始化成功") return self.environment_manager except Exception as e: logger.error(f"❌ 环境管理器初始化失败: {str(e)}") logger.warning("⚠️ 环境交互功能将不可用") return None def initialize_ai_core(self): logger.info("✅ 模拟AI核心初始化") self.ai_core = type('AICore', (), { 'status': 'running', 'get_state': lambda: {"status": "running", "model": "gpt-3.5-turbo"} })() def initialize_hardware_manager(self): logger.info("✅ 模拟硬件管理器初始化") self.hardware_manager = type('HardwareManager', (), { 'get_status': lambda: { "cpu_usage": psutil.cpu_percent(), "memory_usage": psutil.virtual_memory().percent, "gpu_usage": 0 } })() @synchronized(lock=threading.Lock()) def initialize_life_scheduler(self): logger.info("✅ 模拟生活调度器初始化") self.life_scheduler = type('LifeScheduler', (), { 'get_status': lambda: { "current_activity": "thinking", "next_activity": "learning", "energy": 85 } })() @synchronized(lock=threading.Lock()) def initialize_ai_agent(self): logger.info("✅ 模拟AI智能体初始化") self.ai_agent = type('AIAgent', (), { 'process_input': lambda self, input, user_id: f"你好{user_id},我收到了你的消息: '{input}'" })() def start_evolution_monitor(self): logger.info("✅ 模拟进化监视器启动") def initialize_all(self): logger.info("=" * 50) logger.info("🚀 开始初始化AI系统") logger.info("=" * 50) self.initialize_system_paths() self.initialize_ai_core() self.initialize_hardware_manager() self.initialize_life_scheduler() self.initialize_ai_agent() self.initialize_environment_manager() self.start_evolution_monitor() logger.info("✅ 所有系统组件初始化完成") return { "ai_core": self.ai_core, "hardware_manager": self.hardware_manager, "life_scheduler": self.life_scheduler, "ai_agent": self.ai_agent, "environment_manager": self.environment_manager } # ========== 环境交互路由 ========== def register_environment_routes(app): @app.route('/environment') def environment_view(): return render_template('environment_view.html') @app.route('/api/environment/state', methods=['GET']) @app.config['LIMITER'].limit("10 per minute") def get_environment_state(): env_manager = app.config['SYSTEM_COMPONENTS'].get('environment_manager') if not env_manager: return jsonify({"success": False, "error": "环境管理器未初始化"}), 503 try: state = env_manager.get_state() return jsonify(state) except Exception as e: app.logger.error(f"获取环境状态失败: {traceback.format_exc()}") return jsonify({"success": False, "error": str(e)}), 500 @app.route('/api/environment/action', methods=['POST']) @app.config['LIMITER'].limit("5 per minute") def execute_environment_action(): env_manager = app.config['SYSTEM_COMPONENTS'].get('environment_manager') if not env_manager: return jsonify({"success": False, "error": "环境管理器未初始化"}), 503 try: data = request.json action = data.get('action') params = data.get('params', {}) if not action: return jsonify({"success": False, "error": "缺少动作参数"}), 400 success = env_manager.execute_action(action, params) return jsonify({"success": success, "action": action}) except Exception as e: app.logger.error(f"执行环境动作失败: {traceback.format_exc()}") return jsonify({"success": False, "error": str(e)}), 500 # ========== 路由注册 ========== def register_routes(app): # 添加根路由 - 关键修复 @app.route('/') def home(): """根路由显示欢迎页面""" current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") return f""" <!DOCTYPE html> <html> <head> <title>AI系统控制中心</title> <style> body {{ font-family: Arial, sans-serif; margin: 40px; background-color: #f5f8fa; }} .container {{ max-width: 800px; margin: 0 auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }} h1 {{ color: #2c3e50; text-align: center; margin-bottom: 30px; }} .status {{ background: #f8f9fa; padding: 20px; border-radius: 8px; margin-top: 30px; border-left: 4px solid #3498db; }} .links {{ margin-top: 20px; display: flex; justify-content: center; flex-wrap: wrap; gap: 15px; }} .links a {{ display: inline-block; padding: 12px 25px; background: #3498db; color: white; text-decoration: none; border-radius: 4px; transition: all 0.3s ease; text-align: center; min-width: 150px; }} .links a:hover {{ background: #2980b9; transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.1); }} .footer {{ text-align: center; margin-top: 30px; color: #7f8c8d; font-size: 0.9em; }} </style> </head> <body> <div class="container"> <h1>🤖 AI系统控制中心</h1> <p>欢迎访问AI系统控制面板,选择以下功能:</p> <div class="links"> <a href="/environment">🌍 环境监控</a> <a href="/life/dashboard">📅 生活调度</a> <a href="/status">📊 系统状态</a> <a href="/health">🩺 健康检查</a> <a href="/chat">💬 聊天交互</a> </div> <div class="status"> <h3>系统状态</h3> <p>✅ 服务器已启动,运行正常</p> <p>🕒 启动时间: {current_time}</p> <p>📍 服务器地址: http://{request.host}</p> </div> <div class="footer"> <p>AI系统控制中心 v1.0 | 技术支持: support@ai-system.com</p> </div> </div> </body> </html> """ register_environment_routes(app) # 静态文件路由 @app.route('/static/<path:filename>') def static_files(filename): return send_from_directory(app.static_folder, filename) # 健康检查路由 @app.route('/health') def health_check(): return jsonify({"status": "healthy", "timestamp": datetime.datetime.now().isoformat()}) # 系统状态路由 @app.route('/status') @app.config['LIMITER'].exempt def status(): components = app.config['SYSTEM_COMPONENTS'] system_info = { "uptime": time.time() - app.config['START_TIME'], "ai_core_status": components['ai_core'].status if components['ai_core'] else "uninitialized", "hardware_status": components['hardware_manager'].get_status() if components[ 'hardware_manager'] else "uninitialized", "life_scheduler_status": components['life_scheduler'].get_status() if components[ 'life_scheduler'] else "uninitialized", "environment_status": components['environment_manager'].is_healthy() if components[ 'environment_manager'] else "uninitialized", "platform": platform.platform(), "python_version": sys.version, "memory_usage": psutil.virtual_memory().percent, "cpu_usage": psutil.cpu_percent(), "thread_count": threading.active_count(), "process_id": os.getpid() } return jsonify(system_info) # 核心系统路由 @app.route('/api/core/state') @app.config['LIMITER'].limit("10 per minute") def get_core_state(): ai_core = app.config['SYSTEM_COMPONENTS'].get('ai_core') if not ai_core: return jsonify({"error": "AI核心未初始化"}), 503 return jsonify(ai_core.get_state()) # 生活系统路由 @app.route('/life/dashboard') def life_dashboard(): return render_template('life_dashboard.html') @app.route('/api/life/status') @app.config['LIMITER'].limit("10 per minute") def get_life_status(): life_scheduler = app.config['SYSTEM_COMPONENTS'].get('life_scheduler') if not life_scheduler: return jsonify({"error": "生活调度器未初始化"}), 503 status = life_scheduler.get_status() return jsonify(status) # 聊天路由 @app.route('/chat', methods=['GET']) def chat_interface(): """聊天界面""" return render_template('chat.html') @app.route('/api/chat', methods=['POST']) @app.config['LIMITER'].limit("30 per minute") def chat_handler(): """处理聊天请求的API端点""" components = app.config['SYSTEM_COMPONENTS'] if not components['ai_agent']: return jsonify({"error": "Agent未初始化"}), 503 try: data = request.get_json() user_input = data.get('message', '') user_id = data.get('user_id', 'default') if not user_input: return jsonify({"error": "消息内容不能为空"}), 400 app.logger.info(f"聊天请求: 用户={user_id}, 内容长度={len(user_input)}") # 使用线程池异步处理 future = executor.submit(components['ai_agent'].process_input, user_input, user_id) response = future.result(timeout=10) # 10秒超时 return jsonify({"response": response}) except TimeoutError: return jsonify({"error": "处理超时"}), 504 except Exception as e: app.logger.error(f"聊天处理失败: {traceback.format_exc()}") return jsonify({"error": "聊天处理失败", "details": str(e)}), 500 # 404处理 @app.route('/<path:path>') def catch_all(path): return jsonify({"error": "路由不存在", "path": path}), 404 def register_error_handlers(app): @app.errorhandler(404) def not_found_error(error): return jsonify({"error": "资源未找到", "message": str(error)}), 404 @app.errorhandler(500) def internal_error(error): app.logger.error(f"服务器内部错误: {str(error)}") return jsonify({"error": "服务器内部错误", "message": "查看日志获取详细信息"}), 500 # ========== WebSocket处理 ========== def setup_websocket_handlers(socketio): @socketio.on('connect') def handle_connect(): logger.info('客户端已连接') socketio.emit('system_status', {'status': 'ready'}) @socketio.on('disconnect') def handle_disconnect(): logger.info('客户端已断开连接') @socketio.on('user_message') def handle_user_message(data): user_id = data.get('user_id', 'guest') message = data.get('message', '') logger.info(f"收到来自 {user_id} 的消息: {message}") # 使用线程池处理消息 def process_message(): try: global coordinator if coordinator: return coordinator.process_message(message) else: return f"已收到您的消息: {message}" except Exception as e: logger.error(f"消息处理失败: {str(e)}") return "处理消息时出错" future = executor.submit(process_message) try: response = future.result(timeout=10) socketio.emit('agent_response', { 'user_id': user_id, 'response': response }) except TimeoutError: socketio.emit('agent_response', { 'user_id': user_id, 'response': "处理超时,重试" }) # ========== 生产环境启动器 ========== def run_production_server(app): try: from waitress import serve logger.info(f"🚀 生产服务器启动: http://{config.HOST}:{config.PORT}") logger.warning("⚠️ 当前运行在生产模式 (Waitress WSGI服务器)") serve(app, host=config.HOST, port=config.PORT, threads=8) except ImportError: logger.error("❌ 缺少生产环境依赖: waitress") logger.info("运行: pip install waitress") sys.exit(1) # ========== Flask应用工厂 ========== def create_app(): app = Flask( __name__, template_folder=str(config.TEMPLATE_DIR), static_folder=str(config.STATIC_DIR), static_url_path='/static' ) app.secret_key = config.SECRET_KEY # 初始化限流器 limiter = Limiter( get_remote_address, app=app, default_limits=["200 per day", "50 per hour"], storage_uri="memory://" ) app.config['LIMITER'] = limiter system_initializer = SystemInitializer() components = system_initializer.initialize_all() app.config['SYSTEM_COMPONENTS'] = components app.config['START_TIME'] = system_initializer.start_time app.config['BASE_DIR'] = system_initializer.base_dir # 配置SocketIO async_mode = 'threading' try: import eventlet async_mode = 'eventlet' logger.info("✅ 使用eventlet异步模式") except ImportError: logger.warning("⚠️ eventlet未安装,使用threading模式") pass # 注册路由和错误处理 register_routes(app) register_error_handlers(app) # 创建SocketIO实例 socketio = SocketIO(app, async_mode=async_mode, logger=False, engineio_logger=False) setup_websocket_handlers(socketio) app.config['SOCKETIO'] = socketio return app, socketio # ========== 主程序入口 ========== if __name__ == '__main__': app, socketio = create_app() # 启动服务器 if os.environ.get('ENV') == 'production': run_production_server(app) else: logger.info(f"🚀 开发服务器启动: http://{config.HOST}:{config.PORT}") socketio.run( app, host=config.HOST, port=config.PORT, debug=config.DEBUG, use_reloader=False ) # E:\AI_System\agent\autonomous_agent.py import os import sys import time import logging import importlib import traceback import psutil import platform import threading import json from pathlib import Path from dotenv import load_dotenv from typing import Dict, Any, Optional, List, Callable from concurrent.futures import ThreadPoolExecutor from ..core.config import system_config # 使用绝对导入 - 确保路径正确 sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) from core.config import system_config from core.exceptions import DependencyError, SubsystemFailure from core.dependency_manager import DependencyManager from core.metrics import PerformanceMetrics, MetricsCollector # 全局线程池 executor = ThreadPoolExecutor(max_workers=4) class AutonomousAgent: def __init__(self): """自主智能体核心类,负责协调所有子系统""" self.logger = self._setup_logger() self.logger.info("🔁 初始化自主智能体核心模块...") self._running = False # 运行状态标志 self._background_thread = None # 后台线程 # 初始化状态跟踪 self.initialization_steps = [] self._last_env_check = 0 self._initialization_time = time.time() self.subsystem_status = {} # 子系统熔断状态 self.metrics = MetricsCollector() # 性能监控 self._status_lock = threading.Lock() # 状态锁 # 依赖管理器 self.dependency_manager = DependencyManager() try: # 记录初始化步骤 self._record_step("加载环境变量") load_dotenv() self._record_step("验证环境") self.verify_environment() self._record_step("初始化核心组件") self._initialize_core_components() self._record_step("初始化子系统") self._initialize_subsystems() self.logger.info(f"✅ 自主智能体初始化完成 (耗时: {time.time() - self._initialization_time:.2f}秒)") self.logger.info(f"初始化步骤: {', '.join(self.initialization_steps)}") # 启动后台任务线程 self._start_background_tasks() except Exception as e: self.logger.exception(f"❌ 智能体初始化失败: {str(e)}") self.logger.error(f"堆栈跟踪:\n{traceback.format_exc()}") raise RuntimeError(f"智能体初始化失败: {str(e)}") from e def _start_background_tasks(self): """启动后台任务线程""" if self._running: self.logger.warning("后台任务已在运行") return self._running = True self._background_thread = threading.Thread( target=self._background_task_loop, daemon=True, name="AutonomousAgentBackgroundTasks" ) self._background_thread.start() self.logger.info("✅ 后台任务线程已启动") def _background_task_loop(self): """后台任务循环""" while self._running: try: start_time = time.time() self.run_periodic_tasks() # 动态调整睡眠时间 task_time = time.time() - start_time sleep_time = max(0.1, 10 - task_time) # 确保至少10秒间隔 time.sleep(sleep_time) except Exception as e: self.logger.error(f"后台任务错误: {str(e)}") self.metrics.record_error('background_task') time.sleep(30) def _record_step(self, step_name: str): """记录初始化步骤""" self.initialization_steps.append(step_name) self.logger.info(f"⏳ 步骤 {len(self.initialization_steps)}: {step_name}") def verify_environment(self): """验证运行环境是否满足要求""" missing = [] warnings = [] # 检查必需模块 required_modules = [ 'os', 'sys', 'logging', 'dotenv', 'flask', 'werkzeug', 'numpy', 'transformers', 'torch', 'psutil' ] for mod in required_modules: try: importlib.import_module(mod) except ImportError: missing.append(mod) # 检查配置文件 if not hasattr(system_config, 'CONFIG_PATH') or not os.path.exists(system_config.CONFIG_PATH): self.logger.error(f"❌ 配置文件缺失: {system_config.CONFIG_PATH}") warnings.append(f"配置文件缺失: {system_config.CONFIG_PATH}") # 检查模型目录 - 如果不存在则创建 model_dir = Path(system_config.MODEL_CACHE_DIR) if not model_dir.exists(): model_dir.mkdir(parents=True, exist_ok=True) self.logger.warning(f"⚠️ 创建模型缓存目录: {model_dir}") # 检查日志目录 - 如果不存在则创建 log_dir = Path(system_config.LOG_DIR) if not log_dir.exists(): log_dir.mkdir(parents=True, exist_ok=True) self.logger.warning(f"⚠️ 创建日志目录: {log_dir}") # 处理警告 for warning in warnings: self.logger.warning(warning) # 处理缺失项 if missing: error_msg = f"环境验证失败,缺失: {', '.join(missing)}" self.logger.error(error_msg) self.dependency_manager.record_missing_dependencies(missing) raise DependencyError(error_msg) self.logger.info("✅ 环境验证通过") def _setup_logger(self) -> logging.Logger: """配置日志记录器""" logger = logging.getLogger('AutonomousAgent') logger.setLevel(system_config.LOG_LEVEL) # 创建控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(system_config.LOG_LEVEL) # 创建文件处理器 log_file = Path(system_config.LOG_DIR) / 'autonomous_agent.log' file_handler = logging.FileHandler(log_file, encoding='utf-8') file_handler.setLevel(system_config.LOG_LEVEL) # 创建格式化器 formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) console_handler.setFormatter(formatter) file_handler.setFormatter(formatter) # 添加处理器 logger.addHandler(console_handler) logger.addHandler(file_handler) logger.propagate = False return logger def _initialize_core_components(self): """初始化不依赖其他组件的核心组件""" # 获取项目根目录 base_dir = Path(__file__).resolve().parent.parent # 环境相关组件 - 使用回退实现 self.environment = self._create_fallback_environment(base_dir) self.logger.info("✅ 环境接口初始化完成") # 记录环境状态 self._log_environment_status() # 初始化状态持久化 self._load_subsystem_status() def _create_fallback_environment(self, base_dir: Path): """创建回退的环境实现""" class FallbackEnvironment: def __init__(self, base_dir): self.base_dir = base_dir self.status_file = base_dir / 'environment_status.json' def get_system_info(self): try: # 尝试从文件加载状态 if self.status_file.exists(): with open(self.status_file, 'r') as f: return json.load(f) except: pass # 创建新状态 status = { "os": platform.system(), "os_version": platform.version(), "cpu": platform.processor(), "cpu_cores": psutil.cpu_count(logical=False), "memory_total": round(psutil.virtual_memory().total / (1024 ** 3), 1), "memory_used": round(psutil.virtual_memory().used / (1024 ** 3), 1), "disk_total": round(psutil.disk_usage('/').total / (1024 ** 3), 1), "disk_used": round(psutil.disk_usage('/').used / (1024 ** 3), 1), "timestamp": time.time() } # 保存状态 try: with open(self.status_file, 'w') as f: json.dump(status, f) except: pass return status return FallbackEnvironment(base_dir) def _log_environment_status(self): """记录环境状态信息""" try: env_status = self.environment.get_system_info() or {} self.logger.info( f"📊 系统状态: OS={env_status.get('os', '未知')} {env_status.get('os_version', '')}, " f"CPU={env_status.get('cpu', '未知')} ({env_status.get('cpu_cores', 0)}核), " f"内存={env_status.get('memory_used', 0)}/{env_status.get('memory_total', 0)}GB, " f"磁盘={env_status.get('disk_used', 0)}/{env_status.get('disk_total', 0)}GB" ) except Exception as e: self.logger.error(f"环境状态获取失败: {str(e)}") self.metrics.record_error('environment_status') def _initialize_subsystems(self): """初始化所有子系统 - 使用动态导入并添加详细错误处理""" # 定义子系统初始化顺序 - 使用更简单的回退实现 subsystems = [ ('健康系统', self._create_fallback_health_system, {}), ('模型管理器', self._create_fallback_model_manager, {}), ('记忆系统', self._create_fallback_memory_system, {}), ('情感系统', self._create_fallback_affective_system, {}), ('认知架构', self._create_fallback_cognitive_architecture, {}), ('通信系统', self._create_fallback_communication_system, {}) ] # 注册子系统依赖关系 self.dependency_manager.register_dependency('通信系统', ['认知架构']) self.dependency_manager.register_dependency('情感系统', ['健康系统', '记忆系统']) self.dependency_manager.register_dependency('认知架构', ['记忆系统']) # 初始化子系统 for name, creator_func, kwargs in subsystems: try: # 检查依赖是否满足 missing_deps = self.dependency_manager.check_dependencies(name) if missing_deps: self.logger.warning(f"⚠️ 子系统 {name} 缺少依赖: {', '.join(missing_deps)}") # 尝试自动安装缺失依赖 self.dependency_manager.install_missing_dependencies(missing_deps) # 创建实例 instance = creator_func(**kwargs) setattr(self, name.lower().replace(' ', '_'), instance) self.logger.info(f"✅ {name}初始化完成") # 标记子系统为活跃状态 with self._status_lock: self.subsystem_status[name] = { 'active': True, 'error_count': 0, 'last_active': time.time(), 'last_recovery_attempt': 0 } except Exception as e: self.logger.error(f"❌ {name}初始化失败: {str(e)}") with self._status_lock: self.subsystem_status[name] = { 'active': False, 'error': str(e), 'error_count': 1, 'last_error': time.time() } # 记录指标 self.metrics.record_error(f'subsystem_init_{name.lower()}') # 保存子系统状态 self._save_subsystem_status() # 各子系统回退实现保持不变... def process_input(self, user_input: str, user_id: str = "default") -> Dict[str, Any]: """处理用户输入(通过通信系统)""" # 检查通信系统是否活跃 with self._status_lock: comm_status = self.subsystem_status.get('通信系统', {}) active = comm_status.get('active', False) if not active: self.logger.error("通信系统未激活,使用回退处理") self.metrics.record_error('communication_system_inactive') return {"response": "系统正在维护中,稍后再试"} try: # 使用性能监控 with PerformanceMetrics() as pm: # 使用线程池异步处理 future = executor.submit( self.communication_system.process_input, user_input, user_id ) response = future.result(timeout=10) # 10秒超时 # 记录性能指标 self.metrics.record_latency('process_input', pm.duration) self.metrics.record_success('process_input') self.logger.info(f"📥 处理输入: '{user_input[:30]}...' → 耗时: {pm.duration:.2f}秒") return response except TimeoutError: self.logger.warning("处理输入超时") self.metrics.record_timeout('process_input') return {"error": "处理超时,重试"} except Exception as e: # 更新错误计数 with self._status_lock: comm_status = self.subsystem_status.get('通信系统', {}) comm_status['error_count'] = comm_status.get('error_count', 0) + 1 comm_status['last_error'] = time.time() # 检查熔断条件 if comm_status['error_count'] >= 5: # 临时阈值 comm_status['active'] = False self.logger.critical(f"🚨 通信系统因连续错误被熔断!") self.metrics.record_event('circuit_breaker', '通信系统') self.logger.error(f"处理输入失败: {str(e)}") self.metrics.record_error('process_input') return {"error": "处理失败,稍后再试"} def run_periodic_tasks(self): """运行周期性任务""" task_start = time.time() tasks_executed = 0 tasks_failed = 0 # 定义任务列表 tasks = [ ('健康系统更新', lambda: self.health_system.update()), ('情感系统更新', lambda: self.affective_system.grow()), ('记忆系统维护', lambda: self.memory_system.consolidate_memories()), ('环境监控', self._monitor_environment), ('子系统心跳检查', self._check_subsystem_heartbeats), ('子系统恢复', self._recover_failed_subsystems) ] # 执行任务 for name, task_func in tasks: try: if name == '环境监控' or self._is_subsystem_active(name.split()[0]): task_func() tasks_executed += 1 except Exception as e: tasks_failed += 1 subsystem_name = name.split()[0] self.logger.error(f"{name}失败: {str(e)}", exc_info=True) self._handle_subsystem_error(subsystem_name, e) self.metrics.record_error(f'periodic_{subsystem_name.lower()}') # 记录任务执行情况 if tasks_executed > 0: task_time = time.time() - task_start self.logger.debug(f"⏱️ 执行 {tasks_executed} 项周期性任务 ({tasks_failed}失败), 耗时: {task_time:.3f}秒") self.metrics.record_latency('periodic_tasks', task_time) self.metrics.record_value('periodic_tasks_count', tasks_executed) self.metrics.record_value('periodic_tasks_failed', tasks_failed) def _is_subsystem_active(self, name: str) -> bool: """检查子系统是否活跃""" with self._status_lock: status = self.subsystem_status.get(name, {}) return status.get('active', False) def _handle_subsystem_error(self, name: str, error: Exception): """处理系统错误""" with self._status_lock: status = self.subsystem_status.get(name, {}) status['error_count'] = status.get('error_count', 0) + 1 status['last_error'] = time.time() # 检查熔断条件 if status['error_count'] >= 5: # 临时阈值 status['active'] = False self.logger.critical(f"🚨 子系统 {name} 因连续错误被熔断!") self.metrics.record_event('circuit_breaker', name) def _check_subsystem_heartbeats(self): """检查子系统心跳""" for name in list(self.subsystem_status.keys()): with self._status_lock: status = self.subsystem_status.get(name, {}) if not status.get('active', False): continue # 跳过已熔断的 subsystem = getattr(self, name.lower().replace(' ', '_'), None) if subsystem and hasattr(subsystem, 'check_heartbeat'): try: if not subsystem.check_heartbeat(): self.logger.warning(f"⚠️ 子系统 {name} 心跳检测失败") self._handle_subsystem_error(name, RuntimeError("心跳检测失败")) else: # 更新最后活跃时间 with self._status_lock: status['last_active'] = time.time() except Exception as e: self.logger.error(f"子系统 {name} 心跳检查异常: {str(e)}") self._handle_subsystem_error(name, e) self.metrics.record_error(f'heartbeat_{name.lower()}') def _recover_failed_subsystems(self): """尝试恢复失败的子系统""" for name in list(self.subsystem_status.keys()): with self._status_lock: status = self.subsystem_status.get(name, {}) if status.get('active', False): continue # 跳过活跃的 # 检查恢复条件:错误后至少等待5分钟 last_error = status.get('last_error', 0) if time.time() - last_error < 300: continue # 检查上次恢复尝试时间 last_attempt = status.get('last_recovery_attempt', 0) if time.time() - last_attempt < 600: # 每10分钟尝试一次 continue self.logger.info(f"🔄 尝试恢复子系统: {name}") status['last_recovery_attempt'] = time.time() try: # 尝试重新初始化子系统 # 这里需要根据子系统名称调用相应的初始化方法 # 简化实现:直接重置状态 subsystem = self._reinitialize_subsystem(name) setattr(self, name.lower().replace(' ', '_'), subsystem) with self._status_lock: status['active'] = True status['error_count'] = 0 status['last_error'] = 0 self.logger.info(f"✅ 子系统 {name} 恢复成功") self.metrics.record_event('subsystem_recovered', name) except Exception as e: with self._status_lock: status['active'] = False status['error_count'] += 1 status['last_error'] = time.time() self.logger.error(f"子系统 {name} 恢复失败: {str(e)}") self.metrics.record_error(f'recovery_{name.lower()}') def _reinitialize_subsystem(self, name: str) -> Any: """重新初始化子系统""" # 根据名称选择初始化方法 creators = { '健康系统': self._create_fallback_health_system, '模型管理器': self._create_fallback_model_manager, '记忆系统': self._create_fallback_memory_system, '情感系统': self._create_fallback_affective_system, '认知架构': self._create_fallback_cognitive_architecture, '通信系统': self._create_fallback_communication_system } if name in creators: return creators[name]() else: raise SubsystemFailure(f"未知子系统: {name}") def _monitor_environment(self): """监控环境状态""" try: self.logger.info("🔍 开始环境监控...") env_status = self.environment.get_system_info() or {} # 获取CPU和内存使用情况 env_status['cpu_usage'] = psutil.cpu_percent() env_status['memory_usage'] = psutil.virtual_memory().percent env_status['disk_usage'] = psutil.disk_usage('/').percent # 记录到日志 self.logger.info( f"📊 环境监控: CPU={env_status['cpu_usage']}%, " f"内存={env_status['memory_usage']}%, " f"磁盘={env_status['disk_usage']}%" ) # 记录到健康系统 if hasattr(self, 'health_system'): self.health_system.record_environment_status(env_status) # 记录指标 self.metrics.record_value('cpu_usage', env_status['cpu_usage']) self.metrics.record_value('memory_usage', env_status['memory_usage']) self.metrics.record_value('disk_usage', env_status['disk_usage']) except Exception as e: self.logger.error(f"环境监控失败: {str(e)}", exc_info=True) self.metrics.record_error('environment_monitoring') def _save_subsystem_status(self): """保存子系统状态到文件""" status_file = Path(system_config.CONFIG_DIR) / 'subsystem_status.json' try: with self._status_lock: data = { 'timestamp': time.time(), 'status': self.subsystem_status } with open(status_file, 'w') as f: json.dump(data, f, indent=2) except Exception as e: self.logger.error(f"保存子系统状态失败: {str(e)}") def _load_subsystem_status(self): """从文件加载子系统状态""" status_file = Path(system_config.CONFIG_DIR) / 'subsystem_status.json' if status_file.exists(): try: with open(status_file, 'r') as f: data = json.load(f) # 只加载24小时内的状态 if time.time() - data.get('timestamp', 0) < 86400: with self._status_lock: self.subsystem_status = data.get('status', {}) self.logger.info("加载子系统状态缓存") except Exception as e: self.logger.error(f"加载子系统状态失败: {str(e)}") def get_status(self) -> Dict[str, Any]: """获取智能体状态报告""" with self._status_lock: status_data = { "uptime": time.time() - self._initialization_time, "subsystems": { name: info.get('active', False) for name, info in self.subsystem_status.items() }, "circuit_breaker": { name: { "active": info.get('active', False), "error_count": info.get('error_count', 0), "last_error": info.get('last_error', 0) } for name, info in self.subsystem_status.items() }, "metrics": self.metrics.get_metrics(), "environment": self.environment.get_system_info() if hasattr(self, 'environment') else {} } # 添加子系统状态 for name in ['健康系统', '情感系统', '记忆系统', '模型管理器', '认知架构', '通信系统']: attr_name = name.lower().replace(' ', '_') if hasattr(self, attr_name) and hasattr(getattr(self, attr_name), 'get_status'): status_data[name] = getattr(self, attr_name).get_status() return status_data def shutdown(self): """关闭智能体""" self.logger.info("🛑 正在关闭智能体...") self._running = False # 停止线程池 executor.shutdown(wait=False) # 保存状态 self._save_subsystem_status() # 等待后台线程 if self._background_thread and self._background_thread.is_alive(): self._background_thread.join(timeout=5.0) if self._background_thread.is_alive(): self.logger.warning("后台线程未正常退出") self.logger.info("✅ 智能体已关闭") 你看看怎么修改 主要是哪个模块没启动 哪里有问题 我需要知道 你理解吗?
最新发布
08-13
<template> <div class="app-container"> <el-row :gutter="20"> <!-- 项目树菜单 --> <el-col :span="6" :xs="24"> <div class="head-container"> <el-input v-model="projectName" placeholder="输入项目名称" clearable size="mini" prefix-icon="el-icon-search" style="margin-bottom: 20px" @input="filterProjectTree" /> </div> <el-row :gutter="10" class="mb8"> <el-col :span="1.5"> <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll" >{{ isExpandAll ? '折叠' : '展开' }}</el-button> </el-col> <el-col :span="1.5"> <el-button type="primary" plain icon="el-icon-folder-add" size="mini" @click="handleAddProject" v-hasPermi="['cms:project:add']" >新增项目</el-button> </el-col> </el-row> <el-tree v-if="refreshTable" style="margin-top: 0.8rem;" :data="filteredProjectTreeData" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" :highlight-current="true" :default-expand-all="isExpandAll" ref="projectTree" empty-text="加载中,稍候" node-key="id" @node-click="handleProjectClick" > <span class="custom-tree-node" slot-scope="{ node, data }"> <div class="tree-node-content"> <el-icon class="tree-icon" :size="16"> <svg-icon v-if="node.expanded" icon-class="folder-open" /> <svg-icon v-else icon-class="folder" /> </el-icon> <div v-if="node.label && node.label.length > 25" class="node-label"> <el-tooltip :show-after="300" :content="node.label" placement="top-start"> <span>{{ ellipsis(node.label, 25) }}</span> </el-tooltip> </div> <div v-else class="node-label"> <span>{{ node.label }}</span> </div> </div> <span class="node-actions"> <el-button type="text" size="mini" icon="el-icon-edit" v-hasPermi="['cms:project:update']" @click.stop="() => handleEditProject(data)" ></el-button> <el-button type="text" size="mini" icon="el-icon-plus" v-hasPermi="['cms:project:add']" @click.stop="() => handleAddSubProject(data)" ></el-button> <el-button type="text" size="mini" icon="el-icon-delete" v-hasPermi="['cms:project:delete']" @click.stop="() => handleDeleteProject(data)" ></el-button> </span> </span> </el-tree> </el-col> <!-- 文档区域 --> <el-col :span="18" :xs="24"> <!-- 文档列表视图 --> <div v-if="activeView === 'list'" class="doc-list-container"> <el-form :model="docQueryParams" ref="docQueryForm" :inline="true" label-width="68px"> <el-form-item label="文档标题" prop="title"> <el-input v-model="docQueryParams.title" placeholder="输入文档标题" clearable size="mini" @keyup.enter.native="getDocumentList" prefix-icon="el-icon-search" /> </el-form-item> <el-form-item label="状态" prop="status"> <el-select v-model="docQueryParams.status" placeholder="状态" size="mini" clearable> <el-option label="编制中✍" value="0" /> <el-option label="待评审✊" value="1" /> <el-option label="已评审👍" value="2" /> <el-option label="修改中🔧" value="3" /> <el-option label="开发中💪" value="4" /> <el-option label="已完成开发🆗" value="5" /> </el-select> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-search" size="mini" @click="getDocumentList">搜索</el-button> <el-button icon="el-icon-refresh" size="mini" @click="resetDocQuery">重置</el-button> </el-form-item> </el-form> <div class="batch-actions"> <el-button type="success" icon="el-icon-download" size="mini" :disabled="selectedDocs.length === 0" @click="handleBatchExport" > 批量导出 ({{ selectedDocs.length }}) </el-button> </div> <el-table v-loading="docLoading" :data="documentList" highlight-current-row @row-click="handleRowClick" @selection-change="handleSelectionChange" ref="docTable" > <el-table-column type="selection" width="55" align="center" /> <el-table-column label="序号" type="index" width="50" align="center" /> <el-table-column label="编号" align="center" prop="serialNum" /> <el-table-column label="标题" align="center" prop="title" class-name="small-padding fixed-width" width="200" :show-overflow-tooltip="true" sortable > <template slot-scope="scope"> <div v-show="scope.row.title.startsWith('[诊断项]')">{{scope.row.title}}<span style="color: #303133;font-family: 'Arial', sans-serif;font-size: 12px;font-weight: normal;font-style: italic;">(v{{scope.row.articleVersion}}版本)</span></div> <el-button v-show="!scope.row.title.startsWith('[诊断项]')" size="normal" type="text" icon="el-icon-tickets" @click="getArticleInfo(scope.row.id)">{{scope.row.title}}<span style="color: #303133;font-family: 'Arial', sans-serif;font-size: 12px;font-weight: normal;font-style: italic;">(v{{scope.row.articleVersion}}版本)</span></el-button> </template> </el-table-column> <el-table-column label="进度" prop="status" width="100"> <template slot-scope="scope"> <el-tag v-if="scope.row.status === '0'" type="info" size="small">编制中✍</el-tag> <el-tag v-if="scope.row.status === '1'" type="warning" size="small">待评审✊</el-tag> <el-tag v-if="scope.row.status === '2'" type="success" size="small">已评审👍</el-tag> <el-tag v-if="scope.row.status === '3'" type="success" size="small">修改中🔧</el-tag> <el-tag v-if="scope.row.status === '4'" type="success" size="small">开发中💪</el-tag> <el-tag v-if="scope.row.status === '5'" type="success" size="small">已完成开发🆗</el-tag> </template> </el-table-column> <el-table-column label="创建人" prop="createBy" width="100" /> <el-table-column label="负责人" prop="director" width="100"/> <el-table-column label="创建时间" prop="createTime" width="140" /> <el-table-column label="操作" width="180" align="center"> <template slot-scope="scope"> <el-button size="mini" type="text" icon="el-icon-edit" @click.stop="handleEditDocument(scope.row)"></el-button> <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleDeleteDocument(scope.row)" v-hasPermi="['cms:project:deleteArticleFromProject']"></el-button> </template> </el-table-column> </el-table> <pagination v-show="docTotal>0" :total="docTotal" :page.sync="docQueryParams.pageNum" :limit.sync="docQueryParams.pageSize" @pagination="getDocumentList" /> </div> <!-- 文档详情视图 --> <div v-else-if="activeView === 'detail'" class="doc-detail-container"> <div class="doc-header"> <el-button type="text" icon="el-icon-back" @click="backToList">返回文档列表</el-button> <h2 class="doc-title"> <el-icon class="title-icon"><svg-icon icon-class="document" /></el-icon> {{ currentDocument.title }} </h2> </div> <!-- 富文本编辑器 --> <el-form :model="currentDocument" ref="docForm" label-width="80px"> <el-form-item label="文档内容"> <Tinymce :height='600' v-model='currentDocument.content'></Tinymce> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-check" @click="saveDocument">保存</el-button> <el-button icon="el-icon-close" @click="backToList">取消</el-button> </el-form-item> </el-form> </div> </el-col> </el-row> <!-- 项目编辑对话框 --> <el-dialog :title="projectDialogTitle" :visible.sync="projectDialogVisible" width="50%"> <el-form :model="projectForm" ref="projectForm" label-width="100px"> <el-form-item label="项目名称" prop="name" required> <el-input v-model="projectForm.name" placeholder="输入项目名称" prefix-icon="el-icon-folder" /> </el-form-item> <el-form-item label="上级项目" prop="parentId"> <treeselect v-model="projectForm.parentId" :options="projectTreeData" :normalizer="normalizer" placeholder="选择上级项目" /> </el-form-item> <el-form-item label="项目描述" prop="description"> <el-input type="textarea" v-model="projectForm.description" :rows="3" /> </el-form-item> </el-form> <div slot="footer"> <el-button @click="projectDialogVisible = false">取消</el-button> <el-button type="primary" icon="el-icon-check" @click="saveProject">保存</el-button> </div> </el-dialog> </div> </template> <script> import { getData, updateData } from "@/api/cms/data"; import { getProjectTree, getDocuments, saveProject, updateProject, deleteProject, removeMenusFromProject } from "@/api/cms/articleProject"; import Tinymce from '@/components/Tinymce'; import Treeselect from "@riophae/vue-treeselect"; import "@riophae/vue-treeselect/dist/vue-treeselect.css"; import axios from 'axios'; export default { name: "ProjectManagement", components: { Treeselect, Tinymce }, data() { return { // 项目树相关数据 projectName: '', projectTreeData: [], filteredProjectTreeData: [], refreshTable: true, isExpandAll: true, defaultProps: { children: "children", label: "label" }, // 项目对话框相关 projectDialogVisible: false, projectDialogTitle: '', projectForm: { id: null, name: '', parentId: null, description: '' }, // 文档列表相关 activeView: 'list', // 'list' 或 'detail' docQueryParams: { serialNums: null, title: '', status: '', pageNum: 1, pageSize: 10 }, documentList: [], docTotal: 0, docLoading: false, selectedDocs: [], // 选中的文档 ids: [], // 选中文档ID集合 // 文档详情相关 currentDocument: { id: null, menuId: null, title: '', content: '', status: '0' }, // 当前选中的项目ID(用于删除操作) currentProjectId: null, // 导出相关数据 form: { ids: [], // 导出的文档ID集合 notesExportFlag: 1 // 默认导出详细 } }; }, created() { this.getProjectTree(); }, methods: { // ================= 项目树方法 ================= ellipsis(text, maxLength) { return text.length > maxLength ? text.substring(0, maxLength) + '...' : text; }, toggleExpandAll() { this.refreshTable = false; this.isExpandAll = !this.isExpandAll; this.$nextTick(() => { this.refreshTable = true; }); }, filterNode(value, data) { if (!value) return true; return data.label.toLowerCase().includes(value.toLowerCase()); }, filterProjectTree() { this.$refs.projectTree.filter(this.projectName); }, handleProjectClick(data) { // 保存当前选中的项目ID this.currentProjectId = data.id; // 将serialNums字符串转换为数组 const serialNumsArray = data.serialNums ? data.serialNums.split(',').map(id => id.trim()) : []; // 将数组转换回逗号分隔的字符串用于查询 this.docQueryParams.serialNums = serialNumsArray.join(','); this.getDocumentList(); }, // ================= 项目管理方法 ================= handleAddProject() { this.projectForm = { id: null, name: '', parentId: null, description: '' }; this.projectDialogTitle = '新增项目'; this.projectDialogVisible = true; }, handleAddSubProject(data) { this.projectForm = { id: null, name: '', parentId: data.id, description: '' }; this.projectDialogTitle = '新增子项目'; this.projectDialogVisible = true; }, handleEditProject(data) { this.projectForm = { id: data.id, name: data.name, parentId: data.parentId, description: data.description || '' }; this.projectDialogTitle = '编辑项目'; this.projectDialogVisible = true; }, // 递归收集项目ID collectProjectIds(node) { let ids = [node.id]; if (node.children && node.children.length > 0) { node.children.forEach(child => { ids = ids.concat(this.collectProjectIds(child)); }); } return ids; }, // 修改后的删除项目方法 handleDeleteProject(data) { this.$confirm(`确定删除项目 "${data.name}" 及其所有子项目吗?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { // 递归收集所有节点ID const ids = this.collectProjectIds(data); // 调用批量删除API deleteProject(ids).then(response => { if (response.code === 200) { this.$message.success('删除成功'); this.getProjectTree(); } else { this.$message.error(response.msg || '删除失败'); } }).catch(error => { this.$message.error('删除失败: ' + error.message); }); }); }, saveProject() { this.$refs.projectForm.validate(valid => { if (valid) { const saveMethod = this.projectForm.id ? updateProject : saveProject; saveMethod(this.projectForm).then(response => { if (response.code === 200) { this.$message.success('保存成功'); this.projectDialogVisible = false; this.getProjectTree(); } else { this.$message.error(response.msg || '保存失败'); } }).catch(error => { this.$message.error('保存失败: ' + error.message); }); } }); }, normalizer(node) { return { id: node.id, label: node.name, children: node.children && node.children.length > 0 ? node.children : undefined }; }, // 获取项目树数据 getProjectTree() { getProjectTree().then(response => { if (response.code === 200 && response.data) { // 处理根节点 const rootNode = response.data; // 转换数据结构 this.projectTreeData = this.transformTreeData([rootNode]); this.filteredProjectTreeData = [...this.projectTreeData]; // 默认展开根节点 this.$nextTick(() => { if (this.projectTreeData.length > 0) { this.$refs.projectTree.setCurrentKey(rootNode.id); this.handleProjectClick(rootNode); } }); } else { this.$message.error('获取项目树失败: ' + (response.msg || '未知错误')); } }).catch(error => { console.error("获取项目树失败:", error); this.$message.error('获取项目树失败: ' + error.message); }); }, // 转换数据结构为el-tree需要的格式 transformTreeData(nodes) { if (!nodes || !Array.isArray(nodes)) return []; return nodes.map(node => ({ id: node.id, label: node.name, name: node.name, parentId: node.parentId, serialNums: node.serialNums, description: node.description, createBy: node.createBy, createTime: node.createTime, updateBy: node.updateBy, updateTime: node.updateTime, children: this.transformTreeData(node.children || []), rawData: node })); }, // ================= 文档管理方法 ================= // 在 methods 中添加递归收集 serialNum 的方法 collectAllSerialNums(node) { let serialNums = []; // 添加当前节点的 serialNum if (node.serialNums) { const ids = node.serialNums.split(',').map(id => id.trim()); serialNums = [...serialNums, ...ids]; } // 递归处理子节点 if (node.children && node.children.length > 0) { node.children.forEach(child => { serialNums = [...serialNums, ...this.collectAllSerialNums(child)]; }); } return serialNums; }, // 修改后的 getDocumentList 方法 getDocumentList() { // 查找当前选中的项目节点 const currentNode = this.$refs.projectTree.getNode(this.currentProjectId); if (!currentNode || !currentNode.data) { this.$message.error('未找到选中的项目'); return; } // 收集当前节点及其所有子节点的 serialNum const allSerialNums = this.collectAllSerialNums(currentNode.data); // 去重并转换为逗号分隔的字符串 const uniqueSerialNums = [...new Set(allSerialNums)].join(','); // 如果没有找到任何 serialNum,显示提示信息 if (!uniqueSerialNums) { this.documentList = []; this.docTotal = 0; this.$message.info('当前项目及其子项目没有关联任何文档'); return; } // 更新查询参数 this.docQueryParams.serialNums = uniqueSerialNums; this.docLoading = true; getDocuments(this.docQueryParams).then(response => { if (response.code === 200) { this.documentList = response.rows; this.docTotal = response.total; this.selectedDocs = []; // 清空选择 this.ids = []; // 清空ID集合 } else { this.$message.error(response.msg || '获取文档列表失败'); } this.docLoading = false; }).catch(error => { this.$message.error('获取文档列表失败: ' + error.message); this.docLoading = false; }); }, resetDocQuery() { this.docQueryParams.title = ''; this.docQueryParams.status = ''; this.getDocumentList(); }, handleEditDocument(row) { getData(row.id).then(response => { if (response.code === 200) { this.currentDocument = { id: response.data.id, menuId: response.data.menuId, title: response.data.title, content: response.data.content, status: response.data.status }; this.activeView = 'detail'; } else { this.$message.error(response.msg || '获取文档详情失败'); } }).catch(error => { this.$message.error('获取文档详情失败: ' + error.message); }); }, handleDeleteDocument(row) { this.$confirm(`确定从项目中移除文档 "${row.title}" 吗?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { // 使用removeMenusFromProject API从项目中移除文档 // 参数: { projectId: 当前项目ID, menusIds: [文档ID] } const params = { projectId: this.currentProjectId, menusIds: [row.id] // 使用文档ID数组 }; removeMenusFromProject(params).then(response => { if (response.code === 200) { this.$message.success('文档已从项目中移除'); this.getDocumentList(); } else { this.$message.error(response.msg || '移除文档失败'); } }).catch(error => { this.$message.error('移除文档失败: ' + error.message); }); }); }, handleRowClick(row) { this.handleEditDocument(row); }, backToList() { this.activeView = 'list'; }, saveDocument() { const saveMethod = this.currentDocument.id ? updateData : addData; saveMethod(this.currentDocument).then(response => { if (response.code === 200) { this.$message.success('保存成功'); this.getDocumentList(); this.backToList(); } else { this.$message.error(response.msg || '保存失败'); } }).catch(error => { this.$message.error('保存失败: ' + error.message); }); }, // ================= 导出功能方法 ================= // 多选处理 handleSelectionChange(selection) { this.selectedDocs = selection; this.ids = selection.map(item => item.id); }, // 导出文档(单篇) handleExportHttp(row, isDetail) { const params = { ids: row.id, notesExportFlag: isDetail ? 1 : 0 }; this.download( 'cms/data/createArticleOutputHttp', params, `word文档_${row.title}_${new Date().getTime()}.docx`, { timeout: 60000 } ); }, // 批量导出文档 handleBatchExport() { if (this.selectedDocs.length === 0) { this.$message.warning('选择要导出的文档'); return; } // 弹出选择导出类型的对话框 this.$confirm('选择导出方式', '提示', { distinguishCancelAndClose: true, confirmButtonText: '导出详细', cancelButtonText: '导出简版', type: 'info' }).then(() => { // 导出详细 this.batchExportHttp(true); }).catch(action => { if (action === 'cancel') { // 导出简版 this.batchExportHttp(false); } }); }, // 批量导出文档实现 batchExportHttp(isDetail) { const params = { ids: this.ids, notesExportFlag: isDetail ? 1 : 0 }; this.download( 'cms/data/createArticleOutputHttp', params, `批量文档_${new Date().getTime()}.zip`, { timeout: 120000 } // 批量导出可能需要更长时间 ); }, // 下载方法实现 download(url, params, fileName, config = {}) { // 显示加载提示 const loading = this.$loading({ lock: true, text: '正在生成文档,稍候...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }); // 发送请求 axios.get(url, { params: params, responseType: 'blob', timeout: config.timeout || 30000, headers: { 'Authorization': `Bearer ${this.$store.getters.token}` } }) .then(response => { // 创建下载链接 const blob = new Blob([response.data], { type: response.headers['content-type'] }); const downloadUrl = window.URL.createObjectURL(blob); // 创建下载链接 const link = document.createElement('a'); link.href = downloadUrl; link.download = fileName; document.body.appendChild(link); // 触发下载 link.click(); // 清理资源 window.URL.revokeObjectURL(downloadUrl); document.body.removeChild(link); this.$message.success('文档导出成功'); }) .catch(error => { console.error('导出失败:', error); // 处理错误响应 if (error.response) { if (error.response.status === 500) { this.$message.error('导出失败:服务器内部错误'); } else if (error.response.status === 401) { this.$message.error('导出失败:未授权访问'); } else if (error.response.status === 404) { this.$message.error('导出失败:API接口不存在'); } else { this.$message.error(`导出失败:服务器错误 (${error.response.status})`); } } else if (error.message.includes('timeout')) { this.$message.error('导出超时,稍后再试'); } else { this.$message.error('导出失败:' + (error.message || '未知错误')); } }) .finally(() => { loading.close(); }); }, // 排序格式化方法 sortableFormatter(row, column) { if (this.ids.includes(row.id)) { return 1; } else { return 2; } }, // 跳转到文章详情页 getArticleInfo(articleId) { // id加密 const articleIdStr = EncryptJs(articleId, "f1827100d08ff039", "ed363078893c0329"); console.log('阅读的文档跳转加密后的ID:'+articleIdStr) let routeUrl = this.$router.resolve({ path: '/cms/doucumentView', query: { id: articleIdStr } }); window.open(routeUrl.href, '_blank'); } } }; </script> <style scoped> .app-container { padding: 20px; background-color: #f5f7fa; } .head-container { padding: 10px; background-color: #ffffff; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .custom-tree-node { flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px; } .tree-node-content { display: flex; align-items: center; } .tree-icon { margin-right: 8px; color: #409EFF; } .node-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .node-actions { display: flex; align-items: center; } .doc-list-container { background-color: #ffffff; padding: 20px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .batch-actions { margin-bottom: 15px; } .doc-detail-container { background-color: #ffffff; padding: 20px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .doc-header { display: flex; align-items: center; margin-bottom: 20px; } .doc-title { display: flex; align-items: center; margin-left: 15px; margin-bottom: 0; font-size: 18px; color: #303133; } .title-icon { margin-right: 10px; color: #409EFF; } .doc-title .doc-icon { margin-right: 8px; color: #909399; } .el-tree { border: 1px solid #ebeef5; border-radius: 4px; padding: 10px; max-height: 70vh; overflow-y: auto; background-color: #ffffff; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .custom-tree-node .el-button { padding: 4px; margin-left: 5px; } .el-table { margin-top: 10px; border-radius: 4px; overflow: hidden; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .el-form-item { margin-bottom: 18px; } .el-tag { margin: 2px; } /* 响应式调整 */ @media (max-width: 768px) { .el-col-xs-24 { width: 100%; margin-bottom: 20px; } .doc-list-container, .doc-detail-container { padding: 10px; } .doc-header h2 { font-size: 16px; } } </style> 加个版本号在项目树上显示
08-05
<template> <div class="app-container"> <el-row :gutter="20"> <!-- 项目树菜单 --> <el-col :span="6" :xs="24"> <div class="head-container"> <el-input v-model="projectName" placeholder="输入项目名称" clearable size="mini" prefix-icon="el-icon-search" style="margin-bottom: 20px" @input="filterProjectTree" /> </div> <el-row :gutter="10" class="mb8"> <el-col :span="1.5"> <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll" >{{ isExpandAll ? '折叠' : '展开' }}</el-button> </el-col> <el-col :span="1.5"> <el-button type="primary" plain icon="el-icon-folder-add" size="mini" @click="handleAddProject" v-hasPermi="['cms:project:add']" >新增项目</el-button> </el-col> </el-row> <el-tree v-if="refreshTable" style="margin-top: 0.8rem;" :data="filteredProjectTreeData" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" :highlight-current="true" :default-expand-all="isExpandAll" ref="projectTree" empty-text="加载中,稍候" node-key="id" @node-click="handleProjectClick" > <span class="custom-tree-node" slot-scope="{ node, data }"> <div class="tree-node-content"> <el-icon class="tree-icon" :size="16"> <svg-icon v-if="node.expanded" icon-class="folder-open" /> <svg-icon v-else icon-class="folder" /> </el-icon> <div v-if="node.label && node.label.length > 25" class="node-label"> <el-tooltip :show-after="300" :content="node.label" placement="top-start"> <span>{{ ellipsis(node.label, 25) }}</span> </el-tooltip> </div> <div v-else class="node-label"> <span>{{ node.label }}</span> </div> </div> <span class="node-actions"> <el-button type="text" size="mini" icon="el-icon-edit" v-hasPermi="['cms:project:update']" @click.stop="() => handleEditProject(data)" ></el-button> <el-button type="text" size="mini" icon="el-icon-plus" v-hasPermi="['cms:project:add']" @click.stop="() => handleAddSubProject(data)" ></el-button> <el-button type="text" size="mini" icon="el-icon-delete" v-hasPermi="['cms:project:delete']" @click.stop="() => handleDeleteProject(data)" ></el-button> </span> </span> </el-tree> </el-col> <!-- 文档区域 --> <el-col :span="18" :xs="24"> <!-- 文档列表视图 --> <div v-if="activeView === 'list'" class="doc-list-container"> <el-form :model="docQueryParams" ref="docQueryForm" :inline="true" label-width="68px"> <el-form-item label="文档标题" prop="title"> <el-input v-model="docQueryParams.title" placeholder="输入文档标题" clearable size="mini" @keyup.enter.native="getDocumentList" prefix-icon="el-icon-search" /> </el-form-item> <el-form-item label="状态" prop="status"> <el-select v-model="docQueryParams.status" placeholder="状态" size="mini" clearable> <el-option label="编制中✍" value="0" /> <el-option label="待评审✊" value="1" /> <el-option label="已评审👍" value="2" /> <el-option label="修改中🔧" value="3" /> <el-option label="开发中💪" value="4" /> <el-option label="已完成开发🆗" value="5" /> </el-select> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-search" size="mini" @click="getDocumentList">搜索</el-button> <el-button icon="el-icon-refresh" size="mini" @click="resetDocQuery">重置</el-button> </el-form-item> </el-form> <div class="batch-actions"> <el-button type="success" icon="el-icon-download" size="mini" :disabled="selectedDocs.length === 0" @click="handleBatchExport" > 批量导出 ({{ selectedDocs.length }}) </el-button> </div> <el-table v-loading="docLoading" :data="documentList" highlight-current-row @row-click="handleRowClick" @selection-change="handleSelectionChange" ref="docTable" > <el-table-column type="selection" width="55" align="center" /> <el-table-column label="序号" type="index" width="50" align="center" /> <el-table-column label="编号" align="center" prop="serialNum" /> <el-table-column label="文档标题" prop="title" align="center"/> <el-table-column label="进度" prop="status" width="100"> <template slot-scope="scope"> <el-tag v-if="scope.row.status === '0'" type="info" size="small">编制中✍</el-tag> <el-tag v-if="scope.row.status === '1'" type="warning" size="small">待评审✊</el-tag> <el-tag v-if="scope.row.status === '2'" type="success" size="small">已评审👍</el-tag> <el-tag v-if="scope.row.status === '3'" type="success" size="small">修改中🔧</el-tag> <el-tag v-if="scope.row.status === '4'" type="success" size="small">开发中💪</el-tag> <el-tag v-if="scope.row.status === '5'" type="success" size="small">已完成开发🆗</el-tag> </template> </el-table-column> <el-table-column label="创建人" prop="createBy" width="100" /> <el-table-column label="负责人" prop="director" width="100"/> <el-table-column label="创建时间" prop="createTime" width="140" /> <el-table-column label="操作" width="180" align="center"> <template slot-scope="scope"> <el-button size="mini" type="text" icon="el-icon-edit" @click.stop="handleEditDocument(scope.row)"></el-button> <el-button size="mini" type="text" icon="el-icon-download" @click.stop="handleExportHttp(scope.row, true)" title="导出详细" ></el-button> <el-button size="mini" type="text" icon="el-icon-download" @click.stop="handleExportHttp(scope.row, false)" title="导出简版" ></el-button> <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleDeleteDocument(scope.row)" v-hasPermi="['cms:project:deleteArticleFromProject']"></el-button> </template> </el-table-column> </el-table> <pagination v-show="docTotal>0" :total="docTotal" :page.sync="docQueryParams.pageNum" :limit.sync="docQueryParams.pageSize" @pagination="getDocumentList" /> </div> <!-- 文档详情视图 --> <div v-else-if="activeView === 'detail'" class="doc-detail-container"> <div class="doc-header"> <el-button type="text" icon="el-icon-back" @click="backToList">返回文档列表</el-button> <h2 class="doc-title"> <el-icon class="title-icon"><svg-icon icon-class="document" /></el-icon> {{ currentDocument.title }} </h2> </div> <!-- 富文本编辑器 --> <el-form :model="currentDocument" ref="docForm" label-width="80px"> <el-form-item label="文档内容"> <Tinymce :height='600' v-model='currentDocument.content'></Tinymce> </el-form-item> <el-form-item> <el-button type="primary" icon="el-icon-check" @click="saveDocument">保存</el-button> <el-button icon="el-icon-close" @click="backToList">取消</el-button> </el-form-item> </el-form> </div> </el-col> </el-row> <!-- 项目编辑对话框 --> <el-dialog :title="projectDialogTitle" :visible.sync="projectDialogVisible" width="50%"> <el-form :model="projectForm" ref="projectForm" label-width="100px"> <el-form-item label="项目名称" prop="name" required> <el-input v-model="projectForm.name" placeholder="输入项目名称" prefix-icon="el-icon-folder" /> </el-form-item> <el-form-item label="上级项目" prop="parentId"> <treeselect v-model="projectForm.parentId" :options="projectTreeData" :normalizer="normalizer" placeholder="选择上级项目" /> </el-form-item> <el-form-item label="项目描述" prop="description"> <el-input type="textarea" v-model="projectForm.description" :rows="3" /> </el-form-item> </el-form> <div slot="footer"> <el-button @click="projectDialogVisible = false">取消</el-button> <el-button type="primary" icon="el-icon-check" @click="saveProject">保存</el-button> </div> </el-dialog> </div> </template> <script> import { listData, getData, addData, updateData } from "@/api/cms/data"; import { getProjectTree, saveProject, updateProject, deleteProject, removeMenusFromProject } from "@/api/cms/articleProject"; import Tinymce from '@/components/Tinymce'; import Treeselect from "@riophae/vue-treeselect"; import "@riophae/vue-treeselect/dist/vue-treeselect.css"; import axios from 'axios'; export default { name: "ProjectManagement", components: { Treeselect, Tinymce }, data() { return { // 项目树相关数据 projectName: '', projectTreeData: [], filteredProjectTreeData: [], refreshTable: true, isExpandAll: true, defaultProps: { children: "children", label: "label" }, // 项目对话框相关 projectDialogVisible: false, projectDialogTitle: '', projectForm: { id: null, name: '', parentId: null, description: '' }, // 文档列表相关 activeView: 'list', // 'list' 或 'detail' docQueryParams: { menuIds: null, title: '', status: '', pageNum: 1, pageSize: 10 }, documentList: [], docTotal: 0, docLoading: false, selectedDocs: [], // 选中的文档 ids: [], // 选中文档ID集合 // 文档详情相关 currentDocument: { id: null, menuId: null, title: '', content: '', status: '0' }, // 当前选中的项目ID(用于删除操作) currentProjectId: null, // 导出相关数据 form: { ids: [], // 导出的文档ID集合 notesExportFlag: 1 // 默认导出详细 } }; }, created() { this.getProjectTree(); }, methods: { // ================= 项目树方法 ================= ellipsis(text, maxLength) { return text.length > maxLength ? text.substring(0, maxLength) + '...' : text; }, toggleExpandAll() { this.refreshTable = false; this.isExpandAll = !this.isExpandAll; this.$nextTick(() => { this.refreshTable = true; }); }, filterNode(value, data) { if (!value) return true; return data.label.toLowerCase().includes(value.toLowerCase()); }, filterProjectTree() { this.$refs.projectTree.filter(this.projectName); }, handleProjectClick(data) { // 保存当前选中的项目ID this.currentProjectId = data.id; // 将menuIds字符串转换为数组 const menuIdsArray = data.menuIds ? data.menuIds.split(',').map(id => id.trim()) : []; // 将数组转换回逗号分隔的字符串用于查询 this.docQueryParams.menuIds = menuIdsArray.join(','); this.getDocumentList(); }, // ================= 项目管理方法 ================= handleAddProject() { this.projectForm = { id: null, name: '', parentId: null, description: '' }; this.projectDialogTitle = '新增项目'; this.projectDialogVisible = true; }, handleAddSubProject(data) { this.projectForm = { id: null, name: '', parentId: data.id, description: '' }; this.projectDialogTitle = '新增子项目'; this.projectDialogVisible = true; }, handleEditProject(data) { this.projectForm = { id: data.id, name: data.name, parentId: data.parentId, description: data.description || '' }; this.projectDialogTitle = '编辑项目'; this.projectDialogVisible = true; }, handleDeleteProject(data) { this.$confirm(`确定删除项目 "${data.name}" 及其所有子项目吗?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { // 使用deleteProject API删除项目 deleteProject(data.id).then(response => { if (response.code === 200) { this.$message.success('删除成功'); this.getProjectTree(); } else { this.$message.error(response.msg || '删除失败'); } }).catch(error => { this.$message.error('删除失败: ' + error.message); }); }); }, saveProject() { this.$refs.projectForm.validate(valid => { if (valid) { const saveMethod = this.projectForm.id ? updateProject : saveProject; saveMethod(this.projectForm).then(response => { if (response.code === 200) { this.$message.success('保存成功'); this.projectDialogVisible = false; this.getProjectTree(); } else { this.$message.error(response.msg || '保存失败'); } }).catch(error => { this.$message.error('保存失败: ' + error.message); }); } }); }, normalizer(node) { return { id: node.id, label: node.name, children: node.children && node.children.length > 0 ? node.children : undefined }; }, // 获取项目树数据 getProjectTree() { getProjectTree().then(response => { if (response.code === 200 && response.data) { // 处理根节点 const rootNode = response.data; // 转换数据结构 this.projectTreeData = this.transformTreeData([rootNode]); this.filteredProjectTreeData = [...this.projectTreeData]; // 默认展开根节点 this.$nextTick(() => { if (this.projectTreeData.length > 0) { this.$refs.projectTree.setCurrentKey(rootNode.id); this.handleProjectClick(rootNode); } }); } else { this.$message.error('获取项目树失败: ' + (response.msg || '未知错误')); } }).catch(error => { console.error("获取项目树失败:", error); this.$message.error('获取项目树失败: ' + error.message); }); }, // 转换数据结构为el-tree需要的格式 transformTreeData(nodes) { if (!nodes || !Array.isArray(nodes)) return []; return nodes.map(node => ({ id: node.id, label: node.name, name: node.name, parentId: node.parentId, menuIds: node.menuIds, description: node.description, createBy: node.createBy, createTime: node.createTime, updateBy: node.updateBy, updateTime: node.updateTime, children: this.transformTreeData(node.children || []), rawData: node })); }, // ================= 文档管理方法 ================= getDocumentList() { if (!this.docQueryParams.menuIds) { return; } this.docLoading = true; listData(this.docQueryParams).then(response => { if (response.code === 200) { this.documentList = response.rows; this.docTotal = response.total; this.selectedDocs = []; // 清空选择 this.ids = []; // 清空ID集合 } else { this.$message.error(response.msg || '获取文档列表失败'); } this.docLoading = false; }).catch(error => { this.$message.error('获取文档列表失败: ' + error.message); this.docLoading = false; }); }, resetDocQuery() { this.docQueryParams.title = ''; this.docQueryParams.status = ''; this.getDocumentList(); }, handleEditDocument(row) { getData(row.id).then(response => { if (response.code === 200) { this.currentDocument = { id: response.data.id, menuId: response.data.menuId, title: response.data.title, content: response.data.content, status: response.data.status }; this.activeView = 'detail'; } else { this.$message.error(response.msg || '获取文档详情失败'); } }).catch(error => { this.$message.error('获取文档详情失败: ' + error.message); }); }, handleDeleteDocument(row) { this.$confirm(`确定从项目中移除文档 "${row.title}" 吗?`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { // 使用removeMenusFromProject API从项目中移除文档 // 参数: { projectId: 当前项目ID, menusIds: [文档ID] } const params = { projectId: this.currentProjectId, menusIds: [row.id] // 使用文档ID数组 }; removeMenusFromProject(params).then(response => { if (response.code === 200) { this.$message.success('文档已从项目中移除'); this.getDocumentList(); } else { this.$message.error(response.msg || '移除文档失败'); } }).catch(error => { this.$message.error('移除文档失败: ' + error.message); }); }); }, handleRowClick(row) { this.handleEditDocument(row); }, backToList() { this.activeView = 'list'; }, saveDocument() { const saveMethod = this.currentDocument.id ? updateData : addData; saveMethod(this.currentDocument).then(response => { if (response.code === 200) { this.$message.success('保存成功'); this.getDocumentList(); this.backToList(); } else { this.$message.error(response.msg || '保存失败'); } }).catch(error => { this.$message.error('保存失败: ' + error.message); }); }, // ================= 导出功能方法 ================= // 多选处理 handleSelectionChange(selection) { this.selectedDocs = selection; this.ids = selection.map(item => item.id); }, // 导出文档(单篇) handleExportHttp(row, isDetail) { const params = { ids: row.id, notesExportFlag: isDetail ? 1 : 0 }; this.download( 'cms/data/createArticleOutputHttp', params, `word文档_${row.title}_${new Date().getTime()}.docx`, { timeout: 60000 } ); }, // 批量导出文档 handleBatchExport() { if (this.selectedDocs.length === 0) { this.$message.warning('选择要导出的文档'); return; } // 弹出选择导出类型的对话框 this.$confirm('选择导出方式', '提示', { distinguishCancelAndClose: true, confirmButtonText: '导出详细', cancelButtonText: '导出简版', type: 'info' }).then(() => { // 导出详细 this.batchExportHttp(true); }).catch(action => { if (action === 'cancel') { // 导出简版 this.batchExportHttp(false); } }); }, // 批量导出文档实现 batchExportHttp(isDetail) { const params = { ids: this.ids, notesExportFlag: isDetail ? 1 : 0 }; this.download( 'cms/data/createArticleOutputHttp', params, `批量文档_${new Date().getTime()}.zip`, { timeout: 120000 } // 批量导出可能需要更长时间 ); }, // 下载方法实现 download(url, params, fileName, config = {}) { // 显示加载提示 const loading = this.$loading({ lock: true, text: '正在生成文档,稍候...', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' }); // 发送请求 axios.get(url, { params: params, responseType: 'blob', timeout: config.timeout || 30000, headers: { 'Authorization': `Bearer ${this.$store.getters.token}` } }) .then(response => { // 创建下载链接 const blob = new Blob([response.data], { type: response.headers['content-type'] }); const downloadUrl = window.URL.createObjectURL(blob); // 创建下载链接 const link = document.createElement('a'); link.href = downloadUrl; link.download = fileName; document.body.appendChild(link); // 触发下载 link.click(); // 清理资源 window.URL.revokeObjectURL(downloadUrl); document.body.removeChild(link); this.$message.success('文档导出成功'); }) .catch(error => { console.error('导出失败:', error); // 处理错误响应 if (error.response) { if (error.response.status === 500) { this.$message.error('导出失败:服务器内部错误'); } else if (error.response.status === 401) { this.$message.error('导出失败:未授权访问'); } else if (error.response.status === 404) { this.$message.error('导出失败:API接口不存在'); } else { this.$message.error(`导出失败:服务器错误 (${error.response.status})`); } } else if (error.message.includes('timeout')) { this.$message.error('导出超时,稍后再试'); } else { this.$message.error('导出失败:' + (error.message || '未知错误')); } }) .finally(() => { loading.close(); }); }, // 排序格式化方法 sortableFormatter(row, column) { if (this.ids.includes(row.id)) { return 1; } else { return 2; } } } }; </script> <style scoped> .app-container { padding: 20px; background-color: #f5f7fa; } .head-container { padding: 10px; background-color: #ffffff; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .custom-tree-node { flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px; } .tree-node-content { display: flex; align-items: center; } .tree-icon { margin-right: 8px; color: #409EFF; } .node-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .node-actions { display: flex; align-items: center; } .doc-list-container { background-color: #ffffff; padding: 20px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .batch-actions { margin-bottom: 15px; } .doc-detail-container { background-color: #ffffff; padding: 20px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .doc-header { display: flex; align-items: center; margin-bottom: 20px; } .doc-title { display: flex; align-items: center; margin-left: 15px; margin-bottom: 0; font-size: 18px; color: #303133; } .title-icon { margin-right: 10px; color: #409EFF; } .doc-title .doc-icon { margin-right: 8px; color: #909399; } .el-tree { border: 1px solid #ebeef5; border-radius: 4px; padding: 10px; max-height: 70vh; overflow-y: auto; background-color: #ffffff; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .custom-tree-node .el-button { padding: 4px; margin-left: 5px; } .el-table { margin-top: 10px; border-radius: 4px; overflow: hidden; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } .el-form-item { margin-bottom: 18px; } .el-tag { margin: 2px; } /* 响应式调整 */ @media (max-width: 768px) { .el-col-xs-24 { width: 100%; margin-bottom: 20px; } .doc-list-container, .doc-detail-container { padding: 10px; } .doc-header h2 { font-size: 16px; } } </style> 原本代码是这样的,如何改
08-02
<template> <div class="vote-container"> <!-- 消息提示 --> <div v-if="showAlert" :class="['alert', alertType]"> {{ alertMessage }} </div> <!-- 投票人信息 --> <div class="voter-info" v-if="voterName && voterIdCard"> <p>投票人:{{ voterName }}</p> <p>身份证:{{ formattedIdCard }}</p> </div> <!-- 投票统计信息 --> <div class="stats"> <div class="stat"> <h3>经理投票</h3> <div class="progress"> <div class="progress-bar" :style="{ width: (votes.A / 5) * 100 + '%' }"></div> </div> <p>{{ votes.A }} / 5</p> </div> <div class="stat"> <h3>厂长投票</h3> <div class="progress"> <div class="progress-bar" :style="{ width: (votes.B / 5) * 100 + '%' }"></div> </div> <p>{{ votes.B }} / 5</p> </div> <div class="stat"> <h3>副厂长投票</h3> <div class="progress"> <div class="progress-bar" :style="{ width: (votes.C / 15) * 100 + '%' }"></div> </div> <p>{{ votes.C }} / 15</p> </div> <div class="stat"> <h3>总票数</h3> <div class="progress"> <div class="progress-bar" :style="{ width: (totalVotes / 25) * 100 + '%' }"></div> </div> <p>{{ totalVotes }} / 25</p> </div> </div> <!-- 被投票人列表 --> <div class="voters-grid"> <div v-for="voter in voters" :key="voter.id" class="voter-card"> <h4>{{ voter.name }}</h4> <p class="voter-id">ID: {{ voter.id }}</p> <div class="vote-options"> <button @click="castVote(voter, 'A')" :disabled="!canVote(voter, 'A')" :class="{ 'selected': voter.vote === 'A', 'disabled': !canVote(voter, 'A') }" > 经理 </button> <button @click="castVote(voter, 'B')" :disabled="!canVote(voter, 'B')" :class="{ 'selected': voter.vote === 'B', 'disabled': !canVote(voter, 'B') }" > 厂长 </button> <button @click="castVote(voter, 'C')" :disabled="!canVote(voter, 'C')" :class="{ 'selected': voter.vote === 'C', 'disabled': !canVote(voter, 'C') }" > 副厂长 </button> </div> </div> </div> <!-- 操作按钮 --> <div class="action-buttons"> <button @click="submitVotes" :disabled="!hasSelectedCandidates || isSubmitting">提交投票</button> <button @click="resetVotes" :disabled="isSubmitting">重置投票</button> </div> </div> </template> <script setup> import { ref, reactive, computed } from 'vue'; import { useRoute, useRouter} from 'vue-router'; import { onMounted } from 'vue'; const route = useRoute(); const router = useRouter() const voters = ref([]); //候选人 // 使用props接收参数 const props = defineProps({ queryParams: { type: Object, default: () => ({}) } }) // 使用计算属性 const activeSurvey = ref({ surveyId: route.params.surveyId,//调查令 qydcl: route.params.qydcl, dclx: route.query.dclx, tffs: route.query.tffs, bt: route.query.bt }); onMounted(async() => { // 确保路由完全解析完成 await router.isReady() // console.log('当前路由对象:', route) // console.log('路径参数:', route.params) // 获取params参数 // console.log('查询参数:', route.query) // 获取query参数 }); // 添加消息提示状态 const alertMessage = ref(''); const showAlert = ref(false); const alertType = ref(''); // 'success' 或 'error' // 安全序列化函数 function safeStringify(obj) { const seen = new WeakSet(); return JSON.stringify(obj, (key, value) => { if (typeof value === "object" && value !== null) { if (seen.has(value)) { // 检测到循环引用,返回占位符或跳过 return "[Circular Reference Removed]"; } seen.add(value); } return value; }); } // onMounted生命周期钩子 onMounted(async () => { // 从sessionStorage获取投票人信息并立即清除 const voterInfo = sessionStorage.getItem('voterInfo'); if (voterInfo) { const { name, idCard } = JSON.parse(voterInfo); voterName.value = name; voterIdCard.value = idCard; sessionStorage.removeItem('voterInfo'); } // 获取投票详情 const route = useRoute(); // 加载候选人数据 voters.value = await fetchCandidates(); }); // 添加用于存储投票人信息的变量 const voterName = ref(''); const voterIdCard = ref(''); // 格式化身份证显示(安全脱敏) const formattedIdCard = computed(() => { if (!voterIdCard.value) return ''; // 显示前6位和后4位,中间用*代替 return voterIdCard.value.substring(0, 6) + '******' + voterIdCard.value.substring(voterIdCard.value.length - 4); }); onMounted(() => { // 从sessionStorage获取数据并立即清除 const voterInfo = sessionStorage.getItem('voterInfo'); if (voterInfo) { const { name, idCard } = JSON.parse(voterInfo); voterName.value = name; voterIdCard.value = idCard; // 关键:立即清除存储防止数据残留 sessionStorage.removeItem('voterInfo'); } }); //获取候选人明细 const fetchCandidates = async () => { try { const response = await fetch('/api/wechat/getInvestigate', { method: 'POST', body: JSON.stringify({ id: '9', dcl: '123' }) }); // console.log('API响应:', response); const result = await response.json(); if (!result || !result.root) throw new Error('无效API响应'); // 提取候选人数据 const candidateArray = []; let idCounter = 1; // 自增计数器,名称序号 result.root.forEach(rootItem => { if (!rootItem.childEntList) return; rootItem.childEntList.forEach(candidate => { if (!candidate.dcbt || !candidate.dcxbt) return; candidateArray.push({ originalid: candidate.dcbt, name: candidate.dcxbt, vote: null, id:idCounter++, tmlx: candidate.tmlx, // 投票类型 }); }); }); console.log('候选人数据:', candidateArray.value.mainId); return candidateArray; } catch (error) { console.error('获取候选人失败:', error); return []; // 返回空数组保持安全 } }; // 新增计算属性 - 获取已选择的候选人 const selectedCandidates = computed(() => { return voters.value .filter(v => v.vote) // 只过滤已投票的 .map(v => ({ id: v.originalid, // 候选人原始ID voteType: v.vote, // 投票类型(A/B/C) voteValue: v.vote === 'A' ? 17 : // 转换类型值 v.vote === 'B' ? 18 : 19, name: v.name, // 候选人姓名 tmlx: v.tmlx // 原始类型 })); }); // 检查是否有选择的候选人 const hasSelectedCandidates = computed(() => { return selectedCandidates.value.length > 0; }); // 投票统计 const votes = reactive({ A: 0, B: 0, C: 0 }); // 计算总票数 const totalVotes = computed(() => { return votes.A + votes.B + votes.C; }); // 投票方法 const canVote = (voter, type) => { // 情况1:用户取消当前选择的类型(总是允许) if (voter.vote === type) return true; // 情况2:用户从其他类型转换到当前类型 if (voter.vote && voter.vote !== type) { if (type === 'A' && votes.A >= 5) return false; if (type === 'B' && votes.B >= 5) return false; if (type === 'C' && votes.C >= 15) return false; } // 情况3:用户首次投票 if (!voter.vote) { if (type === 'A' && votes.A >= 5) return false; if (type === 'B' && votes.B >= 5) return false; if (type === 'C' && votes.C >= 15) return false; if (totalVotes.value >= 25) return false; } return true; }; // 投票方法 const castVote = (voter, type) => { // 如果已投票且点击相同类型,取消投票 if (voter.vote === type) { voter.vote = null; votes[type]--; return; } // 如果之前有投票,先取消 if (voter.vote !== null) { votes[voter.vote]--; } // 投新票 voter.vote = type; votes[type]++; }; //投票人信息 // 添加投票人信息数据模型 const voterInfo = reactive({ name: '', idNumber: '' }); // // 添加基本信息验证 // const isValid = computed(() => { // return voterInfo.name.trim() !== '' && // voterInfo.idNumber.trim() !== '' && // /^\d{17}[\dXx]$/.test(voterInfo.idNumber); // }); // 提交投票 // 防止重复提交 const isSubmitting = ref(false); // 提交投票到API const submitVotes = async () => { // console.log("dclx", activeSurvey.value.dclx); // 添加防御性检查 if (!hasSelectedCandidates.value) { showMessage('先选择候选人', 'error'); return; } // 防止重复提交 if (isSubmitting.value) return; isSubmitting.value = true; try { const mainData = [ { fieldName: "bt", fieldValue: activeSurvey.value.bt }, { fieldName: "tprxm", fieldValue: voterName.value }, { fieldName: "tprsfz", fieldValue: voterIdCard.value }, { fieldName: "mb", fieldValue: activeSurvey.value.id }, { fieldName: "dclx", fieldValue: activeSurvey.value.dclx }, { fieldName: "tffs", fieldValue: activeSurvey.value.tffs } ]; const workflowRequestTableRecords = selectedCandidates.value.map(candidate => ({ workflowRequestTableFields: [ { fieldName: "dcbt", fieldValue: candidate.originalid }, { fieldName: "tmlx", fieldValue: candidate.tmlx }, { fieldName: "dcxx", fieldValue: candidate.vote === 'A' ? 17 : candidate.vote === 'B' ? 18 : 19 } ] })); console.log('提交数据:', { mainData, workflowRequestTableRecords }); const requestBody = { requestName: activeSurvey.value.bt, // 投票标题 workflowId: 118, // 固定工作流ID mainData, workflowRequestTableRecords }; // 发送POST请求 const response = await fetch('/api/wechat/addInvestigateWorkflow1', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: safeStringify(requestBody)// 使用安全序列化,避免重复引用 }); const result = await response.json(); // 根据 api_status 判断 if (result.api_status === true) { // 成功处理 const successMsg = result.msg || '投票提交成功!'; showMessage('投票提交成功!', 'success'); // 存储已投票标识 localStorage.setItem('voted_' + voterIdCard.value, 'true'); } else { // 处理错误情况 if (result.msg === '你已提交或不满足提交条件') { showMessage(result.msg, 'error'); // 特殊处理:用户已投票,存储标识防止重复提交 localStorage.setItem('voted_' + voterIdCard.value, 'true'); } else { // 其他错误情况 const errorMsg = result.msg ? `提交失败: ${result.msg}` : '未知错误,稍后重试'; showMessage(errorMsg, 'error'); } } } catch (error) { console.error('网络请求失败:', error); showMessage('网络错误,检查连接后重试', 'error'); } finally { isSubmitting.value = false; } }; // 重置投票 const resetVotes = () => { if (confirm('确定要重置所有投票吗?')) { voters.value.forEach(voter => { voter.vote = null; }); votes.A = 0; votes.B = 0; votes.C = 0; voterInfo.name = ''; voterInfo.idNumber = ''; } }; //后台响应信息showMessage const showMessage = (message, type = 'error') => { // 更新消息提示状态 alertMessage.value = message; showAlert.value = true; alertType.value = type; // 错误提示停留3秒,成功提示停留2秒 const timeout = type === 'error' ? 3000 : 2000; setTimeout(() => { showAlert.value = false; }, timeout); }; </script> <style scoped> /* 移动端垂直布局 */ @media (max-width: 480px) { .input-group { flex-direction: column; } } /* 平板/桌面端水平布局 */ @media (min-width: 768px) { .input-group { flex-direction: row; } } /* 消息提示样式 */ .alert { padding: 15px; margin-bottom: 20px; border-radius: 4px; text-align: center; position: fixed; top: 20px; left: 50%; transform: translateX(-50%); z-index: 1000; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); min-width: 300px; opacity: 0.95; } .alert.error { background-color: #ffebee; color: #b71c1c; border: 1px solid #ffcdd2; } .alert.success { background-color: #e8f5e9; color: #1b5e20; border: 1px solid #c8e6c9; } .vote-container { max-width: 1200px; margin: 0 auto; padding: 20px; } .stats { display: flex; justify-content: space-between; margin-bottom: 30px; background: #f5f7fa; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); } .stat { flex: 1; text-align: center; padding: 0 15px; } .progress { height: 20px; background: #e0e0e0; border-radius: 10px; margin: 10px 0; overflow: hidden; } .progress-bar { height: 100%; background: #3498db; transition: width 0.3s; } .voters-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 20px; } .voter-card { background: white; border-radius: 8px; padding: 15px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); transition: transform 0.2s; } .voter-card:hover { transform: translateY(-5px); } .voter-id { color: #777; font-size: 0.9rem; margin-bottom: 15px; } .vote-options { display: flex; justify-content: space-between; } .vote-options button { flex: 1; margin: 0 5px; padding: 8px 0; border: none; border-radius: 4px; cursor: pointer; transition: all 0.2s; } .vote-options button:not(.selected):hover { opacity: 0.9; transform: scale(1.05); } .vote-options button:first-child { background: #ff6b6b; color: white; } .vote-options button:nth-child(2) { background: #4ecdc4; color: white; } .vote-options button:last-child { background: #ffd166; color: white; } .selected { border: 2px solid #2c3e50 !important; font-weight: bold; box-shadow: 0 0 2 rgba(61, 60, 60, 0.5); } .disabled { opacity: 0.5 !important; cursor: not-allowed !important; } .action-buttons { margin-top: 30px; display: flex; justify-content: center; gap: 20px; } .action-buttons button { padding: 12px 30px; border: none; border-radius: 6px; cursor: pointer; font-size: 1rem; font-weight: 600; transition: all 0.2s; } .action-buttons button:first-child { background: #3498db; color: white; } .action-buttons button:first-child:disabled { background: #bdc3c7; cursor: not-allowed; } .action-buttons button:last-child { background: #e74c3c; color: white; } .action-buttons button:hover:not(:disabled) { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); } </style>我想要在获取候选人明细中,响应的数据里面获取到mainId也就是最后点击提交传到接口的mb,响应的数据如下:{ "api_status": true, "root": [ { "bt": "经理、厂长、副厂长选举", "bz": "", "childEntList": [ { "answer": [], "dcbt": 167, "dcxbt": "石富元", "gtsfbt": 0, "id": 180, "mainId": 9, "selectEntList": [ { "fz": 1.0, "id": 19, "xxmc": "副厂长" }, { "fz": 1.0, "id": 18, "xxmc": "厂长" }, { "fz": 1.0, "id": 17, "xxmc": "经理" } ], "tmlx": 0 }, { "answer": [], "dcbt": 170, "dcxbt": "宋永洪", "gtsfbt": 0, "id": 181, "mainId": 9, "selectEntList": [ { "fz": 1.0, "id": 19, "xxmc": "副厂长" }, { "fz": 1.0, "id": 18, "xxmc": "厂长" }, { "fz": 1.0, "id": 17, "xxmc": "经理" } ], "tmlx": 0 },
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值