const express = require('express');
const router = express.Router();
const PDFGenerator = require('../utils/pdfGenerator');
const path = require('path');
const fs = require('fs-extra');
const axios = require('axios');

const pdfGenerator = new PDFGenerator();
// 从配置文件读取基础URL
const BASE_URL = process.env.API_BASE_URL || 'http://192.168.1.100:8080'; // 请替换为实际的医疗系统地址

// 从医疗系统获取报告数据
async function getReportData(medicalSn) {
    try {
        console.log(`正在请求医疗系统API: ${BASE_URL}/inspect/patient/getReportAll`);
        console.log('请求参数:', { medicalSn });
        const response = await axios.get(`${BASE_URL}/inspect/patient/getReportAll`, {
            params: {
                medicalSn: medicalSn
            }
        });
        return response.data;
    } catch (error) {
        console.error('获取报告数据失败:', {
            message: error.message,
            code: error.code,
            response: error.response?.data,
            status: error.response?.status
        });
        throw error;
    }
}

// 生成PDF的路由
router.post('/generate', async (req, res) => {
    try {
        console.log('收到生成PDF请求:', req.body);
        const { medicalSn } = req.body;
        if (!medicalSn) {
            throw new Error('体检编号不能为空');
        }
        const reportData = await getReportData(medicalSn);
        
        // 检查是否为无效数据
        const isInvalidData = reportData.code === 0 && 
            reportData.data && 
            Object.values(reportData.data).every(value => value === null);
            
        if (!reportData || isInvalidData) {
            throw new Error('体检编号不存在或未查询到相关报告数据');
        }
      
        console.log('开始生成PDF...');
        const result = await pdfGenerator.generatePDF(reportData);
        console.log('PDF生成成功:', result);
        
        res.json({
            success: true,
            data: {
                fileName: result.fileName,
                path: `/pdfs/${result.fileName}`
            }
        });
    } catch (error) {
        console.error('生成PDF失败，详细错误:', error);
        res.status(500).json({
            success: false,
            message: error.message || '生成PDF失败'
        });
    }
});

// 下载PDF的路由
router.get('/download/:fileName', async (req, res) => {
    try {
        const { fileName } = req.params;
        const filePath = path.join(__dirname, '../public/pdfs', fileName);
        
        const exists = await fs.pathExists(filePath);
        if (!exists) {
            return res.status(404).json({
                success: false,
                message: 'PDF文件不存在'
            });
        }
        
        res.download(filePath);
    } catch (error) {
        console.error('下载PDF失败:', error);
        res.status(500).json({
            success: false,
            message: '下载PDF失败'
        });
    }
});

module.exports = router;