//公式相关

const BASE_WIND_COUNT = 10;
const SPOT_CHECK_COUNT = 5;

// 展开或者关闭公式
function toggleFormula(element) {
    const content = element.nextElementSibling;
    content.style.display = content.style.display === "none" ? "block" : "none";
    element.textContent = element.textContent.includes("▶") 
        ? element.textContent.replace("▶", "▼") 
        : element.textContent.replace("▼", "▶");
}

// 加载时运行
document.addEventListener('DOMContentLoaded', function() { 
    renderMathInElement(document.body, { 
        delimiters: [ 
            {left: "$$", right: "$$", display: true}, 
            {left: "$", right: "$", display: false} 
        ], 
        throwOnError: false 
    });

    // 确保数据已加载
    if (window.weatherData) {
        const versionElement = document.querySelector('.version');
        const dbVersion = window.weatherData.version || 'default';

        // 更新页面显示
        if (versionElement) {
            versionElement.textContent = `版本号: ${dbVersion}`;
        }

        downloadpdf(window.weatherData);
    } else {
        console.error("错误：window.weatherData 未定义");
    }
});

// 下载按钮
function downloadpdf(data) {
    
    const areaTypeMap = {
        urban: "城市",
        rural: "农村",
    };

        let htmlString = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>总体适宜度测量报表</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            line-height: 1.6;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .report-container {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 25px;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .divider {
            border-top: 1px solid #ddd;
            margin: 20px 0;
        }
        .data-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 15px;
        }
        .data-row {
            display: flex;
            align-items: center;
        }
        .data-row-long {
            display: flex;
            flex-direction: column;
        }
        .data-label {
            font-weight: bold;
            color: #2980b9;
            margin-bottom: 4px;
            width: 200px; /* 设置你想要的固定宽度 */
            white-space: nowrap; /* 防止换行 */
            overflow: hidden; /* 隐藏溢出内容 */
            text-overflow: ellipsis; /* 添加省略号 */
        }
        .data-value {
            font-weight: normal;
        }
        .section-title {
            font-size: 16px;
            font-weight: bold;
            margin: 15px 0 5px;
            color: #34495e;
        }
        .ten-values {
            background-color: #f9f9f9;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            margin-top: 5px;
        }
        .footer {
            position: absolute;
            bottom: 0%;
            left: 50%;
            transform: translateX(-50%); /* 水平居中 */
            font-size: 12px;
            color: #7f8c8d;
            text-align: center; /* 文本居中 */
        }
    </style>
</head>
<body>
    <div class="report-container">
        <h1>总体适宜度测量报表</h1>
        
      <div class="data-grid">
    <div class="data-row-long">
        <div class="data-label">文件编号：</div>
        <div class="data-value">${data.id}</div>
    </div>
    
    <div class="data-row-long">
        <div class="data-label">检测类型：</div>
        <div class="data-value">${data.inspectiontype}</div>
    </div>
    
    <div class="data-row-long">
        <div class="data-label">委托单号：</div>
        <div class="data-value">${data.assignmentnumber}</div>
    </div>
    
    <div class="data-row-long">
        <div class="data-label">项目名称：</div>
        <div class="data-value">${data.title}</div>
    </div>
    
    <div class="data-row-long">
        <div class="data-label">经纬度：</div>
        <div class="data-value">E ${data.longitude}, N ${data.latitude}</div>
    </div>
    
    <div class="data-row-long">
        <div class="data-label">测试时间：</div>
        <div class="data-value">${formatDateToYYYYMMDD(data.date)} ${data.hours}:${data.min}</div>
    </div>
</div>

<div class="divider"></div>

<div class="data-grid">
    <div class="data-row">
        <div class="data-label">日期序数：</div>
        <div class="data-value">${data.daySinceJanFirst}</div>
    </div>
    <div class="data-row">
        <div class="data-label">太阳倾角：</div>
        <div class="data-value">${data.solarDeclination}°</div>
    </div>
    <div class="data-row">
        <div class="data-label">太阳高度角：</div>
        <div class="data-value">${data.sunAltitude}°</div>
    </div>
    <div class="data-row">
        <div class="data-label">总云量：</div>
        <div class="data-value">${data.overallCloudiness}</div>
    </div>
    <div class="data-row">
        <div class="data-label">低云量：</div>
        <div class="data-value">${data.lowCloudiness}</div>
    </div>
    <div class="data-row">
        <div class="data-label">辐射等级：</div>
        <div class="data-value">${data.solarRadiationLevel}</div>
    </div>
    <div class="data-row">
        <div class="data-label">平均风速：</div>
        <div class="data-value">${data.averageWindSpeed}m/s</div>
    </div>
    <div class="data-row">
        <div class="data-label">风速适宜度：</div>
        <div class="data-value">${data.windSpeedSuitability}</div>
    </div>
    <div class="data-row">
        <div class="data-label">平均风向：</div>
        <div class="data-value">${data.averageWindDirection}°</div>
    </div>
    <div class="data-row">
        <div class="data-label">风向标准差：</div>
        <div class="data-value">${data.windDirectionStandardDeviation}°</div>
    </div>
    <div class="data-row">
        <div class="data-label">风向适宜度：</div>
        <div class="data-value">${data.windDirectionSuitability}</div>
    </div>
    <div class="data-row">
        <div class="data-label">大气稳定度：</div>
        <div class="data-value">${data.atmosphericStability}</div>
    </div>
    <div class="data-row">
        <div class="data-label">稳定度适宜度：</div>
        <div class="data-value">${data.suitabilityDegree}</div>
    </div>
    <div class="data-row">
        <div class="data-label">总体适宜度：</div>
        <div class="data-value">${replaceSuitabilityText(data.overallSuitability, "overall")}</div>
    </div>
</div>

<div class="divider"></div>

<!-- 原有数据网格：始终显示风速/风向的前十项 -->
<div class="data-grid">
    <div class="data-row-long">
        <div class="data-label">十次风速值：</div>
        <div class="data-value">
            <div class="ten-values">${data.windSpeed.slice(0, BASE_WIND_COUNT).join('，')}</div>
        </div>
    </div>
    <div class="data-row-long">
        <div class="data-label">十次风向值：</div>
        <div class="data-value">
            <div class="ten-values">${data.windDirection.slice(0, BASE_WIND_COUNT).join('，')}</div>
        </div>
    </div>
</div>

<!-- 新增：仅当有抽测时显示，展示后5项抽测数据 -->
${data.hasSpotCheckWindSpeed ? `
<div class="data-grid" style="margin-top: 16px;">
    <div class="data-row-long">
        <div class="data-label">抽测风速值：</div>
        <div class="data-value">
            <div class="ten-values">${data.windSpeed.slice(BASE_WIND_COUNT, BASE_WIND_COUNT + SPOT_CHECK_COUNT).map(val => val ?? '').join('，')}</div>
        </div>
    </div>
    <div class="data-row-long">
        <div class="data-label">抽测风向值：</div>
        <div class="data-value">
            <div class="ten-values">${data.windDirection.slice(BASE_WIND_COUNT, BASE_WIND_COUNT + SPOT_CHECK_COUNT).map(val => val ?? '').join('，')}</div>
        </div>
    </div>
</div>
` : ''}

<div class="data-row-long">
    <div class="data-label">是否有抽测风速：${data.hasSpotCheckWindSpeed ? '是' : '否'}</div>
</div>

<div class="divider"></div>

<div class="data-grid">
`
    // 根据条件显示相应的数据
    if (data.hasMeasuredWindSpeed === true) {
        htmlString+=`
            <div class="data-row">
                <div class="data-label">实测风速：</div>
                <div class="data-value">${data.measuredWindSpeed} m/s</div>
            </div>
            <div class="data-row">
                <div class="data-label">转换风速：</div>
                <div class="data-value">${data.convertedWindSpeed} m/s</div>
            </div>
        `
    } else {
        htmlString+=`
            <div class="data-row">
                <div class="data-label">区域类型：</div>
                <div class="data-value">${areaTypeMap[data.areaType]}</div>
            </div>
            <div class="data-row">
                <div class="data-label">测点高度：</div>
                <div class="data-value">${data.pointHeight} m</div>
            </div>
            <div class="data-row">
                <div class="data-label">点位风速：</div>
                <div class="data-value">${data.pointWindSpeed} m/s</div>
            </div>
            <div class="data-row">
                <div class="data-label">推算风速：</div>
                <div class="data-value">${data.calculatedWindSpeed} m/s</div>
            </div>
        `
    }
        htmlString += `
            </div>
            <br>
            <div class="footer">----报表结束 version:${data.version}----</div>
        </body>
        </html>
        `
        const filename = `${data.id}-${data.version || 'unknown'}.pdf`
        var opt = {
            margin: 10,
            filename: filename,
            image: {
                type: 'jpeg',
                quality: 0.99
            },
            html2canvas: {
                scale: 2
            },
            jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'portrait'
            }
        };

        // 执行下载，使用htmlString作为内容源
        html2pdf().set(opt).from(htmlString).save();
};

// 工具函数

// 函数用于将日期格式化为 xxxx-xx-xx 形式
function formatDateToYYYYMMDD(date) {
    const parsed = new Date(date);
    const year = parsed.getFullYear();
    const month = (parsed.getMonth() + 1).toString().padStart(2, '0');
    const day = parsed.getDate().toString().padStart(2, '0');
    return year + '-' + month + '-' + day;
}

//稳定度描述映射
function replaceSuitabilityText(data, type) {
  // 定义映射关系
  const suitabilityMap = {
      'a': '不利于污染物的扩散和稀释，适宜于进行无组织排放监测',
      'b': '较不利于污染物的扩散和稀释，较适宜于进行无组织排放监测',
      'c': '有利于污染物的扩散和稀释，较不适宜于进行无组织排放监测',
      'd': '很有利于污染物的扩散和稀释，不适宜于进行无组织排放监测',
      'wind0': '静风',
      'overall0': '取消监测或改期'
  };
  // 将输入转换为小写（或大写）以实现大小写不敏感
  const normalizedData = String(data).toLowerCase();
  
  // 处理特殊类型
  if (type === 'wind' && normalizedData === '0') 
    return suitabilityMap['wind0'];
  
  if (type === 'overall' && normalizedData === '0') 
    return suitabilityMap['overall0'];

  // 处理普通类型
  if (type === 'normal' || type === "wind" || type === "overall") {
    // 检查映射表中是否存在转换后的小写字段
    if (suitabilityMap[normalizedData]) {
      return suitabilityMap[normalizedData];
    }
    // 如果找不到，返回原值
    return data;
  }

  // 默认返回原值
  return data;
}

// 显示通知
function showNotification(message, type = 'success') {
    const notification = document.getElementById('notification');
    notification.textContent = message;
    notification.style.backgroundColor = type === 'success' ? '#4CAF50' : '#f44336';
    notification.style.display = 'block';
    
    setTimeout(() => {
        notification.style.display = 'none';
    }, 3000);
}
