// import origin_data_model from '../Model/origin_data_model';
const origin_data_model = require("../Model/origin_data_model")

class origin_data_controllers {

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

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

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

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

            // 找出不存在的materialId
            const nonExistentMaterialIds = maxIds.filter(
                id => !existingMaterialIds.has(id)
            );

            return {
                success: true,
                data: {
                    total: maxIds.length,
                    existing: existingMaterialIds.size,
                    nonExistent: nonExistentMaterialIds.length,
                    nonExistentIds: nonExistentMaterialIds
                }
            };

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


    async getOriginDataById(params) {
        try {
            // 参数验证
            if (!params?.video_id) {
                throw  'origin_data_controllers:materialId is required';
            }

            const video_id = params.video_id;
            const filterData = await origin_data_model.findOne({ video_id: video_id });

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

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

            throw error;
        }
    }

    async getOriginData(params) {
        try {
            // 参数验证
            if (!params?.materialId) {
                throw  'origin_data_controllers:materialId is required';
            }

            const materialId = params.materialId;
            const filterData = await origin_data_model.findOne({ materialId: materialId });

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

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

            throw error;
        }
    }

    async findByDateRange(conditions = {}, dateField, startDate, endDate, limit = null, offset = 0, orderBy = null){
        try {
            const filterData =  await origin_data_model.findByDateRange(conditions,dateField,startDate,endDate,limit,offset,orderBy)
            if (!filterData) {
                return {
                    success: false,
                    data: null
                };
            }
    
            return {
                success: true,
                data: filterData
            };
        }catch(error){
            throw error;
        }
 
    }

    async getOriginDataByStatusAndLimit(params,limit=1) {
        try {
            // 参数验证
            if (params.status==undefined||params.status==null) {
                throw  'origin_data_controllers:status is required';
            }

            const status = params.status;
            const filterData = await origin_data_model.findDataByLimit({ status: status },limit);

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

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

            throw error;
        }
    }

    async getOriginDataByStatus(params) {
        try {
            // 参数验证
            if (params.status==undefined||params.status==null) {
                throw  'origin_data_controllers:status is required';
            }

            const status = params.status;
            const filterData = await origin_data_model.findOne({ status: status });

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

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

            throw error;
        }
    }


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

            // 检查必要字段
            const requiredFields = ['video_id', 'video_link', 'title', 'publish_time', 'kepp_num', 'comment_num', 'like_num', 'shared_num','is_guajian','guajian_link']; // 替换为实际必要字段
            for (const field of requiredFields) {
                if (tableData[field]==undefined||tableData[field]==null) {
                    throw `Missing required field: ${field}`;
                }
            }

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

            const id = await origin_data_model.createOriginData(tableData);


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


    async updateOriginDataByIds(params, tableData) {
        try {
            // 参数验证
            if (!params?.ids || !Array.isArray(params.ids) || params.ids.length === 0) {
                throw new Error('ids must be a non-empty array');
            }
    
            if (!tableData || Object.keys(tableData).length === 0) {
                throw new Error('No data to update');
            }
    
            const ids = params.ids;
    
            // 构建批量更新SQL
            const updateFields = Object.entries(tableData)
                .map(([key, value]) => `${key} = ?`)
                .join(', ');
                
            const placeholders = ids.map(() => '?').join(',');
            
            const sql = `
                UPDATE origin_data 
                SET ${updateFields}
                WHERE id IN (${placeholders})
            `;
    
            // 构建参数数组：先是set的值，然后是where in的值
            const values = [
                ...Object.values(tableData),
                ...ids
            ];
    
            // 执行更新
            const result = await origin_data_model.query(sql, values);
    
            return {
                success: true,
                message: `Successfully updated ${result.affectedRows} records`,
                data: {
                    affectedRows: result.affectedRows
                }
            };
    
        } catch (error) {
            console.error('Error in updateOriginData:', error);
            throw error;
        }
    }

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

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

            const id = params.id;

            // 使用乐观锁更新
            const affectedRows = await origin_data_model.updateOriginData(
                id,
                tableData // 假设使用版本控制
            );

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

module.exports = new origin_data_controllers();