<template>
  <div class="assessment-reports-container">
    <div class="page-header">
      <h2>评估报告管理</h2>
      <div class="header-desc">管理系统中的所有心理健康评估报告</div>
    </div>

    <div class="filter-container">
      <el-input
        v-model="data.search"
        placeholder="搜索患者姓名"
        prefix-icon="Search"
        clearable
        @input="filterReports"
        style="max-width: 300px;"
      ></el-input>
      <div class="filter-right">
        <el-select v-model="data.periodFilter" placeholder="报告类型" @change="filterReports" style="width: 120px;" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="周报" value="周报"></el-option>
          <el-option label="月报" value="月报"></el-option>
        </el-select>
        <el-date-picker
          v-model="data.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="filterReports"
        ></el-date-picker>
        <el-button type="primary" @click="refreshData">刷新</el-button>
        <el-button @click="exportReports" :loading="data.exporting">导出报告</el-button>
      </div>
    </div>

    <div v-if="data.loading" class="loading-container">
      <el-skeleton style="width: 100%" animated :rows="5" />
    </div>

    <div v-else>
      <el-empty v-if="data.filteredReports.length === 0" description="暂无匹配的评估报告"></el-empty>

      <div v-else>
        <el-table
          :data="data.displayReports"
          style="width: 100%"
          border
          stripe
          :default-sort="{ prop: 'createTime', order: 'descending' }"
        >
          <el-table-column label="患者姓名" prop="patientName" min-width="120"></el-table-column>
          <el-table-column label="报告类型" prop="reportPeriod" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.reportPeriod === '周报' ? 'success' : 'primary'" size="small">
                {{ scope.row.reportPeriod }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="报告时段" min-width="200">
            <template #default="scope">
              {{ formatDate(scope.row.startDate) }} 至 {{ formatDate(scope.row.endDate) }}
            </template>
          </el-table-column>
          <el-table-column label="生成时间" prop="createTime" min-width="170" sortable>
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.status === '已读'" type="success" size="small">已读</el-tag>
              <el-tag v-else type="info" size="small">未读</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="医生批注" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.doctorComment" type="warning" size="small">
                已添加批注
              </el-tag>
              <span v-else class="no-comment">未添加</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" plain @click="viewReport(scope.row.id)">
                查看详情
              </el-button>
              <el-button type="danger" size="small" @click="confirmDelete(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="data.currentPage"
            v-model:page-size="data.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.filteredReports.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </div>
    </div>

    <!-- 统计信息卡片 -->
    <el-card class="statistics-card" v-if="!data.loading && data.reports.length > 0">
      <template #header>
        <div class="card-header">
          <span>评估报告统计</span>
        </div>
      </template>
      <div class="statistics-content">
        <div class="stat-item">
          <div class="stat-value">{{ data.reports.length }}</div>
          <div class="stat-label">总报告数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ data.reports.filter(r => r.reportPeriod === '周报').length }}</div>
          <div class="stat-label">周报数量</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ data.reports.filter(r => r.reportPeriod === '月报').length }}</div>
          <div class="stat-label">月报数量</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ data.reports.filter(r => r.status === '已读').length }}</div>
          <div class="stat-label">已读报告</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ data.reports.filter(r => r.doctorComment).length }}</div>
          <div class="stat-label">有医生批注</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { reactive, onMounted, computed } from 'vue';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue';

const router = useRouter();

