using Infrastructure;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.Algo.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.Algo;

public class AlgoInstanceServiceApp : SqlSugarBaseApp<LasaAlgoInstance, SugarDbContext>
{
    public AlgoInstanceServiceApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<LasaAlgoInstance> repository, IAuth auth) : base(unitWork, repository, auth)
    {
    }

    public async Task<Response<bool>> AddAlgoInstance(LasaAlgoInstance info)
    {
        info.Id = Guid.NewGuid().ToString();
        if (await Repository.InsertAsync(info))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "添加成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "添加失败"
        };
    }

    public async Task<Response<bool>> DeleteAlgoInstance(string id)
    {
        if (await Repository.DeleteByIdAsync(id))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "删除成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "删除失败"
        };
    }

    public async Task<Response<bool>> UpdateAlgoInstance(LasaAlgoInstance info)
    {
        // todo 关于会更新空值问题
        if (await Repository.UpdateAsync(info))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "修改成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "修改失败"
        };
    }

    public async Task<Response<PageInfo<IEnumerable<dynamic>>>> GetAlgoInstanceList(AlgoInstancePageRequest req)
    {
        RefAsync<int> totalCount = 0;
        var page = await Repository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(req.key), x => x.Name.Contains(req.key))
            .ToPageListAsync(req.page, req.limit, totalCount);

        if (page != null && page.Count > 0)
        {
            var ids = page.Select(x => x.Id).ToList();
            var sql = @$"SELECT
	            a.""Id"" as ""algoInstanceId"",
	            l.""Name"" as ""TagName"",
	            r.""Name"" as ""AlgoName"" 
                FROM
	            lasa_algoinstance a
	            CROSS JOIN LATERAL UNNEST ( string_to_array( A.""Tags"", ',' ) ) AS TempB ( Tag )
	            left join lasa_modellabel l on l.""Id"" = TempB.Tag
	            left join lasa_algorithmsrepository r on r.""Id"" = l.""PId"" 
                 WHERE
	            a.""Id"" in ( {string.Join(",", ids.Select(id => $"'{id}'"))} )
               ";
            var infos = await Repository.AsSugarClient().SqlQueryable<dynamic>(sql)
                .ToListAsync();
            var result = page.Select(x => new
            {
                x.Id,
                x.Name,
                x.Cover,
                x.DisplayScheme,
                x.Description,
                x.DisplayColor,
                x.RecognitionX,
                x.RecognitionY,
                x.SpaceConstraint,
                x.ExpansionDistance,
                x.TemporalConstraints,
                x.TcStartTime,
                x.TcEndTime,
                x.FlySpeed,
                x.GimbalPitchDegree,
                x.RecognitionCoverage,
                x.Tags,
                x.AlgoIds,
                TagNames = infos.Where(y => y.algoInstanceId == x.Id).Select(y => y.TagName).ToArray(),
                AlgoNames = infos.Where(y => y.algoInstanceId == x.Id).Select(y => y.AlgoName).ToList()
            });

            return new Response<PageInfo<IEnumerable<dynamic>>>
            {
                Result = new PageInfo<IEnumerable<dynamic>>
                {
                    Items = result,
                    Total = totalCount.Value
                }
            };
        }
        else 
        {
            return  new Response<PageInfo<IEnumerable<dynamic>>>
            {
                Result = new PageInfo<IEnumerable<dynamic>>
                {
                    Items = null,
                    Total = 0
                }
            };
        }
        
       
    }

    public async Task<Response<LasaAlgoInstance>> GetAlgoInstance(string id)
    {
        // 关于添加算法及标签信息
        return new Response<LasaAlgoInstance>
        {
            Result = await Repository.GetByIdAsync(id)
        };
    }
}