<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ title }}</title>
    <style>
      body {
          font-size: 1.0em;
        font-family: -apple-system, "Noto Sans", "Helvetica Neue", Helvetica, "Nimbus Sans L", Arial, "Liberation Sans", "PingFang SC", "Hiragino Sans GB", "Noto Sans CJK SC", "Source Han Sans SC", "Source Han Sans CN", "Microsoft YaHei", "Wenquanyi Micro Hei", "WenQuanYi Zen Hei", "ST Heiti", SimHei, "WenQuanYi Zen Hei Sharp", sans-serif;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-top: 20px;
      }

      .camera-preview {
        border: 2px solid #007bff;
        border-radius: 4px;
        width: 640px;
        height: 480px;
      }

      .canvas-hidden {
        display: none;
      }

      .image-preview {
          display: none;
          max-width: 320px;
          height: auto;
          margin-top: 10px;
          border: 1px solid #ccc;
      }

      .image-show {
          max-width: 320px;
          height: auto;
      }

      .file-input {
            margin-top: 20px;
            margin-bottom: 10px;
      }

      .capture-button, .submit-button, .start-button, .stop-button {
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 4px;
        padding: 10px 20px;
        margin: 10px 0;
        cursor: pointer;
        font-size: 16px;
      }

      .stop-button:disabled, .stop-button:hover:disabled {
          background-color: #ccc;
          cursor: not-allowed;
      }

      .submit-button:disabled, .submit-button:hover:disabled {
          background-color: #ccc;
          cursor: not-allowed;
      }

      .capture-button:hover, .submit-button:hover, .start-button:hover, .stop-button:hover {
        background-color: #0056b3;
      }

      .time-label, .status-label {
          margin: 10px 0;
      }

      .text-input {
          padding: 8px;
          margin: 10px 0;
          border: 1px solid #ccc;
          border-radius: 4px;
          width: 640px;
          min-height: 20px;
          line-height: 20px;
          max-height: 300px;
          font-size: 16px;
          overflow-y: auto;
          resize: none;
      }

      .output-area {
          width: 640px;
        margin: 20px auto;
        padding: 10px;
        border-radius: 8px;
        background-color: white;
        box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
          max-height: 600px;
          overflow-y: auto;
      }

      .user-display {
          background: #eee;
          padding: 10px;
      }

      .ai-display {
          background: #fff;
          padding: 10px;
      }

      .ai-display-text {
          background: #fff;
          padding: 10px;
      }

      .loading-message{
          height: 20px;
          font-weight: bold;
          color: #4CAF50;
          margin: 10px 0;
        }

      img {
        max-width: 100%;
        height: auto;
      }

      audio {
        width: 400px;
        margin-top: 10px;
      }
    </style>
    <script src="{{ url_for('static', filename='js/marked.min.js') }}"></script>
