using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using MySqlConnector;
using Newtonsoft.Json.Linq;
using CncModels.Dto.Machine;
using CncRepository.Base;
using CncRepository.Interface;

namespace CncRepository.Impl
{
    /// <summary>
    /// 设备最新Tag数据仓储（查询日志库 raw_json，按 Tag ID 提取指标）
    /// </summary>
    public class MachineLatestTagRepository : LogRepository, IMachineLatestTagRepository
    {
        private readonly string _businessConn;

        /// <summary>
        /// 初始化，同时持有日志库和业务库连接字符串
        /// </summary>
        /// <param name="logConn">cnc_log 连接字符串</param>
        /// <param name="businessConn">cnc_business 连接字符串</param>
        public MachineLatestTagRepository(string logConn, string businessConn) : base(logConn)
        {
            _businessConn = businessConn;
        }

        /// <summary>
        /// 获取指定设备的最新6个Tag及其采集时间
        /// </summary>
        /// <param name="machineId">设备ID</param>
        /// <returns>6个Tag数据列表（找不到时返回空列表）</returns>
        public List<MachineLatestTagItem> GetLatestTags(int machineId)
        {
            // 1. 从业务库获取设备的 device_code
            string deviceCode;
            using (var bconn = new MySqlConnection(_businessConn))
            {
                deviceCode = bconn.ExecuteScalar<string>(
                    "SELECT device_code FROM cnc_machine WHERE id = @Id",
                    new { Id = machineId });
            }
            if (string.IsNullOrEmpty(deviceCode))
                return new List<MachineLatestTagItem>();

            // 2. 从日志库获取最新一条成功的 raw_json
            string rawJson;
            using (var conn = CreateConnection())
            {
                rawJson = conn.ExecuteScalar<string>(
                    "SELECT raw_json FROM log_collect_raw WHERE is_success = 1 ORDER BY request_time DESC LIMIT 1");
            }
            if (string.IsNullOrEmpty(rawJson))
                return new List<MachineLatestTagItem>();

            // 3. 解析 JSON，提取6个目标 Tag
            var targetTags = new[] { "_io_status", "Tag5", "Tag8", "Tag1", "Tag9", "Tag26" };
            var result = new List<MachineLatestTagItem>();

            try
            {
                var devices = JArray.Parse(rawJson);
                foreach (JObject d in devices.OfType<JObject>())
                {
                    string dev = d?.Value<string>("device") ?? "";
                    // 模糊匹配：raw_json 中的 device 可能是 device_code 的一部分（分隔符可能不同）
                    if (!deviceCode.Contains(dev) && !dev.Contains(deviceCode.Replace("_", "-")))
                        continue;

                    var tags = d?.Value<JArray>("tags");
                    if (tags == null)
                        continue;

                    foreach (JObject t in tags.OfType<JObject>())
                    {
                        string tagId = t?.Value<string>("id") ?? "";
                        if (!targetTags.Contains(tagId))
                            continue;

                        string timeStr = t?.Value<string>("time") ?? "";
                        DateTime? collectTime = null;
                        if (DateTime.TryParse(timeStr, out var ct))
                            collectTime = ct;

                        result.Add(new MachineLatestTagItem
                        {
                            Id = tagId,
                            Desc = t?.Value<string>("desc") ?? "",
                            Value = t?.Value<string>("value") ?? "",
                            CollectTime = collectTime
                        });
                    }
                    break; // 找到匹配设备后退出
                }
            }
            catch
            {
                // JSON 解析失败返回空列表
            }

            return result;
        }
    }
}
