import { ERRORENUM } from "../config/enum/errorEnum";
import { BizError } from "../util/bizError";
import * as archiver from 'archiver';
import * as fs from 'fs-extra';
import * as path from 'path';
import * as ExcelJS from 'exceljs';
import { selectData } from "../data/operationalData";
import { OPERATIONALDATATYPE, TABLENAME } from "../config/enum/dbEnum";
import { getAllDwOutPut } from './zaiFu';

const moment = require("moment");
const fetch = require('node-fetch');


/**
 * 下载企业相关文件、数据表格和详情Excel的zip包
 */
export async function downloadEnterpriseFilesZip(eId: string) {
    if (!eId) throw new BizError(ERRORENUM.参数错误, `下载企业文件缺失eId`);

    try {
        const projectRoot = path.resolve(__dirname, '../..');
        const tempBaseDir = path.join(projectRoot, 'temp');
        await fs.ensureDir(tempBaseDir);
        
        const tempDir = path.join(tempBaseDir, `temp_enterprise_files_${eId}_${Date.now()}`);
        console.log(`创建临时目录: ${tempDir}`);
        await fs.ensureDir(tempDir);

        // 获取企业名称
        console.log('=== 开始获取企业信息 ===');
        const enterpriseInfo = await getEnterpriseInfo(eId);
        const enterpriseName = enterpriseInfo?.enterpriseName || '未知企业';
        console.log(`企业名称: ${enterpriseName}`);

        // 步骤1: 获取企业详情数据并生成Excel
        console.log('=== 开始生成企业详情Excel ===');
        const excelFilePath = await generateEnterpriseDetailExcel(eId, enterpriseName, tempDir);
        
        // 步骤2: 下载企业相关文件
        console.log('=== 开始下载企业文件 ===');
        await downloadEnterpriseFiles(eId, tempDir);

        // 步骤3: 创建zip文件
        const safeEnterpriseName = sanitizeFileName(enterpriseName);
        const zipFileName = `企业完整数据_${safeEnterpriseName}_${eId}_${moment().format('YYYYMMDDHHmmss')}.zip`;
        const zipFilePath = path.join(tempBaseDir, zipFileName);

        console.log(`创建ZIP文件: ${zipFilePath}`);
        await createZipArchive(tempDir, zipFilePath);

        const zipStats = await fs.stat(zipFilePath);
        console.log(`ZIP文件创建成功，大小: ${zipStats.size} bytes`);

        // 清理临时目录
        console.log('清理临时目录...');
        await fs.remove(tempDir);

        return {
            success: true,
            filePath: zipFilePath,
            fileName: zipFileName
        };
    } catch (error) {
        console.error('下载企业文件zip包失败:', error);
        throw new BizError(ERRORENUM.系统错误, '文件打包失败: ' + error.message);
    }
}


/**
 * 生成企业详情Excel文件
 */
async function generateEnterpriseDetailExcel(eId: string, enterpriseName: string, tempDir: string): Promise<string> {
    try {
        console.log('获取企业详情数据...');
        const details = await getAllDwOutPut(eId);
        
        console.log('企业详情数据结构:', JSON.stringify(details, null, 2));
        
        const safeEnterpriseName = sanitizeFileName(enterpriseName);
        const excelFileName = `企业详情_${safeEnterpriseName}_${eId}.xlsx`;
        const excelFilePath = path.join(tempDir, excelFileName);

        const workbook = new ExcelJS.Workbook();
        
        // 设置文档属性
        workbook.creator = '企业管理系统';
        workbook.lastModifiedBy = '企业管理系统';
        workbook.created = new Date();
        workbook.modified = new Date();

        // 1. 基础信息工作表
        await createBasicInfoSheet(workbook, details.enterprise, '基础信息');
        
        // 2. 经营数据工作表
        await createBusinessDataSheet(workbook, details.manage, '经营数据');
        
        // 3. 融资情况工作表
        await createFinancingSheet(workbook, details.financing, '融资情况');
        
        // 4. 荣誉奖项工作表
        await createHonorSheet(workbook, details.honor, '荣誉奖项');

        // 保存Excel文件
        await workbook.xlsx.writeFile(excelFilePath);
        console.log(`Excel文件生成成功: ${excelFilePath}`);

        return excelFilePath;
    } catch (error) {
        console.error('生成企业详情Excel失败:', error);
        throw new BizError(ERRORENUM.系统错误, '生成Excel文件失败: ' + error.message);
    }
}


