<template>
  <div class="container">
    <div class="header-container">
      <!-- 返回按钮 -->
      <el-button style="color:#4A90C4" class="back-button" type="text" @click="goBack">
        <el-icon><Back /></el-icon>
      </el-button>
      <!-- 标题 -->
    </div>
    <!-- 基本信息卡片 -->
    <el-card class="compact-card">
      <template #header>
        <h1 class="page-title">{{props.assignmentName}}</h1>
        <div class="card-header">整体信息</div>
        <div class="card-time">
          提交时间：{{
            new Date(speakingAIDialogue.committedTime).toLocaleString()
          }}
        </div>
      </template>
      <span class="info-label" style="margin-left:3%">数据统计</span>
      <div class="time-info">
        <div class="word-count-box">
          <div class="label">作业时长</div>
          <span class="value"
            >{{
              Number(speakingAIDialogue.totalVideoTime).toFixed(2) || 0
            }}
            s</span
          >
        </div>
        <div class="word-count-box">
          <div class="label">录音时长</div>
          <span class="value"
            >{{
              Number(speakingAIDialogue.totalSpeakingTime).toFixed(2) || 0
            }}
            s</span
          >
        </div>
        <div class="word-count-box">
          <div class="label">总单词数</div>
          <span class="value">{{ Number(speakingAIDialogue.totalUserWordCount) || 0 }}</span>
        </div>
        <div class="word-count-box">
          <div class="lable">交流次数</div>
          <span class="value">{{ Number(speakingAIDialogue.chatTimes) }}</span>
        </div>
      </div>
      <div class="time-info">
        <div class="word-count-box">
          <div class="label">发言时长占比</div>
          <div class="value">{{(Number(speakingAIDialogue.totalUserWordCount)/ Number(speakingAIDialogue.totalAssistantWordCount) * 100).toFixed(0) }}%</div>
        </div>
        <div class="word-count-box">
          <div class="label">每分钟单词数</div>
          <div class="value">{{(Number(speakingAIDialogue.totalUserWordCount)/ Number(speakingAIDialogue.totalSpeakingTime) * 60).toFixed(0) }}</div>
        </div>
        <div class="word-count-box">
          <div class="label">平均句长</div>
          <div class="value">{{(Number(speakingAIDialogue.totalUserWordCount)/ Number(speakingAIDialogue.chatTimes)).toFixed(0) }}</div>
        </div>
      </div>
      <!-- 新增的图表容器 -->
      <div class="info-item">
        <span class="info-label">口语评分</span>
        <div
          ref="avgScoreChart"
          class="chart-container"
          style="width: 100%; height: 300px"
        ></div>
      </div>
      <div class="info-item">
        <span class="info-label">录像片段</span>
        <div class="video-segments">
          <div
            v-for="(url, index) in speakingAIDialogue.audioSigment"
            :key="index"
            class="video-item"
          >
            <video
              :src="url.split('?')[0]"
              controls
              class="video-player"
            ></video>
            <div class="duration-label">
              Duration: {{ getDuration(index) }}s
            </div>
          </div>
        </div>
      </div>
      <div class="info-item">
        <span class="info-label">录像情感</span>
        <div class="video-segments" v-loading="isVideoEmotionLoading" 
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.1)">
          <video
            v-if="speakingAIDialogue.videoAnalysis"
            :src="speakingAIDialogue.videoAnalysis.merged_video_path"
            controls
            class="video-player"
          ></video>
          <div
            ref="emotionChartRef"
            style="margin-left:40%; width:400px; height: 300px"
          ></div>
        </div>
      </div>
    </el-card>
    <el-card class="compact-card">
      <template #header>
        <div class="card-header">建议信息</div>
        <el-table
        :data="formattedSuggestions"
        stripe
        v-loading="isSuggestionLoading"
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.1)"
      >
        <el-table-column prop="title" label="方向" width="120px">
          <template #default="{ row }">
            <span class="highlight-title">{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="items" label="建议项">
          <template #default="{ row }">
            <span>{{ String(row.items).split("-").join("\n") }}</span>
          </template>
        </el-table-column>
      </el-table>
      </template>

    </el-card>

    <!-- 对话条目卡片 -->
    <el-card class="compact-card">
      <template #header>
        <div class="card-header">对话条目</div>
      </template>
      <el-table
        :data="speakingAIDialogue.dialogues.slice(1, -2)"
        stripe
        style="width: 100%; min-width: 800px"
        :row-class-name="getRowClassName"
      >
        <el-table-column prop="role" label="Role" width="100">
          <template #default="scope">
            <span
              v-if="scope.row.role == 'assistant'"
              >ASSISTANT</span
            >
            <span v-else>
              USER
            </span>
          </template>
        </el-table-column>
        <el-table-column label="Content" width="400">
          <template #default="scope">
            {{
              scope.row.content +
              (scope.row.audioSentiment ? ` ${scope.row.audioSentiment}` : "")
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="wordCount"
          label="Count"
          width="80"
        ></el-table-column>
        <el-table-column label="Audio" width="300">
          <template #default="scope">
            <audio
              controls
              style="width: 250px; height: 40px"
              v-if="scope.row.audioUrl"
            >
              <source :src="scope.row.audioUrl" type="audio/mp3" />
              <source :src="scope.row.audioUrl" type="audio/wav" />
              您的浏览器不支持音频播放。
            </audio>
          </template>
        </el-table-column>
        <!-- <el-table-column label="Timestamp" width="200px">
          <template #default="scope">
          <div style="font-size: 15px">
              {{ new Date(scope.row.timestamp).toLocaleString() }}
            </div>
          </template>
        </el-table-column> -->
        <el-table-column label="Score">
          <template #default="scope">
            <div
              :ref="(el) => setChartRef(el, scope.$index)"
              class="chart-container"
            ></div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 老师评语卡片 -->
    <el-card class="compact-card">
      <template #header>
        <div class="card-header">作业评价</div>
      </template>
      <div class="teacher-comment">
        <!-- 学生角色：展示老师的评价和分数 -->
        <template v-if="ROLE === 'STUDENT'">
          <div
            v-if="engagement.remark || engagement.score"
            class="comment-container"
          >
            <div class="comment-item">
              <span class="comment-label">评语：</span>
              <span class="comment-content">{{
                engagement?.remark || "暂无评语"
              }}</span>
            </div>
            <div class="comment-item">
              <span class="comment-label">评分：</span>
              <el-rate
                v-model="engagement.score"
                :max="10"
                show-score
                disabled
                score-template="{value} 分"
              />
            </div>
          </div>
          <el-empty v-else description="暂无老师评语" />
        </template>

        <!-- 老师角色：展示评价框和评分器 -->
        <template v-else>
          <el-input
            v-model="engagement.remark"
            type="textarea"
            :rows="6"
            style="width: 1000px"
            placeholder="请输入评语"
            class="comment-input"
          />
          <div class="score-input">
            <span class="score-label">评分：</span>
            <el-rate
              v-model="engagement.score"
              :max="10"
              show-score
              score-template="{value} 分"
            />
          </div>
          <div class="correction-actions">
            <div class="button-container">
              <div class="left-buttons">
                <el-button 
                  style="background-color:#4A90C4;color:white;width:200px" 
                  @click="submitComment" 
                  class="submit-button"
                  :loading="submitting"
                >
                  提交评语
                </el-button>
                
                <el-button
                  style="background-color:#4A90C4;color:white;width:200px;margin-top:50px"
                  @click="handleNext"
                  :disabled="isAllCorrected"
                >
                  下一个
                </el-button>
                <!-- 新增：评语模板 -->
                <el-button
                  style="background-color:#4A90C4;color:white;width:200px;margin-top:50px;"
                  @click="showTemplateDialog"
                >
                  评语模板
                </el-button>

                <el-button
                  style="background-color:#4A90C4;color:white;width:200px;margin-top:50px;"
                  @click="goBack"
                >
                  返回
                </el-button>
              </div>
              
              <!-- 批改进度显示 -->
              <div class="progress-numbers">
                已批改/未批改：{{ correctionStats.correctNumber }}/{{ uncorrectedNumber }}
              </div>
            </div>
          </div>
        </template>
      </div>
    </el-card>

    <!-- 添加评语模板弹窗 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="评语模板"
      width="50%"
      :close-on-click-modal="false"
    >
      <div class="template-list">
        <div 
          v-for="(template, index) in remarkTemplates" 
          :key="index"
          class="template-item"
          @click="selectTemplate(template)"
        >
          <el-tooltip
            v-if="isTruncatedList[index]"
            :content="template"
            placement="top"
            :show-after="500"
            effect="light"
          >
            <div class="template-content" :ref="el => setTemplateContentRef(el, index)">
              {{ index + 1 }}. {{ template }}
            </div>
          </el-tooltip>
          <div
            v-else
            class="template-content"
            :ref="el => setTemplateContentRef(el, index)"
          >
            {{ index + 1 }}. {{ template }}
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, defineProps, computed, watch } from "vue";
import doubaoApis from "@/apis/doubao";
import engagementApis from "@/apis/engagement";
import mediaApis from "@/apis/media";
import * as echarts from "echarts";
import { ElEmpty, ElMessage } from "element-plus";
import { Back } from "@element-plus/icons-vue"; // 引入 Element UI
import { useRouter } from "vue-router";
import {useStore} from "@/store";
import useApis from "@/apis";

const router = useRouter();
const store = useStore();
const apis = useApis();

// 添加courseId ref
const courseId = ref(0);

const props = defineProps({
  userId: {
    type: Number,
    required: true,
    default: null
  },
  assignmentId: {
    type: Number,
    required: true,
    default: null
  },
  assignmentName: {
    type: String,
    default: '未命名作业'
  }
});
const speakingAIDialogue = ref({
  id: "",
  assignmentId: null,
  userId: null,
  suggestion: "",
  videoUrl: "",
  audioSigment: [],
  audioDuration: [],
  hasCommitted: false,
  dialogues: [],
  totalVideoTime: 0,
  totalSpeakingTime: 0,
  totalWordCount: 0,
  chatTimes: 0,
  accuracyScoreAvg: 0,
  fluencyScoreAvg: 0,
  integrityScoreAvg: 0,
  standardScoreAvg: 0,
  totalScoreAvg: 0,
  videoAnalysis: {
    merged_video_path: "",
    emotion_percentage_dict: [],
  },
});

const engagement = ref({
  score: 0,
  remark: "",
});

const isSuggestionLoading = ref(true);
const isVideoEmotionLoading = ref(true);
const submitting = ref(false);

// 批改进度统计
const correctionStats = ref({
  engageNumber: 0,
  correctNumber: 0
});

// 计算批改进度百分比（暂时不使用，保留以防将来需要）
// const progressPercentage = computed(() => {
//   if (correctionStats.value.engageNumber === 0) return 0;
//   return Math.round((correctionStats.value.correctNumber / correctionStats.value.engageNumber) * 100);
// });

// 计算未批改数量
const uncorrectedNumber = computed(() => {
  return correctionStats.value.engageNumber - correctionStats.value.correctNumber;
});

// 判断是否全部批改完成
const isAllCorrected = computed(() => {
  return uncorrectedNumber.value === 0;
});

// 获取批改进度统计
const fetchCorrectionStats = async () => {
  try {
    const res = await engagementApis.getAssignmentCorrectionStats(props.assignmentId);
    if (res.data.code === 200) {
      correctionStats.value = res.data.data;
    }
  } catch (error) {
    console.error('获取批改进度失败:', error);
  }
};

// 获取作业详情以获取courseId
const fetchAssignmentDetails = async () => {
  try {
    const response = await apis.getAssignmentById(props.assignmentId);
    if (response.data.code === 200) {
      const assignmentData = response.data.data;
      courseId.value = assignmentData.courseId || 0;
      console.log('获取到AI口语作业courseId:', courseId.value);
    }
  } catch (error) {
    console.error('获取AI口语作业详情失败:', error);
    // 如果普通作业API失败，尝试AI口语作业API
    try {
      const aiResponse = await apis.getAiSpeakingAssignmentById(props.assignmentId);
      if (aiResponse.data.code === 200 && aiResponse.data.data.courseId) {
        courseId.value = aiResponse.data.data.courseId;
        console.log('从AI口语API获取到courseId:', courseId.value);
      }
    } catch (aiError) {
      console.error('获取AI口语作业详情也失败:', aiError);
    }
  }
};

// 获取下一个学生作业ID
const getNextStudentAssignment = async () => {
  try {
    const res = await engagementApis.getNextStudentAssignment(props.assignmentId, props.userId);
    if (res.data.code === 200) {
      return res.data.data;
    }
  } catch (error) {
    console.error('获取下一个学生失败:', error);
  }
  return null;
};

const emotionChartRef = ref(null);
let emotionChartInstance = null;
const createEmotionPieChart = (emotionList) => {
  console.log(emotionList);
  if (!emotionChartRef.value) return;
  // 如果已经存在图表实例，先销毁
  if (emotionChartInstance) {
    emotionChartInstance.dispose();
  }
  // 初始化图表
  emotionChartInstance = echarts.init(emotionChartRef.value);
  const option = {
    title: {
      text: "情感分析结果",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "-1%",
      
    },
    series: [
      {
        name: "情感占比",
        type: "pie",
        radius: "50%",
        data: emotionList.map((item) => ({
          value: item.percentage,
          name: item.emotion,
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
        
      },
    ],
  };
  emotionChartInstance.setOption(option);
  window.addEventListener("resize", () => emotionChartInstance.resize());
};

// 处理下一个按钮点击
const handleNext = async () => {
  const nextStudentId = await getNextStudentAssignment();
  if (nextStudentId) {
    router.push({
      path: `/home/assignment/${props.assignmentId}/airecord`,
      query: {
        userId: nextStudentId,
        assignmentId: props.assignmentId,
        assignmentName: props.assignmentName
      }
    }).then(() => {
      window.location.reload();
    });
    ElMessage.success("已自动跳转到下一个学生");
  } else {
    ElMessage.info("没有下一个学生");
  }
};

// 修改提交评语函数,移除跳转逻辑
const submitComment = async () => {
  if (!engagement.value.remark || engagement.value.score === 0) {
    ElMessage.warning("请填写评语和评分");
    return;
  }
  
  submitting.value = true;
  try {
    const response = await engagementApis.engagementCorrect(
      props.userId,
      props.assignmentId,
      {
        score: engagement.value.score,
        remark: engagement.value.remark,
      }
    );
    if (response.data.code === 200) {
      ElMessage.success("评语提交成功");
      await fetchCorrectionStats();
    } else {
      ElMessage.error("评语提交失败");
    }
  } catch (error) {
    console.error("提交评语失败:", error);
    ElMessage.error("网络错误，请重试");
  } finally {
    submitting.value = false;
  }
};

const chartRefs = ref([]); // 用于存储图表容器的引用
const charts = ref([]); // 用于存储 ECharts 实例

// 动态绑定 ref 并渲染图表
const setChartRef = (el, index) => {
  if (el) {
    chartRefs.value[index + 1] = el;

    if (speakingAIDialogue.value.role == "user") {
      renderChart(index, speakingAIDialogue.value.dialogues[index]);
    }
  }
};
// 渲染图表
const renderChart = (index, data) => {
  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: "0%",
        right: "20%",
        bottom: "5%",
        top: "5%",
        containLabel: true,
      },
      xAxis: {
        type: "value",
        max: 100,
        axisLabel: { show: false }, // 隐藏 x 轴标签
      },
      yAxis: {
        type: "category",
        data: ["准确度", "流利度", "完整性", "标准度", "总分"],
        axisTick: { show: false }, // 隐藏刻度
      },
      series: [
        {
          name: "得分",
          type: "bar",
          barWidth: "30%",
          data: [
            data.accuracyScore,
            data.fluencyScore,
            data.integrityScore,
            data.standardScore,
            data.totalScore,
          ],
          label: {
            show: true,
            position: "right",
            formatter: "{c}",
            color: "#1E88E5",
            fontSize: 10, // 调整字体大小
          },
          itemStyle: {
            barBorderRadius: [5, 5, 5, 5],
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: "#90caf9" },
              { offset: 1, color: "#1E88E5" },
            ]),
            shadowBlur: 3, // 减小阴影
            shadowColor: "rgba(0, 0, 0, 0.1)",
          },
          animationDuration: 1000,
        },
      ],
    };

    // 设置图表配置
    charts.value[index].setOption(option);

    // 监听窗口大小变化，调整图表尺寸
    window.addEventListener("resize", () => charts.value[index].resize());
  });
};

