<template>
  <el-row style="height: 100vh; padding: 20px;" :gutter="20">

    <!-- 左侧：学习单词区域 -->
    <el-col :span="12" class="left-panel" style="height: 100%;">

      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2>短期记忆区域</h2>
        <div>
          <el-button type="primary" @click="openSelectedDialog">查看已选单词</el-button>
          <el-button type="success" @click="openDialog" style="margin-left: 10px;">选择单词</el-button>
        </div>
      </div>

      <!-- 待复习单词数量 -->
      <div class="pending-count" v-if="reviewList.length">
        待复习单词数量: {{ pendingCount }}
      </div>

      <!-- 单词卡片 -->
      <div class="card-container" v-if="reviewList.length">

        <div class="card-wrapper">
          <div class="card" :class="{ flipped: isFlipped }">

            <div class="card-face card-front">
              <!-- 正面不显示通过次数，如果需要，类似写这里 -->
              <h1>{{ currentWord.word }}</h1>
              <el-button @click.stop="speakWord(currentWord.word)">🔊 发音</el-button>
            </div>

            <div class="card-face card-back" style="position: relative;">
              <!-- 通过次数左上角绝对定位 -->
              <div class="score-badge">
                通过次数: {{ currentWord.score ?? 0 }}
              </div>
              <h1 style="margin-top: 40px;">{{ currentWord.word }}</h1>
              <p><strong>释义：</strong>{{ currentWord.definition }}</p>
              <el-button @click.stop="speakWord(currentWord.word)">🔊 发音</el-button>
            </div>

          </div>

          <div class="btn-group">
            <el-button type="danger" v-if="!isFlipped" @click="flipCard">忘记</el-button>
            <el-button type="success" v-if="!isFlipped" @click="flipCard">认识</el-button>
            <el-button type="danger" v-if="isFlipped" @click="submitReviewResult(false)">忘记</el-button>
            <el-button type="success" v-if="isFlipped" @click="submitReviewResult(true)">认识</el-button>
          </div>
        </div>
      </div>

      <!-- 无可复习单词提示 -->
      <div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;">
        无可复习单词，复习完成！
      </div>

      <!-- 已选单词弹窗 -->
      <el-dialog v-model="selectedDialogVisible" title="已选单词列表" width="800px">
        <el-table
            :data="selectedWords"
            style="width: 100%;"
            border
            @selection-change="handleSelectedChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="word" label="单词" />
          <el-table-column prop="definition" label="释义" />
          <el-table-column label="操作" width="100">
            <template #default="scope">
              <el-button type="danger" size="small" @click="removeWord(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="selectedDialogVisible = false">关闭</el-button>
            <el-button type="danger" :disabled="!selectedToDelete.length" @click="batchRemoveWords">
              批量删除（{{ selectedToDelete.length }}）
            </el-button>
          </span>
        </template>
      </el-dialog>

    </el-col>

    <!-- 右侧区域：长期记忆区域 -->
    <el-col :span="12" class="right-panel" style="border: 1px solid #eee; padding: 20px;">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2>长期记忆区域</h2>
        <div>
          <el-button size="small" type="primary" @click="refreshLongTermReview" style="margin-left: 10px;">
            刷新
          </el-button>
        </div>
      </div>


      <div v-if="longTermReviewList.length">

        <div class="card-container">

          <div class="card-wrapper">
            <div class="card" :class="{ flipped: longTermIsFlipped }">

              <div class="card-face card-front">
                <h1>{{ currentLongTermWord.word }}</h1>
                <el-button @click.stop="speakWord(currentLongTermWord.word)">🔊 发音</el-button>
              </div>

              <div class="card-face card-back" style="position: relative;">
                <div class="score-badge">
                  复习次数: {{ currentLongTermWord.reviewCount ?? 0 }} <br/>
                  间隔天数: {{ currentLongTermWord.intervalDays ?? 0 }}
                </div>
                <h1 style="margin-top: 40px;">{{ currentLongTermWord.word }}</h1>
                <p><strong>释义：</strong>{{ currentLongTermWord.definition }}</p>
                <el-button @click.stop="speakWord(currentLongTermWord.word)">🔊 发音</el-button>
              </div>

            </div>

            <div class="btn-group">
              <el-button type="danger" v-if="!longTermIsFlipped" @click="flipLongTermCard">忘记</el-button>
              <el-button type="success" v-if="!longTermIsFlipped" @click="flipLongTermCard">认识</el-button>
              <el-button type="danger" v-if="longTermIsFlipped" @click="submitLongTermReviewResult(false)">忘记</el-button>
              <el-button type="success" v-if="longTermIsFlipped" @click="submitLongTermReviewResult(true)">认识</el-button>
            </div>
          </div>
        </div>

      </div>

      <div v-else style="text-align:center; margin-top: 50px; font-size: 20px; color: #999;">
        无可复习的长期记忆单词，复习完成！
      </div>
    </el-col>

    <!-- 选择待学习单词弹窗 -->
    <el-dialog v-model="dialogVisible" title="选择待学习单词" width="600px">
      <el-table :data="pendingWords" style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="word" label="单词" />
        <el-table-column prop="definition" label="释义" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSelectedWords">确认选择（{{ selectedToAdd.length }}）</el-button>
        </span>
      </template>
    </el-dialog>

  </el-row>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = 'http://localhost:8080'

