using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenAuth.App.Interface;
using SqlSugar;
using Infrastructure;
using OpenAuth.App.ServiceApp.Response;
using DocumentFormat.OpenXml.EMMA;
using NPOI.SS.Formula.Functions;
using Infrastructure.Extensions;
using DocumentFormat.OpenXml.Math;

namespace OpenAuth.App.ServiceApp
{
    public class AirportMaintenanceApp : SqlSugarBaseApp<LasaDronePort, SugarDbContext>
    {
        public AirportMaintenanceApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<LasaDronePort> repository, IAuth auth) : base(unitWork, repository, auth)
        {
        }
        //获取设备绑定码
        public async Task<Response<LasaDeviceBindingCode>> GetDeviceBindingCode()
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var info = await db.LasaDeviceBindingCode.AsQueryable().Where(r => r.BindStatus == 0).FirstAsync();

                if (info != null)
                {
                    return new Response<LasaDeviceBindingCode>
                    {
                        Code = 200,
                        Message = "获取设备绑定码成功",
                        Result = info
                    };
                }
                else
                {
                    //如果设备绑定码不存在，则创建一个新的设备绑定码
                    var newBindingCode = new LasaDeviceBindingCode
                    {
                        Id = Guid.NewGuid().ToString(),
                        DeviceBindingCode = Guid.NewGuid().ToString("N").Substring(0, 8), // 生成一个新的绑定码
                        OrgId = "371300", // 默认组织ID
                        OrgName = "临沂市", // 默认组织名称
                        BindStatus = 0 // 未绑定状态
                    };
                    await db.LasaDeviceBindingCode.InsertAsync(newBindingCode);
                    if (db.Commit())
                    {
                        return new Response<LasaDeviceBindingCode>
                        {
                            Code = 200,
                            Message = "获取设备绑定码成功",
                            Result = newBindingCode
                        };
                    }
                    else
                    {
                        return new Response<LasaDeviceBindingCode>
                        {
                            Code = 500,
                            Message = "获取设备绑定码失败",

                        };
                    }
                }

            }
        }
        /// <summary>
        /// 修改注册码状态
        /// </summary>
        /// <param name="DeviceBindingCode"></param>
        /// <returns></returns>
        public async Task<bool> UpdateCodeStatus(string DeviceBindingCode)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaDeviceBindingCode.UpdateAsync(it => new LasaDeviceBindingCode()
                {
                    BindStatus = 1,
                }, it => it.DeviceBindingCode == DeviceBindingCode);
                if (db.Commit())
                    return true;
                else
                    return false;
            }

        }

        //使用网关
        public async Task<Response<LasaGateway>> GetGateway()
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var info = await db.LasaGateway.AsQueryable().Where(r => r.BindStatus == 0).FirstAsync();

                if (info != null)
                {
                    return new Response<LasaGateway>
                    {
                        Code = 200,
                        Message = "获取设备绑定码成功",
                        Result = info
                    };
                }
                else
                {
                    //如果网关不存在，则创建一个新的
                    var newGateway = new LasaGateway
                    {
                        Id = Guid.NewGuid().ToString(),
                        CreateTime = DateTime.Now,
                        GatewayAccount = "sdhc",
                        GatewaySn = Guid.NewGuid().ToString("N").Substring(0, 8).ToUpper(), // 生成一个新的
                        MqttGateway = "175.27.168.120:6011",
                        MqttPassword = "",
                        OrgId = "371300", // 默认组织ID
                        BindStatus = 0 // 未绑定状态
                    };
                    await db.LasaGateway.InsertAsync(newGateway);
                    if (db.Commit())
                    {
                        return new Response<LasaGateway>
                        {
                            Code = 200,
                            Message = "获取设备绑定码成功",
                            Result = newGateway
                        };
                    }
                    else
                    {
                        return new Response<LasaGateway>
                        {
                            Code = 500,
                            Message = "获取设备绑定码失败",
                        };
                    }
                }

            }
        }
        public async Task<bool> UpdateGateway(string gateway, string did)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaGateway.UpdateAsync(it => new LasaGateway()
                {
                    BindStatus = 1,
                    Did = did,
                    UpdateTime = DateTime.Now,
                }, it => it.GatewaySn == gateway);
                if (db.Commit())
                    return true;
                else
                    return false;
            }

        }
        //获取网关
        public async Task<List<string>> GetGatewaysnList()
        {
            using (var db = UnitWork.CreateContext())
            {
                var info = await db.LasaGateway.AsQueryable().Select(r => r.GatewaySn).ToListAsync();
                if (info != null)
                {
                    return info;
                }
                else
                {
                    return new List<string>();
                }
            }
        }

        #region 固件版本管理
        public async Task<Response<bool>> AddFirmware(LasaFirmware info)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaFirmware.InsertAsync(info);
                if (db.Commit())
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "添加成功"
                    };
                else
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "添加失败"
                    };
            }
        }
        #endregion

        #region 健康报警
        /// <summary>
        /// 添加健康报警
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool AddManageDeviceHms(List<LasaManageDeviceHms> newAlarms)
        {
            using (var db = UnitWork.CreateContext())
            {
                var now = DateTime.Now;
                //获取当前所有未处理的告警信息
                var existing = db.LasaManageDeviceHms.AsQueryable()
                         .Where(x => x.IsResolved == 0).ToList();
                var currentKeys = newAlarms.Select(x => x.Code).ToHashSet();
                var existingKeys = existing.Select(x => x.Code).ToHashSet();
                // 需要解除的（老有，新没有） 起的隆冬强
                var toResolve = existing
                    .Where(x => !currentKeys.Contains(x.Code)).ToList();
                foreach (var resolved in toResolve)
                {
                    resolved.IsResolved = 1;
                    resolved.UpdateTime = now;
                }
                db.LasaManageDeviceHms.UpdateRange(toResolve);
                // 需要新增的（新有，老没有）
                var toInsert = newAlarms
                    .Where(x => !existingKeys.Contains(x.Code))
                    .ToList();
                if (toInsert.Count > 0)
                    db.LasaManageDeviceHms.InsertRange(toInsert);
                //var flag = db.LasaManageDeviceHms.InsertRange(newAlarms);
                if (db.Commit())
                    return true;
                else
                    return false;
            }
        }
        //根据时间获取告警信息列表
        public async Task<Response<PageInfo<List<LasaManageDeviceHms>>>> GetManageDeviceHmsList(int level, int model, DateTime startTime, DateTime endTime, int page, int limit)
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var list = await db.LasaManageDeviceHms.AsQueryable()
                    .Where(x => x.CreateTime >= startTime && x.CreateTime <= endTime && x.IsResolved == 0)
                    .WhereIF(level!=0,x=>x.Level==level)
                    .WhereIF(model != 0, x => x.Module == model)
                    .OrderBy(x => x.CreateTime, OrderByType.Desc)
                    .ToPageListAsync(page, limit, totalCount);
                return new Response<PageInfo<List<LasaManageDeviceHms>>>
                {
                    Result = new PageInfo<List<LasaManageDeviceHms>> { Items = list, Total = totalCount }
                };
            }
        }
        #endregion

        #region 日志
        /// <summary>
        /// 添加日志
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool AddLog(LasaLog info)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = db.LasaLog.Insert(info);
                if (db.Commit())
                    return true;
                else
                    return false;
            }
        }
        #endregion
    }
}
