<template>
  <div class="patient-reports-container">
    <div class="page-header">
      <h2>患者评估报告</h2>
      <div class="header-desc">查看您负责的患者的心理健康评估报告</div>
    </div>

    <div class="search-container">
      <el-input
        v-model="data.search"
        placeholder="搜索患者姓名"
        prefix-icon="Search"
        clearable
        @input="filterReports"
      ></el-input>
      <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>
    </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>

      <el-table
        v-else
        :data="data.filteredReports"
        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="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="warning" size="small" @click="addComment(scope.row)">
              {{ scope.row.doctorComment ? '修改批注' : '添加批注' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加批注的对话框 -->
    <el-dialog v-model="data.commentDialogVisible" title="添加医生批注" width="50%">
      <el-form :model="data.commentForm">
        <el-form-item label="患者姓名">
          <span>{{ data.selectedReport?.patientName }}</span>
        </el-form-item>
        <el-form-item label="报告类型">
          <span>{{ data.selectedReport?.reportPeriod }}
            ({{ formatDate(data.selectedReport?.startDate) }} 至 {{ formatDate(data.selectedReport?.endDate) }})
          </span>
        </el-form-item>
        <el-form-item label="医生批注">
          <el-input
            v-model="data.commentForm.comment"
            type="textarea"
            :rows="6"
            placeholder="请输入对此评估报告的批注和建议..."
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.commentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveComment">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

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

const data = reactive({
  reports: [],
  filteredReports: [],
  loading: true,
  search: '',
  periodFilter: '',
  commentDialogVisible: false,
  selectedReport: null,
  commentForm: {
    comment: ''
  }
});

// 格式化日期
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;
    return matchesSearch && matchesPeriod;
  });
};

// 添加批注
const addComment = (report) => {
  data.selectedReport = report;
  data.commentForm.comment = report.doctorComment || '';
  data.commentDialogVisible = true;
};

// 保存批注
const saveComment = async () => {
  if (!data.selectedReport) return;
  
  if (!data.commentForm.comment || data.commentForm.comment.trim() === '') {
    ElMessage.error('评论内容不能为空');
    return;
  }
  
  try {
    const res = await request.put(`/assessmentReport/comment/${data.selectedReport.id}?comment=${encodeURIComponent(data.commentForm.comment)}`);
    if (res.code === '200') {
      ElMessage.success('批注保存成功');
      // 更新本地数据
      const index = data.reports.findIndex(r => r.id === data.selectedReport.id);
      if (index !== -1) {
        data.reports[index].doctorComment = data.commentForm.comment;
        filterReports(); // 重新过滤列表
      }
      data.commentDialogVisible = false;
    } else {
      ElMessage.error(res.msg || '保存批注失败');
    }
  } catch (error) {
    console.error('保存批注失败:', error);
    ElMessage.error('保存批注失败');
  }
};

// 获取患者评估报告列表
const getPatientReports = async () => {
  data.loading = true;
  try {
    const res = await request.get('/assessmentReport/doctor');
    if (res.code === '200') {
      data.reports = res.data || [];
      filterReports(); // 初始化过滤后的列表
    } else {
      ElMessage.error(res.msg || '获取评估报告失败');
    }
  } catch (error) {
    console.error('获取评估报告失败:', error);
    ElMessage.error('获取评估报告失败');
  } finally {
    data.loading = false;
  }
};

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

<style scoped>
.patient-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;
}

.search-container {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

.loading-container {
  padding: 20px;
}

.no-comment {
  color: #909399;
  font-size: 13px;
}
</style> 