const data = reactive({
  reports: [],
  filteredReports: [],
  displayReports: [], // 分页后显示的数据
  loading: true,
  exporting: false,
  search: '',
  periodFilter: '',
  dateRange: null,
  currentPage: 1,
  pageSize: 10
});

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return `${formatDate(dateTimeStr)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 查看报告详情
const viewReport = (reportId) => {
  router.push(`/manager/reportDetail/${reportId}`);
};

// 过滤报告
const filterReports = () => {
  data.filteredReports = data.reports.filter(report => {
    // 按名称搜索
    const matchesSearch = !data.search || report.patientName.toLowerCase().includes(data.search.toLowerCase());
    
    // 按报告类型过滤
    const matchesPeriod = !data.periodFilter || report.reportPeriod === data.periodFilter;
    
    // 按日期范围过滤
    let matchesDateRange = true;
    if (data.dateRange && data.dateRange[0] && data.dateRange[1]) {
      const reportDate = new Date(report.createTime);
      const startDate = new Date(data.dateRange[0]);
      const endDate = new Date(data.dateRange[1]);
      endDate.setHours(23, 59, 59); // 设置为当天结束时间
      
      matchesDateRange = reportDate >= startDate && reportDate <= endDate;
    }
    
    return matchesSearch && matchesPeriod && matchesDateRange;
  });
  
  // 重置分页
  data.currentPage = 1;
  updateDisplayReports();
};

// 更新显示的报告列表（分页）
const updateDisplayReports = () => {
  const startIndex = (data.currentPage - 1) * data.pageSize;
  const endIndex = startIndex + data.pageSize;
  data.displayReports = data.filteredReports.slice(startIndex, endIndex);
};

// 处理页面大小变化
const handleSizeChange = (size) => {
  data.pageSize = size;
  updateDisplayReports();
};

// 处理当前页变化
const handleCurrentChange = (page) => {
  data.currentPage = page;
  updateDisplayReports();
};

// 确认删除报告
const confirmDelete = (report) => {
  ElMessageBox.confirm(
    `确定要删除 ${report.patientName} 的${report.reportPeriod}吗？此操作不可逆。`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteReport(report.id);
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 删除报告
const deleteReport = async (reportId) => {
  try {
    const res = await request.delete(`/assessmentReport/${reportId}`);
    if (res.code === '200') {
      ElMessage.success('报告删除成功');
      // 更新列表
      data.reports = data.reports.filter(r => r.id !== reportId);
      filterReports();
    } else {
      ElMessage.error(res.msg || '删除报告失败');
    }
  } catch (error) {
    console.error('删除报告失败:', error);
    ElMessage.error('删除报告失败');
  }
};

// 导出报告
const exportReports = () => {
  data.exporting = true;
  try {
    // 构建CSV内容
    let csvContent = 'ID,患者姓名,报告类型,开始日期,结束日期,状态,是否有批注,生成时间\n';
    
    data.filteredReports.forEach(report => {
      const row = [
        report.id,
        report.patientName,
        report.reportPeriod,
        formatDate(report.startDate),
        formatDate(report.endDate),
        report.status,
        report.doctorComment ? '是' : '否',
        formatDateTime(report.createTime)
      ];
      
      // 处理CSV中的特殊字符
      csvContent += row.map(field => {
        if (typeof field === 'string' && (field.includes(',') || field.includes('"') || field.includes('\n'))) {
          return `"${field.replace(/"/g, '""')}"`;
        }
        return field;
      }).join(',') + '\n';
    });
    
    // 创建Blob并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.setAttribute('href', url);
    link.setAttribute('download', `评估报告_${new Date().toISOString().split('T')[0]}.csv`);
    link.style.visibility = 'hidden';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    ElMessage.success('报告导出成功');
  } catch (error) {
    console.error('导出报告失败:', error);
    ElMessage.error('导出报告失败');
  } finally {
    data.exporting = false;
  }
};

// 刷新数据
const refreshData = () => {
  getAllReports();
};

// 获取所有评估报告列表
const getAllReports = async () => {
  data.loading = true;
  try {
    const res = await request.get('/assessmentReport/admin');
    if (res.code === '200') {
      data.reports = res.data || [];
      filterReports();
      updateDisplayReports(); // 初始化显示数据
    } else {
      ElMessage.error(res.msg || '获取评估报告失败');
    }
  } catch (error) {
    console.error('获取评估报告失败:', error);
    ElMessage.error('获取评估报告失败');
  } finally {
    data.loading = false;
  }
};

// 页面加载时获取报告列表
onMounted(() => {
  getAllReports();
});
</script>

<style scoped>
.assessment-reports-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #303133;
}

.header-desc {
  color: #909399;
  font-size: 14px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-right {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.loading-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.no-comment {
  color: #909399;
  font-size: 13px;
}

.statistics-card {
  margin-top: 30px;
}

.card-header {
  font-weight: bold;
}

.statistics-content {
  display: flex;
  flex-wrap: wrap;
  gap: 40px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  margin-top: 5px;
  color: #606266;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
  }
  
  .filter-right {
    margin-top: 10px;
  }
  
  .statistics-content {
    gap: 20px;
    justify-content: space-between;
  }
  
  .stat-item {
    flex-basis: calc(50% - 10px);
  }
}
</style>