<template>
  <div class="report-detail-container">
    <div class="page-header">
      <div class="header-left">
        <h2>评估报告详情</h2>
        <el-tag v-if="data.report" size="small" :type="getReportTypeColor(data.report.reportPeriod)">
          {{ data.report.reportPeriod }}
        </el-tag>
      </div>
      <div class="header-actions">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <el-button type="primary" @click="printReport" icon="Printer">打印报告</el-button>
      </div>
    </div>

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

    <div v-else-if="!data.report" class="error-container">
      <el-empty description="未找到报告或无权限查看"></el-empty>
    </div>

    <div v-else class="report-content" ref="reportContent">
      <el-card class="report-card">
        <!-- 报告头部 -->
        <div class="report-header">
          <div class="report-title">
            {{ data.report.patientName }}的{{ data.report.reportPeriod === '周报' ? '每周' : '每月' }}心理评估报告
          </div>
          <div class="report-meta">
            <div class="report-period">
              报告时段: {{ formatDate(data.report.startDate) }} 至 {{ formatDate(data.report.endDate) }}
            </div>
            <div class="report-time">
              生成时间: {{ formatDateTime(data.report.createTime) }}
            </div>
          </div>
        </div>

        <!-- 报告主体 -->
        <div class="report-body">
          <div class="report-section">
            <div class="section-title">
              <el-icon><DataAnalysis /></el-icon>
              总体评估
            </div>
            <div class="section-content" v-html="formatContentWithLineBreaks(data.report.summary)"></div>
          </div>

          <div class="report-section">
            <div class="section-title">
              <el-icon><TrendCharts /></el-icon>
              趋势分析
            </div>
            <div class="section-content" v-html="formatContentWithLineBreaks(data.report.trendAnalysis)"></div>
          </div>

          <div class="report-section">
            <div class="section-title">
              <el-icon><TrendCharts /></el-icon>
              改善建议
            </div>
            <div class="section-content" v-html="formatContentWithLineBreaks(data.report.recommendation)"></div>
          </div>

          <!-- 医生批注，仅当有批注且不为空时显示 -->
          <div v-if="data.report.doctorComment" class="report-section doctor-comment">
            <div class="section-title">
              <el-icon><ChatDotRound /></el-icon>
              医生批注
            </div>
            <div class="section-content" v-html="formatContentWithLineBreaks(data.report.doctorComment)"></div>
          </div>
        </div>
      </el-card>

      <!-- 医生添加批注区域，仅对医生显示 -->
      <el-card v-if="isDoctor && data.report" class="comment-card">
        <div class="comment-header">
          添加/修改批注
        </div>
        <el-form :model="data.commentForm">
          <el-form-item>
            <el-input
              v-model="data.commentForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入对此评估报告的批注和建议..."
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveComment" :loading="data.submitting">保存批注</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import { ArrowLeft, Printer, DataAnalysis, TrendCharts, ChatDotRound } from '@element-plus/icons-vue';

const route = useRoute();
const router = useRouter();
const reportContent = ref(null);
const currentUser = JSON.parse(localStorage.getItem('xm-user') || '{}');

// 计算当前用户是否是医生
const isDoctor = computed(() => currentUser.role === 'doctor');

const data = reactive({
  report: null,
  loading: true,
  submitting: false,
  commentForm: {
    comment: ''
  }
});

// 根据报告类型设置标签颜色
const getReportTypeColor = (type) => {
  return type === '周报' ? 'success' : 'primary';
};

// 格式化日期
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')}`;
};

