<template>
  <div class="focus-student-container">
    <el-row :gutter="20">
      <!-- 左侧分类统计 -->
      <el-col :span="6">
        <vab-card title="关注类型统计" class="h-full">
          <div class="type-list">
            <div 
              v-for="type in typeStats" 
              :key="type.key" 
              class="type-item"
              :class="{ active: currentType === type.key }"
              @click="handleTypeClick(type.key)"
            >
              <div class="icon-box" :class="type.color">
                <vab-icon :icon="type.icon" />
              </div>
              <div class="info">
                <div class="label">{{ type.label }}</div>
                <div class="desc">{{ type.desc }}</div>
              </div>
              <div class="count">{{ type.count }}</div>
            </div>
          </div>
        </vab-card>
      </el-col>

      <!-- 右侧学生列表 -->
      <el-col :span="18">
        <vab-card>
          <template #header>
            <div class="card-header">
              <span>重点关注名单</span>
              <div class="header-actions">
                <el-button icon="settings-line" size="small" @click="handleManageTypes"> <vab-icon icon="settings-line" /> 管理类型</el-button>
                <el-button type="primary" size="small" @click="handleAdd"> <vab-icon icon="add-line" /> 添加关注</el-button>
              </div>
            </div>
          </template>

          <el-table v-loading="loading" :data="tableData" border stripe>
            <el-table-column prop="studentName" label="姓名" width="100" />
            <el-table-column prop="studentId" label="学号" width="120" />
            <el-table-column prop="college" label="学院" width="120" />
            <el-table-column prop="tags" label="关注标签" min-width="200">
              <template #default="{ row }">
                <el-tag 
                  v-for="tag in row.tags" 
                  :key="tag" 
                  class="mr-5" 
                  :type="getTagType(tag)"
                  effect="light"
                >
                  {{ getTagLabel(tag) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="level" label="关注等级" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getLevelType(row.level)" effect="dark">{{ getLevelLabel(row.level) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastRecord" label="最近关怀" width="160" />
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" text size="small" @click="handleRecord(row)">写纪实</el-button>
                <el-button type="info" text size="small" @click="handleDetail(row)">档案</el-button>
                <el-popconfirm title="确定解除对该学生的重点关注吗？" @confirm="handleRemove(row)">
                  <template #reference>
                    <el-button type="danger" text size="small">解除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </vab-card>
      </el-col>
    </el-row>

    <!-- 关怀纪实弹窗 -->
    <record-dialog ref="recordDialogRef" @success="handleQuery" />

    <!-- 添加关注弹窗 -->
    <add-focus-dialog ref="addFocusDialogRef" :type-options="availableTypes" @success="handleQuery" />

    <!-- 类型管理弹窗 -->
    <TypeManageDialog ref="typeManageDialogRef" :types="dynamicTypeStats" @change="handleTypeUpdate" />

    <!-- 档案详情抽屉 -->
    <FocusDetailDrawer ref="detailDrawerRef" :type-options="availableTypes" />
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import RecordDialog from './components/RecordDialog.vue'
import AddFocusDialog from './components/AddFocusDialog.vue'
import TypeManageDialog from './components/TypeManageDialog.vue'
import FocusDetailDrawer from './components/FocusDetailDrawer.vue'

defineOptions({
  name: 'FocusStudent',
})

// --- Data ---
const currentType = ref('all')
const loading = ref(false)
const tableData = ref([])
const recordDialogRef = ref()
const addFocusDialogRef = ref()
const typeManageDialogRef = ref()
const detailDrawerRef = ref()

// Initial Types Data
const defaultTypes = [
  { key: 'academic', label: '学业预警', count: 5, icon: 'book-mark-line', color: 'text-warning', desc: '挂科/缺课较多', value: 'academic' },
  { key: 'psychology', label: '心理关注', count: 3, icon: 'heart-pulse-line', color: 'text-danger', desc: '需定期心理疏导', value: 'psychology' },
  { key: 'poverty', label: '经济困难', count: 4, icon: 'money-cny-box-line', color: 'text-success', desc: '助学金/勤工助学', value: 'poverty' },
  { key: 'discipline', label: '违纪常客', count: 0, icon: 'error-warning-line', color: 'text-info', desc: '多次违反校规', value: 'discipline' },
  { key: 'health', label: '特殊疾病', count: 0, icon: 'hospital-line', color: 'text-danger', desc: '需关注身体状况', value: 'health' }
]

const dynamicTypeStats = ref(defaultTypes)

// Computed for Display (Includes 'all')
const typeStats = computed(() => {
  const allCount = dynamicTypeStats.value.reduce((acc, cur) => acc + (cur.count || 0), 0)
  return [
    { key: 'all', label: '全部关注', count: allCount, icon: 'group-line', color: 'text-primary', desc: '所有在库名单' },
    ...dynamicTypeStats.value
  ]
})

// Computed for AddFocusDialog options
const availableTypes = computed(() => {
  return dynamicTypeStats.value.map(t => ({ label: t.label, value: t.value || t.key }))
})

// --- Helpers ---
const getTagLabel = (tag) => {
  const found = dynamicTypeStats.value.find(t => t.value === tag || t.key === tag)
  return found ? found.label : tag
}
const getTagType = (tag) => {
  const found = dynamicTypeStats.value.find(t => t.value === tag || t.key === tag)
  // Map color class to Element tag type
  if (found) {
    if (found.color.includes('danger')) return 'danger'
    if (found.color.includes('warning')) return 'warning'
    if (found.color.includes('success')) return 'success'
    if (found.color.includes('primary')) return ''
  }
  return 'info'
}
const getLevelLabel = (level) => {
  const map = { 1: '一般', 2: '重要', 3: '紧急' }
  return map[level]
}
const getLevelType = (level) => {
  const map = { 1: 'info', 2: 'warning', 3: 'danger' }
  return map[level]
}

// --- Methods ---
const generateMockData = () => {
  return [
    {
      studentName: '梁健',
      studentId: '31901001',
      college: 'ZJUI',
      tags: ['academic', 'discipline'],
      level: 2,
      lastRecord: '2026-01-20 (谈话)'
    },
    {
      studentName: '鲁永波',
      studentId: '31901002',
      college: 'ZJE',
      tags: ['psychology'],
      level: 3,
      lastRecord: '2026-01-22 (家访)'
    },
    {
      studentName: '王应哲',
      studentId: '31901003',
      college: 'ZIBS',
      tags: ['poverty'],
      level: 1,
      lastRecord: '2025-12-15 (发放补助)'
    },
    {
      studentName: '曹青青',
      studentId: '31901006',
      college: 'ZIBS',
      tags: ['health'],
      level: 2,
      lastRecord: '2026-01-10 (体检复查)'
    }
  ]
}

const handleTypeClick = (key) => {
  currentType.value = key
  handleQuery()
}

const handleQuery = () => {
  loading.value = true
  setTimeout(() => {
    tableData.value = generateMockData()
    if (currentType.value !== 'all') {
      tableData.value = tableData.value.filter(item => item.tags.includes(currentType.value))
    }
    loading.value = false
  }, 500)
}

const handleRecord = (row) => {
  recordDialogRef.value.open(row)
}

const handleAdd = () => {
  addFocusDialogRef.value.open()
}

const handleManageTypes = () => {
  typeManageDialogRef.value.open()
}

const handleTypeUpdate = (newTypes) => {
  // Merge new types with existing counts if needed, but here we just replace
  // In real app, we would reload from backend
  dynamicTypeStats.value = newTypes
}

const handleRemove = (row) => {
  ElMessage.success('已解除关注')
  handleQuery()
}

const handleDetail = (row) => {
  detailDrawerRef.value.open(row)
}

handleQuery()
</script>

<style lang="scss" scoped>
.focus-student-container {
  .h-full { height: 100%; }
  .mr-5 { margin-right: 5px; }
  .card-header { display: flex; justify-content: space-between; align-items: center; width: 100%; }
  .text-primary { color: var(--el-color-primary); }
  .text-warning { color: var(--el-color-warning); }
  .text-danger { color: var(--el-color-danger); }
  .text-success { color: var(--el-color-success); }

  .type-list {
    .type-item {
      display: flex;
      align-items: center;
      padding: 15px;
      margin-bottom: 10px;
      border: 1px solid #eee;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover, &.active {
        border-color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
      }

      .icon-box {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        background: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        margin-right: 12px;
        
        &.text-primary { color: var(--el-color-primary); }
        &.text-warning { color: var(--el-color-warning); }
        &.text-danger { color: var(--el-color-danger); }
        &.text-success { color: var(--el-color-success); }
      }

      .info {
        flex: 1;
        .label { font-weight: bold; font-size: 14px; }
        .desc { font-size: 12px; color: #999; margin-top: 2px; }
      }

      .count {
        font-size: 18px;
        font-weight: bold;
      }
    }
  }
}
</style>