/**
 * 创建基础信息工作表 - 表格格式
 */
async function createBasicInfoSheet(workbook: ExcelJS.Workbook, enterpriseData: any, sheetName: string) {
    const worksheet = workbook.addWorksheet(sheetName);
    
    if (!enterpriseData || !enterpriseData.dataList || !Array.isArray(enterpriseData.dataList)) {
        worksheet.getCell('A1').value = '暂无基础信息数据';
        return;
    }

    const dataList = enterpriseData.dataList;
    
    // 设置列宽
    worksheet.columns = [
        { width: 15 },
        { width: 20 },
        { width: 15 },
        { width: 25 },
        { width: 12 },
        { width: 25 },
        { width: 12 },
        { width: 8 },
        { width: 8 }
    ];

    // 添加标题
    worksheet.mergeCells('A1:I1');
    const titleCell = worksheet.getCell('A1');
    titleCell.value = '企业基础信息';
    titleCell.font = { bold: true, size: 14 };
    titleCell.alignment = { horizontal: 'center', vertical: 'middle' };
    titleCell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFDDEBF7' }
    };

    // 添加表头（第一行）
    if (dataList.length > 0 && Array.isArray(dataList[0])) {
        const headerRow = worksheet.addRow(dataList[0]);
        
        // 设置表头样式
        headerRow.font = { bold: true, color: { argb: 'FFFFFFFF' } };
        headerRow.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FF2F75B5' }
        };
        headerRow.alignment = { horizontal: 'center', vertical: 'middle' };
        headerRow.height = 25;
    }

    // 添加数据行（从第二行开始）
    let currentRow = 3; // 标题占1行，表头占1行，数据从第3行开始
    for (let i = 1; i < dataList.length; i++) {
        if (Array.isArray(dataList[i])) {
            const dataRow = worksheet.addRow(dataList[i]);
            
            // 设置数据行样式
            dataRow.alignment = { horizontal: 'left', vertical: 'middle' };
            
            // 交替行颜色
            if (i % 2 === 0) {
                dataRow.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: { argb: 'FFF2F2F2' }
                };
            }
            
            currentRow++;
        }
    }

    // 设置边框
    const dataRange = `A2:I${currentRow}`;
    for (let row = 2; row <= currentRow; row++) {
        for (let col = 1; col <= 9; col++) {
            const cell = worksheet.getCell(row, col);
            cell.border = {
                top: { style: 'thin' },
                left: { style: 'thin' },
                bottom: { style: 'thin' },
                right: { style: 'thin' }
            };
        }
    }

    console.log(`基础信息工作表创建完成，共 ${dataList.length - 1} 条数据`);
}


/**
 * 创建经营数据工作表
 */
