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

namespace OpenAuth.App.ServiceApp.DroneCloudQuery;

public class DroneCloudQueryContentApp : SqlSugarBaseApp<DroneCloudQueryContent, SugarDbContext>
{
    ISqlSugarClient client;


    public DroneCloudQueryContentApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<DroneCloudQueryContent> repository, ISqlSugarClient sqlSugarClient, IAuth auth) : base(
        unitWork, repository, auth)
    {
        client = sqlSugarClient;
    }

    public async Task<Response<PageInfo<List<DroneCloudQueryContent>>>> LoadPage(DroneCloudQueryContentReq req)
    {
        RefAsync<int> totalCount = 0;
        var sources = await base.Repository.AsQueryable()
            .WhereIF(req.Code != null, a => a.Code == req.Code)
            .WhereIF(req.key != null, a => a.Name.Contains(req.key))
            .WhereIF(req.StartTime != null && req.EndTime != null,
                a => a.CreateTime >= req.StartTime && a.CreateTime <= req.EndTime)
            .ToPageListAsync(req.page, req.limit, totalCount);

        foreach (var droneCloudQueryContent in sources)
        {
            droneCloudQueryContent.OverlayList = droneCloudQueryContent.Overlay.Split(",").ToList();
        }

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

    public DroneCloudQueryContent Get(string id)
    {
        var result = Repository.GetById(id);
        result.OverlayList = result.Overlay.Split(",").ToList();
        return result;
    }

    public void Add(AddOrUpdateCloudQueryContentReq req)
    {
        var obj = req.MapTo<DroneCloudQueryContent>();
        obj.Overlay = String.Join(",", req.OverlayList);
        obj.CountyName = String.Join(",", req.CountyNameList);
        obj.Id = Guid.NewGuid().ToString();
        obj.CreateTime = DateTime.Now;
        var user = _auth.GetCurrentUser().User;
        obj.CreateUser = user.Id + "";
        obj.CreateUser = user.Name;
        Repository.Insert(obj);
    }

    public void Update(AddOrUpdateCloudQueryContentReq req)
    {
        var obj = req.MapTo<DroneCloudQueryContent>();
        obj.Overlay = String.Join(",", req.OverlayList);
        obj.CountyName = String.Join(",", req.CountyNameList);
        using var db = Repository.AsSugarClient();
        db.Updateable(obj).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
    }

    public void Delete(string id)
    {
        Repository.DeleteById(id);
    }
}