
const get_fq_book_tab_model =  require('../Model/get_fq_book_tab_model');
class get_fq_book_tab_controllers {
    async getData(params) {
        try {
            // 参数验证
            if (!params?.book_id) {
                throw  'get_fq_book_tab_controllers:book_id ID is required';
            }

            const book_id = params.book_id;
            const filterData = await get_fq_book_tab_model.findOne({ book_key: book_id });

            if (!filterData) {
                return {
                    success: false,
                    data: null
                };
            }

            return {
                success: true,
                data: filterData
            };
        } catch (error) {

            throw error;
        }
    }
    async getDataByBookId(params) {
        try {
            // 参数验证
            if (!params?.book_id) {
                throw  'getDataByBookId:book_id ID is required';
            }

            const book_id = params.book_id;
            const filterData = await get_fq_book_tab_model.findOne({ book_id: book_id });

            if (!filterData) {
                return {
                    success: false,
                    data: null
                };
            }

            return {
                success: true,
                data: filterData
            };
        } catch (error) {

            throw error;
        }
    }

     async findNonExistentProductIds(ProductIds) {
        try {
            if (!Array.isArray(ProductIds) || ProductIds.length === 0) {
                throw 'materialIds must be a non-empty array';
            }

            // 限制最大处理数量为500
            const maxIds = ProductIds.slice(0, 500);

            // 构建 IN 查询条件
            const placeholders = maxIds.map(() => '?').join(',');
            const sql = `SELECT * FROM ${get_fq_book_tab_model.tableName} WHERE book_key IN (${placeholders})`;
            
            // 执行查询
            const existingRecords = await get_fq_book_tab_model.query(sql, maxIds);

            // 获取已存在的ProductIds集合
            const existingProductIds = new Set(
                existingRecords.map(record => record.book_id)
            );

            // 找出不存在的ProductIds
            const nonExistentProductIds = maxIds.filter(
                id => !existingProductIds.has(id)
            );

            return {
                success: true,
                data: {
                    total: maxIds.length,
                    existing: existingProductIds.size, //存在
                    existingProductIds:existingProductIds,
                    existingRecords:existingRecords,
                    nonExistent: nonExistentProductIds.length,
                    nonExistentIds: nonExistentProductIds
                }
            };

        } catch (error) {
            console.error('Error in findNonExistentProductIds:', error);
            return {
                success: false,
                error: error.message || error
            };
        }
    }

    async createData(tableData) {
        try {
            // 数据验证
            if (!tableData || Object.keys(tableData).length === 0) {
                throw 'Invalid table data';
            }

            // 检查必要字段
            const requiredFields = ['book_key', 'book_id', 'info']; // 替换为实际必要字段
            for (const field of requiredFields) {
                if (tableData[field]==null||tableData[field]==undefined) {
                    throw `Missing required field: ${field}${tableData}`;
                }
            }

            // 添加创建时间戳
            // const dataToCreate = {
            //     ...tableData
            //     // created_at: new Date(),
            //     // updated_at: new Date()
            // };

            const id = await get_fq_book_tab_model.createData(tableData);


            return {
                success: true,
                data: { id }
            };
        } catch (error) {
            throw error;
        }
    }
}

module.exports =  new get_fq_book_tab_controllers();