async function createBusinessDataSheet(workbook: ExcelJS.Workbook, manageData: any, sheetName: string) {
    const worksheet = workbook.addWorksheet(sheetName);
    
    if (!manageData || !manageData.dataList || !Array.isArray(manageData.dataList)) {
        worksheet.getCell('A1').value = '暂无经营数据';
        return;
    }

    const dataList = manageData.dataList;
    
    // 设置列宽
    worksheet.columns = [
        { width: 15 },
        { width: 20 },
        { width: 15 },
        { width: 15 },
        { width: 15 },
        { width: 15 }
    ];

    // 添加标题
    worksheet.mergeCells('A1:F1');
    const titleCell = worksheet.getCell('A1');
    titleCell.value = '企业经营数据';
    titleCell.font = { bold: true, size: 14 };
    titleCell.alignment = { horizontal: 'center', vertical: 'middle' };
    titleCell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE2EFDA' }
    };

    // 添加表头（第一行）
    if (dataList.length > 0 && Array.isArray(dataList[0])) {
        const headerRow = worksheet.addRow(dataList[0]);
        
        // 设置表头样式
        headerRow.font = { bold: true, color: { argb: 'FFFFFFFF' } };
        headerRow.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FF70AD47' }
        };
        headerRow.alignment = { horizontal: 'center', vertical: 'middle' };
        headerRow.height = 25;
    }

    // 添加数据行
    let currentRow = 3;
    let hasData = false;
    
    for (let i = 1; i < dataList.length; i++) {
        if (Array.isArray(dataList[i]) && dataList[i].some((cell: any) => cell && cell !== '-')) {
            const dataRow = worksheet.addRow(dataList[i]);
            
            // 设置数据行样式
            dataRow.alignment = { horizontal: 'left', vertical: 'middle' };
            
            // 交替行颜色
            if (i % 2 === 0) {
                dataRow.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: { argb: 'FFF2F2F2' }
                };
            }
            
            currentRow++;
            hasData = true;
        }
    }

    if (!hasData) {
        worksheet.getCell('A3').value = '暂无经营数据';
        worksheet.getCell('A3').alignment = { horizontal: 'center', vertical: 'middle' };
    } else {
        // 设置边框
        const dataRange = `A2:F${currentRow}`;
        for (let row = 2; row <= currentRow; row++) {
            for (let col = 1; col <= 6; col++) {
                const cell = worksheet.getCell(row, col);
                cell.border = {
                    top: { style: 'thin' },
                    left: { style: 'thin' },
                    bottom: { style: 'thin' },
                    right: { style: 'thin' }
                };
            }
        }
    }

    console.log(`经营数据工作表创建完成，共 ${dataList.length - 1} 条数据`);
}


/**
 * 创建融资情况工作表
 */
async function createFinancingSheet(workbook: ExcelJS.Workbook, financingData: any, sheetName: string) {
    const worksheet = workbook.addWorksheet(sheetName);
    
    if (!financingData || !financingData.dataList || !Array.isArray(financingData.dataList)) {
        worksheet.getCell('A1').value = '暂无融资数据';
        return;
    }

    const dataList = financingData.dataList;
    
    // 设置列宽
    worksheet.columns = [
        { width: 15 },
        { width: 20 },
        { width: 15 },
        { width: 15 },
        { width: 15 },
        { width: 20 }
    ];

    // 添加标题
    worksheet.mergeCells('A1:F1');
    const titleCell = worksheet.getCell('A1');
    titleCell.value = '企业融资情况';
    titleCell.font = { bold: true, size: 14 };
    titleCell.alignment = { horizontal: 'center', vertical: 'middle' };
    titleCell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFFFE699' }
    };

    // 添加表头（第一行）
    if (dataList.length > 0 && Array.isArray(dataList[0])) {
        const headerRow = worksheet.addRow(dataList[0]);
        
        // 设置表头样式
        headerRow.font = { bold: true, color: { argb: 'FFFFFFFF' } };
        headerRow.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFFC000' }
        };
        headerRow.alignment = { horizontal: 'center', vertical: 'middle' };
        headerRow.height = 25;
    }

    // 添加数据行
    let currentRow = 3;
    let hasData = false;
    
    for (let i = 1; i < dataList.length; i++) {
        if (Array.isArray(dataList[i]) && dataList[i].some((cell: any) => cell && cell !== '-')) {
            const dataRow = worksheet.addRow(dataList[i]);
            
            // 设置数据行样式
            dataRow.alignment = { horizontal: 'left', vertical: 'middle' };
            
            // 交替行颜色
            if (i % 2 === 0) {
                dataRow.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: { argb: 'FFF2F2F2' }
                };
            }
            
            currentRow++;
            hasData = true;
        }
    }

    if (!hasData) {
        worksheet.getCell('A3').value = '暂无融资数据';
        worksheet.getCell('A3').alignment = { horizontal: 'center', vertical: 'middle' };
    } else {
        // 设置边框
        for (let row = 2; row <= currentRow; row++) {
            for (let col = 1; col <= 6; col++) {
                const cell = worksheet.getCell(row, col);
                cell.border = {
                    top: { style: 'thin' },
                    left: { style: 'thin' },
                    bottom: { style: 'thin' },
                    right: { style: 'thin' }
                };
            }
        }
    }

    console.log(`融资情况工作表创建完成，共 ${dataList.length - 1} 条数据`);
}


