using DocumentFormat.OpenXml.EMMA;
using Infrastructure;
using Infrastructure.CloudSdk.minio;
using Infrastructure.Extensions;
using Microsoft.AspNetCore.Http;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.Response;
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.ServiceApp
{
    public class AlgorithmsRepositoryApp : SqlSugarBaseApp<LasaAlgorithmsRepository, SugarDbContext>
    {
        public AlgorithmsRepositoryApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<LasaAlgorithmsRepository> repository, IAuth auth) : base(unitWork, repository, auth)
        {
        }
        #region 算法库管理
        //添加算法库
        public async Task<Response<bool>> AddAlgorithmsRepository(LasaAlgorithmsRepository info)
        {
            using (var db = UnitWork.CreateContext())
            {
                info.Id = Guid.NewGuid().ToString();
                await db.LasaAlgorithmsRepository.InsertAsync(info);
                foreach (var item in info.ModelLabels)
                {
                    item.Id = Guid.NewGuid().ToString();
                    item.PId = info.Id;
                }
                await db.LasaModelLabel.InsertRangeAsync(info.ModelLabels);
                if (db.Commit())
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "添加成功"
                    };
                else
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "添加失败"
                    };
            }
        }
        //修改算法库
        public async Task<Response<bool>> UpdateAlgorithmsRepository(LasaAlgorithmsRepository info)
        {
            using (var db = UnitWork.CreateContext())
            {
                // 更新主表
                await db.LasaAlgorithmsRepository.UpdateAsync(info);
                var modelLabelsInDb = db.LasaModelLabel.AsQueryable()
                    .Where(r => r.PId == info.Id)
                    .ToList();

                var newModelLabels = info.ModelLabels ?? new List<LasaModelLabel>();
                var toDelete = modelLabelsInDb
                    .Where(dbItem => !newModelLabels.Any(newItem => newItem.Id == dbItem.Id))
                    .ToList();

                if (toDelete.Any())
                {
                    await db.LasaModelLabel.DeleteAsync(toDelete);
                }
                var toAdd = new List<LasaModelLabel>();
                var toUpdate = new List<LasaModelLabel>();

                foreach (var newItem in newModelLabels)
                {
                    newItem.PId = info.Id;
                    if (string.IsNullOrEmpty(newItem.Id) || !modelLabelsInDb.Any(dbItem => dbItem.Id == newItem.Id))
                    {
                        // 新增
                        newItem.Id = Guid.NewGuid().ToString();
                        toAdd.Add(newItem);
                    }
                    else
                    {
                        // 更新
                        toUpdate.Add(newItem);
                    }
                }

                if (toAdd.Any())
                    await db.LasaModelLabel.InsertRangeAsync(toAdd);

                if (toUpdate.Any())
                    await db.LasaModelLabel.UpdateRangeAsync(toUpdate);

                // 提交事务
                if (db.Commit())
                {
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "修改成功"
                    };
                }
                else
                {
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "修改失败"
                    };
                }
            }
        }
        //删除算法库
        public async Task<Response<bool>> DeleteAlgorithmsRepository(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                await db.LasaAlgorithmsRepository.DeleteByIdAsync(id);
                await db.LasaModelLabel.DeleteAsync(r => r.PId == id);
                if (db.Commit())
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "删除成功"
                    };
                else
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "删除失败"
                    };
            }
        }
        /// <summary>
        /// 分页获取所有数据 
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<LasaAlgorithmsRepository>>>> GetPageList(int page, int limit, string key)
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var list = await db.LasaAlgorithmsRepository.AsQueryable().Includes(a => a.ModelLabels)
                    .WhereIF(!string.IsNullOrEmpty(key), a => a.Name.Contains(key))
                    .ToPageListAsync(page, limit, totalCount);
                return new Response<PageInfo<List<LasaAlgorithmsRepository>>>
                {
                    Result = new PageInfo<List<LasaAlgorithmsRepository>> { Items = list, Total = totalCount }
                };
            }
        }
        #endregion

        #region 变化检测
        /// <summary>
        /// 分页获取所有变化检测
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<Lasa_ChangeDetection>>>> GetChangeDetectionPageList(int page, int limit, string key, DateTime startTime, DateTime endTime)
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var list = await db.Lasa_ChangeDetection.AsQueryable()
                    .WhereIF(!string.IsNullOrEmpty(key), a => a.Title.Contains(key))
                    .WhereIF(!"0001/1/1 0:00:00".Equal(startTime.ToString()), a => a.CreateTime >= startTime && a.CreateTime <= endTime)
                    .OrderByDescending(a => a.CreateTime)
                    .ToPageListAsync(page, limit, totalCount);
                return new Response<PageInfo<List<Lasa_ChangeDetection>>>
                {
                    Result = new PageInfo<List<Lasa_ChangeDetection>> { Items = list, Total = totalCount }
                };
            }
        }
        public async Task<Response<string>> AddChangeDetection(Lasa_ChangeDetection info)
        {
            using (var db = UnitWork.CreateContext())
            {
                info.Id = Guid.NewGuid().ToString();
                info.CreateTime = DateTime.Now;
                await db.Lasa_ChangeDetection.InsertAsync(info);
                if (db.Commit())
                    return new Response<string>
                    {
                        Result = info.Id,
                        Message = "添加成功"
                    };
                else
                    return new Response<string>
                    {
                        Result = info.Id,
                        Message = "添加失败"
                    };
            }
        }
        //删除
        public async Task<Response<bool>> DeleteChangeDetection(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                await db.Lasa_ChangeDetection.DeleteByIdAsync(id);
                if (db.Commit())
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "删除成功"
                    };
                else
                    return new Response<bool>
                    {
                        Result = false,
                        Message = "删除失败"
                    };
            }
        }
        public async Task<Response<ChangeDetectionResp>> GetChangeDetectionById(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                ChangeDetectionResp changeDetectionResp = new ChangeDetectionResp();
                var info = await db.Lasa_ChangeDetection.GetByIdAsync(id);
                if (info != null)
                {
                    changeDetectionResp = info.MapTo<ChangeDetectionResp>();
                    changeDetectionResp.AiAchievementDetailList = await db.LasaAiAchievementDetail.AsQueryable().Where(r => r.AiAchievementId == info.AiAchievementId).ToListAsync();
                }
                return new Response<ChangeDetectionResp>
                {
                    Result = changeDetectionResp,
                    Message = "获取数据成功"
                };
            }
        }
        #endregion
    }
}
