using BPA.SAAS.Manage.Application.DataBase.Dtos.GoodsType;
using BPA.SAAS.Manage.Application.DataBase.Interface;
using BPA.SAAS.Manage.Application.Org.Dtos.Organize;
using BPA.SAAS.Manage.Application.Org.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Comm.Util;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.DataBase;
using BPA.SAAS.Manage.Core.Org;
using Furion.LinqBuilder;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.DataBase.Services
{
    public class GoodsTypeService: IGoodsTypeService, ITransient
    {
        private readonly ISqlSugarClient _db;
        public GoodsTypeService(ISqlSugarClient db)
        {
            _db= db;
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<PageUtil> GetGoodsTypePage(GoodsTypeQueryDto 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.Status))
            {
                conModels.Add(new ConditionalModel() { FieldName = "Status", ConditionalType = ConditionalType.Equal, FieldValue = dto.Status });
            }
           
            int total = new RefAsync<int>();
            var res =await _db.Queryable<BPA_GoodsType>()
                .Where(conModels)
                .OrderBy(a => a.CreateAt, OrderByType.Desc)
                .Select(it => new GoodsTypeTree() { Id = it.Id, Name = it.Name, Pid = it.Pid,Sort=it.Sort,Remark=it.Remark,Status=it.Status }).ToTreeAsync(it => it.Children, it => it.Pid, 0);
            //.ToPageList(dto.Current, dto.PageSize, ref total);
            List<GoodsTypeTree> list = new();
            if (res != null)
            {
                list = res.Skip((dto.Current - 1) * dto.PageSize).Take(dto.PageSize).ToList();
            }
        PageUtil util = new PageUtil()
            {
                Total = res==null?0:res.Count,
                Data = list

        };
            return util;
        }
        /// <summary>
        /// 添加商品类型
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<bool> AddGoodsType(GoodsTypeDto dto)
        {
            var newType = new BPA_GoodsType
            {
                Pid = string.IsNullOrEmpty(dto.Pid)?"0": dto.Pid,
                Name = dto.Name,
                Remark = dto.Remark,
                Sort = dto.Sort,
                Status = CommonStatus.ENABLE,
            };
            if (string.IsNullOrWhiteSpace(dto.Pid))
            {
                newType.Pid = "0";
            }
            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> UpdateGoodsType(GoodsTypeDto dto)
        {
            // 查询数据库中是否存在未删除的商品类型
                var resEntity = _db.Queryable<BPA_GoodsType>().First(it => it.Id == dto.Id);
                if (null == resEntity)
                {
                    return false;
                }

                resEntity.Name = dto.Name;
                resEntity.Pid =string.IsNullOrEmpty(dto.Pid)?"0": dto.Pid;
                resEntity.Sort = dto.Sort;
                resEntity.Remark = dto.Remark;
            
                resEntity.Status = (CommonStatus)Enum.ToObject(typeof(CommonStatus), dto.Status);
            
            var res =await _db.Updateable(resEntity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            return res > 0;
        }
        public async Task<List<dynamic>> GetGoodsTypeList_alm()
        {
            var groupId = App.HttpContext.Request.Headers["groupId"].ToString();
            if (string.IsNullOrWhiteSpace(groupId)) throw Oops.Oh("加盟商id不能为空");
            var res = await _db.Queryable<BPA_GoodsType>().Where(x => x.GroupId == groupId).Select<dynamic>(x => new

            {
                id = x.Id,
                name = x.Name,
                pid= x.Pid,
            }).ToListAsync();
            return res;
        }
        /// <summary>
        /// 删除商品类型
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> DelGoodsType(string Id)
        {
            // 查询数据库中是否存在未删除的商品类型
            var check = _db.Queryable<BPA_GoodsInfo>().Any(it => it.GoodsTypeId == Id);
            if (check)
            {
                throw Oops.Oh("该类已经使用无法删除");
            }
            var resEntity = _db.Queryable<BPA_GoodsType>().First(it => it.Id == Id);
            var res =await _db.Deleteable(resEntity).ExecuteCommandAsync();
            return res > 0;
        }
        /// <summary>
        /// 查询商品类型树结构
        /// </summary>
        /// <returns></returns>
        public async Task<dynamic> GetGoodsTypeTree()
        {
            var dataScopeList = new List<string>();
            var groupId = App.User?.FindFirst(ClaimConst.GroupId)?.Value;
            var orgs = await _db.Queryable<BPA_GoodsType>().WhereIF(dataScopeList.Count > 0, u => dataScopeList.Contains(u.Id))
                                                        .Where(u => u.Status == CommonStatus.ENABLE && u.IsDeleted==0 && u.GroupId == groupId).OrderBy(u => u.Sort)
                                                        .Select(u => new OrgTreeNode
                                                        {
                                                            key = u.Id,
                                                            parentId = u.Pid,
                                                            title = u.Name,
                                                            value = u.Id.ToString(),
                                                            weight = u.Sort,
                                                            Type = 0,
                                                        }).ToListAsync();

            return new TreeBuildUtil<OrgTreeNode>().Build(orgs);

        }
    }
}