/**
 * 创建荣誉奖项工作表
 */
async function createHonorSheet(workbook: ExcelJS.Workbook, honorData: any, sheetName: string) {
    const worksheet = workbook.addWorksheet(sheetName);
    
    if (!honorData || !honorData.dataList || !Array.isArray(honorData.dataList)) {
        worksheet.getCell('A1').value = '暂无荣誉数据';
        return;
    }

    const dataList = honorData.dataList;
    
    // 设置列宽
    worksheet.columns = [
        { width: 15 },
        { width: 25 },
        { width: 20 },
        { width: 15 },
        { width: 15 }
    ];

    // 添加标题
    worksheet.mergeCells('A1:E1');
    const titleCell = worksheet.getCell('A1');
    titleCell.value = '企业荣誉奖项';
    titleCell.font = { bold: true, size: 14 };
    titleCell.alignment = { horizontal: 'center', vertical: 'middle' };
    titleCell.fill = {
        type: 'pattern',
        pattern: 'solid',
        fgColor: { argb: 'FFE6E0EC' }
    };

    // 添加表头（第一行）
    if (dataList.length > 0 && Array.isArray(dataList[0])) {
        const headerRow = worksheet.addRow(dataList[0]);
        
        // 设置表头样式
        headerRow.font = { bold: true, color: { argb: 'FFFFFFFF' } };
        headerRow.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FF8064A2' }
        };
        headerRow.alignment = { horizontal: 'center', vertical: 'middle' };
        headerRow.height = 25;
    }

    // 添加数据行
    let currentRow = 3;
    let hasData = false;
    
    for (let i = 1; i < dataList.length; i++) {
        if (Array.isArray(dataList[i]) && dataList[i].some((cell: any) => cell && cell !== '-')) {
            const dataRow = worksheet.addRow(dataList[i]);
            
            // 设置数据行样式
            dataRow.alignment = { horizontal: 'left', vertical: 'middle' };
            
            // 交替行颜色
            if (i % 2 === 0) {
                dataRow.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: { argb: 'FFF2F2F2' }
                };
            }
            
            currentRow++;
            hasData = true;
        }
    }

    if (!hasData) {
        worksheet.getCell('A3').value = '暂无荣誉数据';
        worksheet.getCell('A3').alignment = { horizontal: 'center', vertical: 'middle' };
    } else {
        // 设置边框
        for (let row = 2; row <= currentRow; row++) {
            for (let col = 1; col <= 5; col++) {
                const cell = worksheet.getCell(row, col);
                cell.border = {
                    top: { style: 'thin' },
                    left: { style: 'thin' },
                    bottom: { style: 'thin' },
                    right: { style: 'thin' }
                };
            }
        }
    }

    console.log(`荣誉奖项工作表创建完成，共 ${dataList.length - 1} 条数据`);
}


/**
 * 下载企业相关文件
 */
