<template>
    <div class="voice-analysis-container" ref="voiceAnalysisContainerRef">
      <h3>实时语音分析</h3>
      <h5> 😊 😐 😔 😡 😰 🤢 😮</h5>
      <!-- 使用 el-empty 表示空状态 -->
      <el-empty v-if="analysisResults.length === 0" description="暂无分析结果" />
      <div v-else>
        <div v-for="(result, index) in analysisResults" :key="index" class="analysis-result">
          <!-- 横向条形图容器 -->
          <p class="content">{{result.content}}<span style="margin-left:10px">{{result.emotion || ''}}</span></p>
          <div ref="chartRefs" class="chart-container"></div>
          <p style="font-size:14px; font-weight:bold;margin-right:70%">各单词得分</p>
          <div class="sentence">
            <span
                v-for="(word, index) in result.wordScoreList"
                :key="index"
                class="word-tag"
            >
                <span class="word">{{ word.word }}</span>
                <span class="score" :style="{ color: getWordColor(word.totalScore) }">{{ word.totalScore }}</span>
            </span>
            </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onBeforeUnmount, nextTick, defineProps } from "vue";
  import * as echarts from "echarts";
  import { ElEmpty } from "element-plus"; // 引入 Element Plus 的 Empty 组件
  import doubaoApis from "@/apis/doubao";
  import fileApis from "@/apis/file";
  import { filterFields } from "element-plus/es/components/form/src/utils";


  const props = defineProps({
    userId: {
    type: Number,
    required: true,
    },
    assignmentId: {
      type: Number,
      required: true,
    }
  })
  const analysisResults = ref([]);
  const chartRefs = ref([]);
  const charts = ref([]);
  const voiceAnalysisContainerRef = ref(null);
  const scrollToBottom = () => {
      nextTick(() => {
        if (voiceAnalysisContainerRef) {
          voiceAnalysisContainerRef.scrollTop = voiceAnalysisContainerRef.scrollHeight;
        }
      });
  };

  const addAnalysisResult = (result) => {
    analysisResults.value.push(result);
    nextTick(() => {
      renderChart(analysisResults.value.length - 1);
      scrollToBottom();
    });
  };
  
  const renderChart = (index) => {
    nextTick(() => {
      const chartDom = chartRefs.value[index];
      if (!chartDom) return;
      if (charts.value[index]) {
        charts.value[index].dispose();
      }
      charts.value[index] = echarts.init(chartDom);
      const option = {
        tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },
        grid: { left: "1%", right: "10%", bottom: "2%", containLabel: true },
        xAxis: {
          type: "value",
          max: 100,
          axisLabel: { formatter: "{value}%" },
          splitLine: { show: false },
        },
        yAxis: {
          type: "category",
          data: ["准确度", "流利度", "完整性", "标准度", "总分"],
          axisTick: { show: false },
        },
        series: [
          {
            name: "得分",
            type: "bar",
            barWidth: "40%",
            data: [
              analysisResults.value[index].accuracyScore,
              analysisResults.value[index].fluencyScore,
              analysisResults.value[index].integrityScore,
              analysisResults.value[index].standardScore,
              analysisResults.value[index].totalScore,
            ],
            label: {
              show: true,
              position: "right",
              formatter: "{c}",
              color: "#1E88E5",
            },
            itemStyle: {
              barBorderRadius: [5, 5, 5, 5],
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                { offset: 0, color: "#90caf9" },
                { offset: 1, color: "#90caf9" },
              ]),
              shadowBlur: 10,
              shadowColor: "rgba(0, 0, 0, 0.1)",
            },
            animationDuration: 1000,
          },
        ],
      };
  
      charts.value[index].setOption(option);
      window.addEventListener("resize", () => charts.value[index].resize());
    });
  };
  
  const getWordColor = (score) => {
    if (score >= 86) return "#a5d6a7"; // Light green for Excellent
    if (score >= 70) return "#80cbc4"; // Light teal for Good
    if (score >= 50) return "#fff59d"; 
    return "#ffcdd2"; // Light red for Poor
  };
  
  onMounted(() => {
    doubaoApis
    .getChatHistory(props.userId, props.assignmentId)
    .then((res) => {
      const dialogues = res.data.data
      // 过滤掉 role 为 assistant 且 totalScore 为 null 的对话
      const filteredDialogues = dialogues.filter(
        (dialogue) => dialogue.role !== 'ASSISTANT' && dialogue.totalScore !== null
      );
      // 将过滤后的数据赋值给 analysisResults
    analysisResults.value =
      filteredDialogues.map((dialogue) => ({
        content: dialogue.content,
        accuracyScore: dialogue.accuracyScore,
        fluencyScore: dialogue.fluencyScore,
        integrityScore: dialogue.integrityScore,
        standardScore: dialogue.standardScore,
        totalScore: dialogue.totalScore,
        wordScoreList: dialogue.wordScoreList,
        emotion:dialogue.audioSentiment
      }))
    nextTick(() => {
      analysisResults.value.forEach((_, index) => renderChart(index));
    });
  })
});
  
  onBeforeUnmount(() => {
    charts.value.forEach((chart) => chart.dispose());
    window.removeEventListener("resize", () => {});
  });
  
  defineExpose({ addAnalysisResult, voiceAnalysisContainerRef });
  </script>
  
  <style scoped>
  .voice-analysis-container {
    padding: 20px;
    background-color: #e3f2fd;
    height: 100%;
    box-sizing: border-box;
    overflow-y: auto;
    min-width: 200px;
    scrollbar-width: none; /* Firefox */
    text-align: center;
  }

  
  .analysis-result {
    margin-top: 20px;
    padding: 15px;
    background-color: #ffffff;
    border-radius: 10px;
    
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  .content{
    border:none;
    background-color: #f1f8e9;
  }
  
  .chart-container {
    width: 100%;
    height: 210px;
    margin-top: -60px;
  }
  
  .sentence {
    font-size: 16px;
    font-weight: bold;
    display: flex;
    flex-wrap: wrap;
  }
  
  .word-tag {
    position: relative;
    margin-right: 8px;
    margin-bottom: 5px;
    padding: 0px 2px;
    border-radius: 5px;
    background-color: rgba(0, 0, 0, 0.05);
    display: inline-block;
  }
  
  .word {
    color: #90caf9;
    display: block;
    text-align: center;
    margin-bottom: 5px;
    font-size: 16px;
  }
  
  .score {
    font-size: 14px;
    font-weight: bold;
    display: block;
    text-align: center;
  }
  </style>