</head>
<body>
    <script>
        function convertMarkdownToHTML(markdownText) {
          return marked.parse(markdownText);
        }

        function createOrUpdateOutputArea() {
            let outputArea = document.getElementById('outputArea');
            if (!outputArea) {
                outputArea = document.createElement('div');
                outputArea.id = 'outputArea';
                outputArea.className = 'output-area'
                document.body.appendChild(outputArea);
            }
            return outputArea;
        }

        function updateContent(data) {
            const outputArea = createOrUpdateOutputArea();
            if (data.image) {
                const userText = document.createElement('p');
                userText.className = 'ai-display';
                userText.innerHTML = `AI: <img src="${data.image}" alt="user input image" class="image-show" />`;
                outputArea.appendChild(userText);
            }
            if (data.audio) {
                const userText = document.createElement('p');
                userText.className = 'ai-display';
                userText.innerHTML = `AI: <audio controls autoplay src="${data.audio}"></audio>`;
                outputArea.appendChild(userText);
            }
            if (data.text) {
                const textContent = convertMarkdownToHTML('AI: ' + data.text);
                const existingTextElement = outputArea.querySelector('.ai-display-text');
                if (existingTextElement) {
                    existingTextElement.innerHTML = textContent;
                } else {
                    const userText = document.createElement('p');
                    userText.className = 'ai-display-text';
                    userText.innerHTML = textContent;
                    outputArea.appendChild(userText);
                }
            }
            outputArea.scrollTop = outputArea.scrollHeight;
        }

        window.onload = function() {
            fetch('/get_components')
                .then(response => response.json())
                .then(components => {
                    components.forEach(component => {
                        if (component.type === 'camera') {
                            const video = document.createElement('video');
                            video.id = component.id;
                            video.className = 'camera-preview'
                            video.width = 640;
                            video.height = 480;
                            video.autoplay = true;
                            document.body.appendChild(video);

                            const captureButton = document.createElement('button');
                            captureButton.className = 'capture-button'
                            captureButton.textContent = '捕获图像';
                            document.body.appendChild(captureButton);

                            const canvas = document.createElement('canvas');
                            canvas.className = 'canvas-hidden'
                            canvas.width = 640;
                            canvas.height = 480;
                            canvas.style.display = 'none';
                            document.body.appendChild(canvas);

                            const previewImg = document.createElement('img');
                            previewImg.id = 'previewImg';
                            previewImg.width = 160;
                            previewImg.height = 120;
                            previewImg.className = 'image-preview';
                            document.body.appendChild(previewImg);

                            navigator.mediaDevices.getUserMedia({ video: true })
                                .then(function(stream) {
                                    video.srcObject = stream;
                                })
                                .catch(function(error) {
                                    console.log("Something went wrong accessing the camera.");
                                });

                            captureButton.addEventListener('click', function() {
                                canvas.getContext('2d').drawImage(video, 0, 0, 640, 480);

                                const imageData = canvas.toDataURL('image/png');

                                previewImg.style.display = 'flex';
                                previewImg.src = imageData;

                                fetch('/save_image', {
                                    method: 'POST',
                                    headers: {
                                        'Content-Type': 'application/json',
                                    },
                                    body: JSON.stringify({ image: imageData })
                                })
                                .then(response => response.json())
                                .then(data => {
                                    console.log('Image saved:', data.filePath);
                                })
                                .catch(error => {
                                    console.error('Error saving image:', error);
                                });
                            });
                        } else if (component.type === 'submit') {
                            const submitButton = document.createElement('button');
                            submitButton.id = component.id;
                            submitButton.className = 'submit-button'
                            submitButton.textContent = '提交';
                            document.body.appendChild(submitButton);

                            const loading = document.createElement('div');
                            loading.id = 'loadingMsg';
                            loading.className = 'loading-message';
                            loading.style.display = 'none';
                            document.body.appendChild(loading);

                            document.getElementById('submitButton').addEventListener('click', function() {
                                const video = document.getElementById('cameraComponent');
                                if (video) {
                                    video.style.display = 'none';}
                                const text = document.getElementById('textComponent');
                                if (text) {
                                    const textContent = text.value;
                                    text.value = '';
                                    text.style.height = 'auto';
                                    fetch('/submit-text', {
                                        method: 'POST', // 使用POST方法发送请求
                                        headers: {
                                          'Content-Type': 'application/json', // 设置请求体的内容类型为JSON
                                        },
                                        body: JSON.stringify({ text: textContent }), // 将文本内容作为JSON发送
                                      })
                                      .then(response => response.json()) // 解析JSON响应
                                      .then(data => {
                                        console.log('Success:', data); // 处理响应数据
                                      })
                                      .catch((error) => {
                                        console.error('Error:', error); // 处理请求错误
                                      });

                                }

                                let audio = document.getElementById('audioPreview');
                                if (audio) {
                                    audio.style.display = 'none';
                                }

                                let image = document.getElementById('imagePreview');
                                if (image) {
                                    image.style.display = 'none';
                                }

                                image = document.getElementById('previewImg');
                                if (image) {
                                    image.style.display = 'none';
                                }

                                fetch('/submit', {
                                    method: 'POST'
                                })
                                .then(response => response.json())
                                .then(data => {
                                    const outputArea = createOrUpdateOutputArea();
                                    if (data.image) {
                                        const userText = document.createElement('p');
                                        userText.className = 'user-display';
                                        userText.innerHTML = `用户: <img src="${data.image}" alt="user input image"  class="image-show"\>`;
                                        outputArea.appendChild(userText);
                                    }
                                    if (data.audio) {
                                        const userText = document.createElement('p');
                                        userText.className = 'user-display';
                                        userText.innerHTML = `用户: <audio controls src="${data.audio}"></audio>`;
                                        outputArea.appendChild(userText);
                                    }
                                    if (data.text) {
                                        const userText = document.createElement('p');
                                        userText.className = 'user-display';
                                        userText.innerHTML = `${convertMarkdownToHTML('用户: ' + data.text.replace(/\n/g, "\n\n"))}`;
                                        outputArea.appendChild(userText);
                                    }
                                    outputArea.scrollTop = outputArea.scrollHeight;
                                    const loading = document.getElementById('loadingMsg');
                                    loading.textContent = '等待AI响应中';
                                    loading.style.display = 'flex';
                                    const submitButton = document.getElementById('submitButton');
                                    submitButton.disabled = true;
                                    const intervalId = setInterval(() => {
                                        fetch('/result')
                                        .then(response => response.json())
                                        .then(data => {
                                            updateContent(data);
                                            if (data.status !== "processing") {
                                                clearInterval(intervalId);
                                                // loading.style.display = 'none';
                                                loading.textContent = '';
                                                submitButton.disabled = false;
                                                const textDiv = outputArea.querySelector('.ai-display-text');
                                                if (textDiv){
                                                    textDiv.className = 'ai-display';
                                                }
                                            }
                                            else {
                                                let text = loading.textContent;
                                                if (text.length >= 17) {
                                                    loading.textContent = '等待AI响应中';
                                                }
                                                else {
                                                    loading.textContent += '.';
                                                }
                                            }
                                        });
                                    }, 300);  // 每0.3秒检查一次
                                });
                            });
                        } else if (component.type === 'text') {
                            const outputText = document.createElement('input');
                            outputText.id = component.id;
                            outputText.type = 'text';
                            document.body.appendChild(outputText);
                        } else if (component.type === 'input_pic') {
                            const fileInput = document.createElement('input');
                            fileInput.type = 'file';
                            fileInput.accept = 'image/*';
                            fileInput.className = 'file-input';
                            document.body.appendChild(fileInput);

                            const imagePreview = document.createElement('img');
                            imagePreview.id = 'imagePreview';
                            imagePreview.className = 'image-preview';
                            imagePreview.style.display = 'none';
                            document.body.appendChild(imagePreview);

                            fileInput.addEventListener('change', function() {
                                if (this.files && this.files[0]) {
                                    const formData = new FormData();
                                    formData.append('file', this.files[0]);

                                    fetch('/upload_image', {
                                        method: 'POST',
                                        body: formData,
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        console.log('Upload successful:', data.fileUrl);
                                        imagePreview.style.display = 'flex';
                                        imagePreview.src = data.fileUrl;
                                    })
                                    .catch(error => {
                                        console.error('Upload error:', error);
                                    });
                                }
                            });
                        } else if (component.type === 'input_audio') {
                            const fileInput = document.createElement('input');
                            fileInput.type = 'file';
                            fileInput.accept = 'audio/*';
                            fileInput.className = 'file-input';
                            document.body.appendChild(fileInput);

                            const audioPreview = document.createElement('audio');
                            audioPreview.id = 'audioPreview';
                            audioPreview.className = 'audio-preview';
                            audioPreview.controls = true;
                            audioPreview.style.display = 'none';
                            document.body.appendChild(audioPreview);

                            fileInput.addEventListener('change', function() {
                                if (this.files && this.files[0]) {
                                    const formData = new FormData();
                                    formData.append('file', this.files[0]);

                                    fetch('/upload_audio', {
                                        method: 'POST',
                                        body: formData,
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        console.log('Upload successful:', data.fileUrl);
                                        audioPreview.style.display = 'flex';
                                        audioPreview.src = data.fileUrl;
                                    })
                                    .catch(error => {
                                        console.error('Upload error:', error);
                                    });
                                }
                            });
                        } else if (component.type === 'record') {
                            if (!navigator.mediaDevices || !window.MediaRecorder) {
                              alert("您的浏览器不支持录音功能。");
                              return 0;
                            }

                            // 创建开始录音按钮
                            const startBtn = document.createElement('button');
                            startBtn.textContent = '开始录音';
                            startBtn.id = 'startBtn';
                            startBtn.className = 'start-button';

                            // 创建停止录音按钮
                            const stopBtn = document.createElement('button');
                            stopBtn.textContent = '停止录音';
                            stopBtn.id = 'stopBtn';
                            stopBtn.disabled = true; // 初始状态下，停止按钮不可点击
                            stopBtn.className = 'stop-button';

                            // 创建状态显示元素
                            const statusLabel = document.createElement('div');
                            statusLabel.textContent = '未录音';
                            statusLabel.id = 'statusLabel';
                            statusLabel.className = 'status-label';

                            // 创建时间显示元素
                            const timeLabel = document.createElement('div');
                            timeLabel.textContent = '时间：00:00';
                            timeLabel.id = 'timeLabel';
                            timeLabel.className = 'time-label';

                            // 将元素添加到文档中
                            document.body.appendChild(startBtn);
                            document.body.appendChild(stopBtn);
                            document.body.appendChild(statusLabel);
                            document.body.appendChild(timeLabel);

                            const audioPreview = document.createElement('audio');
                            audioPreview.id = 'audioPreview';
                            audioPreview.className = 'audio-preview';
                            audioPreview.controls = true;
                            audioPreview.style.display = 'none';
                            document.body.appendChild(audioPreview);

                            let mediaRecorder;
                            let audioChunks = [];
                            let recordingStartTime;
                            let recordingInterval;

                            navigator.mediaDevices.getUserMedia({ audio: true })
                              .then(stream => {
                                mediaRecorder = new MediaRecorder(stream);

                                mediaRecorder.ondataavailable = event => {
                                  audioChunks.push(event.data);
                                };

                                mediaRecorder.onstart = () => {
                                  recordingStartTime = Date.now();
                                  recordingInterval = setInterval(updateRecordingTime, 1000); // 每秒更新时间
                                  statusLabel.textContent = '正在录音...';
                                  timeLabel.textContent = '时间：00:00';
                                };

                                mediaRecorder.onstop = () => {
                                  clearInterval(recordingInterval); // 停止计时器
                                  statusLabel.textContent = '录音结束';

                                  const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                                  const formData = new FormData();
                                  formData.append('audioFile', audioBlob, 'recording.wav');

                                  audioPreview.src = URL.createObjectURL(audioBlob);
                                  audioPreview.style.display = 'flex';
                                  audioChunks = [];

                                  fetch('/save_audio', {
                                    method: 'POST',
                                    body: formData,
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        console.log('Audio uploaded successfully', data.filePath);
                                    })
                                    .catch(error => {
                                        console.error('Error uploading audio:', error);
                                    });

                                    };
                              });

                            // 更新录音时间的函数
                            function updateRecordingTime() {
                                const elapsedTime = Date.now() - recordingStartTime;
                                const seconds = Math.floor((elapsedTime / 1000) % 60).toString().padStart(2, '0');
                                const minutes = Math.floor((elapsedTime / (1000 * 60)) % 60).toString().padStart(2, '0');
                                timeLabel.textContent = `时间：${minutes}:${seconds}`;
                            }

                            document.getElementById('startBtn').onclick = () => {
                              if (mediaRecorder) {
                                mediaRecorder.start();
                                document.getElementById('startBtn').disabled = true;
                                document.getElementById('stopBtn').disabled = false;
                                audioChunks = [];
                                console.log("录音开始...");
                              }
                            };

                            document.getElementById('stopBtn').onclick = () => {
                              if (mediaRecorder) {
                                mediaRecorder.stop();
                                document.getElementById('startBtn').disabled = false;
                                document.getElementById('stopBtn').disabled = true;
                                console.log("录音停止...");
                              }
                            };
                        } else if (component.type === 'input_text') {
                            const textInput = document.createElement('textarea');
                            textInput.type = 'text';
                            textInput.id = 'textComponent';
                            textInput.className = 'text-input';
                            textInput.placeholder = '请输入文字内容';
                            document.body.appendChild(textInput);
                            textInput.addEventListener('input', function() {
                                const textarea = this;
                                // 先重置高度，以获取准确的 scrollHeight
                                textarea.style.height = 'auto';

                                const computedStyle = window.getComputedStyle(textarea);
                                const lineHeight = parseInt(computedStyle.lineHeight, 10);
                                const borderTopWidth = parseInt(computedStyle.borderTopWidth, 10);
                                const borderBottomWidth = parseInt(computedStyle.borderBottomWidth, 10);
                                const paddingTop = parseInt(computedStyle.paddingTop, 10);
                                const paddingBottom = parseInt(computedStyle.paddingBottom, 10);

                                const externalHeight = borderTopWidth + borderBottomWidth + paddingTop + paddingBottom;
                                const scrollHeight = textarea.scrollHeight - externalHeight; // 减去额外高度
                                const maxHeightInLines = 15;
                                const maxAllowedHeight = maxHeightInLines * lineHeight;

                                if (scrollHeight < maxAllowedHeight) {
                                    textarea.style.height = `${scrollHeight}px`;
                                    textarea.style.overflowY = 'hidden';
                                } else {
                                    textarea.style.height = `${maxAllowedHeight}px`;
                                    textarea.style.overflowY = 'auto';
                                }
                            });
                        }
                    });
                });
        };
    </script>
</body>
</html>
