using BPA.SAAS.Manage.Application.Device.Dtos.ProductFunction;
using BPA.SAAS.Manage.Application.Device.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.Device;
using BPA.SAAS.Manage.Core.Product;
using Microsoft.AspNetCore.Server.IISIntegration;
using Newtonsoft.Json;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.Device.Services
{
    public class ProductFunctionService: IProductFunctionService, ITransient
    {
        ISqlSugarClient _db;
        public ProductFunctionService(ISqlSugarClient db)
        {
            _db = db;
        }
        #region 产品功能
        /// <summary>
        /// 获取功能基础信息列表
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<PageUtil> GetProductFunctionPage(ProductFunctionPageBase inputDto)
        {
            RefAsync<int> total = 0;
            var res = await _db.Queryable<BPA_ProductFunction, BPA_ProductVesion>((x, b) => new JoinQueryInfos(JoinType.Left, b.Id == x.DeviceVersionKey))
                .Where((x,b)=>x.ProductId == inputDto.ProductId && x.DeviceVersionKey== inputDto.ProductVesionId)
                .WhereIF(!string.IsNullOrWhiteSpace(inputDto.Name), (x, b) => x.Name.Contains(inputDto.Name))
                  .WhereIF(!string.IsNullOrWhiteSpace(inputDto.Type), (x, b) => x.Type==(FunctionTypeEnum)(Enum.Parse(typeof(FunctionTypeEnum), inputDto.Type)))
                    .WhereIF(!string.IsNullOrWhiteSpace(inputDto.Vesion), (x, b) => x.DeviceVersionKey == inputDto.Vesion)
                    //.WhereIF(inputDto.IsDefault!=null, (x, b) => x.IsDefault == inputDto.IsDefault)
                 .WhereIF(inputDto.Status != null, (x, b) => x.Status == inputDto.Status)
                  .OrderBy((x, b) => x.CreateAt, OrderByType.Desc).OrderBy((x, b) => x.Name, OrderByType.Desc)
                .Select((x, b) => new
                {
                    Name = x.Name,
                    Status = x.Status,
                    x.Id,
                    x.ForeignKeyRe,
                    x.DeviceVersionKey,
                    x.DataJson,
                    DeviceTypeKey = b.ProductId,
                    Vesion = b.Vesion,
                    CreateAt=x.CreateAt,
                    Type= x.Type,
                    DataType= x.DataType,
                    DataRange= x.DataRange,
                    Unit= x.Unit,
                    StepSize= x.StepSize,
                    EnumValue= x.EnumValue,
                    DataLength = x.DataLength,
                    BoolLabel = x.BoolLabel,
                    ReadWrite = x.ReadWrite,
                    Description= x.Description,
                    IsDefault= x.IsDefault,
                    EventType= x.EventType,
                })
                .ToPageListAsync(inputDto.Current, inputDto.PageSize, total);
            return new PageUtil()
            {
                Data = res,
                Total = total
            };
        }
        /// <summary>
        /// 查询所有功能信息
        /// </summary>
        /// <returns></returns>
        public async Task<List<ProductFunctionDto>> GetProductFunction()
        {
            var res =await _db.Queryable<BPA_ProductFunction>().Where(x => x.Status == 0)
                .OrderBy(i => i.CreateAt, OrderByType.Desc)
                .Select(x => new ProductFunctionDto()
                {
                    Id = x.Id,
                    Name = x.Name,
                    IsBatch = SqlFunc.Subqueryable<BPA_ProductFunctionAction>().Where(p => p.ProductFunctionId == x.Id).Any()
                })
                .ToListAsync();
            return res;
        }
        public async Task<List<ProductFunctionView>> GetProductFunction(string deviceId)
        {
            var device=_db.Queryable<BPA_DeviceInfo>().Where(x => x.Id == deviceId).First();
            var res = await _db.Queryable<BPA_ProductFunction>().Where(x => x.DeviceVersionKey == device.ProductVersionId)
                .OrderBy(i => i.CreateAt, OrderByType.Desc)
                .Select(x => new ProductFunctionView()
                {
                    Id = x.Id.SelectAll(),
                    Name = x.Name,
                    //IsBatch = SqlFunc.Subqueryable<BPA_ProductFunctionAction>().Where(p => p.ProductFunctionId == x.Id).Any()
                })
                .Mapper(x =>
                {
                    x.ProductFunctionValue = _db.Queryable<BPA_ProductFunctionAction>().Where(p => p.ProductFunctionId == x.Id).ToList();
                })
                .ToListAsync();
            return res;
        }
        public async Task<List<ProductFunctionView>> GetProductFunction_alm(string deviceId)
        {
            var device = _db.Queryable<BPA_DeviceInfo>().Where(x => x.Id == deviceId).First();
            var res = await _db.Queryable<BPA_ProductFunction>().Where(x => x.DeviceVersionKey == device.ProductVersionId)
                .OrderBy(i => i.CreateAt, OrderByType.Desc)
                .Select(x => new ProductFunctionView()
                {
                    Id = x.Id.SelectAll(),
                    Name = x.Name,
                    //IsBatch = SqlFunc.Subqueryable<BPA_ProductFunctionAction>().Where(p => p.ProductFunctionId == x.Id).Any()
                })
                .Mapper(x =>
                {
                    x.ProductFunctionValue = _db.Queryable<BPA_ProductFunctionAction>().Where(p => p.ProductFunctionId == x.Id).ToList();
                })
                .ToListAsync();
            return res;
        }
        /// <summary>
        /// 添加功能
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> AddProductFunction(ProductFunctionBaseDto inputDto)
        {
      
            var data = _db.Queryable<BPA_ProductFunction>()
                .Where(a => a.Name == inputDto.Name && a.ProductId== inputDto.ProductId).ToList();
            if (data.Count > 0)
            {
                throw Oops.Oh("功能名称已存在");
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(inputDto.DataJson))
                {
                    if (!IsValidJson(inputDto.DataJson.Replace("\n", ""))) throw Oops.Oh("json字符格式不正确");
                }
                var res =await _db.Insertable(new BPA_ProductFunction()
                {
                    Id = Guid.NewGuid().ToString(),
                    Name = inputDto.Name,
                    Status = CommonStatus.ENABLE,
                    CreateAt = DateTime.Now,
                    IsDeleted = 0,
                    Type= inputDto.Type,
                    ForeignKeyRe = inputDto.ForeignKeyRe,
                    DeviceVersionKey = inputDto.DeviceVersionKey,
                    DataType = inputDto.DataType,
                    DataRange = inputDto.DataRange,
                    Unit =inputDto.Unit,
                    StepSize = inputDto.StepSize,
                    EnumValue = inputDto.EnumValue,
                    DataLength = inputDto.DataLength,
                    BoolLabel = inputDto.BoolLabel,
                    ReadWrite = inputDto.ReadWrite,
                    Description=inputDto.Description,
                    ProductId= inputDto.ProductId,
                    EventType= inputDto.EventType,
                    DataJson= inputDto.DataJson?.Replace("\n",""),
                }).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                return res > 0;
            }
        }
        /// <summary>
        /// 修改功能
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateProductFunction(ProductFunctionBaseDto inputDto)
        {
            var check = _db.Queryable<BPA_ProductFunction>().Any(a => a.Id != inputDto.Id && a.Name == inputDto.Name);
            if (check) throw Oops.Oh("功能名称已存在");
            if (!string.IsNullOrWhiteSpace(inputDto.DataJson))
            {
                if(!IsValidJson(inputDto.DataJson.Replace("\n", ""))) throw Oops.Oh("json字符格式不正确");
            }
            var data = _db.Queryable<BPA_ProductFunction>().Where(a => a.Id == inputDto.Id).First();
            data.Name = inputDto.Name;
            data.DeviceVersionKey = inputDto.DeviceVersionKey;
            data.ForeignKeyRe = inputDto.ForeignKeyRe;
            data.DataType = inputDto.DataType;
            data.DataRange = inputDto.DataRange;
            data.Unit = inputDto.Unit;
            data.StepSize = inputDto.StepSize;
            data.EnumValue = inputDto.EnumValue;
            data.DataLength = inputDto.DataLength;
            data.BoolLabel = inputDto.BoolLabel;
            data.ReadWrite = inputDto.ReadWrite;
            data.Description= inputDto.Description;
            data.EventType = inputDto.EventType;
            data.DataJson= inputDto.DataJson?.Replace("\n", "");
            data.Status = (CommonStatus)Enum.ToObject(typeof(CommonStatus), inputDto.Status);
            var res =await _db.Updateable(data).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 删除功能
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteProductFunction(List<string> ids)
        {
            var resEntity = _db.Queryable<BPA_ProductFunction>().Where(x => ids.Contains(x.Id)).ToList();
       
            var res =await _db.Deleteable(resEntity).ExecuteCommandAsync();
            return res > 0;
        }
        #endregion
        #region 功能参数
        /// <summary>
        /// 根据功能id查询功能参数
        /// </summary>
        /// <returns></returns>
        public async Task<List<BPA_ProductFunctionAction>> GetProductFunctionActionList(string productFunctionId)
        {

            var res = await _db.Queryable<BPA_ProductFunctionAction>().Where(x => x.IsDeleted == 0 && x.ProductFunctionId == productFunctionId)
                .OrderBy(i => i.Sort, OrderByType.Asc)
                .ToListAsync();
            return res;
        }
       /// <summary>
       /// 查询所功能参数
       /// </summary>
       /// <returns></returns>
        public async Task<List<BPA_ProductFunctionAction>> GetProductFunctionActionList()
        {

            var res = await _db.Queryable<BPA_ProductFunctionAction>().Where(x => x.IsDeleted == 0)
                .OrderBy(i => i.Sort, OrderByType.Asc)
                .ToListAsync();
            return res;
        }
        /// <summary>
        /// 添加功能参数
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> AddProductFunctionAction(ProductFunctionActionBaseDto inputDto)
        {
            var check = _db.Queryable<BPA_ProductFunctionAction>()
                .Any(a => a.ProductFunctionId == inputDto.ProductFunctionId && a.ActionName == inputDto.ActionName );
            if (check)
            {
                throw Oops.Oh("功能参数已存在");
            }
            else
            {
                var res = await _db.Insertable(new BPA_ProductFunctionAction()
                {
                    ProductFunctionId = inputDto.ProductFunctionId,
                    ActionName = inputDto.ActionName,
                    ActionType = inputDto.ActionType,
                    ActionValue = inputDto.ActionValue,
                    Unit = inputDto.Unit,
                   // IsBatch = true,//inputDto.IsBatch,
                    IsDeleted = 0,
                    Sort = inputDto.Sort,
                }).CallEntityMethod(m => m.Create()).ExecuteCommandAsync(); ;
                return res > 0;
            }
        }
        /// <summary>
        /// 修改功能参数
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateProductFunctionAction(ProductFunctionActionBaseDto inputDto)
        {
            var check = _db.Queryable<BPA_ProductFunctionAction>().Any(a => a.ProductFunctionId == inputDto.ProductFunctionId && a.ActionName == inputDto.ActionName && a.ActionType == inputDto.ActionType && a.Id != inputDto.Id);
            if (check) throw Oops.Oh("功能参数已存在");
            var data = _db.Queryable<BPA_ProductFunctionAction>().Where(a => a.Id == inputDto.Id).First();
            if (data == null) throw Oops.Oh("功能参数不存在");
            data.ActionName = inputDto.ActionName;
            data.ActionType = inputDto.ActionType;
            data.ActionValue = inputDto.ActionValue;
            data.Unit = inputDto.Unit;
           // data.IsBatch = inputDto.IsBatch;
            data.Sort = inputDto.Sort;
            var res = await _db.Updateable(data).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 删除功能参数
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteProductFunctionAction(List<string> ids)
        {
            var resEntity = _db.Queryable<BPA_ProductFunctionAction>().Where(x => ids.Contains(x.Id)).ToList();
            foreach (var item in resEntity)
            {
                item.IsDeleted = 1;
            }
            var res = await _db.Updateable(resEntity).ExecuteCommandAsync();
            return res > 0;
        }
        #endregion

        private bool IsValidJson(string jsonString)
        {
            try
            {
                JsonConvert.DeserializeObject<object>(jsonString);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Invalid JSON string: " + ex.Message);
                return false;
            }
        }
    }
}
