using BPA.SAAS.Manage.Application.DataBase.Interface;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsAttribute;
using StackExchange.Profiling.Internal;
using BPA.SAAS.Manage.Comm.Enum;

namespace BPA.Franchisee.Application.FranchiseeCenter.GoodsServices
{
    public class GoodsAttributeService: IGoodsAttributeService, ITransient
    {
        private readonly ISqlSugarClient _db;
        public GoodsAttributeService(ISqlSugarClient db)
        {
            _db = db;   // 推荐操作
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="dto"></param>m
        /// <returns></returns>
        public PageUtil GetGoodsAttributePageAsync(GoodsAttributeQueryDto dto)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            string groupId = App.User.FindFirst(ClaimConst.GroupId)?.Value;
          
            int total = new RefAsync<int>();

            var res = _db.Queryable<BPA_GoodsAttribute>()
                .Where(a=> a.IsDeleted == 0)
                .WhereIF(!dto.AttributeName.IsNullOrWhiteSpace(),x=>x.AttributeName.Contains(dto.AttributeName))
                .WhereIF(!dto.GoodsTypeId.IsNullOrWhiteSpace(), x => x.GoodsTypeId.Contains(dto.GoodsTypeId))
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .Select(a => new GoodsAttributeView
                {
                    Id = a.Id,
                    AttributeName=a.AttributeName,
                    GoodsTypeId=   a.GoodsTypeId,
                    Sort =a.Sort,
                })
                .Mapper(x =>
                {
                    var list=_db.Queryable<BPA_GoodsAttributeValue>().Where(p=> p.GoodsAttributeId==x.Id).ToList();
                    x.AttributeValueList = list;
                })
                .ToPageList(dto.Current, dto.PageSize, ref total);
            PageUtil util = new PageUtil()
            {
                Total = total,
                Data = res
            };
            return util;
        }
        public async Task<List<GoodsAttributeView>> GetGoodsAttributeList_alm()
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            string groupId = App.HttpContext.Request.Headers["groupId"].ToString();
            if (string.IsNullOrWhiteSpace(groupId)) throw Oops.Oh("加盟商id不能为空");
            var res =await _db.Queryable<BPA_GoodsAttribute>()
                .Where(a => a.GroupId == groupId)
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .Select(a => new GoodsAttributeView
                {
                    Id = a.Id,
                    AttributeName = a.AttributeName,
                    GoodsTypeId = a.GoodsTypeId,
                    Sort = a.Sort,
                })
                .Mapper(x =>
                {
                    var list = _db.Queryable<BPA_GoodsAttributeValue>().Where(p => p.GoodsAttributeId == x.Id).ToList();
                    x.AttributeValueList = list;
                })
                .ToListAsync();
            return res;
        }
        /// <summary>
        /// 添加/修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddGoodsAttribute(GoodsAttributeDto dto)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(dto.Id))
                {
                    _db.Ado.BeginTran();
                    var resEntity = _db.Queryable<BPA_GoodsAttribute>().Where(it => it.IsDeleted == 0).First(it => it.Id == dto.Id);
                    if (null == resEntity)
                    {
                        return false;
                    }
                    resEntity.AttributeName = dto.AttributeName;
                    resEntity.GoodsTypeId = dto.GoodsTypeId;
                    resEntity.Sort = dto.Sort;
                    await _db.Updateable(resEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();

                    var dellist = _db.Queryable<BPA_GoodsAttributeValue>().Where(it => it.GoodsAttributeId == dto.Id).ToList();
                    await _db.Deleteable(dellist).ExecuteCommandAsync(); ;
                    List<BPA_GoodsAttributeValue> list = new();
                    for (int i = 0; i < dto.GoodsAttributeValueList.Count; i++)
                    {
                        BPA_GoodsAttributeValue GoodsAttributeValue = new();
                        GoodsAttributeValue.AttributeValue = dto.GoodsAttributeValueList[i].AttributeValue;
                        GoodsAttributeValue.GoodsAttributeId = dto.Id;
                        GoodsAttributeValue.Sort= dto.GoodsAttributeValueList[i].Sort;
                        list.Add(GoodsAttributeValue);
                    }
                    var res = await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                    _db.Ado.CommitTran();
                    return res > 0;
                }
                else
                {
                    _db.Ado.BeginTran();
                    var newGoodsAttribute = new BPA_GoodsAttribute
                    {
                        AttributeName = dto.AttributeName,
                        GoodsTypeId = dto.GoodsTypeId,
                        Sort = dto.Sort,
                    };
                    var GoodsAttribute = await _db.Insertable(newGoodsAttribute).CallEntityMethod(m => m.Create()).ExecuteReturnEntityAsync();
                    List<BPA_GoodsAttributeValue> list = new();
                    for (int i = 0; i < dto.GoodsAttributeValueList.Count; i++)
                    {
                        BPA_GoodsAttributeValue GoodsAttributeValue = new();
                        GoodsAttributeValue.AttributeValue = dto.GoodsAttributeValueList[i].AttributeValue;
                        GoodsAttributeValue.GoodsAttributeId = GoodsAttribute.Id;
                        GoodsAttributeValue.Sort = dto.GoodsAttributeValueList[i].Sort;
                        list.Add(GoodsAttributeValue);
                    }
                    var res = await _db.Insertable(list).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
                    _db.Ado.CommitTran();
                    return res > 0;
                }
            }
            catch (Exception)
            {
                _db.Ado.RollbackTran();
                throw Oops.Oh("添加失败");
            }
          

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
        public async Task<bool> DeleteGoodsAttribute(string[] Ids)
        {
                // 查询数据库中是否存在未删除的商品
                var resEntitites = _db.Queryable<BPA_GoodsAttribute>().In(Ids).ToList();
                var res =await _db.Deleteable(resEntitites).ExecuteCommandAsync();
                if (res > 0)
                {
                    var resEntititesattr = _db.Queryable<BPA_GoodsAttributeValue>().In("GoodsAttributeId", Ids).ToList();
                    if (resEntititesattr != null)
                    {
                       
                        await _db.Deleteable(resEntititesattr).ExecuteCommandAsync();
                    }
                }
                return res > 0;
          
        }
        /// <summary>
        /// 查询商品属性值列表
        /// </summary>
        /// <param name="goodsAttributeId"></param>
        /// <returns></returns>
        public async Task<List<BPA_GoodsAttributeValue>> GetGoodsAttributeValueAsync(string goodsAttributeId)
        {
            string groupId = App.User.FindFirst(ClaimConst.GroupId)?.Value;

            var res =await _db.Queryable<BPA_GoodsAttributeValue>().Where(x=>x.GoodsAttributeId== goodsAttributeId && x.IsDeleted==0)
               
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .Select(a => new BPA_GoodsAttributeValue
                {
                    Id = a.Id.SelectAll(),
                })
                .ToListAsync();
            return res;
        }
        /// <summary>
        /// 添加/修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddGoodsAttributeValue(List<GoodsAttributeValueDto> dto)
        {
            List<BPA_GoodsAttributeValue> editlist = new();
            List<BPA_GoodsAttributeValue> addlist = new();
            var res = 0;
            for (int i = 0; i < dto.Count; i++)
            {
                Guid newGuid = Guid.Empty;
                if (Guid.TryParse(dto[i].Id, out newGuid))
                {
                    var resEntity = _db.Queryable<BPA_GoodsAttributeValue>().Where(it => it.IsDeleted == 0).First(it => it.Id == dto[i].Id);
                    resEntity.AttributeValue = dto[i].AttributeValue;
                    resEntity.Sort = dto[i].Sort;
                    resEntity.WaiKey= dto[i].WaiKey;
                    editlist.Add(resEntity);
                }
                else
                {
                    var newGoods = new BPA_GoodsAttributeValue
                    {
                        GoodsAttributeId = dto[i].GoodsAttributeId,
                        AttributeValue = dto[i].AttributeValue,
                        Sort = dto[i].Sort,
                        WaiKey = dto[i].WaiKey
                };
                    addlist.Add(newGoods);
                }
            }
            if (editlist.Count > 0)
            {
                 res = await _db.Updateable(editlist).ExecuteCommandAsync();
            }
            if (addlist.Count > 0)
            {
                 res = await _db.Insertable(addlist).CallEntityMethod(m => m.Create()).ExecuteCommandAsync();
            }
            return res > 0;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteGoodsAttributeValue(string id)
        {
         
                // 查询数据库中是否存在未删除的商品
                var resEntitites = _db.Queryable<BPA_GoodsAttributeValue>().In(id).ToList();
                var res =await _db.Deleteable(resEntitites).ExecuteCommandAsync();
                if (res > 0)
                {

                    //1.查询上架商品
                    //2.删除上架商品
                }
                return res > 0;
           
        }
        /// <summary>
        /// 根据商品id查询商品属性
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<List<GoodsAttributeList>> GetByGoodsIdAttribute(string id)
        {
            var goods=await _db.Queryable<BPA_GoodsInfo>().Where(x => x.Id == id).FirstAsync();
            if (goods == null) throw Oops.Oh("商品不存在");
            var goodsAttributeList = await _db.Queryable<BPA_GoodsAttribute>().Where(x => x.GoodsTypeId.Contains( goods.GoodsTypeId) && x.IsDeleted == 0)
                .Select(x=>new GoodsAttributeList()
                {
                    GoodsAttributeId=x.Id,
                    AttributeName=x.AttributeName,
                    GoodsTypeId=goods.GoodsTypeId,
                    Sort=x.Sort,
                }).Mapper(p =>
                {
                    p.GoodsAttributeValueList = _db.Queryable<BPA_GoodsAttributeValue>().Where(x => x.GoodsAttributeId == p.GoodsAttributeId && x.IsDeleted==0).Select(x => new GoodsAttributeValueList()
                    {
                        GoodsAttributeValuId = x.Id,
                        GoodsAttributeId = p.GoodsAttributeId,
                        AttributeValue = x.AttributeValue,
                        Sort = x.Sort
                    }).ToList();
                })
                .OrderBy(x=>x.Sort,OrderByType.Asc)
                .ToListAsync();
            return goodsAttributeList;
        }
        public async Task<List<GoodsAttributeList>> GetByNameAttribute(string  name)
        {
            //var goods = await _db.Queryable<BPA_GoodsInfo>().Where(x => x.Id == id).FirstAsync();
            //if (goods == null) throw Oops.Oh("商品不存在");
            var goodsAttributeList = await _db.Queryable<BPA_GoodsAttribute>().Where(x => x.AttributeName== name && x.IsDeleted == 0)
                .Select(x => new GoodsAttributeList()
                {
                    GoodsAttributeId = x.Id,
                    AttributeName = x.AttributeName,
                    //GoodsTypeId = goods.Goods_TypeID,
                    Sort = x.Sort,
                }).Mapper(p =>
                {
                    p.GoodsAttributeValueList = _db.Queryable<BPA_GoodsAttributeValue>().Where(x => x.GoodsAttributeId == p.GoodsAttributeId && x.IsDeleted == 0).Select(x => new GoodsAttributeValueList()
                    {
                        GoodsAttributeValuId = x.Id,
                        GoodsAttributeId = p.GoodsAttributeId,
                        AttributeValue = x.AttributeValue,
                        Sort = x.Sort
                    }).ToList();
                })
                .OrderBy(x => x.Sort, OrderByType.Asc)
                .ToListAsync();
            return goodsAttributeList;
        }
        
    }
}