// 将文本中的换行符转换为HTML标签
const formatContentWithLineBreaks = (text) => {
  if (!text) return '';
  return text.replace(/\n/g, '<br>');
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 获取报告详情
const getReportDetail = async () => {
  const reportId = route.params.id;
  if (!reportId) {
    ElMessage.error('报告ID不能为空');
    data.loading = false;
    return;
  }

  try {
    // 确保API路径正确
    const res = await request.get(`/assessmentReport/${reportId}`);
    if (res.code === '200') {
      data.report = res.data;
      
      // 如果返回数据为空，可能是API路径问题
      if (!data.report) {
        console.error('无法获取报告数据，响应对象:', res);
        ElMessage.error('无法获取报告数据');
        return;
      }
      
      // 如果是医生，初始化批注表单
      if (isDoctor.value && data.report) {
        data.commentForm.comment = data.report.doctorComment || '';
      }
      
      // 如果是患者且报告状态为未读，标记为已读
      if (currentUser.role === 'patient' && data.report.status === '未读') {
        markReportAsRead(reportId);
      }
    } else {
      ElMessage.error(res.msg || '获取报告详情失败');
    }
  } catch (error) {
    console.error('获取报告详情失败:', error);
    ElMessage.error('获取报告详情失败');
  } finally {
    data.loading = false;
  }
};

// 标记报告为已读
const markReportAsRead = async (reportId) => {
  try {
    await request.put(`/assessmentReport/read/${reportId}`);
  } catch (error) {
    console.error('标记报告为已读失败:', error);
  }
};

// 保存医生批注
const saveComment = async () => {
  const reportId = route.params.id;
  if (!reportId) return;
  
  if (!data.commentForm.comment || data.commentForm.comment.trim() === '') {
    ElMessage.error('评论内容不能为空');
    return;
  }
  
  data.submitting = true;
  try {
    const res = await request.put(`/assessmentReport/comment/${reportId}?comment=${encodeURIComponent(data.commentForm.comment)}`);
    if (res.code === '200') {
      ElMessage.success('批注保存成功');
      // 更新报告显示
      data.report.doctorComment = data.commentForm.comment;
    } else {
      ElMessage.error(res.msg || '保存批注失败');
    }
  } catch (error) {
    console.error('保存批注失败:', error);
    ElMessage.error('保存批注失败');
  } finally {
    data.submitting = false;
  }
};

// 打印报告
const printReport = () => {
  if (!data.report) return;
  
  const printContent = reportContent.value.innerHTML;
  const printWindow = window.open('', '_blank');
  
  printWindow.document.write(`
    <html>
      <head>
        <title>评估报告 - ${data.report.patientName}</title>
        <style>
          body { font-family: Arial, sans-serif; padding: 20px; }
          .report-header { margin-bottom: 20px; }
          .report-title { font-size: 22px; font-weight: bold; margin-bottom: 10px; }
          .report-meta { display: flex; justify-content: space-between; color: #666; }
          .section-title { font-size: 18px; font-weight: bold; margin: 20px 0 10px; border-bottom: 1px solid #eee; padding-bottom: 5px; }
          .section-content { line-height: 1.6; }
          .doctor-comment { background-color: #f8f8f8; padding: 10px; margin-top: 20px; }
        </style>
      </head>
      <body>
        <div class="report-content">
          ${printContent}
        </div>
      </body>
    </html>
  `);
  
  printWindow.document.close();
  printWindow.focus();
  printWindow.print();
  printWindow.close();
};

// 页面加载时获取报告详情
onMounted(() => {
  getReportDetail();
});
</script>

<style scoped>
.report-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-left h2 {
  margin: 0;
  margin-right: 10px;
}

.loading-container {
  padding: 20px;
}

.error-container {
  margin: 40px 0;
  text-align: center;
}

.report-card, .comment-card {
  margin-bottom: 20px;
}

.report-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #EBEEF5;
  padding-bottom: 15px;
}

.report-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
}

.report-meta {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
}

.report-section {
  margin-bottom: 25px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.section-title .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.section-content {
  line-height: 1.6;
  color: #606266;
}

.doctor-comment {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
}

.doctor-comment .section-title .el-icon {
  color: #E6A23C;
}

.comment-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
}
</style> 