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

            const book_id = params.book_id;
            const filterData = await video_product_model.findOne({ product_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 ${video_product_model.tableName} WHERE product_id IN (${placeholders})`;
            
            // 执行查询
            const existingRecords = await video_product_model.query(sql, maxIds);

            // 获取已存在的ProductIds集合
            const existingProductIds = new Set(
                existingRecords.map(record => record.product_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 createProductData(tableData) {
        try {
            // 数据验证
            if (!tableData || Object.keys(tableData).length === 0) {
                throw 'Invalid table data';
            }

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

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

            const id = await video_product_model.createData(tableData);


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


    async getProductDataByBookPlatformAndWordsZero(params) {
            try {
                // 参数验证
                if (!params?.book_platform) {
                    throw  'getProductDataByBookPlatformAndWordsZero:book_platform  is required:'+params;
                }
    
                const filterData = await video_product_model.findOne({ book_platform:params.book_platform,words:"0" });
    
                if (!filterData) {
                    return {
                        success: false,
                        data: null
                    };
                }
    
                return {
                    success: true,
                    data: filterData
                };
            } catch (error) {
    
                throw error;
            }
    }


    async updateData(params, tableData) {
        try {
            // 参数验证
            if (!params?.id) {
                throw 'ID is required';
            }


            if (!tableData || Object.keys(tableData).length === 0) {
                throw 'No data to update';
            }


            // 添加更新时间戳
            // const dataToUpdtableDataate = {
            //     ...,
            // };

            // 使用乐观锁更新
            const affectedRows = await video_product_model.updateData(
                params.id,
                tableData
            );

            if (affectedRows === 0) {
                throw 'Data was modified by another process';
            }
            return {
                success: true,
                message: 'Filter data updated successfully'
            };
        } catch (error) {
            throw error;
        }
    }

    async getDataByBookPlatform(params,limit=1000) {
        try {
            // 参数验证
            if (!params?.book_platform) {
                throw  'getDataByBookPlatform:book_platform  is required:'+params;
            }

            const filterData = await video_product_model.findDataByLimit({ book_platform:params.book_platform },limit);

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

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

            throw error;
        }
    }


    async getDataByBookPlatformAndOriginBook(params) {
        try {
            // 参数验证
            if (!params?.book_platform) {
                throw  'getDataByBookPlatform:book_platform  is required:'+params;
            }

            const filterData = await video_product_model.findDataByLimit({ book_platform:params.book_platform,product_parent_id:"",genre:3 },10);

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

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

            throw error;
        }
    }
}

module.exports =  new video_product_controllers();