async function downloadEnterpriseFiles(eId: string, tempDir: string) {
    // 先获取所有文件信息并验证
    console.log('=== 开始验证文件信息 ===');
    
    const leaseFiles = await getLeaseFiles(eId);
    const leaseValidCount = await validateAndLogFiles(leaseFiles, '租赁信息');
    
    const trademarkFiles = await getTrademarkFiles(eId);
    const trademarkValidCount = await validateAndLogFiles(trademarkFiles, '商标');
    
    const copyrightFiles = await getCopyrightFiles(eId);
    const copyrightValidCount = await validateAndLogFiles(copyrightFiles, '作品著作权');
    
    const softwareCopyrightFiles = await getSoftwareCopyrightFiles(eId);
    const softwareValidCount = await validateAndLogFiles(softwareCopyrightFiles, '软件著作权');
    
    const patentFiles = await getPatentFiles(eId);
    const patentValidCount = await validateAndLogFiles(patentFiles, '专利');
    
    console.log('=== 文件验证完成，开始下载 ===');

    // 下载文件
    await downloadAndSaveFiles(leaseFiles, path.join(tempDir, '租赁信息'), tempDir);
    await downloadAndSaveFiles(trademarkFiles, path.join(tempDir, '商标'), tempDir);
    await downloadAndSaveFiles(copyrightFiles, path.join(tempDir, '作品著作权'), tempDir);
    await downloadAndSaveFiles(softwareCopyrightFiles, path.join(tempDir, '软件著作权'), tempDir);
    await downloadAndSaveFiles(patentFiles, path.join(tempDir, '专利'), tempDir);
}


/**
 * 获取企业信息
 */
async function getEnterpriseInfo(eId: string): Promise<any> {
    try {
        // 根据你的数据库结构调整查询
        const enterpriseInfo = await selectData(
            OPERATIONALDATATYPE.查询单个,
            'enterprise', // 或者你的企业表名
            { eId },
            ['enterpriseName'] // 可能的名称字段
        );
        
        if (!enterpriseInfo) {
            console.warn(`未找到企业信息: ${eId}`);
            return null;
        }
        
        console.log(`获取到企业信息:`, enterpriseInfo);
        return enterpriseInfo;
    } catch (error) {
        console.error(`获取企业信息失败: ${eId}`, error);
        return null;
    }
}


