using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsEnergyConfig;
using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsType;
using BPA.SAAS.Manage.Application.DataBase.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using NPOI.POIFS.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.DataBase.Services
{
    public class GoodsEnergyConfigService: IGoodsEnergyConfigService, ITransient
    {
        private readonly ISqlSugarClient _db;
        public GoodsEnergyConfigService(ISqlSugarClient db)
        {
            _db = db;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<PageUtil> GetGoodsEnergyConfigPage(GoodsEnergyConfigQueryDto dto)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            //string groupId = App.User.FindFirst(ClaimConst.GroupId)?.Value;
            if (!string.IsNullOrEmpty(dto.Name))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Name", ConditionalType = ConditionalType.Like, FieldValue = dto.Name });
            }
            if (!string.IsNullOrEmpty(dto.GoodsId))
            {
                conModels.Add(new ConditionalModel() { FieldName = "GoodsId", ConditionalType = ConditionalType.Like, FieldValue = dto.GoodsId });
            }
            int total = new RefAsync<int>();
            var res = await _db.Queryable<BPA_GoodsEnergyConfig>()
                .Where(conModels)
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .ToPageListAsync(dto.Current, dto.PageSize, total);
            PageUtil util = new PageUtil()
            {
                Total = total,
                Data = res

            };
            return util;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddGoodsEnergyConfig(GoodsEnergyConfigDto dto)
        {
            try
            {
                _db.Ado.BeginTran();
                var resEntity = _db.Queryable<BPA_GoodsEnergyConfig>().First(it => it.Name == dto.Name && it.GoodsId != dto.GoodsId);
                if (resEntity != null) throw Oops.Oh("配置名称已存在");
                var newType = new BPA_GoodsEnergyConfig
                {
                    GoodsId = dto.GoodsId,
                    Name = dto.Name,
                    Uint = dto.Uint,
                };
                var model = await _db.Insertable(newType).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                List<BPA_GoodsEnergyConfigDetails> list = new();
                for (int i = 0; i < dto.Details.Count; i++)
                {
                    var model1 = new BPA_GoodsEnergyConfigDetails
                    {
                        GoodsenergyconfigId = model.Id,
                        Key = dto.Details[i].Key,
                        Value = dto.Details[i].Value,
                    };
                    list.Add(model1);
                }
                var res = await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return res > 0;
            }
            catch (Exception e)
            {
                _db.Ado.RollbackTran();
                throw Oops.Oh("系统异常，异常信息："+ e.Message);
            }
          
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateGoodsEnergyConfig(GoodsEnergyConfigDto dto)
        {
            try
            {
                _db.Ado.BeginTran();
                // 查询数据库中是否存在未删除的商品类型
                var resEntity = _db.Queryable<BPA_GoodsEnergyConfig>().First(it => it.Id == dto.Id);
                if (null == resEntity) throw Oops.Oh("配置不存在");
                var resEntity1 = _db.Queryable<BPA_GoodsEnergyConfig>().First(it => it.Name == dto.Name && it.Id != dto.Id && it.GoodsId!= dto.GoodsId);
                if (resEntity1 != null) throw Oops.Oh("配置名称已存在");
                resEntity.Name = dto.Name;
                resEntity.Uint = dto.Uint;
                await _db.Updateable(resEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                var model = _db.Queryable<BPA_GoodsEnergyConfigDetails>().Where(it => it.GoodsenergyconfigId == dto.Id).ToList();
                if (model.Count > 0) await _db.Deleteable(model).ExecuteCommandAsync();
                List<BPA_GoodsEnergyConfigDetails> list = new();
                for (int i = 0; i < dto.Details.Count; i++)
                {
                    var model1 = new BPA_GoodsEnergyConfigDetails
                    {
                        GoodsenergyconfigId = dto.Id,
                        Key = dto.Details[i].Key,
                        Value = dto.Details[i].Value,
                    };
                    list.Add(model1);
                }
                var res = await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return res > 0;
            }
            catch (Exception e)
            {
                _db.Ado.RollbackTran();
                throw Oops.Oh("系统异常，异常信息：" + e.Message);
            }
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> DelGoodsEnergyConfig(string Id)
        {
            try
            {
                _db.Ado.BeginTran();
                // 查询数据库中是否存在未删除的商品类型
                var resEntity = _db.Queryable<BPA_GoodsEnergyConfig>().First(it => it.Id == Id);
                if (resEntity == null)
                {
                    throw Oops.Oh("配置不存在");
                }
                var model = _db.Queryable<BPA_GoodsEnergyConfigDetails>().Where(it => it.GoodsenergyconfigId == Id).ToList();
                if (model.Count > 0) await _db.Deleteable(model).ExecuteCommandAsync();
                var res = await _db.Deleteable(resEntity).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return res > 0;
            }
            catch (Exception e)
            {

                _db.Ado.RollbackTran();
                throw Oops.Oh("系统异常，异常信息：" + e.Message);
            }
           
        }
        
        public async Task<List<GoodsEnergyConfigDetailsViewDto>> GetGoodsEnergyConfigDetailsList(string goodsenergyconfigId)
        {

            int total = new RefAsync<int>();
            var res = await _db.Queryable<BPA_GoodsEnergyConfigDetails>()
                .Where(x=>x.GoodsenergyconfigId== goodsenergyconfigId)
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .Select(x => new GoodsEnergyConfigDetailsViewDto() { Id=x.Id,Key=x.Key,Value=x.Value})
                .ToListAsync();
            return res;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddGoodsEnergyConfigDetails(GoodsEnergyConfigDetailsDto dto)
        {
            var resEntity = _db.Queryable<BPA_GoodsEnergyConfigDetails>().First(it => it.Key == dto.Key);
            if(resEntity!=null) throw Oops.Oh("key已存在");
            var newType = new BPA_GoodsEnergyConfigDetails
            {
                GoodsenergyconfigId = dto.GoodsenergyconfigId,
                Key = dto.Key,
                Value = dto.Value,
            };
            var res = await _db.Insertable(newType).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> UpdateGoodsEnergyConfigDetails(GoodsEnergyConfigDetailsDto dto)
        {
            // 查询数据库中是否存在未删除的商品类型
            var resEntity = _db.Queryable<BPA_GoodsEnergyConfigDetails>().First(it => it.Id == dto.Id);
            if (null == resEntity) throw Oops.Oh("配置不存在");
            var resEntity1 = _db.Queryable<BPA_GoodsEnergyConfigDetails>().First(it => it.Key == dto.Key && it.Id != dto.Id);
            if (resEntity1 != null) throw Oops.Oh("配置Key已存在");
            resEntity.Key = dto.Key;
            resEntity.Value = dto.Value;
            var res = await _db.Updateable(resEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> DelGoodsEnergyConfigDetails(string Id)
        {
            // 查询数据库中是否存在未删除的商品类型
            var resEntity = _db.Queryable<BPA_GoodsEnergyConfigDetails>().First(it => it.Id == Id);
            if (resEntity == null)
            {
                throw Oops.Oh("配置不存在");
            }
            var res = await _db.Deleteable(resEntity).ExecuteCommandAsync();
            return res > 0;
        }
    }
}
