import os
import json
from flask import Flask, render_template, request, jsonify
from PIL import Image

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False  # 确保JSON响应中的中文字符正确显示

# 添加全局变量来存储当前界面
current_page = "主页"

# 确保templates和static文件夹存在
templates_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
static_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')

if not os.path.exists(templates_dir):
    os.makedirs(templates_dir)
if not os.path.exists(static_dir):
    os.makedirs(static_dir)

# 图片路径
image_paths = {
    "主页": "E:/文件/LLM_model/RAG/图片/D3/主页.PNG",
    "工程信息": "E:/文件/LLM_model/RAG/图片/D3/工程信息.PNG",
    "取费设置": "E:/文件/LLM_model/RAG/图片/D3/取费设置.PNG",
    "组合件": "E:/文件/LLM_model/RAG/图片/D3/组合件.PNG",
    "工程量": "E:/文件/LLM_model/RAG/图片/D3/工程量.PNG",
    "材机分析": "E:/文件/LLM_model/RAG/图片/D3/材机分析.PNG",
    "工程费用": "E:/文件/LLM_model/RAG/图片/D3/工程费用.PNG",
    "报表输出": "E:/文件/LLM_model/RAG/图片/D3/报表输出.PNG"
}

# 创建HTML模板
with open(os.path.join(templates_dir, 'index.html'), 'w', encoding='utf-8') as f:
    f.write('''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面切换示例</title>
    <script>
    window.difyChatbotConfig = {
    token: 'lijvRv14EYBUUllM',
    baseUrl: 'https://172.20.0.145'
    }
    </script>
    <script
    src="https://172.20.0.145/embed.min.js"
    id="lijvRv14EYBUUllM"
    defer>
    </script>
    <style>
    #dify-chatbot-bubble-button {
        background-color: #1C64F2 !important;
    }
    #dify-chatbot-bubble-window {
        width: 580px !important;
        height: 40rem !important;
    }
        /* 隐藏按钮的样式 */
        .hidden-buttons {
    padding-left: 4px;
    position: absolute;
    z-index: 999999;
}
        /* 显示按钮的样式 */
        .show-buttons {
            display: block;
        }
        /* 页面内容的样式 */
        .page {
            display: none;
        }
        .active {
            display: block;
        }
		
.hidden-buttons button {
    cursor: pointer;
    width: 52px;
    height: 29px;
    opacity: 0.01;
}
    </style>
</head>
<body>

    <!-- 隐藏的按钮组 -->
    <div id="buttonGroup" class="hidden-buttons">
        <button onclick="showPage(0)">页面0</button>
        <button onclick="showPage(1)">页面1</button>
        <button onclick="showPage(2)" style="    width: 72px;">页面2</button>
        <button onclick="showPage(3)" style="    width: 72px;">页面3</button>
        <button onclick="showPage(4)" style="    width: 66px;">页面4</button>
        <button onclick="showPage(5)" style="    width: 62px;">页面5</button>
        <button onclick="showPage(6)" style="    width: 70px;">页面6</button>
        <button onclick="showPage(7)" style="    width: 76px;">页面7</button>
        <button onclick="showPage(8)" style="    width: 77px;">页面8</button>
    </div>

    <!-- 页面内容 -->
    <div id="page1" class="page active">
        <img src="/static/主页.png" alt="页面1">
    </div>
    <div id="page2" class="page">
        <img src="/static/工程信息.png" alt="页面2">
    </div>
    <div id="page3" class="page">
        <img src="/static/取费设置.png" alt="页面3">
    </div>
    <div id="page4" class="page">
        <img src="/static/组合件.png" alt="页面4">
    </div>
    <div id="page5" class="page">
        <img src="/static/工程量.png" alt="页面5">
    </div>
    <div id="page6" class="page">
        <img src="/static/材机分析.png" alt="页面6">
    </div>
    <div id="page7" class="page">
        <img src="/static/工程费用.png" alt="页面7">
    </div>
    <div id="page8" class="page">
        <img src="/static/报表输出.png" alt="页面8">
    </div>

    <script>
        // 显示页面的函数
        function showPage(pageNumber) {
            // 处理清空JSON的特殊情况
            if (pageNumber === 0) {
                // 清空JSON但不改变当前页面显示
                fetch('/clear_json')
                    .then(response => response.json())
                    .then(data => {
                        console.log('JSON已清空');
                    })
                    .catch(error => {
                        console.error('清空JSON失败:', error);
                    });
                return; // 直接返回，不执行后续代码
            }
            
            // 隐藏所有页面
            var pages = document.querySelectorAll('.page');
            pages.forEach(function(page) {
                page.classList.remove('active');
            });

            // 显示指定页面
            var pageToShow = document.getElementById('page' + pageNumber);
            pageToShow.classList.add('active');
            
            // 获取页面标题并更新当前界面
            var pageTitle = '';
            switch(pageNumber) {
                case 1: pageTitle = '主页'; break;
                case 2: pageTitle = '工程信息'; break;
                case 3: pageTitle = '取费设置'; break;
                case 4: pageTitle = '组合件'; break;
                case 5: pageTitle = '工程量'; break;
                case 6: pageTitle = '材机分析'; break;
                case 7: pageTitle = '工程费用'; break;
                case 8: pageTitle = '报表输出'; break;
            }
            
            // 调用接口更新当前界面
            if(pageTitle) {
                fetch('/get_current_page?title=' + encodeURIComponent(pageTitle))
                    .then(response => response.json())
                    .then(data => {
                        console.log('软件信息:', JSON.stringify(data, null, 2));
                        console.log('当前界面:', data['当前界面']);
                    })
                    .catch(error => {
                        console.error('获取界面名称失败:', error);
                    });
            }
        }

        // 页面加载时显示第一个页面
        window.onload = function() {
            showPage(1);
        };
    </script>
</body>
</html>
    ''')

