<template>
  <div class="generate-report-container">
    <div class="page-header">
      <h2>生成评估报告</h2>
      <div class="header-desc">为患者生成周报或月报评估报告，或设置自动生成规则</div>
    </div>

    <el-card class="form-card">
      <div class="form-header">手动生成报告</div>
      <el-form :model="form" label-width="120px" class="report-form">
        <el-form-item label="报告类型">
          <el-radio-group v-model="form.reportPeriod">
            <el-radio :value="'week'">周报</el-radio>
            <el-radio :value="'month'">月报</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="选择患者">
          <el-select v-model="form.patientId" placeholder="请选择患者" style="width: 100%">
            <el-option
              v-for="patient in data.patients"
              :key="patient.id"
              :label="patient.name"
              :value="patient.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="generateReport" :loading="data.loading">生成报告</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="info-card">
      <div class="info-header">报告生成说明</div>
      <div class="info-content">
        <p><b>周报：</b> 分析患者过去一周的症状记录，生成综合评估报告。</p>
        <p><b>月报：</b> 分析患者过去一个月的症状记录，生成更全面的趋势分析。</p>
        <p><b>自动生成：</b> 系统已设置以下自动规则：</p>
        <ul>
          <li>每周一凌晨2点：自动为所有有症状记录的患者生成周报</li>
          <li>每月1日凌晨3点：自动为所有有症状记录的患者生成月报</li>
        </ul>
      </div>
    </el-card>

    <!-- 消息提示 -->
    <el-dialog v-model="data.reportGenerated" title="报告生成成功" width="500px">
      <div class="success-message">
        <el-icon class="success-icon"><CircleCheckFilled /></el-icon>
        <div class="message-content">
          <div class="message-title">评估报告已成功生成</div>
          <div class="message-desc">您可以在相应的报告管理页面查看此报告</div>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button @click="data.reportGenerated = false">关闭</el-button>
        <el-button type="primary" @click="viewReport">查看报告</el-button>
      </div>
    </el-dialog>
  </div>
</template>

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

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

const data = reactive({
  patients: [],
  loading: false,
  reportGenerated: false,
  generatedReportId: null
});

const form = reactive({
  reportPeriod: 'week',
  patientId: null
});

// 获取患者列表
const loadPatients = async () => {
  try {
    const res = await request.get(currentUser.role === 'admin' ? '/account/listPatients' : '/doctor/myPatients');
    if (res.code === '200') {
      data.patients = res.data || [];
      // 对于医生用户，需要从医生-患者关系中提取患者信息
      if (currentUser.role === 'doctor' && data.patients.length > 0) {
        data.patients = data.patients.map(dp => ({
          id: dp.patient.id,
          name: dp.patient.name
        }));
      }
    }
  } catch (error) {
    console.error('加载患者列表失败:', error);
    ElMessage.error('加载患者列表失败');
  }
};

// 生成报告
const generateReport = async () => {
  if (!form.patientId) {
    ElMessage.warning('请选择患者');
    return;
  }

  data.loading = true;
  try {
    const res = await request.post('/assessmentReport/generate', {
      patientId: form.patientId,
      reportPeriod: form.reportPeriod
    });
    if (res.code === '200') {
      data.reportGenerated = true;
      data.generatedReportId = res.data.id;
      ElMessage.success('报告生成成功');
    } else {
      ElMessage.error(res.msg || '报告生成失败');
    }
  } catch (error) {
    console.error('生成报告失败:', error);
    ElMessage.error('生成报告失败: ' + (error.response?.data?.msg || '未知错误'));
  } finally {
    data.loading = false;
  }
};

// 重置表单
const resetForm = () => {
  form.reportPeriod = 'week';
  form.patientId = null;
};

// 查看报告
const viewReport = () => {
  if (data.generatedReportId) {
    router.push(`/manager/reportDetail/${data.generatedReportId}`);
  }
};

// 页面加载时获取患者列表
onMounted(() => {
  loadPatients();
});
</script>

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

.form-card, .info-card {
  margin-bottom: 20px;
}

.form-header, .info-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #EBEEF5;
}

.report-form {
  max-width: 600px;
}

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

.info-content p {
  margin: 8px 0;
}

.info-content ul {
  padding-left: 20px;
  margin: 8px 0;
}

.success-message {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.success-icon {
  font-size: 40px;
  color: #67C23A;
  margin-right: 15px;
}

.message-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 6px;
}

.message-desc {
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 