const selectedWords = ref([])
const pendingWords = ref([])
const selectedToAdd = ref([])
const selectedToDelete = ref([])
const dialogVisible = ref(false)
const selectedDialogVisible = ref(false)

const round = ref(1)
const reviewList = ref([])
const reviewIndex = ref(0)
const pendingCount = ref(0)

const isFlipped = ref(false)

const currentWord = computed(() => reviewList.value[reviewIndex.value] || {})

const utterance = new SpeechSynthesisUtterance()
utterance.lang = 'en-US'

// 长期记忆相关状态
const longTermReviewList = ref([])
const longTermReviewIndex = ref(0)
const longTermIsFlipped = ref(false)
const currentPage = ref(0)

const currentLongTermWord = computed(() => longTermReviewList.value[longTermReviewIndex.value] || {})

async function refreshLongTermReview() {
  currentPage.value = 0           // 刷新时重置页码
  longTermReviewIndex.value = 0   // 复位当前卡片索引
  await fetchLongTermReviewList() // 重新获取数据
}

async function fetchPendingCount() {
  const userId = localStorage.getItem('userId')
  if (!userId) return ElMessage.warning('请先登录或设置 userId')
  try {
    const res = await axios.get('/study/pending-count', { params: { userId: Number(userId) } })
    pendingCount.value = res.data
  } catch {
    ElMessage.error('获取待复习单词数量失败')
  }
}

async function fetchSelectedWords() {
  const userId = localStorage.getItem('userId')
  if (!userId) return ElMessage.warning('请先登录或设置 userId')
  try {
    const res = await axios.get('/study/select-words', { params: { userId } })
    selectedWords.value = res.data
  } catch {
    ElMessage.error('获取已选单词失败')
  }
}

async function fetchReviewList() {
  const userId = localStorage.getItem('userId')
  if (!userId) return ElMessage.warning('请先登录或设置 userId')
  try {
    const res = await axios.get('/study/review-list', {
      params: { userId: Number(userId), round: round.value }
    })
    reviewList.value = res.data
    reviewIndex.value = 0
    isFlipped.value = false

    if (reviewList.value.length > 0) {
      speakWord(currentWord.value.word)
    }
  } catch (e) {
    ElMessage.error('加载复习单词失败')
    console.error(e)
  }
}

function flipCard() {
  if (!currentWord.value.word) return
  speakWord(currentWord.value.word)
  isFlipped.value = true
}

async function submitReviewResult(remembered) {
  const userId = localStorage.getItem('userId')
  if (!userId) {
    ElMessage.warning('请先登录或设置 userId')
    return
  }

  try {
    await axios.post('/study/review-result', {
      userId: Number(userId),
      wordId: currentWord.value.wordId || currentWord.value.id,
      round: round.value,
      remembered: remembered
    })

    reviewIndex.value++
    isFlipped.value = false

    await fetchPendingCount() // 刷新待复习数量

    if (reviewIndex.value >= reviewList.value.length) {
      round.value++
      await fetchReviewList()
    } else {
      speakWord(currentWord.value.word)
    }
  } catch (e) {
    ElMessage.error('提交复习结果失败')
    console.error(e)
  }
}

function speakWord(text) {
  if (!text) return
  if (speechSynthesis.speaking) speechSynthesis.cancel()
  utterance.text = text
  speechSynthesis.speak(utterance)
}

async function openSelectedDialog() {
  await fetchSelectedWords()
  selectedToDelete.value = []
  selectedDialogVisible.value = true
}

async function openDialog() {
  const userId = localStorage.getItem('userId')
  if (!userId) return ElMessage.warning('请先登录或设置 userId')
  try {
    const res = await axios.get('/study/pending-words', {
      params: { userId, limit: 100 }
    })
    pendingWords.value = res.data
    dialogVisible.value = true
  } catch {
    ElMessage.error('获取待学习单词失败')
  }
}

function handleSelectionChange(val) {
  selectedToAdd.value = val
}

function handleSelectedChange(val) {
  selectedToDelete.value = val
}

async function submitSelectedWords() {
  const userId = localStorage.getItem('userId')
  const wordIds = selectedToAdd.value.map(item => item.wordId || item.id)
  if (wordIds.length < 10) {
    ElMessage.warning('请至少选择10个单词')
    return
  }
  try {
    await axios.post('/study/select-words', { userId: Number(userId), wordIds })
    dialogVisible.value = false
    await fetchSelectedWords()
    await fetchPendingCount() // 选择后刷新数量
    await fetchReviewList()
    ElMessage.success('添加成功')
  } catch {
    ElMessage.error('添加单词失败')
  }
}

