using OpenAuth.App.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using OpenAuth.App.Interface;
using Infrastructure;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Core;
using Oracle.ManagedDataAccess.Types;

namespace OpenAuth.App
{
    public class SysPositionApp : SqlSugarBaseApp<SysPosition, SugarDbContext>
    {
        public SysPositionApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<SysPosition> repository, IAuth auth) : base(unitWork, repository, auth)
        {
        }

        public async Task<Response<SysPosition>> Get(long id)
        {
            var pos = await base.Repository.GetByIdAsync(id);
            return new Response<SysPosition>
            {
                Result = pos,
                Message = "success"
            };
        }

        public async Task<Response<PageInfo<List<SysPosition>>>> Load(QueryPositonListReq req)
        {
            RefAsync<int> totalCount = 0;
            var list = await base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(req.key), p => p.Name.Contains(req.key))
                .WhereIF(req.GroupId != 0, p => p.GroupId == req.GroupId)
                .OrderBy(p => p.Id)
                .ToPageListAsync(req.page, req.limit, totalCount);

            return new Response<PageInfo<List<SysPosition>>>
            {
                Result = new PageInfo<List<SysPosition>>
                {
                    Items = list,
                    Total = totalCount
                }
            };
        }

        public async Task<Response<List<TreeItemLong>>> PositionsTree(long groupId)
        {
            var result = new Response<List<TreeItemLong>>();

            if (groupId != 0)
            {
                object[] posIds = (await base.Repository.AsQueryable()
                    .Where(a => a.GroupId == groupId)
                    .Select(it => it.Id).ToListAsync()).Cast<object>().ToArray();

                result.Result = await base.Repository.AsQueryable()
                                .Select<TreeItemLong>()
                                .ToTreeAsync(a => a.Children, a => a.ParentId, 0, posIds);
            }
            else
            {
                result.Result = await base.Repository.AsQueryable()
                                    .Select<TreeItemLong>()
                                    .ToTreeAsync(a => a.Children, a => a.ParentId, 0, a => a.Id);
            }

            return result;
        }

        public async Task<Response<bool>> Add(SysPosition pos)
        {
            pos.Id = Yitter.IdGenerator.YitIdHelper.NextId();
            var flag = await base.Repository.InsertAsync(pos);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        public async Task<Response<bool>> Update(SysPosition pos)
        {
            var flag = await base.Repository.UpdateAsync(pos);
            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };
        }

        #region 根据部门查询职级
        public async Task<Response<List<TreeItemLong>>> LoadPositionByOrg(long orgid)
        {
            //var list = new List<TreeItemLong>();
            //var org = base.Repository.ChangeRepository<SugarRepositiry<SysOrg>>().AsQueryable()
            //    .Where(r => r.Id == orgid).First();
            //if (org != null)
            //{
            //    list = await base.Repository
            //        .AsQueryable()
            //        .Where(r => r.GroupId == org.PosGroupId)
            //        .OrderBy(r => r.Name)
            //        .Select<TreeItemLong>()
            //        .ToTreeAsync(a => a.Children, a => a.ParentId, 0, a => a.Id);
            //}
            //return new Response<List<TreeItemLong>>
            //{
            //    Result = list
            //};

            var poses = await base.Repository.AsQueryable()
                .LeftJoin<SysPosition>((p1, p2) => p1.ParentId == p2.Id && p2.OrgId == orgid)
                .Where(p1 => p1.OrgId == orgid)
                .Select((p1, p2) => new TreeItemLong
                {
                    Id = p1.Id,
                    ParentId = p2.Id == null ? 0 : p1.ParentId,
                    Name = p1.Name
                }).ToTreeAsync(a => a.Children, a => a.ParentId, 0, a => a.Id);

            return new Response<List<TreeItemLong>>
            {
                Result = poses
            };


        }
        #endregion
    }
}