const avgScoreChart = ref(null); // 用于存储图表容器的引用
let chartInstance = null; // 用于存储 ECharts 实例

// 渲染平均值图表
const renderAvgScoreChart = () => {
  if (!avgScoreChart.value) return;

  // 如果已经存在图表实例，先销毁
  if (chartInstance) {
    chartInstance.dispose();
  }

  // 初始化图表
  chartInstance = echarts.init(avgScoreChart.value);
  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    graphic: [
      // 总分标注
      {
        type: "text",
        left: "11%", // 调整位置
        top: "86%", // 调整位置
        style: {
          text: "总分",
          fontSize: 14,
          fill: "#333", // 文字颜色
        },
      },
      // 准确度标注
      {
        type: "text",
        left: "28%", // 调整位置
        top: "48%", // 调整位置
        style: {
          text: "准确度",
          fontSize: 14,
          fill: "#333", // 文字颜色
        },
      },
      // 流利度标注
      {
        type: "text",
        left: "28%", // 调整位置
        top: "87%", // 调整位置
        style: {
          text: "流利度",
          fontSize: 14,
          fill: "#333", // 文字颜色
        },
      },
      // 完整性标注
      {
        type: "text",
        left: "43%", // 调整位置
        top: "48%", // 调整位置
        style: {
          text: "完整性",
          fontSize: 14,
          fill: "#333", // 文字颜色
        },
      },
      // 标准度标注
      {
        type: "text",
        left: "43%", // 调整位置
        top: "87%", // 调整位置
        style: {
          text: "标准度",
          fontSize: 14,
          fill: "#333", // 文字颜色
        },
      },
    ],
    series: [
      // 左侧大圆形百分比图（总分）
      {
        name: "总分",
        type: "pie",
        radius: ["50%", "60%"], // 环形图，内半径 50%，外半径 70%
        center: ["12%", "50%"],
        data: [
          {
            value: speakingAIDialogue.value.totalScoreAvg,
            name: "总分",
            label: {
              show: true,
              position: "center",
              fontSize: 20,
              formatter: function (params) {
                // 将百分比值转换为整数
                return Math.round(params.percent);
              },
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgb(84,112,198)" },
                { offset: 0.6, color: "rgb(84,112,198)" },
              ]),
            },
          },
          {
            value: 100 - speakingAIDialogue.value.totalScoreAvg, // 剩余部分
            name: "",
            itemStyle: {
              color: "#eee",
            },
          },
        ],
      },
      // 右侧上方第一个小圆形百分比图（准确度）
      {
        name: "准确度",
        type: "pie",
        radius: ["20%", "28%"],
        center: ["30%", "30%"],
        data: [
          {
            value: speakingAIDialogue.value.accuracyScoreAvg,
            name: "准确度",
            label: {
              show: true,
              position: "center",
              fontSize: 14,
              formatter: function (params) {
                // 将百分比值转换为整数
                return Math.round(params.percent);
              },
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgb(115,192,222)" },
                { offset: 1, color: "rgb(115,192,222)" },
              ]),
            },
          },
          {
            value: 100 - speakingAIDialogue.value.accuracyScoreAvg,
            name: "",
            itemStyle: {
              color: "#eee",
            },
          },
        ],
      },
      // 右侧上方第二个小圆形百分比图（流利度）
      {
        name: "流利度",
        type: "pie",
        radius: ["20%", "28%"],
        center: ["30%", "70%"],
        data: [
          {
            value: speakingAIDialogue.value.fluencyScoreAvg,
            name: "流利度",
            label: {
              show: true,
              position: "center",
              fontSize: 14,
              formatter: function (params) {
                // 将百分比值转换为整数
                return Math.round(params.percent);
              },
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgb(250,200,88)" },
                { offset: 1, color: "rgb(250,200,88)" },
              ]),
            },
          },
          {
            value: 100 - speakingAIDialogue.value.fluencyScoreAvg,
            name: "",
            itemStyle: {
              color: "#eee",
            },
          },
        ],
      },
      // 右侧下方第一个小圆形百分比图（完整性）
      {
        name: "完整性",
        type: "pie",
        radius: ["20%", "28%"],
        center: ["45%", "30%"],
        data: [
          {
            value: speakingAIDialogue.value.integrityScoreAvg,
            name: "完整性",
            label: {
              show: true,
              position: "center",
              fontSize: 14,
              formatter: function (params) {
                // 将百分比值转换为整数
                return Math.round(params.percent);
              },
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgb(252,132,82)" },
                { offset: 1, color: "rgb(252,132,82)" },
              ]),
            },
          },
          {
            value: 100 - speakingAIDialogue.value.integrityScoreAvg,
            name: "",
            itemStyle: {
              color: "#eee",
            },
          },
        ],
      },
      // 右侧下方第二个小圆形百分比图（标准度）
      {
        name: "标准度",
        type: "pie",
        radius: ["20%", "28%"],
        center: ["45%", "70%"],
        data: [
          {
            value: speakingAIDialogue.value.standardScoreAvg,
            name: "标准度",
            label: {
              show: true,
              position: "center",
              fontSize: 14,
              formatter: function (params) {
                // 将百分比值转换为整数
                return Math.round(params.percent);
              },
            },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgb(59,162,114)" },
                { offset: 1, color: "rgb(59,162,114)" },
              ]),
            },
          },
          {
            value: 100 - speakingAIDialogue.value.standardScoreAvg,
            name: "",
            itemStyle: {
              color: "#eee",
            },
          },
        ],
      },
    ],
  };

  // 设置图表配置
  chartInstance.setOption(option);

  // 监听窗口大小变化，调整图表尺寸
  window.addEventListener("resize", () => chartInstance.resize());
};

