using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using WCS.BLL.DbModels;
using WCS.BLL.HardWare;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
using WCS.BLL.Services.Service;
using WCS.DAL.Db;
using WCS.Model;
using WCS.Model.ApiModel.Home;
using Mode = WCS.BLL.HardWare.Mode;

namespace WCS.WebApi.Controllers
{
    /// <summary>
    /// 主页面的接口
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class HomeController : ControllerBase
    {
        public IHomerService _homerService { get; set; }
        public ISelfCheckService _selfCheckService { get; set; }

        public HomeController(IHomerService homerService, ISelfCheckService selfCheckService)
        {
            _homerService = homerService;
            _selfCheckService = selfCheckService;
        }

        [Route("getShelfStatus")]
        [HttpPost(Name = "getShelfStatus")]
        public async Task<ResponseBase> getShelfStatus(GetShelfStatusRequest request)
        {
            try
            {
                var shelfs = ShelfManager.Shelves
                                         .WhereIF(request.GroupNames?.Count > 0, t => request.GroupNames!.Contains(t.GroupName))
                                         .ToList();
                //直接返回当前内存中缓存的货架和状态
                return new GetShelfStatusResponse()
                {
                    Code = 200,
                    Message = "success",
                    Data = shelfs.Select(t => new ShelfModel
                    {
                        ShelfId = t.ShelfId,
                        ShelfCode = t.ShelfCode,
                        CurrentCom = t.CurrentCom,
                        SetCurrentModeTime = t.SetCurrentModeTime,
                        CurentMode = (int)t.CurrentMode,
                        ModulesStr = t.ModulesStr,
                        GroupName = t.GroupName,
                        OrderNumber = t.OrderNumber,
                    }).ToList(),
                };
            }
            catch (Exception ex)
            {
                return new ResponseBase()
                {
                    Code = 300,
                    Message = "获取失败：" + ex.Message,
                };
            }
        }

        [Route("getShelfStatusDetails")]
        [HttpPost(Name = "getShelfStatusDetails")]
        public async Task<ResponseBase> getShelfStatusDetails(GetShelfStatusRequest request)
        {
            try
            {
                var shelfs = ShelfManager.Shelves
                                         .WhereIF(request.GroupNames?.Count > 0, t => request.GroupNames!.Contains(t.GroupName))
                                         .ToList();
                //直接返回当前内存中缓存的货架和状态
                return new ResponseBase<object>()
                {
                    Code = 200,
                    Message = "success",
                    Data = shelfs,
                };
            }
            catch (Exception ex)
            {
                return new ResponseBase()
                {
                    Code = 300,
                    Message = "获取失败：" + ex.Message,
                };
            }
        }

        [Route("getTCPClientsDetails")]
        [HttpPost(Name = "getTCPClientsDetails")]
        public async Task<ResponseBase> getTCPClientsDetails(GetShelfStatusRequest request)
        {
            try
            {
                var tcpClients = TCPClientManager.TCPClients.Select(t => new
                {
                    RemoteIPHost = t.RemoteIPHost,
                    IsOnline = t.IsOnline,
                    IsFirstConnected = t.IsFirstConnected,
                    tcpClientIsNull = t.tcpClient == null,
                    tcpClientIsOnLine = t.tcpClient?.Online,

                }).ToList();
                //直接返回当前内存中缓存的货架和状态
                return new ResponseBase<object>()
                {
                    Code = 200,
                    Message = $"success！连接数量：{tcpClients.Count}",
                    Data = tcpClients,
                };
            }
            catch (Exception ex)
            {
                return new ResponseBase()
                {
                    Code = 300,
                    Message = "获取失败：" + ex.Message,
                };
            }
        }

        /// <summary>
        /// 重置货架的状态 使其回到待机模式
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("resetShelfStatus")]
        [HttpPost(Name = "resetShelfStatus")]
        public async Task<ResponseBase> resetShelfStatus(ResetShelfStatusRequest request)
        {
            try
            {
                if (request.IsResetAll == false && (request.SelfIds == null || request.SelfIds.Count == 0))
                {
                    return new ResponseBase()
                    {
                        Code = 201,
                        Message = "复位失败：请选择需要复位的货架！",
                    };
                }
                if (request.IsResetAll == true && (request.GroupNames == null || request.GroupNames.Count == 0))
                {
                    return new ResponseBase()
                    {
                        Code = 201,
                        Message = "复位失败：请选择需要复位的货架区域！",
                    };
                }
                var shelfs = new List<IShelfBase>();
                if (request.IsResetAll == false)
                    shelfs = ShelfManager.Shelves
                                             .Where(t => request.SelfIds.Contains(t.ShelfId))
                                             .Where(t => t.CurrentMode != Mode.待机模式)
                                             .ToList();
                else
                    shelfs = ShelfManager.Shelves
                                             .Where(t => request.GroupNames.Contains(t.GroupName))
                                             .Where(t => t.CurrentMode != Mode.待机模式)
                                             .ToList();
                foreach (var shelf in shelfs)
                {
                    shelf.Reset();
                }
                return new ResponseBase()
                {
                    Code = 200,
                    Message = "success",
                };

            }
            catch (Exception ex)
            {
                return new ResponseBase()
                {
                    Code = 300,
                    Message = ex.Message,
                };
            }
        }

        /// <summary>
        /// 获取货架对应的服务端的Ip和端口号
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("getShelfServer")]
        [HttpPost(Name = "getShelfServer")]
        public async Task<ResponseBase> getShelfServer(RequestBase request)
        {
            try
            {
                return await _homerService.GetShelfServer(request);
            }
            catch (Exception ex)
            {
                return new ResponseBase<object>()
                {
                    Code = 300,
                    Message = "查询失败" + ex.Message,
                    Data = null
                };
            }
        }

        [Route("getWebSocketWarnings")]
        [HttpPost(Name = "getWebSocketWarnings")]
        public async Task<ResponseBase> getWebSocketWarnings(RequestBase request)
        {
            try
            {
                return new ResponseBase<object>()
                {
                    Code = 200,
                    Message = "success",
                    Data = WarningManager.Warnings
                };
            }
            catch (Exception ex)
            {
                return new ResponseBase<object>()
                {
                    Code = 300,
                    Message = "查询失败" + ex.Message,
                    Data = null
                };
            }
        }





        [Route("getShelfTypes")]
        [HttpPost(Name = "getShelfTypes")]
        public async Task<ResponseBase> getShelfTypes(RequestBase request)
        {
            try
            {
                //直接获取当前所有货架类型并返回
                var shelfTypes = DbHelp.db.Queryable<ShelfTypeInfo>()
                                          .Select(t => new ShelfTypeInfo()
                                          {
                                              Id = t.Id,
                                              ShelfTypeName = t.ShelfTypeName
                                          })
                                          .ToList();
                return new PageQueryResponse<ShelfTypeInfo>()
                {
                    Code = 200,
                    Message = "success",
                    Data = new PageQueryResponseData<ShelfTypeInfo>
                    {
                        Lists = shelfTypes,
                        Count = shelfTypes.Count
                    }
                };
            }
            catch (Exception ex)
            {
                return new PageQueryResponse<ShelfTypeInfo>()
                {
                    Code = 300,
                    Message = $"查询失败:{ex.Message}",
                };
            }
        }


    }
}
