using DocumentFormat.OpenXml.Spreadsheet;
using Infrastructure;
using OpenAuth.App.Base.Tree;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Core;
using OpenAuth.Repository.Domain.DataMaintenance;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace OpenAuth.App.ServiceApp.DataMaintenance
{
    /// <summary>
    /// 应用管理
    /// </summary>
    public class ApplicationManagementApp : SqlSugarBaseApp<ApplicationData, SugarDbContext>
    {
        public ApplicationManagementApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<ApplicationData> repository, IAuth auth) : base(unitWork,
        repository,
        auth)
        {
            _auth = auth;
        }
        /// <summary>
        /// 获取应用列表
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<Response<List<ApplicationData>>> GetApplicationList(string name)
        {
            using (var db = UnitWork.CreateContext())
            {
                var user = _auth.GetCurrentUser().User;
                var result = new Response<List<ApplicationData>>();

                // 使用参数化
                var level = await db.Db.Ado.GetIntAsync("select min(\"Level\") from sys_userorg where \"UserId\" = @userId",
                    new { userId = user.Id });

                // 构建基础查询
                var baseQuery = db.ApplicationData.AsQueryable();

                // 根据用户级别过滤数据
                if (level > 0)
                {
                    var orgs = await db.SysUserOrg.AsQueryable()
                        .Where(a => a.UserId == user.Id)
                        .Select(a => a.OrgId)
                        .ToListAsync();

                    var userIds = await db.SysUserOrg.AsQueryable()
                        .Where(a => orgs.Contains(a.OrgId))
                        .Select(a => a.UserId)
                        .ToListAsync();
                    baseQuery = baseQuery.Where(r => userIds.Contains(r.CreateUserId));
                }

                // 应用名称过滤
                if (!string.IsNullOrEmpty(name))
                {
                    baseQuery = baseQuery.Where(a => a.ApplicationName.Contains(name));
                }

                // 执行查询并构建树形结构
                var query = await baseQuery.Select<ApplicationData>().ToListAsync();
                result.Result = UtilMethods.BuildTree(db.Db, query, "Id", "Pid", "Child", 0).ToList();
                return result;
            }
        }
        //添加应用
        public async Task<Response<bool>> Add(ApplicationData app)
        {
            app.Id = YitIdHelper.NextId();
            app.CreateUserId = _auth.GetCurrentUser().User.Id;
            app.CreateTime = DateTime.Now;
            if (await Repository.AsInsertable(app).ExecuteCommandAsync() > 0)
                return new Response<bool> { Result = true };
            else
                return new Response<bool> { Result = false, Message = "添加失败" };
        }
        //编辑应用
        public async Task<Response<bool>> Update(ApplicationData app)
        {
            if (await Repository.AsUpdateable(app).SetColumns(r => new ApplicationData
            {
                ApplicationName = app.ApplicationName,
                ServerId = app.ServerId,
                ServerName = app.ServerName,
                Sort = app.Sort,
                Pid = app.Pid,
            }).ExecuteCommandAsync() > 0)
                return new Response<bool> { Result = true };
            else
                return new Response<bool> { Result = false, Message = "编辑失败" };
        }
        //删除应用
        public async Task<Response<bool>> Delete(long id)
        {
            if (await Repository.AsDeleteable().Where(a => a.Id == id).ExecuteCommandAsync() > 0)
                return new Response<bool> { Result = true };
            else
                return new Response<bool> { Result = false, Message = "删除失败" };
        }
        //获取应用详情
        public async Task<Response<ApplicationData>> Get(long id)
        {
            var result = new Response<ApplicationData>();
            result.Result = await Repository.AsQueryable().FirstAsync(a => a.Id == id);
            return result;
        }
        //获取应用列表
        public async Task<Response<PageInfo<List<ApplicationData>>>> GetList(PageReq req)
        {
            var result = new Response<PageInfo<List<ApplicationData>>>();
            var totalCount = 0;
            var objs = Repository.AsQueryable();
            objs.WhereIF(!string.IsNullOrEmpty(req.key), u => u.ApplicationName.Contains(req.key));
            var data = await objs.OrderByDescending(u => u.CreateTime).ToPageListAsync(req.page, req.limit, totalCount);
            result.Result = new PageInfo<List<ApplicationData>>
            {
                Items = data,
                Total = totalCount
            };
            return result;
        }
    }
}