// 获取格式化后的时长
const getDuration = (index) => {
  const duration = speakingAIDialogue.value.audioDuration[index];
  return Number(duration).toFixed(2);
};

const formattedSuggestions = ref([]);

const parseSuggestion = (suggestion) => {
  const sections = [];
  const parts = suggestion.split(/\n(?=\d+\.)/);
  parts.forEach((part) => {
    const splitIndex = part.indexOf("：");
    if (splitIndex !== -1) {
      const title = part.slice(2, splitIndex).trim();
      const items = part
        .slice(splitIndex + 1)
        .trim()
        .split("\n - ");
      sections.push({
        title,
        items,
      });
    }
  });
  return sections;
};

const getRowClassName = ({ row }) => {
  return row.role === "ASSISTANT"
    ? "assistant-row"
    : row.role === "USER"
    ? "user-row"
    : "";
};

// 组件销毁时清理图表实例
onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  charts.value.forEach((chart) => chart.dispose());
  window.removeEventListener("resize", () => {});
});

const goBack = () => {
  // 根据用户角色决定返回页面
  if (ROLE === 'STUDENT') {
    // 学生返回 myHomework 页面，并传递courseId
    if (!courseId.value) {
      ElMessage.warning('获取课程信息失败，将返回作业列表');
      router.push({ name: 'myHomework' });
      return;
    }
    
    console.log('AI口语作业返回，courseId:', courseId.value);
    router.push({ 
      name: 'myHomework',
      query: { 
        courseId: courseId.value.toString(),
        fromAssignment: 'true' // 标记是从作业页面返回
      }
    });
  } else {
    // 老师返回到批改页面（CoursePage），并自动选中对应的课程和作业
    if (!courseId.value) {
      ElMessage.warning('获取课程信息失败，将返回批改列表');
      router.push({ name: 'myCorrectWithCourse' });
      return;
    }
    
    console.log('AI口语批改返回，courseId:', courseId.value, 'assignmentId:', props.assignmentId);
    router.push({
      name: 'myCorrectWithCourse',
      query: {
        courseId: courseId.value.toString(),
        assignmentId: props.assignmentId.toString(),
        fromCorrect: 'true' // 标记是从批改页面返回
      }
    });
  }
};

