using Dapper;
using SWRIS.Core;
using SWRIS.Enums;
using SWRIS.Models;
using System;

namespace SWRIS.Repository
{
    public class AlarmRepository : SqLiteBaseRepository, IAlarmRepository
    {
        public int AddAlarm(AlarmDataModel alarm, AlarmSourceType sourceType, double damageExtent)
        {
            if (alarm != null)
            {
                damageExtent = Math.Abs(damageExtent / 2);
                using (var cnn = DbConnection())
                {
                    try
                    {
                        cnn.Open();
                        var sql = @"
                            -- 先插入新记录
                            INSERT INTO Alarms (RopeNumber, DamagePosition, DamageValue, DamageLevel, CreateTime, SourceType)
                            VALUES (@RopeNumber, @DamagePosition, @DamageValue, @DamageLevel, @CreateTime, @SourceType);
                            
                            -- 查询该位置范围内的总报警次数（包括刚插入的这条）
                            SELECT COUNT(*) 
                            FROM Alarms 
                            WHERE RopeNumber = @RopeNumber 
                            AND SourceType = @SourceType 
                            AND ABS(DamagePosition - @DamagePosition) <= @DamageExtent;";

                        var parameters = new
                        {
                            alarm.RopeNumber,
                            alarm.DamagePosition,
                            alarm.DamageValue,
                            alarm.DamageLevel,
                            CreateTime = DateTime.Now,
                            DamageExtent = damageExtent,
                            SourceType = sourceType
                        };

                        int totalCount = cnn.QueryFirst<int>(sql, parameters);
                        return totalCount;
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Error("执行AddAlarm SQL语句时出错：" + ex.Message, ex);
                        return -1;
                    }
                }
            }
            return -1;
        }
        public bool ClearAlarms(int ropeNumbner)
        {
            using (var cnn = DbConnection())
            {
                try
                {
                    cnn.Open();
                    var sql = "DELETE FROM Alarms WHERE RopeNumber=@RopeNumber;";
                    int effect = cnn.Execute(sql, new
                    {
                        RopeNumbner = ropeNumbner
                    });
                    cnn.Close();
                    return effect > 0;
                }
                catch (Exception ex)
                {
                    LogHelper.Error("执行ClearAlarms SQL语句时出错：" + ex.Message, ex);
                    return false;
                }
            }
        }
    }
}