/**
 * 清理文件名中的非法字符
 */
 function sanitizeFileName(fileName: string): string {
    if (!fileName) return '未知企业';
    
    // 移除或替换文件名中的非法字符
    return fileName
        .replace(/[<>:"/\\|?*]/g, '_') // 替换Windows非法字符
        .replace(/\s+/g, ' ')          // 合并多个空格
        .trim()                         // 去除首尾空格
        .substring(0, 100);            // 限制长度避免过长
}


/**
 * 验证并记录文件信息
 */
async function validateAndLogFiles(files: {url: string, fileName: string}[], category: string) {
    console.log(`\n=== ${category}文件验证 ===`);
    console.log(`总数: ${files.length} 个文件`);
    
    let existingCount = 0;
    
    for (const file of files) {
        console.log(`文件: ${file.fileName}`);
        console.log(`URL: ${file.url}`);
        
        // 检查文件是否存在
        const exists = await checkFileExists(file.url);
        console.log(`存在性: ${exists ? '存在' : '不存在'}`);
        
        if (exists) {
            existingCount++;
        }
        console.log('---');
    }
    
    console.log(`${category}文件统计: 存在 ${existingCount}/${files.length} 个文件`);
    return existingCount;
}


/**
 * 改进的下载函数 - 跳过不存在的文件
 */
async function downloadAndSaveFiles(files: {url: string, fileName: string}[], targetDir: string, baseTempDir: string): Promise<void> {
    if (files.length === 0) {
        console.log(`没有文件需要下载到目录: ${targetDir}`);
        return;
    }

    await fs.ensureDir(targetDir);

    // 先检查所有文件的存在性
    const validFiles: {url: string, fileName: string}[] = [];
    
    for (const file of files) {
        const exists = await checkFileExists(file.url);
        if (exists) {
            validFiles.push(file);
            console.log(`✅ 文件可用: ${file.fileName}`);
        } else {
            console.warn(`❌ 文件不存在，跳过: ${file.fileName} (${file.url})`);
        }
    }

    console.log(`有效文件数量: ${validFiles.length}/${files.length}`);

    if (validFiles.length === 0) {
        console.log(`没有可下载的有效文件，跳过目录: ${targetDir}`);
        return;
    }

    // 只下载存在的文件
    const downloadPromises = validFiles.map(async (file) => {
        try {
            if (!file.url || typeof file.url !== 'string') {
                console.warn(`文件URL无效:`, file.url);
                return;
            }
            
            console.log(`开始下载文件: ${file.fileName} from ${file.url}`);
            
            const fetchOptions: any = {
                method: 'GET',
                timeout: 30000,
                headers: {
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    'Accept': '*/*'
                }
            };
            
            // 关键修复：添加认证 token
            const SECRET_TOKEN = "Ngz86cuAKxblwXR9OiKSWbfkj7oZ8R0lMU8pTfpVYBDCkvtUb0ZwbaBvwWyfv2O9";
            
            // 如果是内部文件服务器的URL，添加认证token
            if (file.url.includes('192.168.0.71') || file.url.includes('fh.tninnopark.cn')) {
                fetchOptions.headers['token'] = SECRET_TOKEN;
                console.log(`添加认证token到请求头`);
            }
            
            const response = await fetch(file.url, fetchOptions);
            
            if (!response.ok) {
                console.warn(`下载文件失败: ${file.url}, 状态码: ${response.status}`);
                return;
            }

            const buffer = await response.buffer();
            
            if (buffer.length === 0) {
                console.warn(`文件内容为空: ${file.fileName}`);
                return;
            }
            
            const filePath = path.join(targetDir, file.fileName);
            await fs.writeFile(filePath, buffer);
            console.log(`✅ 文件下载成功: ${file.fileName}, 大小: ${buffer.length} bytes`);
            
        } catch (error) {
            console.error(`下载文件失败: ${file.fileName} (${file.url})`, error.message);
        }
    });

    const results = await Promise.allSettled(downloadPromises);
    
    const successful = results.filter(result => result.status === 'fulfilled').length;
    const failed = results.filter(result => result.status === 'rejected').length;
    
    console.log(`目录 ${targetDir} 下载完成: 成功 ${successful} 个, 失败 ${failed} 个, 总共 ${validFiles.length} 个有效文件`);
}


/**
 * 检查文件是否存在于文件服务器
 */
async function checkFileExists(url: string): Promise<boolean> {
    try {
        const SECRET_TOKEN = "Ngz86cuAKxblwXR9OiKSWbfkj7oZ8R0lMU8pTfpVYBDCkvtUb0ZwbaBvwWyfv2O9";
        
        const fetchOptions: any = {
            method: 'HEAD',
            timeout: 10000,
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        };
        
        // 同样为HEAD请求添加认证token
        if (url.includes('192.168.0.71') || url.includes('fh.tninnopark.cn')) {
            fetchOptions.headers['token'] = SECRET_TOKEN;
        }
        
        const response = await fetch(url, fetchOptions);
        return response.ok;
    } catch (error) {
        console.log(`文件存在性检查失败: ${url}`, error.message);
        return false;
    }
}


/**
 * 安全的URL构建函数，避免中文编码问题
 */
 function buildSafeUrl(baseUrl: string, filePath: string): string {
    // 确保基础URL格式正确
    const cleanBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
    
    // 确保文件路径格式正确
    const cleanFilePath = filePath.startsWith('/') ? filePath : `/${filePath}`;
    
    // 直接拼接，避免URL对象的自动编码
    return `${cleanBaseUrl}${cleanFilePath}`;
}


/**
 * 统一处理文件路径，将相对路径转换为绝对URL
 * 修复中文文件名编码问题
 * http://192.168.0.71:9097
 * https://fh.tninnopark.cn
 */
function processFilePath(filePath: any, baseUrl: string = 'http://192.168.0.71:9097'): string | null {
    if (!filePath) {
        console.log('文件路径为空');
        return null;
    }

    console.log(`原始文件路径: ${filePath}, 类型: ${typeof filePath}`);
    
    // 如果是数组，取第一个元素
    if (Array.isArray(filePath)) {
        filePath = filePath[0];
    }
    
    // 处理JSON字符串格式
    if (typeof filePath === 'string' && filePath.startsWith('[')) {
        try {
            const pathArray = JSON.parse(filePath);
            filePath = pathArray[0];
            console.log(`解析JSON数组路径: ${filePath}`);
        } catch (e) {
            console.warn('解析文件路径数组失败:', filePath);
            return null;
        }
    }
    
    // 验证路径格式
    if (!filePath || typeof filePath !== 'string') {
        return null;
    }
    
    // 如果已经是完整的URL，直接返回
    if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
        return filePath;
    }
    
    // 格式化基础URL
    const formattedBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
    
    // 关键修复：确保路径格式正确且中文不被编码
    let finalPath = filePath;
    if (!finalPath.startsWith('/')) {
        finalPath = '/' + finalPath;
    }
    
    // 构建完整的URL（不对路径部分进行编码）
    const url = new URL(formattedBaseUrl);
    url.pathname = finalPath;

    const fullUrl = buildSafeUrl(baseUrl, finalPath);
    console.log(`安全构建的URL: ${fullUrl}`);
    return fullUrl;
}


/**
 * 获取租赁信息相关文件
 */
async function getLeaseFiles(eId: string): Promise<{url: string, fileName: string}[]> {
    const filesList = [
        "sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong",
        "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua",
        "yaJinZhiFu", "cardCopy"
    ];

    const leaseInfo = await selectData(
        OPERATIONALDATATYPE.查询多个, 
        TABLENAME.租赁信息, 
        { eId }, 
        filesList
    );

    const files: {url: string, fileName: string}[] = [];

    leaseInfo.forEach(lease => {
        filesList.forEach(field => {
            if (lease[field]) {
                const processedUrl = processFilePath(lease[field]);
                if (processedUrl) {
                    const fileName = getLeaseFileName(field, lease);
                    files.push({
                        url: processedUrl,
                        fileName: fileName
                    });
                }
            }
        });
    });

    return files;
}


/**
 * 获取租赁文件显示名称
 */
function getLeaseFileName(field: string, lease: any): string {
    const nameMap: {[key: string]: string} = {
        sanFangXieYi: '三方协议',
        fuHuaXieYi: '孵化协议',
        fangWuZuLing: '房屋租赁合同',
        fuHuaXieYiBuChong: '孵化协议补充协议书',
        chengXinChengNuoHan: '诚信承诺函',
        yingYeZhiZhao: '营业执照复印件',
        ruFuZiLiao: '入孵资料明细',
        ruZhuJiHua: '入驻计划复印件',
        yaJinZhiFu: '押金支付凭证',
        cardCopy: '身份证复印件'
    };

    const baseName = nameMap[field] || field;
    
    // 获取实际的文件扩展名
    let extension = '';
    if (lease[field] && typeof lease[field] === 'string') {
        const processedUrl = processFilePath(lease[field]);
        if (processedUrl) {
            const ext = path.extname(processedUrl);
            if (ext) {
                extension = ext;
            } else {
                // 如果没有扩展名，根据字段类型推测
                if (field === 'cardCopy' || field === 'yingYeZhiZhao') {
                    extension = '.jpg'; // 身份证和营业执照通常是图片
                } else {
                    extension = '.pdf'; // 其他文件默认PDF
                }
            }
        }
    }
    
    // 确保文件名安全
    const safeFileName = baseName.replace(/[<>:"/\\|?*]/g, '_');
    return `${safeFileName}${extension}`;
}


/**
 * 获取商标相关文件
 */
async function getTrademarkFiles(eId: string): Promise<{url: string, fileName: string}[]> {
    const trademarkInfo = await selectData(
        OPERATIONALDATATYPE.查询多个,
        'trade_mark',
        { eId },
        ["tmId", "regNo", "name", "imageUrl"]
    );

    const files: {url: string, fileName: string}[] = [];

    trademarkInfo.forEach(trademark => {
        if (trademark.imageUrl) {
            let processedUrl = processFilePath(trademark.imageUrl);
            
            // 特殊处理商标图片URL：移除多余的 /img 后缀
            // if (processedUrl && processedUrl.endsWith('/img')) {
            //     processedUrl = processedUrl.slice(0, -4); // 移除最后的 '/img'
            //     console.log(`修复商标图片URL: ${processedUrl}`);
            // }
            
            if (processedUrl) {
                const extension = path.extname(processedUrl) || '.jpg';
                // 清理文件名中的特殊字符
                const safeName = (trademark.name || '').replace(/[<>:"/\\|?*]/g, '_');
                const fileName = `商标_${trademark.regNo || trademark.tmId}_${safeName}${extension}`;
                files.push({
                    url: processedUrl,
                    fileName: fileName
                });
            }
        }
    });

    return files;
}


/**
 * 获取作品著作权相关文件
 */
async function getCopyrightFiles(eId: string): Promise<{url: string, fileName: string}[]> {
    const copyrightInfo = await selectData(
        OPERATIONALDATATYPE.查询多个,
        'copy_right',
        { eId },
        ["crId", "registerNo", "name", "iprUrl"]
    );

    const files: {url: string, fileName: string}[] = [];

    copyrightInfo.forEach(copyright => {
        if (copyright.iprUrl) {
            const processedUrl = processFilePath(copyright.iprUrl);
            if (processedUrl) {
                const extension = path.extname(processedUrl) || '.pdf';
                const fileName = `作品著作权_${copyright.registerNo || copyright.crId}_${copyright.name}${extension}`;
                files.push({
                    url: processedUrl,
                    fileName: fileName
                });
            }
        }
    });

    return files;
}


/**
 * 获取软件著作权相关文件
 */
async function getSoftwareCopyrightFiles(eId: string): Promise<{url: string, fileName: string}[]> {
    const softwareCopyrightInfo = await selectData(
        OPERATIONALDATATYPE.查询多个,
        'software_copyright',
        { eId },
        ["scId", "registerNo", "name", "iprUrl"]
    );

    const files: {url: string, fileName: string}[] = [];

    softwareCopyrightInfo.forEach(software => {
        if (software.iprUrl) {
            const processedUrl = processFilePath(software.iprUrl);
            if (processedUrl) {
                const extension = path.extname(processedUrl) || '.pdf';
                const fileName = `软件著作权_${software.registerNo || software.scId}_${software.name}${extension}`;
                files.push({
                    url: processedUrl,
                    fileName: fileName
                });
            }
        }
    });

    return files;
}


/**
 * 获取专利相关文件
 */
async function getPatentFiles(eId: string): Promise<{url: string, fileName: string}[]> {
    const patentInfo = await selectData(
        OPERATIONALDATATYPE.查询多个,
        'patent',
        { eId },
        ["patentId", "applicationNumber", "title", "iprUrl"]
    );

    const files: {url: string, fileName: string}[] = [];

    patentInfo.forEach(patent => {
        if (patent.iprUrl) {
            const processedUrl = processFilePath(patent.iprUrl);
            if (processedUrl) {
                const extension = path.extname(processedUrl) || '.pdf';
                const fileName = `专利_${patent.applicationNumber || patent.patentId}_${patent.title}${extension}`;
                files.push({
                    url: processedUrl,
                    fileName: fileName
                });
            }
        }
    });

    return files;
}


/**
 * 简单的图片文件头验证
 */
function isValidImageHeader(header: string): boolean {
    const validHeaders = [
        'ffd8ffe0', // JPEG
        'ffd8ffe1', // JPEG
        'ffd8ffe2', // JPEG
        '89504e47', // PNG
        '47494638', // GIF
        '424d'      // BMP (前2字节)
    ];
    
    return validHeaders.some(valid => header.startsWith(valid));
}


/**
 * 创建ZIP压缩包
 */
async function createZipArchive(sourceDir: string, outPath: string): Promise<void> {
    return new Promise((resolve, reject) => {
        const output = fs.createWriteStream(outPath);
        const archive = archiver('zip', {
            zlib: { level: 9 } // 最高压缩级别
        });

        output.on('close', () => {
            console.log(`ZIP文件创建完成: ${outPath}, 大小: ${archive.pointer()} bytes`);
            resolve();
        });

        archive.on('error', (err) => {
            reject(err);
        });

        archive.pipe(output);
        archive.directory(sourceDir, false);
        archive.finalize();
    });
}






















