using BPA.KitChen.GroupMeal.SqlSugar;
using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsAttribute;
using BPA.SAAS.Manage.Application.Device.Dtos.Device;
using BPA.SAAS.Manage.Application.Device.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Comm.Model;
using BPA.SAAS.Manage.Comm.Util;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Device;
using BPA.SAAS.Manage.Core.Org;
using BPA.SAAS.Manage.Core.Product;
using BPA.SAAS.Manage.Core.system;
using BPA.SAAS.Manage.Core.System;
using Dm;
using Furion.RemoteRequest.Extensions;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.Device.Services
{
    public class DeviceService: IDeviceService, ITransient
    {
        ISqlSugarClient _db;
        StoreServers storeServer = new();
        public DeviceService(ISqlSugarClient db) 
        {
            _db=db;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<PageUtil> GetDeviceInfoPage(DeviceQueryInputDto inputDto)
        {
            RefAsync<int> total =0;
            var dataStore=await storeServer.GetStop();
            var data = await _db.Queryable<BPA_DeviceInfo, BPA_Product>((a, b) => new JoinQueryInfos(JoinType.Left, a.ProductId == b.Id))

                   .WhereIF(!string.IsNullOrWhiteSpace(inputDto.StoreId), (a, b) => a.StopId == inputDto.StoreId)
               .WhereIF(!string.IsNullOrWhiteSpace(inputDto.DeviceName), (a, b) => a.DeviceName.Contains(inputDto.DeviceName))
               .WhereIF(!string.IsNullOrWhiteSpace(inputDto.DeviceTypeId), (a, b) => a.DeviceTypeId == inputDto.DeviceTypeId)
               .OrderBy((a, b) => a.CreateAt, OrderByType.Desc)
               .Select((a, b) => new DeviceInfoQueryDto
               {
                   Id = a.Id.SelectAll(),
                   ProductName=b.Name,
                   ProductCode=b.Code,
                   StopId=a.StopId,
                   ProductVersionName = ""
               })
               .Mapper(x =>
               {
                   var Vesion = _db.Queryable<BPA_ProductVesion>().Where(c => c.Id == x.ProductVersionId).First();
                   var Stop=dataStore?.Where(f => f.Id == x.StopId).FirstOrDefault();
                   x.ProductVersionName = Vesion?.Vesion;
                  x.StopName= Stop?.Name;
               })
               .ToPageListAsync(inputDto.Current, inputDto.PageSize, total);
            return new PageUtil()
            {
                Data = data,
                Total = total
            };
        }
        /// <summary>
        /// 查询设备列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<ListSelectDeviceQuery>> GetDeviceList()
        {
            RefAsync<int> total = 0;
            var data = await _db.Queryable<BPA_DeviceInfo>()
               .Select(a=> new ListSelectDeviceQuery
               {
                   Id = a.Id,
                   Name = a.DeviceName,
                   AutoKey=a.AutoKey.ToString(),
                   ProductVersionId=a.ProductVersionId,
                   ProductId=a.ProductId,
                  
               }) .ToListAsync();
            data.ForEach(x =>
            {
                x.Vesion = _db.Queryable<BPA_ProductVesion>().Where(s => s.Id == x.ProductVersionId).First()?.Vesion;
                x.ProductNumber = _db.Queryable<BPA_ProductVesion>().Where(s => s.Id == x.ProductVersionId).First()?.ProductNumber;
                x.ProductUrl = _db.Queryable<BPA_ProductVesion>().Where(s => s.Id == x.ProductVersionId).First()?.ProductUrl; 
                x.ProductName = _db.Queryable<BPA_Product>().Where(s => s.Id == x.ProductId).First()?.Name;
                x.PrductKey = _db.Queryable<BPA_Product>().Where(s => s.Id == x.ProductId).First()?.Key;
            });
            return data;
        }
        public async Task<List<ListSelectDeviceQuery>> GetDeviceByStopList(string stopId)
        {
            RefAsync<int> total = 0;
            var data = await _db.Queryable<BPA_DeviceInfo>().Where(x=>x.StopId== stopId)
               .Select(a => new ListSelectDeviceQuery
               {
                   Id = a.Id,
                   Name = a.DeviceName,
                   AutoKey = a.AutoKey.ToString(),
                   ProductVersionId = a.ProductVersionId,
                   ProductId = a.ProductId,
               }).ToListAsync();
            data.ForEach(x =>
            {
                x.Vesion = _db.Queryable<BPA_ProductVesion>().Where(s => s.Id == x.ProductVersionId).First()?.Vesion;
                x.ProductNumber = _db.Queryable<BPA_ProductVesion>().Where(s => s.Id == x.ProductVersionId).First()?.ProductNumber;
                x.ProductName = _db.Queryable<BPA_Product>().Where(s => s.Id == x.ProductId).First()?.Name;
                x.PrductKey = _db.Queryable<BPA_Product>().Where(s => s.Id == x.ProductId).First()?.Key;
            });
            return data;
        }
        public async Task<BPA_DeviceInfo> GetDevice(string productId)
        {
            var data = await _db.Queryable<BPA_DeviceInfo>().Where(x => x.Id == productId).FirstAsync();
            return data;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> AddDevice(DeviceInfoBaseDto inputDto)
        {
            BPA_DeviceInfo bPA_DeviceInfo = inputDto.Adapt<BPA_DeviceInfo>();
            var product=_db.Queryable<BPA_Product>().Where(x => x.Id == inputDto.ProductId).First();
            bPA_DeviceInfo.Status = CommonStatus.ENABLE;
            //bPA_DeviceInfo.ProductCode= product?.Code;
            var res =await _db.Insertable(bPA_DeviceInfo) .CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
            //mqttsub(res.AutoKey, product?.Code);
            return res != null;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateDevice(DeviceInfoBaseDto inputDto)
        {
            var data = await _db.Queryable<BPA_DeviceInfo>().Where(x => x.Id == inputDto.Id).FirstAsync();

            if (data != null)
            {
                //mqttsub(data.AutoKey, data.ProductCode);
                var product = _db.Queryable<BPA_Product>().Where(x => x.Id == inputDto.ProductId).First();
                var inputData = inputDto.Adapt<BPA_DeviceInfo>();
                //inputData.ProductCode = product?.Code;
                var res = await _db.Updateable(inputData)
                    .UpdateColumns(x => new
                    {
                        x.DeviceName,
                        x.DeviceTypeId,
                        x.StopId,
                        x.ProductId,
                        //x.ProductCode,
                        x.Status,
                        x.ProductVersionId,
                       // x.TechnologyOrBom
                    })
                    .Where(x => x.Id == inputDto.Id).ExecuteCommandAsync();
               
                return res > 0;
            }
            return false;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="inputList"></param>
        /// <returns></returns>
        public async Task<bool> DelDeviceInfo(List<string> inputList)
        {
            var data = await _db.Queryable<BPA_DeviceInfo>().Where(x => inputList.Contains(x.Id)).ToListAsync();
            var GoodsTechnology = await _db.Queryable<BPA_GoodsTechnologyAction>().Where(x => inputList.Contains(x.DeviceId)).AnyAsync();
            if (GoodsTechnology) throw Oops.Oh("商品工艺已经关联到该设备下面，无法删除，请先解除商品工艺对应的设备");
            var WarehouseTemplate = await _db.Queryable<BPA_WarehouseTemplate>().Where(x => inputList.Contains(x.DeviceId)).AnyAsync();
            if (WarehouseTemplate) throw Oops.Oh("该设备已绑定了仓位模板，无法删除，请先删除该设备的仓位模板");
            var res = await _db.Deleteable(data) .ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 添加设备标签
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> AddDeviceTypeAsync(DeviceTypeBaseDto inputDto)
        {
            var res = await _db.Insertable(new BPA_DeviceType
            {
                Name = inputDto.Name,
            }).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 查询设备标签
        /// </summary>
        /// <returns></returns>
        public async Task<List<ListSelectQuery>> GetDeviceTypeList()
        {
            var listquery = await _db.Queryable<BPA_DeviceType>().Where(a => a.IsDeleted == 0).Select(a => new ListSelectQuery
            {
                Id = a.Id,
                Name = a.Name

            }).ToListAsync();
            return listquery;
        }
        /// <summary>
        /// (调用订单服务)
        /// </summary>
        /// <param name="AutoKey"></param>
        /// <param name="DeviceTypeKey"></param>
        /// <returns></returns>
        private bool mqttsub(int AutoKey, string DeviceTypeKey)
        {

            var list = _db.Queryable<BPA_DictData>().Where(x => x.Code == "SubDevice")
                .Select(x => x.Value).ToList();
            if (!list.Contains(DeviceTypeKey)) return true;
            var url = Utiily.OrderUrl + Utiily.newmqttsub + $"/{DeviceTypeKey}/{AutoKey}";

            try
            {
                Utiily.HttpGet(url, "");
            }
            catch (Exception e)
            {
                throw Oops.Oh($"调用订单服务:{url}" + e.Message);
               // BPALog.WriteLog($"调用订单服务:{url}" + e.Message, LogEnum.Error);
            }
            Console.WriteLine($"调用订单服务:{url},调用成功");
          //  BPALog.WriteLog($"调用订单服务:{url},调用成功");
            return true;
        }




       

    }
}
