using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Common;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.App.ServiceApp.Request;
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.DroneCaseInfo
{
    public class DroneCaseinfoApp : SqlSugarBaseApp<DroneCaseinfo, SugarDbContext>
    {
        IConfiguration _configuration;
        private ILogger<DroneCaseinfoApp> _logger;
        private ISqlSugarClient db;
        private CommonData commonData;

        public DroneCaseinfoApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<DroneCaseinfo> repository,
            IAuth auth,
            ILogger<DroneCaseinfoApp> logger,
            CommonData commonData) : base(unitWork, repository, auth)
        {
            _logger = logger;
            db = unitWork.Db;
            this.commonData = commonData;
        }

        #region 初始化
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="user"></param>
        /// <param name="db"></param>
        public void Init(DroneCaseinfo dcs)
        {
            var user = _auth.GetCurrentUser().User;
            //主键
            dcs.Id = Guid.NewGuid().ToString();

            //创建人和创建时间
            dcs.createtime = DateTime.Now;
            dcs.createuser = user.Id.ToString();
            dcs.createusername = user.Name;

            //案件是否关闭，默认0 未关闭
            dcs.is_closed = 0;

            //是否删除，默认0 未删除
            dcs.is_delete = 0;

            //是否判读
            dcs.is_intact = 0;

            //是否退回
            dcs.is_improve = 0;

            //是否审核
            dcs.is_review = 0;

            //处理状态
            dcs.handle_status_id = 0;
            dcs.handle_status_name = "未办理";

            //时间戳标识案件编号
            dcs.case_no = DateTime.Now.ToString("yyyyMMddHHmmssffff");

            if (string.IsNullOrEmpty(dcs.case_description)) dcs.case_description = "";
            if (string.IsNullOrEmpty(dcs.address)) dcs.address = "";

            if (string.IsNullOrEmpty(dcs.typeid)) dcs.typeid = "";
            if (string.IsNullOrEmpty(dcs.typename)) dcs.typename = "";
            if (string.IsNullOrEmpty(dcs.sec_typeid)) dcs.sec_typeid = "";
            if (string.IsNullOrEmpty(dcs.sec_typename)) dcs.sec_typename = "";
            if (string.IsNullOrEmpty(dcs.thr_typeid)) dcs.thr_typeid = "";
            if (string.IsNullOrEmpty(dcs.thr_typename)) dcs.thr_typename = "";

            if (string.IsNullOrEmpty(dcs.countyid)) dcs.countyid = "";
            if (string.IsNullOrEmpty(dcs.countyname)) dcs.countyname = "";
            if (string.IsNullOrEmpty(dcs.streetid)) dcs.streetid = "";
            if (string.IsNullOrEmpty(dcs.streetname)) dcs.streetname = "";
            if (string.IsNullOrEmpty(dcs.communityid)) dcs.communityid = "";
            if (string.IsNullOrEmpty(dcs.communityname)) dcs.communityname = "";

            InitOther(dcs);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="user"></param>
        /// <param name="db"></param>
        public void Update(DroneCaseinfo dcs)
        {
            InitOther(dcs);
        }

        /// <summary>
        /// 初始化 类型、状态、县镇村等名称
        /// </summary>
        /// <param name="db"></param>
        private void InitOther(DroneCaseinfo dcs)
        {
            //类型
            if (!string.IsNullOrEmpty(dcs.typeid))
            {
                var typeModel = db.Queryable<SysDataItemDetail>().Where(c => c.ItemDetailId == dcs.typeid && c.ItemCode == "HFK_HANDLE_STATUS").First();
                if (typeModel != null)
                {
                    dcs.typename = typeModel.ItemName;
                }
            }

            //案件状态
            if (!string.IsNullOrEmpty(dcs.case_status_id))
            {
                var statusModel = db.Queryable<SysDataItemDetail>().Where(c => c.ItemDetailId == dcs.case_status_id&&c.ItemCode== "HFK_HANDLE_STATUS").First();
                if (statusModel != null)
                {
                    dcs.case_status_name = statusModel.ItemName;
                }
            }

            //县
            if (!string.IsNullOrEmpty(dcs.countyid))
            {
                var model = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == dcs.countyid).First();
                if (model != null)
                {
                    dcs.countyname = model.Name;
                }
            }

            //镇
            if (!string.IsNullOrEmpty(dcs.streetid))
            {
                var model = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == dcs.streetid).First();
                if (model != null)
                {
                    dcs.streetname = model.Name;
                }
            }

            //村
            if (!string.IsNullOrEmpty(dcs.communityid))
            {
                var model = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == dcs.communityid).First();
                if (model != null)
                {
                    dcs.communityname = model.Name;
                }
            }
        }
        #endregion

        //#region 案件

        /// <summary>
        /// 无人机添加案件
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public string AddDroneCaseByDrone(AddDroneCaseByDroneReq req)
        {
            var user = _auth.GetCurrentUser().User;
            DroneCaseinfo model = req.MapTo<DroneCaseinfo>();
            var picList = req.pic_list;

            Init(model);

            List<DroneFiles> filesList = new List<DroneFiles>();
            //图片
            for (int i = 0; i < picList.Count; i++)
            {
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = Guid.NewGuid().ToString();
                fileModel.path = picList[i];
                fileModel.type = 0;
                fileModel.tablename = "drone_caseinfo";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            if (model.lng != 0 && model.lat != 0)
            {
                //根据经纬度查询地区
                var lngLat = GetOrgAreaByPoint(Convert.ToDecimal(model.lng), Convert.ToDecimal(model.lat));

                //县
                model.countyid = lngLat["countyid"].ToString();
                var countyname = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == model.countyid).First();
                if (countyname != null)
                {
                    model.countyname = countyname.Name;
                }

                //镇
                model.streetid = lngLat["streetid"].ToString();
                var streetname = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == model.streetid).First();
                if (streetname != null)
                {
                    model.streetname = streetname.Name;
                }

                //乡社区
                model.communityid = lngLat["communityid"].ToString();
                var communityname = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == model.communityid).First();
                if (communityname != null)
                {
                    model.communityname = communityname.Name;
                }
            }

            //使用事务提交数据
            var transFlag = db.AsTenant().UseTran(() =>
            {
                //新增案件数据
                db.Insertable(model).ExecuteCommand();

                //新增文件数据
                db.Insertable(filesList).ExecuteCommand();
            });

            if (transFlag.IsSuccess)
                return model.Id;
            else
                throw new Exception("上报失败");

        }



        /// <summary>
        /// 上报案件
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public string AddDroneCaseInfo(AddOrUpdateDroneCaseInfoReq req)
        {
            var user = _auth.GetCurrentUser().User;


            //案件实体
            var model = req.info;
            Init(model);

            //区分权限，创建人就是判读人
            model.identification_userid = model.createuser;
            model.identification_user = model.identification_user;

            if (model.lng != 0 && model.lat != 0)
            {
                //根据经纬度查询地区
                var lngLat = GetOrgAreaByPoint(Convert.ToDecimal(model.lng), Convert.ToDecimal(model.lat));

                //县
                model.countyid = lngLat["countyid"].ToString();
                var countyname = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == model.countyid).First();
                if (countyname != null)
                {
                    model.countyname = countyname.Name;
                }

                //镇
                model.streetid = lngLat["streetid"].ToString();
                var streetname = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == model.streetid).First();
                if (streetname != null)
                {
                    model.streetname = streetname.Name;
                }

                //乡社区
                model.communityid = lngLat["communityid"].ToString();
                var communityname = db.Queryable<SysOrg>().Where(c => c.Id.ToString() == model.communityid).First();
                if (communityname != null)
                {
                    model.communityname = communityname.Name;
                }

            }

            var picList = req.pic_list;
            var videoList = req.video_list;

            List<DroneFiles> filesList = new List<DroneFiles>();
            //图片
            for (int i = 0; i < picList.Count; i++)
            {
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = Guid.NewGuid().ToString();
                fileModel.path = picList[i];
                fileModel.type = 0;
                fileModel.tablename = "drone_caseinfo";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //视频
            for (int i = 0; i < videoList.Count; i++)
            {
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = Guid.NewGuid().ToString();
                fileModel.path = videoList[i];
                fileModel.type = 1;
                fileModel.tablename = "drone_caseinfo";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //关联案件
            var caserelationList = req.relationCaseNo;
            List<DroneCaseinfoRelation> relationList = new List<DroneCaseinfoRelation>();
            foreach (var item in caserelationList)
            {
                relationList.Add(new DroneCaseinfoRelation
                {
                    caseid = model.Id,
                    relation_case_no = item
                });
            }

            //案件标签
            var tags = req.tags;
            List<DroneCaseinfoTag> tagList = new List<DroneCaseinfoTag>();
            foreach (var item in tags)
            {
                tagList.Add(new DroneCaseinfoTag
                {
                    caseid = model.Id,
                    tagid = item
                });
            }

            //使用事务提交数据
            var transFlag = db.AsTenant().UseTran(() =>
            {
                //新增案件数据
                db.Insertable(model).ExecuteCommand();

                //新增文件数据
                db.Insertable(filesList).ExecuteCommand();

                //新增关联案件
                db.Insertable(relationList).ExecuteCommand();

                //新增案件标签
                db.Insertable(tagList).ExecuteCommand();
            });

            if (transFlag.IsSuccess)
                return model.Id;
            else
                throw new Exception("上报失败");
        }


        /// <summary>
        /// 修改完善案件
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public string UpdateDroneCaseInfo(AddOrUpdateDroneCaseInfoReq req)
        {
            var user = _auth.GetCurrentUser().User;

            //案件实体
            var model = req.info;
            Update(model);

            //处理事否审核
            if (model.is_review == null)
            {
                model.is_review = 0;
            }

            //查询面积
            var areaDecimal = db.Queryable<DroneShpData>().Where(c => c.relid == model.Id).Sum(c => c.area);
            if (areaDecimal != null)
            {
                model.area = Decimal.Round((Decimal)areaDecimal, 2).ToString();
            }

            var picList = req.pic_list;
            var videoList = req.video_list;


            var existFiles = db.Queryable<DroneFiles>().Where(c => c.relid == req.info.Id).ToList();
            List<DroneFiles> filesList = new List<DroneFiles>();
            //图片
            for (int i = 0; i < picList.Count; i++)
            {
                var item = picList[i];

                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = Guid.NewGuid().ToString();
                fileModel.path = picList[i];
                fileModel.type = 0;
                fileModel.tablename = "drone_caseinfo";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //视频
            for (int i = 0; i < videoList.Count; i++)
            {
                var item = videoList[i];

                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;
                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = Guid.NewGuid().ToString();
                fileModel.path = videoList[i];
                fileModel.type = 1;
                fileModel.tablename = "drone_caseinfo";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //关联案件
            var caserelationList = req.relationCaseNo;
            List<DroneCaseinfoRelation> relationList = new List<DroneCaseinfoRelation>();
            foreach (var item in caserelationList)
            {
                relationList.Add(new DroneCaseinfoRelation
                {
                    caseid = model.Id,
                    relation_case_no = item
                });
            }

            //案件标签
            var tags = req.tags;
            List<DroneCaseinfoTag> tagList = new List<DroneCaseinfoTag>();
            foreach (var item in tags)
            {
                tagList.Add(new DroneCaseinfoTag
                {
                    caseid = model.Id,
                    tagid = item
                });
            }

            //专题及平台数据处理
            var dataBaseList = db.Queryable<DatabasePicture>().Where(c => req.databaseid.Contains(c.Id)).IgnoreColumns(c => new { c.org_id }).ToList();
            List<DroneCaseSubject> subjectList = new List<DroneCaseSubject>();
            //遍历库
            for (int i = 0; i < dataBaseList.Count; i++)
            {
                //当前库
                var _item = dataBaseList[i];
                //专题信息
                var subjectlist = db.Queryable<Subject>().Where(r => req.subjectkeys.Contains(r.Key) && r.PId == _item.Id).ToList();
                var subjectkeys = "";
                if (req.subjectkeys != null && req.subjectkeys.Count > 0 && subjectlist.Count > 0)
                {
                    subjectkeys = db.Queryable<Subject>().Where(r => req.subjectkeys.Contains(r.Key) && r.PId == _item.Id).Select(r => r.Key).ToList().Aggregate((current, next) => current + "," + next);
                }
                DroneCaseSubject cject = new DroneCaseSubject();
                cject.Id = Guid.NewGuid().ToString();
                cject.CaseId = model.Id;
                cject.DataBaseId = _item.Id;
                cject.SubjectKeys = subjectkeys;
                cject.CreateTime = DateTime.Now;
                cject.CreateUser = user.Id.ToString();
                cject.CreateUserName = user.Name;
                subjectList.Add(cject);
            }

            //使用事务提交数据
            var transFlag = db.AsTenant().UseTran(() =>
            {
                //新增案件数据
                db.Updateable(model).ExecuteCommand();

                //新增文件数据
                db.Insertable(filesList).ExecuteCommand();

                //关联案件
                db.Deleteable<DroneCaseinfoRelation>().Where(a => a.caseid == model.Id).ExecuteCommand();
                db.Insertable(relationList).ExecuteCommand();

                //案件标签
                db.Deleteable<DroneCaseinfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                db.Insertable(tagList).ExecuteCommand();

                //案件平台专题
                db.Deleteable<DroneCaseSubject>().Where(a => a.CaseId == model.Id).ExecuteCommand();
                db.Insertable(subjectList).ExecuteCommand();
            });

            if (transFlag.IsSuccess)
                return model.Id;
            else
                throw new Exception("上报失败");

        }

        /// <summary>
        /// 事件判读
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public string UpdateDroneCaseInfoIntact(AddOrUpdateDroneCaseInfoDataBaseReq req)
        {
            var user = _auth.GetCurrentUser().User;


            //案件实体
            var model = req.info;
            Update(model);

            //是否判读、判读人和判读时间
            model.is_intact = 1;
            model.identification_user = user.Name;
            model.identification_userid = user.Id.ToString();
            model.identification_time = DateTime.Now;
            if (model.is_review == null)
            {
                model.is_review = 0;
            }

            //查询面积
            var areaDecimal = db.Queryable<DroneShpData>().Where(c => c.relid == model.Id).Sum(c => c.area);
            if (areaDecimal != null)
            {
                model.area = Decimal.Round((Decimal)areaDecimal, 2).ToString();
            }

            var picList = req.pic_list;
            var videoList = req.video_list;

            var existFiles = db.Queryable<DroneFiles>().Where(c => c.relid == req.info.Id).ToList();
            List<DroneFiles> filesList = new List<DroneFiles>();
            //图片
            for (int i = 0; i < picList.Count; i++)
            {
                var item = picList[i];

                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;

                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = Guid.NewGuid().ToString();
                fileModel.path = picList[i];
                fileModel.type = 0;
                fileModel.tablename = "drone_caseinfo";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //视频
            for (int i = 0; i < videoList.Count; i++)
            {
                var item = videoList[i];

                var count = existFiles.Where(c => c.path == item).Count();
                if (count > 0)
                    continue;

                DroneFiles fileModel = new DroneFiles();
                fileModel.Id = Guid.NewGuid().ToString();
                fileModel.path = videoList[i];
                fileModel.type = 1;
                fileModel.tablename = "drone_caseinfo";
                fileModel.createtime = DateTime.Now;
                fileModel.createuser = user.Id.ToString();
                fileModel.createusername = user.Name;
                fileModel.is_delete = 0;
                fileModel.relid = model.Id;

                filesList.Add(fileModel);
            }

            //后续写
            //List<Sugar_Relevance> relevanceList = new List<Sugar_Relevance>();
            //for (int i = 0; i < req.databaseid.Count(); i++)
            //{
            //    //不用进行判断是由于判读只能判读一次
            //    Sugar_Relevance rel = new Sugar_Relevance();
            //    rel.Id = Guid.NewGuid().ToString();
            //    rel.Key = Define.DATABASE_CASE;
            //    rel.Description = "";
            //    rel.Status = 0;
            //    rel.FirstId = req.databaseid[i];
            //    rel.SecondId = model.Id;
            //    rel.OperateTime = DateTime.Now;
            //    relevanceList.Add(rel);
            //}

            //关联案件
            var caserelationList = req.relationCaseNo;
            List<DroneCaseinfoRelation> relationList = new List<DroneCaseinfoRelation>();
            foreach (var item in caserelationList)
            {
                relationList.Add(new DroneCaseinfoRelation
                {
                    caseid = model.Id,
                    relation_case_no = item
                });
            }

            //案件标签
            var tags = req.tags;
            List<DroneCaseinfoTag> tagList = new List<DroneCaseinfoTag>();
            foreach (var item in tags)
            {
                tagList.Add(new DroneCaseinfoTag
                {
                    caseid = model.Id,
                    tagid = item
                });
            }

            #region 专题及平台数据处理
            //专题及平台数据处理
            var dataBaseList = db.Queryable<DatabasePicture>().Where(c => req.databaseid.Contains(c.Id)).IgnoreColumns(c => new { c.org_id }).ToList();
            List<DroneCaseSubject> subjectList = new List<DroneCaseSubject>();
            //遍历库
            for (int i = 0; i < dataBaseList.Count; i++)
            {
                //当前库
                var _item = dataBaseList[i];
                //专题信息
                var subjectlist = db.Queryable<Subject>().Where(r => req.subjectkeys.Contains(r.Key) && r.PId == _item.Id).ToList();
                var subjectkeys = "";
                if (req.subjectkeys.Count > 0 && subjectlist.Count > 0)
                {
                    subjectkeys = db.Queryable<Subject>().Where(r => req.subjectkeys.Contains(r.Key) && r.PId == _item.Id).Select(r => r.Key).ToList().Aggregate((current, next) => current + "," + next);
                }
                DroneCaseSubject cject = new DroneCaseSubject();
                cject.Id = Guid.NewGuid().ToString();
                cject.CaseId = model.Id;
                cject.DataBaseId = _item.Id;
                cject.SubjectKeys = subjectkeys;
                cject.CreateTime = DateTime.Now;
                cject.CreateUser = user.Id.ToString();
                cject.CreateUserName = user.Name;
                subjectList.Add(cject);
            }
            #endregion

            //使用事务提交数据
            var transFlag = db.AsTenant().UseTran(() =>
            {
                //新增案件数据
                db.Updateable(model).ExecuteCommand();

                //新增文件数据
                db.Insertable(filesList).ExecuteCommand();

                ////删除关联关系再新增
                //db.Deleteable<Relevance>().Where(c => c.SecondId == model.Id && c.Key == Define.DATABASE_CASE).ExecuteCommand();

                //后续写
                //关联表 
                //db.Insertable(relevanceList).ExecuteCommand();

                //案件关联
                db.Deleteable<DroneCaseinfoRelation>().Where(a => a.caseid == model.Id).ExecuteCommand();
                db.Insertable(relationList).ExecuteCommand();

                //案件标签
                db.Deleteable<DroneCaseinfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                db.Insertable(tagList).ExecuteCommand();

                //案件平台专题
                db.Deleteable<DroneCaseSubject>().Where(a => a.CaseId == model.Id).ExecuteCommand();
                db.Insertable(subjectList).ExecuteCommand();
            });
            //同步到对应的库
            var flag = AsynchDroneCaseData(req.databaseid, req.info.Id, req.subjectkeys);

            if (transFlag.IsSuccess && flag == "成功")
            {
                return model.Id;
            }
            else
            {
                _logger.LogError(transFlag.ErrorMessage);
                if (flag == "成功")
                {
                    throw new Exception("上报失败");
                }
                else
                {
                    throw new Exception(flag);
                }
            }


        }





        /// <summary>
        /// 同步数据公共方法
        /// </summary>
        /// <param name="db"></param>
        /// <param name="dataBaseIds"></param>
        /// <param name="caseId"></param>
        /// <returns></returns>
        private string AsynchDroneCaseData(string[] dataBaseIds, string caseId, List<string> subjects)
        {
            //查询同步数据
            var dataBaseList = db.Queryable<DatabasePicture>().Where(c => dataBaseIds.Contains(c.Id)).IgnoreColumns(c => new { c.org_id }).ToList();

            //查询案件详情
            var model = db.Queryable<DroneCaseinfo>().Where(c => c.Id == caseId).First();

            //图斑数据
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" SELECT gid,relid,createuser,createtime,cast(geom as text) geom,area FROM \"drone_shp_data\" where relid = '{caseId}'");
            var shps = db.SqlQueryable<DroneShpData>(sql.ToString()).ToList();

            //图片文件数据
            var files = db.Queryable<DroneFiles>().Where(c => c.relid == caseId).ToList();

            var fileList = files.Select(c => c.path).ToList();

            //本地图片服务器的地址
            string pictureFilesApi = _configuration.GetSection("PictureFilesApi").Value;

            //关联案件
            var relationList = db.Queryable<DroneCaseinfoRelation>().Where(a => a.caseid == caseId).ToList();

            //案件标签
            var tagList = db.Queryable<DroneCaseinfoTag>().Where(a => a.caseid == caseId).ToList();



            var dataflag = false;
            var fileflag = false;
            string infos = "";
            //遍历库
            for (int i = 0; i < dataBaseList.Count; i++)
            {
                //当前库
                var _item = dataBaseList[i];

                //专题信息
                var subjectlist = db.Queryable<Subject>().Where(r => subjects.Contains(r.Key) && r.PId == _item.Id).ToList();
                var subjectnames = "";
                if (subjects.Count > 0 && subjectlist.Count > 0)
                {
                    subjectnames = db.Queryable<Subject>().Where(r => subjects.Contains(r.Key) && r.PId == _item.Id).Select(r => r.Name).ToList().Aggregate((current, next) => current + "," + next);
                }

                //同步数据参数
                AddOrUpdateAsyncDroneCaseDataReq postData = new AddOrUpdateAsyncDroneCaseDataReq();
                postData.model = model;
                postData.files = files;
                postData.shps = shps;
                postData.relations = relationList;
                postData.tags = tagList;
                postData.subjects = subjectlist;


                //状态，数据，发送请求
                string statusCode = string.Empty;
                string postDataStr = postData.ToJson();

                if (_item.database_url.IndexOf("http") >= 0)
                {
                    //使用接口同步
                    var postDataResult = Infrastructure.Helpers.HttpClientHelper.PostResponse(_item.database_url + "api/DroneCaseinfo/AsynchDroneCaseDataLast", postDataStr, out statusCode);
                    //判断是否推送成功
                    var res = JsonConvert.DeserializeObject<Response<string>>(postDataResult);
                    if (res.Code == 200)
                    {
                        dataflag = true;
                        //添加日志
                        AddPushLogs(postDataStr, dataflag, 1, _item.database_name, _item.Id, subjectnames);
                    }
                    else
                    {
                        dataflag = false;
                        infos += res.Message;
                        //添加日志
                        AddPushLogs(postDataStr, dataflag, 1, _item.database_name, _item.Id, subjectnames);
                        break;
                    }
                }
                else
                {
                    //使用数据库同步数据
                    string res = AsynchDroneCaseData(postData, _item.database_url);
                    if (res == "同步成功")
                    {
                        dataflag = true;
                    }
                    else
                    {
                        dataflag = false;
                        break;
                    }
                }

                //同步图片参数
                AddOrUpdateDownLoadInternetToLocalReq postFiles = new AddOrUpdateDownLoadInternetToLocalReq();
                postFiles.uri = pictureFilesApi;
                postFiles.files = fileList;

                //状态，数据，发送请求
                string statusCodePic = string.Empty;
                string postFilesStr = postFiles.ToJson();
                var postFilesResult = Infrastructure.Helpers.HttpClientHelper.PostResponse(_item.picture_url + "api/Platform/DownLoadInternetToLocal", postFilesStr, out statusCodePic);

                //判断是否推送成功
                var fileres = JsonConvert.DeserializeObject<Response<string>>(postFilesResult);
                if (fileres.Code == 200)
                {
                    fileflag = true;
                    //添加日志
                    AddPushLogs(postFilesStr, fileflag, 2, _item.database_name, _item.Id, subjectnames);
                }
                else
                {
                    fileflag = false;
                    infos += fileres.Message;
                    //添加日志
                    AddPushLogs(postFilesStr, fileflag, 2, _item.database_name, _item.Id, subjectnames);
                    break;
                }
            }
            //返回最终结果
            if (dataflag && fileflag)
            {
                return "成功";
            }
            else
            {
                return infos;
            }
        }

        //添加推送日志
        public bool AddPushLogs(string data, bool issuccess, int type, string databasename, string databaseid, string subjectname)
        {

            var pl = new DroneCaseinfoPushLog();
            pl.Id = Guid.NewGuid().ToString();
            pl.PushTime = DateTime.Now;
            pl.DatabaseName = databasename;
            pl.Data = data;
            pl.IsSuccess = issuccess;
            pl.Type = type;
            pl.DataBaseId = databaseid;
            pl.SubjectName = subjectname;

            var transFlag = db.AsTenant().UseTran(() =>
            {
                //新增推送日志
                db.Insertable(pl).ExecuteCommand();
            });
            return transFlag.IsSuccess;

        }

        //查询专题数据
        public List<SubjectRes> GetSubjectInfos()
        {
            var list = db.Queryable<DatabasePicture>().Select(r => new SubjectRes
            {
                Id = r.Id,
                Name = r.database_name,
                Children = SqlFunc.Subqueryable<Subject>().Where(a => a.PId == r.Id).ToList(a => new ChildSubject
                {
                    Key = a.Key,
                    Name = a.Name
                })
            }).ToList();
            return list;     
        }

        /// <summary>
        /// 同步航飞库数据
        /// </summary>
        /// <param name="req"></param>
        /// <param name="database"></param>
        /// <returns></returns>
        private string AsynchDroneCaseData(AddOrUpdateAsyncDroneCaseDataReq req, string database)
        {

            //案件
            var model = req.model;

            //文件
            var files = req.files;

            //shp
            var shps = req.shps;

            //关联案件
            var relations = req.relations;

            //案件标签
            var tags = req.tags;

            //查询是否存在此数据
            var _count = db.Queryable<DroneCaseinfo>().Where(c => c.Id == model.Id).Count();

            //使用事务提交数据
            var transFlag = db.AsTenant().UseTran(() =>
            {
                if (_count > 0)
                {
                    //已存在此数据，修改数据
                    db.Updateable(model).ExecuteCommand();
                }
                else
                {
                    //新增数据
                    db.Insertable(model).ExecuteCommand();
                }

                if (!string.IsNullOrEmpty(model.Id))
                {
                    //新增修改图斑
                    //先删除，后新增
                    db.Deleteable<DroneShpData>().Where(c => c.relid == model.Id).ExecuteCommand();
                    var _gidStr = commonData.GetMaxKeyVal("gid", "drone_shp_data", 1);
                    int _gid = int.Parse(_gidStr);
                    for (int i = 0; i < shps.Count; i++)
                    {
                        var _item = shps[i];
                        _item.gid = _gid + i;
                    }

                    db.Insertable(shps).ExecuteCommand();

                    //新增修改图片
                    //先删除，后新增
                    db.Deleteable<DroneFiles>().Where(c => c.relid == model.Id).ExecuteCommand();
                    db.Insertable(files).ExecuteCommand();

                    //关联案件
                    //先删除后新增
                    db.Deleteable<DroneCaseinfoRelation>().Where(c => c.caseid == model.Id).ExecuteCommand();
                    db.Insertable(relations).ExecuteCommand();

                    //案件标签
                    //先删除后新增
                    db.Deleteable<DroneCaseinfoTag>().Where(a => a.caseid == model.Id).ExecuteCommand();
                    db.Insertable(tags).ExecuteCommand();
                }
            });

            if (transFlag.IsSuccess)
                return "同步成功";
            else
                throw new Exception("同步失败");

        }

        /// <summary>
        /// 关闭案件（判读用）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string CloseDroneCaseInfo(string id)
        {
            var user = _auth.GetCurrentUser().User;

            var flag = db.Updateable<DroneCaseinfo>()
                .SetColumns(c => new DroneCaseinfo
                {
                    is_intact = 99,
                    close_time = DateTime.Now,
                    close_user = user.Name,
                    close_userid = user.Id.ToString()
                })
                .Where(c => c.Id == id)
                .ExecuteCommand();

            if (flag > 0)
                return "关闭成功";
            else
                throw new Exception("关闭失败");

        }

        /// <summary>
        /// 查询案件列表
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public TableData LoadCaseInfoList(QueryCaseInfoListReq req)
        {
            TableData tableData = new TableData();

            req.Init();

            DateTime curDatetime = DateTime.Now;

            var user = _auth.GetCurrentUser().User;

            //总条数
            int totalNumber = 0;

            var oldIntacts = new List<int?> { 1, 99, 6 };

            var list = db.Queryable<DroneCaseinfo>().Where("(is_delete = 0 or is_delete is null)")
                //关键字过滤数据
                .WhereIF(!string.IsNullOrEmpty(req.key), c => c.case_no.Contains(req.key) || c.case_name.Contains(req.key) || c.case_description.Contains(req.key))
                //是否完整
                //.WhereIF(req.is_intact != null && req.is_intact != 0, c => c.is_intact == req.is_intact)
                //已判读、已关闭
                .WhereIF(req.is_intact != null && oldIntacts.Contains(req.is_intact), c => c.is_intact == req.is_intact)
                //未判读
                .WhereIF(req.is_intact == 0, c => c.is_intact == null || c.is_intact == 0)
                //已审核
                .WhereIF(req.is_intact == 2, c => c.is_review == 1)
                //已通过
                .WhereIF(req.is_intact == 3, c => c.is_review == 1 && c.is_agree == true && c.is_intact == 1)
                //未通过
                .WhereIF(req.is_intact == 4, c => c.is_review == 1 && c.is_agree == false && c.is_intact == 1)
                //上报人
                .WhereIF(req.is_reporter == 1 && user.Account != Define.SYSTEM_USERNAME, c => c.createuser == user.Id.ToString())
                //执行人
                .WhereIF(req.is_dealer==1&&user.Account != Define.SYSTEM_USERNAME,c=> SqlFunc.Subqueryable<SysUserOrg>().Where(it=>it.OrgId.ToString()==c.countyid||it.OrgId.ToString() == c.streetid||it.OrgId.ToString() == c.communityid).Any())
                //执行人
                //.WhereIF(req.is_dealer == 1 && user.Account != Define.SYSTEM_USERNAME, c => SqlFunc.Subqueryable<Sugar_Relevance>().Where(it => it.SecondId == c.communityid && it.FirstId == user.Id && it.Key == Define.USERORG).Any()
                //                    || SqlFunc.Subqueryable<Sugar_Relevance>().Where(it => it.SecondId == c.streetid && it.FirstId == user.Id && it.Key == Define.USERORG).Any()
                //                    || SqlFunc.Subqueryable<Sugar_Relevance>().Where(it => it.SecondId == c.countyid && it.FirstId == user.Id && it.Key == Define.USERORG).Any()
                //                    || c.createuser == user.Id)
                //处理状态
                .WhereIF(req.handle_status_id != null, c => c.handle_status_id == req.handle_status_id)
                //案件状态
                .WhereIF(!string.IsNullOrEmpty(req.case_status_id), c => c.case_status_id == req.case_status_id)
                //开始时间
                .WhereIF(req.report_start_time != null, c => c.createtime >= req.report_start_time)
                //结束时间
                .WhereIF(req.report_end_time != null, c => c.createtime <= req.report_end_time)
                //上报人
                .WhereIF(!string.IsNullOrEmpty(req.report_name), c => c.createusername.Contains(req.report_name))
                //执行人
                .WhereIF(!string.IsNullOrEmpty(req.deal_username), c => c.deal_username.Contains(req.deal_username))
                //判读开始时间
                .WhereIF(req.identification_start_time != null, c => c.identification_time >= req.identification_start_time)
                //判读结束时间
                .WhereIF(req.identification_end_time != null, c => c.identification_time <= req.identification_end_time)
                //县id
                .WhereIF(!string.IsNullOrEmpty(req.countyid), c => c.countyid == req.countyid)
                //镇id
                .WhereIF(!string.IsNullOrEmpty(req.streetid), c => c.streetid == req.streetid)
                //村id
                .WhereIF(!string.IsNullOrEmpty(req.communityid), c => c.communityid == req.communityid)
                //判读人id
                //.WhereIF(!string.IsNullOrEmpty(req.identification_userid), c => c.identification_userid == req.identification_userid)
                //判读人查看创建人或者判读人是自己的，或者判读人是空的
                .WhereIF(!string.IsNullOrEmpty(req.identification_userid) && user.Account != Define.SYSTEM_USERNAME,
                c => c.identification_userid == req.identification_userid || c.createuser == req.identification_userid || SqlFunc.IsNullOrEmpty(req.identification_userid))
                //判读人
                .WhereIF(!string.IsNullOrEmpty(req.identification_user), c => c.identification_user == req.identification_user)
                //判读人账号
                .WhereIF(!string.IsNullOrEmpty(req.identification_account), c => SqlFunc.Subqueryable<SysUser>().Where(it => c.identification_userid == it.Id.ToString() && it.Account == req.identification_account).Any())
                //是否违法
                .WhereIF(req.is_illegal != null, c => c.is_illegal == req.is_illegal)
                //是否判读审核
                .WhereIF(req.is_review != null, c => c.is_review == req.is_review)
                //审核判读数据权限过滤
                //.WhereIF(req.is_Reviewer == 1 && user.Account != Define.SYSTEM_USERNAME, c => SqlFunc.Subqueryable<Sugar_Relevance>().Where(it => it.SecondId == user.Id && it.FirstId == c.identification_userid && it.Key == Define.UserAndUser).Any())
                //村名称
                .WhereIF(!string.IsNullOrEmpty(req.communityname), c => c.communityname.Contains(req.communityname))
                //案件编号
                .WhereIF(!string.IsNullOrEmpty(req.case_no), c => c.case_no.Contains(req.case_no))
                //案件类型
                .WhereIF(!string.IsNullOrEmpty(req.typeid), c => c.typeid == req.typeid || c.sec_typeid == req.typeid || c.thr_typeid == req.typeid)
                //地址
                .WhereIF(!string.IsNullOrEmpty(req.address), c => c.address.Contains(req.address))
                //案件描述
                .WhereIF(!string.IsNullOrEmpty(req.case_description), c => c.case_description.Contains(req.case_description))
                //排序
                .OrderBy(c => c.createtime, OrderByType.Desc)
                //分页查询数据
                .ToPageList(req.page, req.limit, ref totalNumber);

            tableData.data = list;
            tableData.count = totalNumber;

            return tableData;

        }



        /// <summary>
        /// 加载处理数据列表
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public TableData LoadDealCaseInfoList(QueryDealCaseInfoListReq obj)
        {
            obj.Init();
            var req = obj.MapTo<QueryCaseInfoListReq>();
            req.is_intact = 1;
            req.is_dealer = 1;

            //查询列表数据
            var tbData = LoadCaseInfoList(req);
            var list = (List<DroneCaseinfo>)tbData.data;

            var caseIdList = list.Select(c => c.Id).ToList();

            var picList = db.Queryable<DroneFiles>().Where(c => caseIdList.Contains(c.relid) && c.type == 0 && c.tablename == "drone_caseinfo").Select(c => new { caseid = c.relid, c.path }).ToList();

            List<DroneCaseInfoExt> result = new List<DroneCaseInfoExt>();
            for (int i = 0; i < list.Count; i++)
            {
                var item = list[i];
                var caseModel = item.MapTo<DroneCaseInfoExt>();
                caseModel.case_pic_list = picList.Where(c => c.caseid == caseModel.Id).Select(c => c.path).ToList();

                result.Add(caseModel);
            }

            TableData tableData = new TableData();
            tableData.count = tbData.count;
            tableData.data = result;

            return tableData;
        }



        /// <summary>
        /// 案件详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AddOrUpdateDroneCaseInfoDataBaseReqExt GetCaseInfo(string id)
        {
            AddOrUpdateDroneCaseInfoDataBaseReqExt res = new AddOrUpdateDroneCaseInfoDataBaseReqExt();
            res.Init();

            //详情
            var info = db.Queryable<DroneCaseinfo>().Where(c => c.Id == id).First();

            //文件
            var fileList = db.Queryable<DroneFiles>().Where(c => c.relid == id && (c.is_delete == null || c.is_delete == 0) && c.tablename == "drone_caseinfo").ToList();

            //图片
            var pic_list = fileList.Where(c => c.type == 0).GroupBy(c => c.path).Select(c => c.Key).ToList();
            var pics = fileList.Where(c => c.type == 0).ToList();

            //视频
            var video_list = fileList.Where(c => c.type == 1).GroupBy(c => c.path).Select(c => c.Key).ToList();
            var videos = fileList.Where(c => c.type == 1).ToList();

            //历史案件
            var relationCaseNoList = db.Queryable<DroneCaseinfoRelation>().Where(a => a.caseid == id).Select(a => a.relation_case_no).ToList();


            //案件标签
            //var tags = db.Queryable<Sugar_Drone_caseinfo_tag>()
            //    .LeftJoin<Sugar_Category>((t, c) => t.tagid == c.Id)
            //    .Where((t, c) => t.caseid == id && c.TypeId == "DRONE_CASE_TAG")
            //    .Select((t, c) => c.Name).ToList();

            var tags = db.Queryable<DroneCaseinfoTag>()
               .Where(t => t.caseid == id)
               .Select(t => t.tagid).ToList();

            //图斑的中心点
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($"SELECT st_astext(ST_Centroid(geom)) lnglat FROM \"drone_shp_data\" where relid = '{id}' and geom is not null");
            var dt = db.Ado.GetDataTable(sql.ToString());
            if (dt.Rows.Count > 0)
            {
                string lngLat = dt.Rows[0]["lnglat"].ToString();

                lngLat = lngLat.Replace("POINT(", "").Replace(")", "");
                var lngLats = lngLat.Split(" ");
                res.lng = Decimal.Round(Decimal.Parse(lngLats[0]), 6);
                res.lat = Decimal.Round(Decimal.Parse(lngLats[1]), 6);
            }

            //通过关联表过滤
            //var database = db.Queryable<Sugar_Database_picture, Sugar_Relevance, Sugar_Drone_caseinfo>((p, r, c) => new JoinQueryInfos(
            //    JoinType.Left, p.Id == r.FirstId,
            //    JoinType.Left, r.SecondId == c.Id
            //    )).
            //    Where((p, r, c) => p.org_id.Contains(info.communityid) && (info.communityid != null || info.communityid != "") && r.SecondId == id && r.Key == Define.DATABASE_CASE)
            //    .Select((p, r, c) => p.Id).ToArray();

            //案件平台及专题
            var databaselist = db.Queryable<DroneCaseSubject>().Where(r => r.CaseId == id)?.Select(r => r.DataBaseId).Distinct().ToList();
            var subjectkeys = db.Queryable<DroneCaseSubject>().Where(r => r.CaseId == id)?.Select(r => r.SubjectKeys).ToList();
            List<string> keys = new List<string>();
            foreach (var item in subjectkeys)
            {
                keys = keys.Concat(item.Split(',').ToList()).ToList();
            }

            res.info = info;
            res.pic_list = pic_list;
            res.video_list = video_list;
            res.pics = pics;
            res.videos = videos;
            res.relationCaseNo = relationCaseNoList;
            res.tags = tags;
            res.databaseid = databaselist.ToArray();
            res.subjectkeys = keys.Distinct().ToList();

            return res;

        }

        /// <summary>
        /// 删除文件 - 通过路径删除
        /// </summary>
        /// <param name="paths"></param>
        /// <returns></returns>
        public string DeleteDroneFilesByPath(string[] paths)
        {
            if (paths == null)
                throw new Exception("paths is null");

            int flag = -1;
            flag = db.Updateable<DroneFiles>()
                .SetColumns(c => new DroneFiles { is_delete = 1 })
                .Where(c => paths.Contains(c.path))
                .ExecuteCommand();

            if (flag >= 0)
                return "删除成功";
            else
                throw new Exception("删除失败");

        }

        #region 图层

        /// <summary>
        /// 添加违建图层
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string AddIllegalBuildeLayer(DroneShpData model)
        {
            var _user = _auth.GetCurrentUser().User;
            model.createtime = DateTime.Now;
            model.createuser = _user.Name;

            //获取主键
            string _gid = commonData.GetMaxKeyVal("gid", "drone_shp_data", 1);
            model.gid = int.Parse(_gid);//转为数字类型
                                        //string _gid = model.gid.ToString();

            //格式化数据
            string _wktModel = commonData.WktDataConvert(model.geom, "MULTIPOLYGON ZM", 4);

            model.geom = null;

            StringBuilder geomSql = new StringBuilder();
            geomSql.AppendFormat($" update drone_shp_data set geom = st_geomfromtext('{_wktModel}',4326) where gid = '{_gid}'");

            //批量更新面积
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" update drone_shp_data set area = st_area(st_transform(geom,4527)) where geom is not null and (area is null)");

            //使用事务提交数据
            var transFlag = db.AsTenant().UseTran(() =>
            {
                //插入图斑数据
                var flag = db.Insertable(model).ExecuteCommand();

                //修改图斑数据
                var flagGeom = db.Ado.ExecuteCommand(geomSql.ToString());

                //修改图斑面积
                var flagUpdate = db.Ado.ExecuteCommand(sql.ToString());
            });

            if (transFlag.IsSuccess)
            {
                return _gid;
            }
            else
            {
                throw new Exception("新增失败");
            }
        }



        /// <summary>
        /// 删除图斑
        /// </summary>
        /// <param name="gid"></param>
        /// <returns></returns>
        public string DeleteDroneLayers(int gid)
        {
            var flag = db.Deleteable<DroneShpData>().Where(c => c.gid == gid).ExecuteCommand();
            if (flag > 0)
                return "删除成功";
            else
                throw new Exception("删除失败");
        }





        /// <summary>
        /// 获取GeoJson
        /// PC获取图层的GeoJson（判读页面用）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public JToken GetDroneGeoJson(string id)
        {
            QueryGeoJsonCommonReq req = new QueryGeoJsonCommonReq();
            req.tablename = "drone_shp_data";
            req.where = "where relid = '" + id + "'";
            req.pageIndex = 1;
            req.limit = 2000;

            var res = commonData.PgsqlGeoJsonCommon(req);
            return res;
        }



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

            //查询坐标属于哪个县
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" SELECT xzqmc FROM \"shp_drone_county\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), geom) = 't'");
            var countyList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
            if (countyList.Count > 0)
            {
                //县名称
                string countyName = countyList[0].xzqmc;
                //根据名称查询组织机构
                var countyModel = db.Queryable<SysOrg>().Where(c => c.Name == countyName).First();
                //组织机构不为空，给县id赋值
                if (countyModel != null)
                {
                    countyid = countyModel.Id.ToString();
                    countyname = countyModel.Name;
                }
            }

            //查询坐标属于哪个镇
            sql = new StringBuilder();
            sql.AppendFormat($" SELECT xzqmc FROM \"shp_drone_town\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), geom) = 't'");
            var streetList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
            if (streetList.Count > 0)
            {
                //镇名称
                string streetName = streetList[0].xzqmc;
                //根据名称查询组织机构
                var streetModel = db.Queryable<SysOrg>().Where(c => c.Name == streetName).First();
                //组织机构不为空，给镇id赋值
                if (streetModel != null)
                {
                    streetid = streetModel.Id.ToString();
                    streetname = streetModel.Name;
                }
            }

            if (!string.IsNullOrEmpty(streetid))
            {
                //查询组织机构属于哪个村
                sql = new StringBuilder();
                sql.AppendFormat($" SELECT zldwmc FROM \"shp_drone_community\" where ST_Within(st_geomfromtext('POINT({lng} {lat})',4326), geom) = 't'");
                var communityidList = db.SqlQueryable<dynamic>(sql.ToString()).ToList();
                if (communityidList.Count > 0)
                {
                    //村名称
                    string communityName = communityidList[0].zldwmc;
                    //根据村名称和镇id查询组织机构
                    var communityModel = db.Queryable<SysOrg>().Where(c => SqlFunc.StartsWith(c.Name, communityName) && c.ParentId.ToString() == streetid).First();
                    //组织机构不为空，给村id赋值
                    if (communityModel != null)
                    {
                        communityid = communityModel.Id.ToString();
                        communityname = communityModel.Name;
                    }
                }
            }

            //拼接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;

        }
        #endregion

        #region 复提更新
        /// <summary>
        /// 复提案件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public bool ReSubmitCaseInfo(ReSubmitInfo submitInfo)
        {
            var flag = db.Updateable<DroneCaseinfo>()
                .SetColumns(c => new DroneCaseinfo
                {
                    is_intact = 6,
                    examinecomments = submitInfo.Remark
                })
                .Where(c => c.case_no == submitInfo.CaseNo)
                .ExecuteCommand();

            if (flag > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        #endregion

        #region 案件关闭
        /// <summary>
        /// 案件关闭
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public bool CloseCaseInfo(CloseCaseInfo submitInfo)
        {


            var flag = db.Updateable<DroneCaseinfo>()
                .SetColumns(c => new DroneCaseinfo
                {
                    is_intact = 99,
                    close_comments = submitInfo.Reason,
                    close_time = DateTime.Now,
                    is_closed = 1
                })
                .Where(c => c.case_no == submitInfo.CaseNo)
                .ExecuteCommand();

            if (flag > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        #endregion
    }
}
