using Model;
using Model.Entity;
using ORM;
using Service.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Service.Implement
{
    /// <summary>
    /// 监测数值记录服务实现
    /// </summary>
    public class MonitorValueService : BaseService<MonitorValueEntity>, IMonitorValueService
    {
        // 继承父类构造函数，注入 SqlSugar 仓储
        public MonitorValueService(SqlSugarRepository<MonitorValueEntity> repository) : base(repository)
        {
        }

        /// <summary>
        /// 批量插入监测数据
        /// </summary>
        public async Task<Result<bool>> InsertRangeAsync(List<MonitorValueEntity> entities)
        {
            if (entities == null || entities.Count == 0)
                return Result<bool>.Success(true);

            try
            {
                // 使用 SqlSugar 的批量插入，底层会转换为 BulkCopy 或是批量 SQL，速度极快
                var result = await _repository.Context.Insertable(entities).ExecuteCommandAsync();
                return Result<bool>.Success(result > 0);
            }
            catch (Exception ex)
            {
                return Result<bool>.Error("批量插入监测数据失败", ex);
            }
        }

        /// <summary>
        /// 根据监测通道名称，分页查询历史记录
        /// </summary>
        public async Task<Result<List<MonitorValueEntity>>> GetPagedByNameAsync(string monitorName, int pageIndex, int pageSize, RefAsync<int> total)
        {
            try
            {
                var query = _repository.Entities;

                // 如果传了名字则按名字过滤
                if (!string.IsNullOrEmpty(monitorName))
                {
                    query = query.Where(x => x.MonitorName == monitorName);
                }

                var list = await query
                    .OrderByDescending(d => d.CreateTime) // 监测项通常优先看最新的数据
                    .ToPageListAsync(pageIndex, pageSize, total);

                // 计算总页数
                total.Value = (int)Math.Ceiling((double)total.Value / pageSize);
                return Result<List<MonitorValueEntity>>.Success(list);
            }
            catch (Exception ex)
            {
                return Result<List<MonitorValueEntity>>.Error($"根据名称 [{monitorName}] 分页查询数据失败", ex);
            }
        }
    }
}