async function removeWord(row) {
  const userId = localStorage.getItem('userId')
  try {
    await axios.post('/study/remove-word', {
      userId: Number(userId),
      wordId: row.wordId || row.id
    })
    await fetchSelectedWords()
    await fetchPendingCount() // 删除后刷新数量
    await fetchReviewList()
    ElMessage.success('删除成功')
  } catch {
    ElMessage.error('删除失败')
  }
}

async function batchRemoveWords() {
  const userId = localStorage.getItem('userId')
  const wordIds = selectedToDelete.value.map(item => item.wordId || item.id)
  if (!wordIds.length) {
    ElMessage.warning('请选择要删除的单词')
    return
  }
  try {
    await axios.post('/study/remove-words', { userId: Number(userId), wordIds })
    await fetchSelectedWords()
    selectedToDelete.value = []
    await fetchPendingCount() // 批量删除后刷新数量
    await fetchReviewList()
    ElMessage.success('批量删除成功')
  } catch {
    ElMessage.error('批量删除失败')
  }
}

// 长期记忆相关方法

async function fetchLongTermReviewList() {
  const userId = localStorage.getItem('userId')
  if (!userId) return ElMessage.warning('请先登录或设置 userId')
  try {
    const res = await axios.get('/study/long-term-review-list', {
      params: {
        userId: Number(userId),
        page: currentPage.value,
        size: 3,
        longmemorySeen: 0
      }
    })
    if (res.data.length === 0 && currentPage.value > 0) {
      currentPage.value = 0
      return await fetchLongTermReviewList()
    }

    longTermReviewList.value = res.data
    longTermReviewIndex.value = 0
    longTermIsFlipped.value = false

    if (longTermReviewList.value.length > 0) {
      speakWord(currentLongTermWord.value.word)
    } else {
      ElMessage.success('长期记忆阶段复习完成！')
    }
  } catch (error) {
    ElMessage.error('加载长期记忆复习列表失败')
    console.error(error)
  }
}

function flipLongTermCard() {
  if (!currentLongTermWord.value.word) return
  speakWord(currentLongTermWord.value.word)
  longTermIsFlipped.value = true
}

async function submitLongTermReviewResult(remembered) {
  if (!currentLongTermWord.value.id) return
  const userId = localStorage.getItem('userId')
  if (!userId) {
    ElMessage.warning('请先登录或设置 userId')
    return
  }

  try {
    await axios.post('/study/long-term-review-result', {
      userId: Number(userId),
      id: currentLongTermWord.value.id,
      remembered
    })

    longTermReviewIndex.value++
    longTermIsFlipped.value = false

    if (longTermReviewIndex.value >= longTermReviewList.value.length) {
      currentPage.value++
      await fetchLongTermReviewList()
    } else {
      speakWord(currentLongTermWord.value.word)
    }
  } catch (error) {
    ElMessage.error('提交长期记忆复习结果失败')
    console.error(error)
  }
}
onMounted(async () => {
  speechSynthesis.speak(new SpeechSynthesisUtterance(' '))
  await fetchPendingCount()
  await fetchReviewList()
  await fetchLongTermReviewList()
})
</script>

<style scoped>
.left-panel {
  display: flex;
  flex-direction: column;
  border: 1px solid #eee;
  height: 100%;
}

.pending-count {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  padding: 10px 0 0 0;
  margin-bottom: 10px;
  user-select: none;
}

.card-container {
  flex-grow: 1;
  margin-top: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  perspective: 1000px;
  width: 100%;
}

.card {
  width: 100%;
  max-width: 550px;
  height: 500px;
  position: relative;
  transition: transform 0.6s;
  transform-style: preserve-3d;
  border-radius: 16px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
  background-color: #fff;
}

.score-badge {
  position: absolute;
  top: 15px;
  left: 15px;
  background-color: #409EFF;
  color: white;
  font-weight: bold;
  padding: 6px 12px;
  border-radius: 12px;
  font-size: 14px;
  pointer-events: none;
  user-select: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

.card.flipped {
  transform: rotateY(180deg);
}

.card-face {
  position: absolute;
  width: 100%;
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  backface-visibility: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.card-front {
  font-size: 1em;
  font-weight: bold;
}

.card-back {
  transform: rotateY(180deg);
  font-size: 1.2em;
  text-align: center;
  line-height: 1.6;
}

.card-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.btn-group {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 30px;
  margin-top: 30px;
}

.btn-group .el-button {
  padding: 18px 40px;
  font-size: 18px;
  border-radius: 10px;
  font-weight: bold;
  min-width: 140px;
  transition: all 0.2s ease-in-out;
}

.btn-group .el-button:hover {
  transform: scale(1.05);
}
</style>
长期记忆区域和短期记忆区域不并齐