# 将图片复制到static文件夹
def copy_image_to_static(source_path, target_name):
    try:
        img = Image.open(source_path)
        target_path = os.path.join(static_dir, f"{target_name}.png")
        img.save(target_path)
        return True
    except Exception as e:
        print(f"复制图片失败: {e}")

@app.route('/')
def index():
    # 在第一次请求时设置图片
    setup_images()
    return render_template('index.html')

@app.route('/get_image')
def get_image():
    title = request.args.get('title', '主页')
    if title in image_paths:
        image_url = f"/static/{title}.png"
        resp = jsonify({'image_url': image_url})
        resp.headers['Content-Type'] = 'application/json; charset=utf-8'
        return resp
    
    resp = jsonify({'error': '图片不存在'})
    resp.headers['Content-Type'] = 'application/json; charset=utf-8'
    return resp

# 设置图片
def setup_images():
    # 检查是否已经设置过图片
    if not hasattr(setup_images, 'done'):
        # 复制内容图片
        for title, path in image_paths.items():
            copy_image_to_static(path, title)
        
        # 标记为已完成
        setup_images.done = True

# 添加处理聊天消息的路由
@app.route('/ask', methods=['POST'])
def ask():
    data = request.json
    message = data.get('message', '')
    
    # 这里可以添加调用Dify API的逻辑
    resp = jsonify({
        'answer': f'您好，我收到了您的问题："{message}"。由于当前无法连接到Dify服务器，我只能提供有限的回复。'
    })
    resp.headers['Content-Type'] = 'application/json; charset=utf-8'
    return resp

# 添加获取当前界面名称的接口
@app.route('/get_current_page', methods=['GET'])
def get_current_page():
    global current_page
    title = request.args.get('title')
    
    # 如果请求中包含title参数，则更新当前界面
    if title:
        current_page = title
        print(f"更新当前界面为: {current_page}")
    
    response = {
        'software_name': '博微配网工程计价通D3软件',#博微配网工程计价通D3软件
        'engineering_type': '单工程',
        'software_version': '3.2.4.23',
        'project_name': '525252.BDD3',
        'current_page': current_page
    }
    
    # 检查是否是浏览器直接访问
    if request.headers.get('Accept', '').find('text/html') != -1:
        # 返回一个HTML页面，显示JSON数据
        html = f'''
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>当前界面信息</title>
            <style>
                body {{ font-family: Arial, sans-serif; padding: 20px; }}
                .json-container {{ background-color: #f5f5f5; padding: 15px; border-radius: 5px; }}
                .json-key {{ color: #0066cc; font-weight: bold; }}
                .json-value {{ color: #006600; }}
                .refresh-btn {{ background-color: #4CAF50; color: white; padding: 10px 15px; 
                               border: none; border-radius: 4px; cursor: pointer; margin-top: 15px; }}
                .refresh-btn:hover {{ background-color: #45a049; }}
            </style>
        </head>
        <body>
            <h2>当前界面信息</h2>
            <div class="json-container">
                <p><span class="json-key">software_name:</span> <span class="json-value">{response['software_name']}</span></p>
                <p><span class="json-key">engineering_type:</span> <span class="json-value">{response['engineering_type']}</span></p>
                <p><span class="json-key">software_version:</span> <span class="json-value">{response['software_version']}</span></p>
                <p><span class="json-key">project_name:</span> <span class="json-value">{response['project_name']}</span></p>
                <p><span class="json-key">current_page:</span> <span class="json-value">{response['current_page']}</span></p>
            </div>
            <p>原始JSON:</p>
            <pre>{json.dumps(response, ensure_ascii=False, indent=2)}</pre>
            <button class="refresh-btn" onclick="location.reload()">刷新信息</button>
        </body>
        </html>
        '''
        return html
    
    # API调用返回JSON
    return json.dumps(response, ensure_ascii=False)

# 添加清空JSON的路由
@app.route('/clear_json')
def clear_json():
    global current_page
    # 重置当前页面
    current_page = ""
    
    # 返回空JSON，添加编码设置
    resp = jsonify({})
    resp.headers['Content-Type'] = 'application/json; charset=utf-8'
    return resp

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=1234, debug=True)