using Infrastructure;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OpenAuth.App
{
    public class IdleLandApp : SqlSugarBaseApp<IdleLand, SugarDbContext>
    {
        ISqlSugarClient client;
        public IdleLandApp(ISqlSugarClient sqlSugarClient, ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<IdleLand> repository,
            IAuth auth) : base(unitWork, repository, auth)
        {
            client = sqlSugarClient;
        }


        #region 查询
        /// <summary>
        /// 分页
        /// </summary>
        public async Task<Response<PageInfo<List<IdleLand>>>> LoadPage(PageReq request)
        {
            RefAsync<int> totalCount = 0;
            var result = new PageInfo<IdleLand>();
            var list = await base.Repository.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(request.key), a => a.SerialNumber.Contains(request.key))
                .ToPageListAsync(request.page, request.limit, totalCount);

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


        /// <summary>
        /// 详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IdleLand> Detail(string id)
        {
            return await Repository.GetByIdAsync(id);
        }
        #endregion

        public byte[] VectorTile(VectorTileSearchModel req)
        {
            req.Init();

            List<double> lons = CommonDataManager.getLon(req.x, req.z);
            List<double> lats = CommonDataManager.getLat(req.y, req.z);
            double lonmin = lons[0];
            double lonmax = lons[1];
            double latmin = lats[1];
            double latmax = lats[0];

            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(
                $"SELECT ST_AsMVT(tile, '{req.source_layer}', 4096, 'geom') tile FROM (" +
                $"SELECT {req.field} ST_AsMVTGeom(ST_GeomFromText(\"Geom\", 4326), ST_Transform(ST_MakeEnvelope({lonmin},{latmin},{lonmax},{latmax}, 4326),4326),4096, 256, true) AS geom " +
                $"FROM public.{req.table} where {req.filter} ) AS tile");

            var aaa = sql.ToString();

            var dataTable = client.Ado.GetDataTable(sql.ToString());
            byte[] result = (Byte[])dataTable.Rows[0]["tile"];
            return result;
        }
    }
}