const ROLE = store.user.role;

const templateDialogVisible = ref(false);
const remarkTemplates = [
  'Our pronunciation is generally clear and understandable.',
  'Try to speak more slowly and clearly to enhance fluency.',
  'Work on intonation and stress to sound more natural.',
  'Practice difficult sounds more to improve articulation.',
  'Good effort! Keep practicing to build confidence in speaking.',
  'Your argument is clear, but could be strengthened with more supporting details.'
];

const showTemplateDialog = () => {
  templateDialogVisible.value = true;
};

const selectTemplate = (template) => {
  engagement.value.remark = template;
  templateDialogVisible.value = false;
};

const isTruncatedList = ref([]);
const templateContentRefs = ref([]);
const setTemplateContentRef = (el, index) => {
  templateContentRefs.value[index] = el;
};
const checkTruncated = () => {
  isTruncatedList.value = remarkTemplates.map((_, idx) => {
    const el = templateContentRefs.value[idx];
    if (!el || !(el instanceof HTMLElement)) return false;
    return el.scrollWidth > el.clientWidth;
  });
};
watch(templateDialogVisible, (val) => {
  if (val) {
    nextTick(() => {
      checkTruncated();
    });
  }
});

// 在数据加载完成后渲染图表
onMounted(async () => {
  try {
    // 先获取作业详情以获取courseId
    await fetchAssignmentDetails();
    
    const response = await doubaoApis.getRecord(
      props.userId,
      props.assignmentId
    );
    console.log(response.data.data)
    speakingAIDialogue.value = response.data.data;
    if (speakingAIDialogue.value.suggestion) {
      formattedSuggestions.value = parseSuggestion(
        speakingAIDialogue.value.suggestion
      );
      isSuggestionLoading.value = false;
    } else {
      mediaApis
        .getSpeakingSuggestion(
          speakingAIDialogue.value.userId,
          speakingAIDialogue.value.assignmentId
        )
        .then((res) => {
          speakingAIDialogue.value.suggestion = res.data.data;
          formattedSuggestions.value = parseSuggestion(
            speakingAIDialogue.value.suggestion
          );
          isSuggestionLoading.value = false;
        });
    }
    if (speakingAIDialogue.value.videoAnalysis == null) {
      mediaApis
        .getVideoSentiment(
          speakingAIDialogue.value.userId,
          speakingAIDialogue.value.assignmentId
        )
        .then((res) => {
          speakingAIDialogue.value.videoAnalysis = res.data.data;
          isVideoEmotionLoading.value = false
          createEmotionPieChart(speakingAIDialogue.value.videoAnalysis);
        });
    } else{
      isVideoEmotionLoading.value = false
      createEmotionPieChart(
        speakingAIDialogue.value.videoAnalysis.emotion_percentage_dict
      );
    }
    const engagementRes = await engagementApis.getEngagement(
      props.userId,
      props.assignmentId
    );

    engagement.value = {
      score: engagementRes.data.data.score || 0,
      remark: engagementRes.data.data.remark || "",
    };
    
    // 获取批改进度统计
    await fetchCorrectionStats();
    
    // 渲染每个对话的图表
    nextTick(() => {
      renderAvgScoreChart();
      speakingAIDialogue.value.dialogues.slice(0).forEach((dialogue, index) => {
        if (dialogue.totalScore !== null) {
          renderChart(index, dialogue);
        }
      });
    });
  } catch (error) {
    console.error("获取数据失败:", error);
  }
});
</script>


