import { join } from 'path';
import { readdirSync, readFileSync } from 'fs';
import * as XLSX from 'xlsx';

export class DataExtractor {
    private static instance: DataExtractor;
    private data: { [key: string]: { [sheet: string]: any } } = {};

    private constructor() {
        this.loadAllData();
    }

    public static getInstance(): DataExtractor {
        if (!DataExtractor.instance) {
            DataExtractor.instance = new DataExtractor();
        }
        return DataExtractor.instance;
    }

    private loadAllData(): void {
        const dirPath = join(__dirname, '../../src/data');
        const files = readdirSync(dirPath).filter(file => file.endsWith('.xlsx'));
        console.log(dirPath);

        files.forEach(file => {
            const filePath = join(dirPath, file);
            this.data[file] = this.parseExcel(filePath);
        });
    }

    private parseExcel(filePath: string): { [sheet: string]: any } {
        const file = readFileSync(filePath);
        const workbook = XLSX.read(file, { type: 'buffer' });
        const sheetNames = workbook.SheetNames;
        const data: { [sheet: string]: any } = {};

        sheetNames.forEach(sheetName => {
            data[sheetName] = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName]);
        });

        return data;
    }

    public getData(fileName: string, sheetName: string): any {
        const fileData = this.data[fileName];
        if (!fileData) {
            throw new Error(`Excel文件不存在`);
        }
        const sheetData = fileData[sheetName];
        if (!sheetData) {
            throw new Error(`表格不存在`);
        }
        return sheetData;
    }

    public getAvailableFiles(): string[] {
        return Object.keys(this.data);
    }

    public getAvailableSheets(fileName: string): string[] {
        const fileData = this.data[fileName + '.xlsx'];
        if (!fileData) {
            throw new Error(`File ${fileName} not found`);
        }
        return Object.keys(fileData);
    }
}
