
using DocumentFormat.OpenXml.Bibliography;
using Infrastructure;
using Newtonsoft.Json.Linq;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using SqlSugar.Extensions;
using System.Text;

namespace OpenAuth.App
{
    public class MiMinePointApp : SqlSugarBaseApp<MiMinePoint, SugarDbContext>
    {
        public MiMinePointApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<MiMinePoint> repository,
            IAuth auth
            ) : base(unitWork, repository, auth)
        {

        }

        #region 查询
        /// <summary>
        /// 分页
        /// </summary>
        public async Task<Response<PageInfo<List<MiMinePoint>>>> LoadAllPage(PageReq request)
        {
            RefAsync<int> totalCount = 0;
            var result = new PageInfo<SysRole>();
            var list = await base.Repository.AsQueryable()
                .Where(r => r.IsClose == false)
                .WhereIF(!string.IsNullOrEmpty(request.key), r => r.Name.Contains(request.key))
                .OrderByDescending(r => r.CreateTime)
                .ToPageListAsync(request.page, request.limit, totalCount);

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

        public async Task<MiMinePoint> Get(string id)
        {
            return await base.Repository.GetByIdAsync(id);
        }


        /// <summary>
        /// 添加
        /// </summary>
        public async Task<Response<bool>> Add(MiMinePoint model)
        {
            var user = _auth.GetCurrentUser().User;
            using (var uow = base.UnitWork.CreateContext())
            {
                MiMinePoint point = model.MapTo<MiMinePoint>();
                point.Id = Guid.NewGuid().ToString();
                point.CreateTime = DateTime.Now;
                point.IsDelete = false;
                point.geom = null;
                point.IsClose = false;
                point.CreateUserId = user.Id.ToString();

                if (!string.IsNullOrEmpty(model.geom))
                {
                    string _wktModel = model.geom;
                    JObject xzqh = GetOrgAreaByPoint(_wktModel);
                    var cc = (string)xzqh["countyid"];
                    point.CountyId = xzqh["countyid"].ToString();
                    point.CountyName = xzqh["countyname"].ToString();
                    point.StreetId = xzqh["streetid"].ToString();
                    point.StreetName = xzqh["streetname"].ToString();
                    point.CommunityId = xzqh["communityid"].ToString();
                    point.CommunityName = xzqh["communityname"].ToString();
                    //oint = cinfo.countyname + " " + cinfo.streetname + " " + cinfo.communityname;
                    var flag = await uow.MiMinePoint.InsertAsync(point);

                    StringBuilder geomSql = new StringBuilder();
                    geomSql.AppendFormat(
                        $"UPDATE mi_mine_point SET " +
                            $"\"geom\" = ST_GeomFromText('{_wktModel}', 4326), " +
                            $"\"Lng\" = ST_X(ST_Centroid(ST_GeomFromText('{_wktModel}', 4326))), " +
                            $"\"Lat\" = ST_Y(ST_Centroid(ST_GeomFromText('{_wktModel}', 4326))) " +
                            $"WHERE \"Id\" = '{point.Id}'");
                    if (flag)
                    {
                        var flag1 = await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
                        if (uow.Commit() && flag1 > 0)
                        {
                            return new Response<bool> { Result = true, Message = "操作成功" };
                        }
                    }
                }
                else
                {
                    var flag = await uow.MiMinePoint.InsertAsync(point);
                    if (uow.Commit() && flag)
                    {
                        return new Response<bool> { Result = true, Message = "操作成功" };
                    }
                }

                // 如果执行到这里，说明操作失败
                return new Response<bool> { Result = false, Message = "操作失败" };
            }
        }


        /// <summary> 
        /// 根据经纬度获取组织机构
        /// </summary>
        /// <param name="lng"></param>
        /// <param name="lat"></param>
        /// <returns></returns>
        public JObject GetOrgAreaByPoint(string geo)
        {
            //县id
            string countyid = "";
            string countyname = "";
            //镇id
            string streetid = "";
            string streetname = "";
            //村id
            string communityid = "";
            string communityname = "";

            //SqlSugar实例
            using (var db = Repository.AsSugarClient())
            {
                //查询坐标属于哪个县
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat($" SELECT xzqdm,xzqmc FROM \"shp_drone_county\" where ST_Within(ST_Centroid(ST_GeomFromText('{geo}', 4326)), ST_SetSRID(geom,4326))");
                var countyList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
                if (countyList.Count > 0)
                {
                    //县名称
                    countyname = countyList[0].xzqmc;
                    //县id
                    countyid = countyList[0].xzqdm;
                }

                //查询坐标属于哪个镇
                sql = new StringBuilder();
                sql.AppendFormat($" SELECT xzqdm,xzqmc FROM \"shp_drone_town\" where ST_Within(ST_Centroid(ST_GeomFromText('{geo}', 4326)), ST_SetSRID(geom,4326))");
                var streetList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
                if (streetList.Count > 0)
                {
                    //镇名称
                    streetname = streetList[0].xzqmc;
                    //镇id
                    streetid = streetList[0].xzqdm;
                }

                if (!string.IsNullOrEmpty(streetid))
                {
                    //查询组织机构属于哪个村
                    sql = new StringBuilder();
                    sql.AppendFormat($" SELECT zldwdm,zldwmc FROM \"shp_drone_community\" where ST_Within(ST_Centroid(ST_GeomFromText('{geo}', 4326)), ST_SetSRID(geom,4326))");
                    var communityidList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
                    if (communityidList.Count > 0)
                    {
                        //村名称
                        communityname = communityidList[0].zldwmc;
                        //村id
                        communityid = communityidList[0].zldwdm;
                    }
                }

                //拼接json数据，返回到前台
                JObject obj = new JObject();

                obj.Add("countyid", countyid);
                obj.Add("countyname", countyname);
                obj.Add("streetid", streetid);
                obj.Add("streetname", streetname);
                obj.Add("communityid", communityid);
                obj.Add("communityname", communityname);

                return obj;
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        public async Task<Response<bool>> Delete(List<MiMinePoint> models)
        {
            var flag = await Repository.DeleteAsync(models);

            return new Response<bool>
            {
                Result = flag,
                Message = flag == true ? "success" : "error"
            };

        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="obj"></param>
        public async Task<Response<bool>> Update(MiMinePoint model)
        {
            using (var uow = base.UnitWork.CreateContext())
            {
                MiMinePoint point = model.MapTo<MiMinePoint>();
                if (!string.IsNullOrEmpty(model.geom))
                {
                    string _wktModel = model.geom;
                    JObject xzqh = GetOrgAreaByPoint(_wktModel);
                    var cc = (string)xzqh["countyid"];
                    point.CountyId = xzqh["countyid"].ToString();
                    point.CountyName = xzqh["countyname"].ToString();
                    point.StreetId = xzqh["streetid"].ToString();
                    point.StreetName = xzqh["streetname"].ToString();
                    point.CommunityId = xzqh["communityid"].ToString();
                    point.CommunityName = xzqh["communityname"].ToString();
                    //oint = cinfo.countyname + " " + cinfo.streetname + " " + cinfo.communityname;
                    var flag = await uow.MiMinePoint.UpdateAsync(point);

                    StringBuilder geomSql = new StringBuilder();
                    geomSql.AppendFormat(
                        $"UPDATE mi_mine_point SET " +
                            $"\"geom\" = ST_GeomFromText('{_wktModel}', 4326), " +
                            $"\"Lng\" = ST_X(ST_Centroid(ST_GeomFromText('{_wktModel}', 4326))), " +
                            $"\"Lat\" = ST_Y(ST_Centroid(ST_GeomFromText('{_wktModel}', 4326))) " +
                            $"WHERE \"Id\" = '{point.Id}'");
                    if (flag)
                    {
                        var flag1 = await uow.Db.Ado.ExecuteCommandAsync(geomSql.ToString());
                        if (uow.Commit() && flag1 > 0)
                        {
                            return new Response<bool> { Result = true, Message = "操作成功" };
                        }
                    }
                }
                else
                {
                    var flag = await uow.MiMinePoint.UpdateAsync(point);
                    if (uow.Commit() && flag)
                    {
                        return new Response<bool> { Result = true, Message = "操作成功" };
                    }
                }

                // 如果执行到这里，说明操作失败
                return new Response<bool> { Result = false, Message = "操作失败" };
            }
        }



        /// <summary>
        /// 关闭巡检点
        /// </summary>
        /// <param name="obj"></param>
        public async Task<Response<bool>> CloseMinePoint(string pointid)
        {
            var user = _auth.GetCurrentUser().User;            
            using (var uow = base.UnitWork.CreateContext())
            {
                var flag = await uow.MiMinePoint.UpdateAsync(r => new MiMinePoint
                {
                    IsClose = true
                }, r => r.Id == pointid);

                if (uow.Commit() && flag)
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    // 如果执行到这里，说明操作失败
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }

        /// <summary>
        /// 事务示例
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Response<bool>> AssignModule()
        {
            using (var uwo = UnitWork.CreateContext())
            {
                //await uwo.SysRoleElement.InsertRangeAsync(model.ElementIds.Select(a => new SysRoleElement { RoleId = model.RoleId, ElementId = a }).ToList());

                var flag = uwo.Commit();
                return new Response<bool>
                {
                    Result = flag,
                    Message = flag == true ? "success" : "error"
                };
            }
        }

    }
}