<style scoped>
.container{
  margin:auto;
  margin-top:30px;
  width:80vw;
}
.header-container {
  display: flex; /* 使用 Flex 布局 */
  align-items: center; /* 垂直居中 */
  margin-bottom: 20px; /* 根据需要调整间距 */
}

.back-button {
  margin-right: 30%; /* 按钮与标题之间的间距 */
  font-size: 50px; /* 图标大小 */
  color: #409eff; /* 按钮颜色，与 Element UI 主题色一致 */
}

.chart-container {
  width: 130px; /* 调整宽度 */
  height: 100px; /* 调整高度 */
}

.page-title{
  text-align: center;
  font-size:40px;
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  margin-bottom: 20px;
  font-size: 23px;
  text-align: center;
}

.card-time {
  font-size: 12px;
  color: gray;
  text-align: center;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  margin-left:50px;
}

.info-label {
  font-weight: bold;
  margin-right: -10px;
  min-width: 100px;
  text-align: left;
  font-size: 18px;
}

.suggestion-list {
  margin-left: 20px;
}

.suggestion-section {
  margin-bottom: 20px;
}

.section-title {
  margin-bottom: 10px;
  font-weight: 600;
  text-align: left;
}

.suggestion-items {
  list-style: disc;
  padding-left: 10px;
  font-size: 15px;
  font-weight: 400;
  text-align: left;
}

