using MWS.Data.InterFace;
using MWS.Library.Common;
using MWS.Library.Common.Module;
using MWS.Library.Enums;
using MWS.Model;
using MWS.Model.Dto;
using MWS.Model.Model;
using System.Collections.Generic;
using System.Linq;

namespace MWS.Data.Manager
{
    public class RecordManager : DapperHelper<T_DataRecord>, IRecord
    {
        public int Insert(string sql)
        {
            return Execute<T_DataRecord>(sql);
        }

        /// <summary>
        /// 获取历史记录
        /// </summary>
        /// <param name="tagIds">变量Id</param>
        /// <param name="startTime">开始时间（时间戳 毫秒）</param>
        /// <param name="endTime">结束时间（时间戳 毫秒）</param>
        /// <param name="skipCount">跳过条数</param>
        /// <param name="pageSize">拉取条数</param>
        /// <returns></returns>
        public PageData<TagRecordDto> GetTagRecord(int[] tagIds, long startTime, long endTime, int pageIndex, int pageSize)
        {
            PageData<TagRecordDto> pagerData = new PageData<TagRecordDto>() { PageIndex = pageIndex, PageSize = pageSize };
            var tagRecords = new List<TagRecordDto>();
            var timeGroup = Query<long>(@"SELECT [Time]	FROM T_DataRecord WHERE  TagId IN  @Ids  AND TIME >= @StartTime AND TIME <= @EndTime 
                                            GROUP BY TIME ORDER BY [Time] ASC",
                                                 new { Ids = tagIds, StartTime = startTime, EndTime = endTime, SkipCount = (pageIndex - 1) * pageSize, TakeCount = pageSize });
            if (!timeGroup.Any())
                return pagerData;
            pagerData.TotalCount = timeGroup.Count;
            timeGroup = timeGroup.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            var tagFirstValue = Query<TagRecordModel>(@"SELECT record.TagId,tag.Name as TagName,tag.TagType,tag.DataType,record.Value,tag.SwitchType,record.Time FROM	T_DataRecord record,(SELECT TagId,MAX (Time) AS Time FROM T_DataRecord AS s 
	                                                    WHERE TagId IN  @Ids  AND TIME <=@StartTime GROUP BY TagId) temp ,V_DeviceTag as tag
                                                     WHERE record.TagId=temp.TagId AND record.Time = temp.Time and record.TagId=tag.Id",
                                                     new { Ids = tagIds, StartTime = timeGroup?.Min() ?? startTime });


            var records = Query<TagRecordModel>(@"SELECT tag.[Id] as TagId,[Name] as TagName,[TagType],tag.[DataType],tag.[SwitchType],record.[Value],record.[Time] 
                                                 FROM  T_DataRecord AS record
	                                                LEFT JOIN T_DeviceTag AS tag ON record.TagId=tag.Id 
                                                 WHERE
	                                                TagId IN  @Ids  and Time>=@StartTime and Time<=@EndTime
                                                 ORDER BY Time ASC",
                                                   new { Ids = tagIds, StartTime = timeGroup?.Min() ?? startTime, EndTime = timeGroup?.Max() ?? endTime });

            tagRecords.Add(new TagRecordDto
            {
                Time = TypeExtension.GetTime(startTime).ToString(),
                Records = tagFirstValue.Select(c => new RecordData
                {
                    TagId = c.TagId,
                    TagName = c.TagName,
                    Value = (c.TagType == 1 || c.TagType == 0) ? (bool.Parse(c.Value) ? (c.SwitchType == 1 ? "动作" : "触发") : "恢复") : c.Value,
                    Light = (c.TagType == 1 || c.TagType == 0) ? Tool.GetLightColor(c.SwitchType, c.Value) : "",
                    UnitSign = ((TagType)c.TagType).GetUnitSign(),
                    ValueVisibility = c.TagType == 0 ? "Collapsed" : "Visible",
                    LightVisibility = c.TagType == 0 ? "Visible" : "Collapsed"
                }).ToList()
            });

            TagRecordDto tagRecord;
            var recordGroup = records.GroupBy(c => c.Time);
            foreach (var group in recordGroup)
            {
                tagRecord = new TagRecordDto();
                tagRecord.Time = TypeExtension.GetTime(group.Key).ToString();
                tagRecord.Records = new List<RecordData>();
                foreach (var tagId in tagIds)
                {
                    var record = group.FirstOrDefault(c => c.TagId == tagId);
                    if (record == null)
                    {
                        var last = tagRecords.Last().Records.FirstOrDefault(c => c.TagId == tagId);
                        if (last == null)
                            continue;
                        tagRecord.Records.Add(last);
                    }
                    else
                    {
                        tagRecord.Records.Add(new RecordData
                        {
                            TagId = record.TagId,
                            TagName = record.TagName,
                            Value = (record.TagType == 1 || record.TagType == 0) ? (bool.Parse(record.Value) ? (record.SwitchType == 1 ? "动作" : "触发") : "恢复") : record.Value,
                            Light = (record.TagType == 1 || record.TagType == 0) ? Tool.GetLightColor(record.SwitchType, record.Value) : "",
                            UnitSign = ((TagType)record.TagType).GetUnitSign(),
                            ValueVisibility = record.TagType == 0 ? "Collapsed" : "Visible",
                            LightVisibility = record.TagType == 0 ? "Visible" : "Collapsed"
                        });
                    }
                }
                tagRecords.Add(tagRecord);
            }
            if (tagRecords.Any())
            {
                tagRecords.RemoveAt(0);
            }           
            pagerData.Data = tagRecords;

            return pagerData;

        }

    }
}
