using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using MySqlConnector;
using CncModels.Dto;
using CncModels.Dto.CollectLog;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;

namespace CncRepository.Impl.Log
{
    /// <summary>
    /// 采集周期仓储实现（日志库 - log_collect_cycle）
    /// </summary>
    public class CollectCycleRepository : LogRepository, ICollectCycleRepository
    {
        public CollectCycleRepository(string connectionString) : base(connectionString) { }

        public PagedResult<CollectCycleListItem> GetCycleList(CollectCycleQuery query)
        {
            using (var conn = CreateConnection())
            {
                var whereParts = new List<string> { "1=1" };
                var p = new DynamicParameters();

                if (query.StartDate.HasValue)
                {
                    whereParts.Add("c.cycle_time >= @StartDate");
                    p.Add("StartDate", query.StartDate);
                }
                if (query.EndDate.HasValue)
                {
                    whereParts.Add("c.cycle_time <= @EndDate");
                    p.Add("EndDate", query.EndDate);
                }
                if (query.CollectAddressId.HasValue)
                {
                    whereParts.Add("c.collect_address_id = @CollectAddressId");
                    p.Add("CollectAddressId", query.CollectAddressId);
                }
                if (query.HasAnomaly.HasValue)
                {
                    whereParts.Add("c.has_anomaly = @HasAnomaly");
                    p.Add("HasAnomaly", query.HasAnomaly);
                }

                var whereSql = string.Join(" AND ", whereParts);

                var total = conn.ExecuteScalar<int>(
                    $"SELECT COUNT(1) FROM log_collect_cycle c WHERE {whereSql}", p);

                var dataSql = $@"SELECT
                        c.id AS Id,
                        DATE_FORMAT(c.cycle_time, '%Y-%m-%d %H:%i:%s') AS CycleTime,
                        c.collect_address_id AS CollectAddressId,
                        NULL AS AddressName,
                        c.total_machines AS TotalMachines,
                        c.success_count AS SuccessCount,
                        c.fail_count AS FailCount,
                        c.has_anomaly AS HasAnomaly,
                        c.change_distribution AS ChangeDistribution,
                        c.cycle_summary AS CycleSummary
                    FROM log_collect_cycle c
                    WHERE {whereSql}
                    ORDER BY c.cycle_time DESC
                    LIMIT @PageSize OFFSET @Offset";

                var items = conn.Query<CollectCycleListItem>(dataSql,
                    new { PageSize = query.PageSize, Offset = query.Offset }).AsList();

                return new PagedResult<CollectCycleListItem>
                {
                    Items = items,
                    Total = total,
                    Page = query.Page,
                    PageSize = query.PageSize
                };
            }
        }

        public long Create(CollectCycle entity)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"INSERT INTO log_collect_cycle
                    (cycle_time, collect_address_id, raw_log_id, end_time, duration_ms,
                     total_machines, success_count, fail_count, change_distribution,
                     has_anomaly, cycle_summary, created_at)
                    VALUES (@CycleTime, @CollectAddressId, @RawLogId, @EndTime, @DurationMs,
                            @TotalMachines, @SuccessCount, @FailCount, @ChangeDistribution,
                            @HasAnomaly, @CycleSummary, NOW());
                    SELECT LAST_INSERT_ID();";
                return conn.ExecuteScalar<long>(sql, new
                {
                    entity.CycleTime,
                    entity.CollectAddressId,
                    entity.RawLogId,
                    entity.EndTime,
                    entity.DurationMs,
                    entity.TotalMachines,
                    entity.SuccessCount,
                    entity.FailCount,
                    entity.ChangeDistribution,
                    entity.HasAnomaly,
                    entity.CycleSummary
                });
            }
        }

        public int DeleteBeforeDate(DateTime date)
        {
            using (var conn = CreateConnection())
            {
                return conn.Execute(
                    "DELETE FROM log_collect_cycle WHERE cycle_time < @Date",
                    new { Date = date });
            }
        }
    }
}