.suggestion-items li {
  margin-bottom: 5px;
}

.audio-segments {
  display: grid;
  gap: 15px;
}

.video-segments {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.video-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  margin-top:20px;
}

.video-player {
  width: 250px;
  height: 180px;
  margin-left: 30px;
}

.duration-label {
  color: #666;
  font-size: 0.9em;
}

.el-table {
  margin-top: 20px;
}

.el-table th,
.el-table td {
  text-align: left;
}

.el-table__body td {
  padding: 10px;
}

.time-info {
  display: flex;
  gap: 30px;
}

.time-info .info-item {
  margin-bottom: 20;
}

.audio-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 5px;
}

.duration-label {
  color: #666;
  font-size: 0.8em;
}

.assistant-row {
  background-color: #f0f9eb; /* 浅绿色背景 */
}

.user-row {
  background-color: #f0f7ff; /* 浅蓝色背景 */
}

.teacher-comment {
  padding: 20px;
  text-align: center;
}

.comment-item {
  margin-bottom: 10px;
  text-align: left;
}

.comment-label {
  font-weight: bold;
  margin-right: 10px;
}

.comment-input {
  margin-bottom: 20px;
}

.score-input {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.score-label {
  font-weight: bold;
  margin-left: 40%;
}

.submit-button {
  width: 30%;
  margin-top: 50px;
}

.survey-link {
  text-align: center;
  padding: 20px;
}

.survey-button {
  display: inline-block;
  margin-top: 10px;
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  text-decoration: none;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.survey-button:hover {
  background-color: #66b1ff;
}

.highlight-title {
  font-weight: bold;
  font-size: 14px; /* 可以根据需要调整字体大小 */
}

.word-count-box {
  background-color: #f0f0f0; /* 浅灰色背景 */
  border-radius: 10px; /* 圆角 */
  padding: 20px; /* 内边距 */
  text-align: center; /* 文字居中 */
  font-family: Arial, sans-serif; /* 字体 */
  width: 150px; /* 盒子宽度 */
  margin-top:20px;
  margin-left:50px;
}

.label {
  font-size: 16px; /* 标签文字大小 */
  color: #333; /* 标签文字颜色 */
  margin-bottom: 10px; /* 与数据的间距 */
}

.value {
  font-size: 24px; /* 数据文字大小 */
  color: #000; /* 数据文字颜色 */
  font-weight: bold; /* 加粗 */
}

.el-card {
  margin-bottom: 30px !important;
}

.correction-actions {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.button-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.left-buttons {
  display: flex;
  gap: 20px;
  margin-bottom: 10px;
}

.left-buttons .el-button.is-disabled {
  background-color: #a8a8a8 !important;
  border-color: #a8a8a8 !important;
  color: #ffffff !important;
  cursor: not-allowed;
}

.progress-numbers {
  font-size: 16px;
  color: #666;
  font-weight: 700;
  margin-top: 10px;
}
/* 新增：评语模板 css样式*/
.template-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 10px;
  .template-item {
    padding: 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    &:hover {
      background-color: #f5f7fa;
      border-color: #597D3B;
    }
    .template-content {
      width: 100%;
      text-align: left;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 14px;
      line-height: 1.5;
      display: block;
    }
  }
}
</style>