using Infrastructure;
using Microsoft.Extensions.Options;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.ShpGeo.Request;
using OpenAuth.App.ServiceApp.ShpGeo.Utils;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.ShpGeo;

public class GeoStyleApp : SqlSugarBaseApp<GeoStyle, SugarDbContext>
{
    private readonly string _filePath;

    public GeoStyleApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<GeoStyle> repository, IAuth auth, IOptions<AppSetting> setOptions) : base(unitWork, repository,
        auth)
    {
        _filePath = setOptions.Value.UploadPath;
        if (string.IsNullOrEmpty(_filePath))
        {
            _filePath = AppContext.BaseDirectory;
        }
    }

    public Response<bool> Add(GeoStyleReq geoStyle)
    {
        // 校验sytleName是否已经存在 
        var isExists = Repository.AsQueryable().Any(c => c.StyleName.Equals(geoStyle.StyleName));
        if (isExists)
        {
            return new Response<bool> { Result = false, Message = "样式名已存在" };
        }

        var record = geoStyle.MapTo<GeoStyle>();
        record.CreateDate = DateTime.Now;
        var sldPath = Path.Combine(_filePath, geoStyle.SldPath);
        var response = GeoUtil.PublishSldStyle(sldPath, geoStyle.StyleName).Result;
        if (!response)
        {
            return new Response<bool> { Result = false, Message = "样式发布失败" };
        }

        record.Id = Guid.NewGuid().ToString();
        var result = Repository.InsertAsync(record).Result;
        return new Response<bool>
        {
            Result = result
        };
    }

    public async Task<Response<PageInfo<List<GeoStyle>>>> Page(GeoStylePageReq req)
    {
        // 分页查询
        RefAsync<int> totalCount = 0;
        var result = Repository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(req.Title), a => a.Title.Contains(req.Title))
            .WhereIF(!string.IsNullOrEmpty(req.StyleName), a => a.StyleName.Contains(req.StyleName))
            .ToPageListAsync(req.page, req.limit, totalCount);

        return new Response<PageInfo<List<GeoStyle>>>
        {
            Result = new PageInfo<List<GeoStyle>>
            {
                Items = await result,
                Total = totalCount
            }
        };
    }

    public Response<bool> BindLayer(string layerName, string styleId)
    {
        var geoStyle = Repository.AsQueryable().Where(a => a.Id == styleId).First();
        if (geoStyle == null)
        {
            return new Response<bool> { Result = false, Message = "样式不存在" };
        }

        var sldPath = Path.Combine(_filePath, geoStyle.SldPath);
        var result = GeoUtil.UpdateSldStyle(sldPath, layerName).Result;
        return new Response<bool>
        {
            Result = result
        };
    }
}