using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TouchSocket.Core;
using WCS.BLL.Manager;
using WCS.BLL.Services.IService;
using WCS.BLL.Tool;
using WCS.DAL;
using WCS.DAL.Db;
using WCS.DAL.Db.AuthDb;
using WCS.DAL.DbModels;
using WCS.Model;
using WCS.Model.ApiModel;
using WCS.Model.ApiModel.SingleLight;
using WCS.Model.ApiModel.User;
using WCS.Model.WebSocketModel;
using static System.Formats.Asn1.AsnWriter;
using static WCS.BLL.Tool.Helper;

namespace WCS.BLL.Services.Service
{
    public class SingleLightService : ISingleLightService
    {
        public async Task<ResponseCommon<object>> SingleLightControl(SingleLightControlRequest request)
        {
            try
            {
                //传入数据校验
                if (request.StoreList == null || request.StoreList.Count == 0)
                {
                    return new ResponseCommon<object>()
                    {
                        Code = 201,
                        Message = "操作失败：没有需要控制的库位",
                    };
                }
                //对应库位
                var storeCodes = request.StoreList.Select(t => t.StoreCode)
                                                  .Distinct()
                                                  .ToList();
                var stores = DbHelp.db.Queryable<StoreInfo>().Where(t => storeCodes.Contains(t.StoreCode))
                                                                .ToList();
                if (stores == null || stores.Count == 0)
                {
                    return new ResponseCommon<object>
                    {
                        Code = 201,
                        Message = $"操作失败：所有库位不存在！"
                    };
                }

                //对应货架（获取TCP和报警灯ID）
                var shelfIds = stores.Select(t => t.ShelfId).Distinct().ToList();
                var shelfs = DbHelp.db.Queryable<ShelfInfo>().Where(t => shelfIds.Contains(t.Id))
                                                             .ToList();
                //对应模组信息
                var moduleIds = stores.Select(t => t.ModuleId).Distinct().ToList();
                var modules = DbHelp.db.Queryable<ModuleInfo>().Where(t => moduleIds.Contains(t.Id))
                                                 .ToList();

                //加载请求参数中的库位灯 板子ID和货架ID
                foreach (var store in request.StoreList)
                {
                    var storeInDb = stores.Where(t => t.StoreCode == store.StoreCode).FirstOrDefault();
                    if (storeInDb == null)
                    {
                        return new ResponseCommon<object>
                        {
                            Code = 201,
                            Message = $"操作失败：库位{store.StoreCode}不存在(store)！"
                        };
                    }
                    else
                        store.ShelfId = storeInDb.ShelfId;

                    var moduleInDb = modules.Where(t => t.Id == storeInDb.ModuleId).FirstOrDefault();
                    if (moduleInDb == null)
                    {
                        return new ResponseCommon<object>
                        {
                            Code = 201,
                            Message = $"操作失败：库位{store.StoreCode}不存在(module)！"
                        };
                    }
                    else
                        store.BoardId = moduleInDb.BoardId;
                }

                //合并：同一个货架的库位合并
                var shelfModels = new List<SingleLightShelfModel>();
                foreach (var shelf in shelfs)
                {
                    var shelfModel = new SingleLightShelfModel();
                    //报警灯
                    shelfModel.WarningLightMode = request.WarningLightMode;
                    shelfModel.WarningBuzzerMode = request.WarningBuzzerMode;
                    shelfModel.WarningLightColor = request.WarningLightColor;
                    shelfModel.WarningBoardId = shelf.LightId;
                    shelfModel.ClientIp = shelf.ClientIp;
                    //库位
                    var storesThisShelf = request.StoreList
                                               .Where(t => t.ShelfId == shelf.Id)
                                               .ToList();
                    foreach (var storeThisShelf in storesThisShelf)
                    {
                        shelfModel.StoreList.Add(new SingleLightStoreModel()
                        {
                            BoardId = storeThisShelf.BoardId,
                            LightColor = storeThisShelf.LightColor,
                            LightMode = storeThisShelf.LightMode,
                        });
                    }
                    shelfModels.Add(shelfModel);
                }

                //合并：同一个TCP的货架合并 报警灯和库位灯统一只发送一条指令
                var clientIpList = shelfs.Select(t => t.ClientIp)
                                         .Distinct()
                                         .ToList();
                foreach (var clientIp in clientIpList)
                {
                    var shelfModelsInOneIp = shelfModels.Where(t => t.ClientIp == clientIp).ToList();
                    var sendData = Helper.SingleLightControl(shelfModelsInOneIp);

                    TCPClient tCPClient = TCPClientManager.GetTCPClientByIPHost(clientIp);
                    tCPClient.Send(sendData);
                    Logs.Write("【单灯单独控制】发送指令" + BitConverter.ToString(sendData));
                }

                //返回成功
                return new ResponseCommon<object>()
                {
                    Code = 200,
                    Message = "success",
                };
            }
            catch (Exception ex)
            {
              
                //操作失败
                return new ResponseCommon<object>()
                {
                    Code = 300,
                    Message = $"操作失败：{ex.Message}",
                };
            }
        }
    }
}
