using System.Globalization;
using Infrastructure;
using Infrastructure.Helpers;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.Achievement.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.Achievement;

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

    public async Task<PageInfo<List<InsAishp>>> Load(InsAishpQuery req)
    {
        RefAsync<int> total = 0;
        var result = await Repository.AsQueryable()
            .WhereIF(req.StartTime != null, p => p.ShpDate >= req.StartTime)
            .WhereIF(req.EndTime != null, p => p.ShpDate <= req.EndTime)
            .WhereIF(!string.IsNullOrEmpty(req.Name), p => p.ShpName.Contains(req.Name))
            .ToPageListAsync(req.page, req.limit, total);
        return new PageInfo<List<InsAishp>>
        {
            Items = result,
            Total = total
        };
    }

    public async Task<Response<bool>> Update()
    {
        // 获取待扫描目录
        var shpDir = ConfigHelper.GetConfigRoot().GetSection("Insight:AiShpDir").Value;
        Console.Write("shpDir:" + shpDir);
        // todo 扫描shp文件
        try
        {
            // 搜索 .shp 后缀的文件，忽略大小写
            var shpFiles = Directory.GetFiles(shpDir, "*.shp", SearchOption.AllDirectories);

            if (shpFiles.Length == 0)
            {
                throw new Exception("未找到任何 .shp 文件。");
            }

            Console.WriteLine("找到的 .shp 文件：");
            foreach (string file in shpFiles)
            {
                // 校验shp是否完整
                if (!ShpUtil.CheckShpFileIntegrity(file))
                {
                    Console.WriteLine($"文件 {file} 缺少必需文件。");
                    continue;
                }

                Console.WriteLine($"shp文件 {file} 完整。");
                // 县区/shp名称
                var fileName = Path.GetFileName(file);
                var dateStr = fileName.Substring(0, 6);
                var date = DateTime.ParseExact(dateStr, "yyMMdd", null);
                var areaName = new DirectoryInfo(file).Parent?.Parent?.Name;
                var shpInfo = ShpUtil.GetShpInfo(file);
                var insAishp = new InsAishp();
                var currentTime = DateTime.Now;
                insAishp.Id = Guid.NewGuid().ToString();
                insAishp.ShpPath = file;
                insAishp.ShpName = fileName;
                insAishp.ShpDate = date;
                // 面积
                insAishp.AreaNum = 0;
                insAishp.PlotName = "地块名称";
                insAishp.AreaId = "areaId";
                // 地区名称
                insAishp.AreaName = areaName;
                // 包含图斑数量
                insAishp.ShpCount = shpInfo.GetType().GetProperty("Count").GetValue(shpInfo);
                ;
                insAishp.CreateTime = currentTime;
                insAishp.UpdateTime = currentTime;
                insAishp.Remark = "备注";
                await Repository.InsertAsync(insAishp);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误：{ex.Message}");
        }

        // 获取区县、日期目录 
        // 
        // 解析数据
        //
        return new Response<bool>() { Result = true };
    }

    public async Task<Response<InsAishp>> GetAiShp(string id)
    {
        return new Response<InsAishp>() { Result = await Repository.GetByIdAsync(id) };
    }

    public async Task<Response<bool>> Insert(List<InsAiShpInsert> req)
    {
        var aiShpList = req.MapToList<InsAishp>();
        var removeList = new List<InsAishp>();
        foreach (var shp in aiShpList)
        {
            shp.Id = Guid.NewGuid().ToString();
            shp.CreateTime = DateTime.Now;
            shp.UpdateTime = DateTime.Now;
            // 重复判定
            if (await Repository.CountAsync(a => a.ShpPath == shp.ShpPath) > 0)
            {
                removeList.Add(shp);
            }
        }

        aiShpList.RemoveAll(a => removeList.Contains(a));
        await Repository.InsertRangeAsync(aiShpList);
        return new Response<bool>
        {
            Result = true
        };
    }
}