const mysql = require('mysql2/promise');
const tools = require('../tools');
const database_config = tools.getDataBaseConfig();
class DailyRecordManager {
    constructor() {
        this.pool = mysql.createPool(database_config);
    }

    // 创建记录
    async createRecord(date, content) {
        try {
            const connection = await this.pool.getConnection();
            try {
                const [result] = await connection.execute(
                    'INSERT IGNORE INTO daily_records (record_date, content) VALUES (?, ?)',
                    [date, JSON.stringify(content)]
                );
                
                return {
                    success: result.affectedRows > 0,
                    message: result.affectedRows > 0 ? '记录创建成功' : '该日期记录已存在'
                };
            } finally {
                connection.release();
            }
        } catch (error) {
            console.error('创建记录失败:', error);
            throw error;
        }
    }

    // 更新记录
    async updateRecord(date, content) {
        try {
            const connection = await this.pool.getConnection();
            try {
                const [result] = await connection.execute(
                    'UPDATE daily_records SET content = ? WHERE record_date = ?',
                    [JSON.stringify(content), date]
                );
                
                return {
                    success: result.affectedRows > 0,
                    message: result.affectedRows > 0 ? '记录更新成功' : '记录不存在'
                };
            } finally {
                connection.release();
            }
        } catch (error) {
            console.error('更新记录失败:', error,content,date);
            throw error;
        }
    }

    async getRecord(date) {
        try {
            const connection = await this.pool.getConnection();
            try {
                const [rows] = await connection.execute(
                    'SELECT * FROM daily_records WHERE record_date = ?',
                    [date]
                );
                
                if (rows.length === 0) {
                    return null;
                }
    
                const record = rows[0];
                
                // 检查 content 的类型
                const content = typeof record.content === 'string' 
                    ? JSON.parse(record.content)  // 如果是字符串，则解析
                    : record.content;             // 如果已经是对象，直接使用
    
                return {
                    ...record,
                    content
                };
                
            } finally {
                connection.release();
            }
        } catch (error) {
            console.error('获取记录失败:', error);
            throw error;
        }
    }

    // 获取日期范围内的记录
    async getRecordsInRange(startDate, endDate) {
        try {
            const connection = await this.pool.getConnection();
            try {
                const [rows] = await connection.execute(
                    'SELECT * FROM daily_records WHERE record_date BETWEEN ? AND ? ORDER BY record_date',
                    [startDate, endDate]
                );
                
                return rows.map(row => ({
                    ...row,
                    content: JSON.parse(row.content)
                }));
            } finally {
                connection.release();
            }
        } catch (error) {
            console.error('获取记录范围失败:', error);
            throw error;
        }
    }

    // 检查日期是否存在记录
    async hasRecord(date) {
        try {
            const connection = await this.pool.getConnection();
            try {
                const [rows] = await connection.execute(
                    'SELECT 1 FROM daily_records WHERE record_date = ?',
                    [date]
                );
                
                return rows.length > 0;
            } finally {
                connection.release();
            }
        } catch (error) {
            console.error('检查记录失败:', error);
            throw error;
        }
    }
}

module.exports = DailyRecordManager;
// 使用示例
async function example() {
    const manager = new DailyRecordManager();

    try {
        // 创建今天的记录
        const today = new Date().toISOString().split('T')[0];
        const result = await manager.createRecord(today, {
            data: '示例数据',
            value: 123
        });
        console.log('创建结果:', result);

        // 尝试再次创建今天的记录（会失败因为已存在）
        const duplicateResult = await manager.createRecord(today, {
            data: '新数据',
            value: 456
        });
        console.log('重复创建结果:', duplicateResult);

        // 更新今天的记录
        const updateResult = await manager.updateRecord(today, {
            data: '更新的数据',
            value: 789
        });
        console.log('更新结果:', updateResult);

        // 获取今天的记录
        const record = await manager.getRecord(today);
        console.log('获取的记录:', record);

        // 获取最近7天的记录
        const sevenDaysAgo = new Date();
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
        const rangeRecords = await manager.getRecordsInRange(
            sevenDaysAgo.toISOString().split('T')[0],
            today
        );
        console.log('范围记录:', rangeRecords);

    } catch (error) {
        console.error('操作失败:', error);
    }
}

// 执行示例
// example();