using Infrastructure;
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 SqlSugar;

namespace OpenAuth.App.ServiceApp.DroneCloudQuery
{
    public partial class DroneCloudQueryApp : SqlSugarBaseApp<Repository.Domain.DroneCloudQuery, SugarDbContext>
    {
        ISqlSugarClient client;
        private ImMsgApp _immsgApp;
        public DroneCloudQueryApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<Repository.Domain.DroneCloudQuery> repository, ISqlSugarClient sqlSugarClient, IAuth auth, ImMsgApp immsgApp) : base(unitWork, repository, auth)
        {
            client = sqlSugarClient;
            _immsgApp = immsgApp;
        }

        //添加任务
        public Response<bool> AddDroneTask(string geomid, string caseno,string countyNmae)
        {
            var user = _auth.GetCurrentUser().User;
            //初始化查询结果
            Repository.Domain.DroneCloudQuery droneCloudQuery = new Repository.Domain.DroneCloudQuery()
            {
                Id = Guid.NewGuid().ToString(),
                GeomId = geomid,
                CreateTime = DateTime.Now,
                CreateUser = user?.Id.ToString() ?? ""
            };
            DroneCloudTask droneCloudTask = new DroneCloudTask()
            {
                Id = Guid.NewGuid().ToString(),
                GeomId = geomid,
                CreateTime = DateTime.Now,
                CreateUser = user?.Id.ToString() ?? "",
                QueryId = droneCloudQuery.Id,
                CaseNo = caseno,
                CountyName = countyNmae

            };
            //添加数据
            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<DroneCloudTaskResp>> LoadDroneTask()
        {
            //返回值
            var data = await client.Queryable<DroneCloudTask>().Where(r => r.State != 2)
                   .OrderByDescending(a => a.CreateTime).ToListAsync();
            List<int> gids = data.SelectMany(item => item.GeomId.Split(',')
               .Select(id => int.TryParse(id, out var gid) ? gid : (int?)null)
               .Where(gid => gid.HasValue)
               .Select(gid => gid.Value)).ToList();
            var geomData = await client.SqlQueryable<DroneShpDataTaskResp>("SELECT gid,\"Id\",handle_status_id,handle_status_name,is_illegal,is_intact,typename,original_case_no,case_no,ST_AsText(geom) AS geom FROM view_drone_shp_data")
                .Where(r => gids.Contains(r.gid))
                .ToListAsync();
            //获取之后，需要把这些任务标记为正在查询
            foreach (var item in data)
            {
                item.State = 1;
            }
            await client.Updateable<DroneCloudTask>(data).ExecuteCommandAsync();
            return new Response<DroneCloudTaskResp>
            {
                Result = new DroneCloudTaskResp
                {
                    droneCloudTasks = data,
                    droneShpDatas = geomData
                }
            };
        }

        #region 接收查询结果
        public async Task<Response<bool>> UpdateCloudQuery(CloudQueryReq req)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                //查询记录
                var query = uow.DroneCloudQuery.AsQueryable().Where(r => r.Id == req.Id).First();
                var task = client.Queryable<DroneCloudTask>().Where(r => r.QueryId == req.Id).First();

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

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

                var flag = uow.Commit();

                var content = new
                {
                    queryid = req.Id,
                    geomid = task == null ? "" : task.GeomId,
                    caseno = task == null ? "" : task.CaseNo
                };
                var contents = Json.ToJson(content);

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

                //推送数据
                if (flag == true)
                {
                    try
                    {
                        await _immsgApp.SendMsg("CloudQuery", users, contents, "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.DroneCloudQuery>> LoadCloudQueryById(string id)
        {
            //返回值
            var data = await client.Queryable<Repository.Domain.DroneCloudQuery>().Where(r => r.Id == id).FirstAsync();
            return new Response<Repository.Domain.DroneCloudQuery>
            {
                Result = data
            };
        }
        #endregion
       
        /// <summary>
        /// 根据云查询id获取查询结果
        /// </summary>
        /// <param name="id">结果id，消息推送的msg</param>
        /// <returns></returns>
        public async Task<Response<DroneCloudTask>> LoadCloudQueryByCaseNo(string geomId,string caseno)
        {
            //返回值
            var data = await client.Queryable<DroneCloudTask>().Where(r =>r.GeomId== geomId && r.CaseNo==caseno).OrderByDescending(a => a.CreateTime).FirstAsync();
            return new Response<DroneCloudTask>
            {
                Result = data
            };
        }


        /// <summary>
        /// 根据云查询id获取查询结果
        /// </summary>
        /// <param name="id">结果id，消息推送的msg</param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<DroneCloudTask>>>> LoadCloudQueryAll(string geomId, string caseno,int page,int limit)
        {

            RefAsync<int> totalCount = 0;
            //返回值
            var data = await client.Queryable<DroneCloudTask>().WhereIF(!string.IsNullOrEmpty(geomId),r=> r.GeomId == geomId)
                .WhereIF(!string.IsNullOrEmpty(caseno), r => r.CaseNo == caseno).OrderByDescending(a => a.CreateTime).ToPageListAsync(page, limit, totalCount);


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

        }

        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
            };
        }
    }
}