using Infrastructure;
using Infrastructure.Extensions;
using Infrastructure.Helpers;
using OpenAuth.App.Base;
using OpenAuth.App.BaseApp;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.DroneCloudQueryManage.Request;
using OpenAuth.App.ServiceApp.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Ocsp;
using SqlSugar;

namespace OpenAuth.App.ServiceApp.DroneCloudQuery
{
    public partial class DroneCloudLandQueryApp : SqlSugarBaseApp<Repository.Domain.DroneCloudLandQuery, SugarDbContext>
    {
        ISqlSugarClient client;
        private ImMsgApp _immsgApp;

        public DroneCloudLandQueryApp(ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<Repository.Domain.DroneCloudLandQuery> repository, ISqlSugarClient sqlSugarClient, IAuth auth,
            ImMsgApp immsgApp) : base(unitWork, repository, auth)
        {
            client = sqlSugarClient;
            _immsgApp = immsgApp;
        }

        //添加任务
        public Response<bool> AddDroneTask(string geomData, string caseid, string code, string name)
        {
            var user = _auth.GetCurrentUser().User;
            //初始化查询结果
            Repository.Domain.DroneCloudLandQuery droneCloudQuery = new Repository.Domain.DroneCloudLandQuery()
            {
                Id = Guid.NewGuid().ToString(),
                name = name,
                CreateTime = DateTime.Now,
                CreateUser = user?.Id.ToString() ?? "",
                caseid = caseid
            };
            DroneCloudLandTask droneCloudTask = new DroneCloudLandTask()
            {
                Id = Guid.NewGuid().ToString(),
                GeomData = geomData,
                CreateTime = DateTime.Now,
                CreateUser = user?.Id.ToString() ?? "",
                QueryId = droneCloudQuery.Id,
                code = code,
                name = name,
                caseid = caseid
            };
            //添加数据
            var flag = client.Ado.UseTran(() =>
            {
                client.Insertable(droneCloudQuery).ExecuteCommand();
                client.Insertable(droneCloudTask).ExecuteCommand();
            });
            if (flag.IsSuccess)
            {
                return new Response<bool> { Result = true };
            }
            else
            {
                return new Response<bool> { Result = false, Message = "操作失败" };
            }
        }

        public async Task<Response<List<DroneCloudLandTask>>> DroneCloudLandTask()
        {
            //返回值
            var data = await client.Queryable<DroneCloudLandTask>().Where(r => r.State != 2)
                .OrderByDescending(a => a.CreateTime).ToListAsync();

            //获取之后，需要把这些任务标记为正在查询
            foreach (var item in data)
            {
                item.State = 1;
            }

            await client.Updateable<DroneCloudLandTask>(data).ExecuteCommandAsync();
            return new Response<List<DroneCloudLandTask>>
            {
                Result = data
            };
        }

        #region 接收查询结果

        public async Task<Response<bool>> UpdateCloudLandQuery(CloudQueryReq req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                //查询记录
                var query = uow.DroneCloudLandQuery.AsQueryable().Where(r => r.Id == req.Id).First();

                //更新记录
                await uow.DroneCloudLandQuery.UpdateAsync(u => new Repository.Domain.DroneCloudLandQuery
                {
                    ReceiveContent = req.ReceiveContent,
                    ReceiveTime = req.ReceiveTime
                }, u => u.Id == req.Id);

                //更新任务状态
                await uow.DroneCloudLandTask.UpdateAsync(u => new Repository.Domain.DroneCloudLandTask
                {
                    State = 2,
                }, u => u.QueryId == req.Id);

                var flag = uow.Commit();

                //添加推送数据的用户
                List<string> users = new List<string>();
                if (query != null)
                {
                    users.Add(query.CreateUser);
                }

                //推送数据
                if (flag == true)
                {
                    try
                    {
                        await _immsgApp.SendMsg("CloudLandQuery", users, req.Id, "4", req.Id);
                    }
                    catch
                    {
                        return new Response<bool>
                        {
                            Result = flag,
                            Message = "数据存储成功，推送失败"
                        };
                    }
                }

                //返回值
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "接收数据成功" : "接收数据失败"
                };
            }
        }

        #endregion

        #region 查询云查询结果

        /// <summary>
        /// 根据云查询id获取查询结果
        /// </summary>
        /// <param name="id">结果id，消息推送的msg</param>
        /// <returns></returns>
        public async Task<Response<Repository.Domain.DroneCloudLandQuery>> LoadCloudQueryById(string id)
        {
            //返回值
            var data = await client.Queryable<Repository.Domain.DroneCloudLandQuery>().Where(r => r.Id == id)
                .FirstAsync();
            return new Response<Repository.Domain.DroneCloudLandQuery>
            {
                Result = data
            };
        }

        #endregion

        public Response<bool> AddOrUpdateDroneLandType(AddOrUpdateDroneLandType req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                //查询记录
                int query = uow.DroneLandType.AsQueryable().ToList().Count;

                if (query == req.count)
                {
                    return new Response<bool>
                    {
                        Result = true,
                        Message = "接收数据成功"
                    };
                }

                var list = req.landList;
                for (int i = 0; i < list.Count; i++)
                {
                    var land = list[i];
                    var one = uow.DroneLandType.AsQueryable().Where(r => r.id == land.id).First();
                    if (one != null)
                    {
                        uow.DroneLandType.Update(u => new Repository.Domain.DroneLandType
                        {
                            name = land.name,
                        }, u => u.id == land.id);
                    }
                    else
                    {
                        uow.DroneLandType.Insert(new Repository.Domain.DroneLandType
                        {
                            id = land.id,
                            name = land.name,
                        });
                    }
                }

                var flag = uow.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "接收数据成功" : "接收数据失败"
                };
            }
        }

        public async Task<Response<List<dynamic>>> getLandType()
        {
            string sql = $"select id,name from drone_land_type";
            //返回值
            var data = await client.Ado.SqlQueryAsync<dynamic>(sql);
            return new Response<List<dynamic>>
            {
                Result = data
            };
        }

        public async Task<Response<bool>> IsPublic()
        {
            var config = ConfigHelper.GetConfigRoot();
            return new Response<bool>
            {
                Result = config["IsPublic"].ToBool()
            };
        }
    }
}