using Infrastructure;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using OpenAuth.App.Base;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.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;
using OpenAuth.App.DroneScreenDisplay.Response;
using OpenAuth.App.ServiceApp.DroneScreenDisplay.Response;
using OpenAuth.App.ServiceApp.Response;
using Infrastructure.Extensions;
using DocumentFormat.OpenXml.Bibliography;
using OpenAuth.App.BaseApp.Base;


namespace OpenAuth.App.DroneScreenDisplay
{
    public partial class DroneScreenDisplayApp : SqlSugarBaseApp<Repository.Domain.DroneCaseInfoSingle, SugarDbContext>
    {
        private IConfiguration _configuration;
        ISqlSugarClient client;
        CommonDataManager _commonDataManager;
        /*
 * 根据不同的标签来区分文件的不同分类
 * drone_files表中tag字段区分
 */
        //整改后照片标签
        private const string afterPicTag = "AfterPicTag";
        //合法文件标签
        private const string EvidenceFileTag = "EvidenceFileTag";
        //处罚通知书
        private const string punishPicTag = "punishPicTag";
        //交款通知书
        private const string paymentPicTag = "paymentPicTag";
        //政府同意完善手续证明
        private const string agreeCheckoutPicTag = "agreeCheckoutPicTag";
        //办理手续
        private const string checkoutPicTag = "checkoutPicTag";
        //勘测定界图
        private const string boundaryPicTag = "boundaryPicTag";
        public DroneScreenDisplayApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<Repository.Domain.DroneCaseInfoSingle> repository, IAuth auth, IConfiguration configuration, ISqlSugarClient client, CommonDataManager commonDataManager) : base(unitWork, repository, auth)
        {
            _configuration = configuration;
            this.client = client;
            _commonDataManager = commonDataManager;
        }

        #region 大屏展示
        /// <summary>
        /// 查询案件公共过滤方法
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        private ISugarQueryable<DroneCaseInfoSingle> GetCaseQueryable(GetQueryCaseReq req = null, int? order = null)
        {
            if (req == null) req = new GetQueryCaseReq();
            req.Init();

            var query = client.Queryable<DroneCaseInfoSingle>()
                    //未删除
                    .Where(c => c.is_delete == null || c.is_delete == 0)
                    //已判读
                    .Where(c => c.is_intact == 1)
                    //处理状态
                    .WhereIF(req.handle_status_id != null, c => c.handle_status_id == req.handle_status_id)
                    //是否核查
                    .WhereIF(req.is_examine == 0, c => c.is_jieshou == 0 || c.is_jieshou == null)
                    .WhereIF(req.is_examine == 1, c => c.is_jieshou == 1)
                    //处理状态
                    .WhereIF(req.handle_status_list.Count != 0, c => req.handle_status_list.Contains(c.handle_status_id))
                    //是否合法
                    .WhereIF(req.is_illegal != null, c => c.is_illegal == req.is_illegal)
                    //处理措施
                    .WhereIF(req.measure_name_type == 0, c => c.measure_name == "拟拆除")
                    .WhereIF(req.measure_name_type == 1, c => c.measure_name == "查处")
                    .WhereIF(req.measure_name_type == 2, c => c.measure_name == "拟完善手续")
                    //街道过滤
                    .WhereIF(!string.IsNullOrEmpty(req.streetid), c => (c.countyid == req.streetid || c.streetid == req.streetid || c.communityid == req.streetid))
                    //.WhereIF(!string.IsNullOrEmpty(req.streetid), c => c.streetid == req.streetid)
                    //.WhereIF(!string.IsNullOrEmpty(req.countyid), c => c.countyid == req.countyid)
                    ;
            return query;
        }

        /// <summary>
        /// 查询条件组装
        /// </summary>
        /// <param name="db"></param>
        /// <param name="req"></param>
        /// <param name="user"></param>
        /// <param name="is_order"></param>
        /// <returns></returns>
        private ISugarQueryable<DroneCaseInfoSingle> QueryCaseInfoList(QueryCaseInfoListReq req, SysUser user, int? is_order = 1, List<string> roles = null)
        {
            DateTime? threeTime = DateTime.Now.AddDays(-3);
            DateTime? sevenTime = DateTime.Now.AddDays(-7);

            ////查询部门及下级部门
            var orgid = client.Queryable<SysOrg>().ToChildList(a => a.ParentId, req.countyid).Select(a => a.Id.ToString()).ToList();


            var query = client.Queryable<DroneCaseInfoSingle>().Where(c => c.is_delete == 0 || c.is_delete == 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 == 0, c => c.is_intact == null || c.is_intact == 0)
                   //上报人
                   .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.communityid && it.UserId == user.Id).Any()
                   || SqlFunc.Subqueryable<SysUserOrg>().Where(it => it.OrgId.ToString() == c.streetid && it.UserId == user.Id).Any()
                   || SqlFunc.Subqueryable<SysUserOrg>().Where(it => it.OrgId.ToString() == c.countyid && it.UserId == user.Id).Any()
                   || c.createuser == user.Id.ToString())
                   //执行人过滤：相当于 执法人员用 
                   .WhereIF(req.dispense_dealer == 1 && user.Account != Define.SYSTEM_USERNAME, c => SqlFunc.Subqueryable<DroneRelevance>().Where(it => it.SecondId == c.Id && it.Key == Define.USERDRONECASE && it.FirstId == user.Id.ToString()).Any())
                   //处理状态：未办理、办理中、已办结
                   .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 => orgid.Contains(c.countyid) || orgid.Contains(c.streetid) || orgid.Contains(c.communityid))
                   ////镇id
                   //.WhereIF(!string.IsNullOrEmpty(req.countyid), c => orgid.Contains(c.streetid))
                   ////村id
                   //.WhereIF(!string.IsNullOrEmpty(req.countyid), c => orgid.Contains(c.communityid))
                   //判读人id
                   .WhereIF(!string.IsNullOrEmpty(req.identification_userid), c => c.identification_userid == req.identification_userid)
                   //判读人
                   .WhereIF(!string.IsNullOrEmpty(req.identification_user), c => c.identification_user.Contains(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(!string.IsNullOrEmpty(req.verify_user), c => c.verifyuser.Contains(req.verify_user))
                   //是否违法
                   .WhereIF(req.is_illegal != null, c => c.is_illegal == req.is_illegal)
                   //是否核销
                   //.WhereIF(req.is_verification == 1, c => c.is_verification == req.is_verification)
                   //.WhereIF(req.is_verification == 0, c => c.is_verification == null || c.is_verification == 0)
                   //是否退回
                   .WhereIF(req.is_drawback == 0, c => c.is_drawback == null || c.is_drawback == 0)
                   .WhereIF(req.is_drawback == 1, c => c.is_drawback == 1)
                   //是否根据退回给谁过滤
                   //.WhereIF(req.is_back_to_userid == 1, c => c.back_to_userid == user.Id.ToString())
                   //是否核查过滤
                   .WhereIF(req.is_examine == 0, c => c.is_jieshou == null || c.is_jieshou == 0)
                   .WhereIF(req.is_examine == 1, c => c.is_jieshou == 1)
                   //处理措施
                   .WhereIF(!string.IsNullOrEmpty(req.measure_name), c => c.measure_name == req.measure_name)
                   //处理措施
                   .WhereIF(req.measure_name_type == 0, c => c.measure_name == "拟拆除")
                   .WhereIF(req.measure_name_type == 1, c => c.measure_name == "查处")
                   .WhereIF(req.measure_name_type == 2, c => c.measure_name == "拟完善手续")
                   /*
                    * 统计相关用到的过滤条件 
                    */
                   //超期时间标识
                   .WhereIF(req.out_time_flag == 1, c => c.identification_time >= threeTime) //1-3天
                   .WhereIF(req.out_time_flag == 2, c => c.identification_time < threeTime && c.identification_time > sevenTime) //3-7天
                   .WhereIF(req.out_time_flag == 3, c => c.identification_time < sevenTime) //7天以上
                   .WhereIF(req.out_time_flag == 4, c => c.identification_time > DateTime.Now.AddDays(-30) && c.identification_time < DateTime.Now.AddDays(-7)) //30天内
                   .WhereIF(req.out_time_flag == 5, c => c.identification_time < DateTime.Now.AddDays(-30)) //30天以上
                                                                                                            //是否处理
                   .WhereIF(req.is_deal == 1, c => c.handle_status_id != 0 || (c.handle_status_id == 0 && c.is_jieshou == 1))
                   //是否整改完成
                   .WhereIF(req.is_complete == 0, c => c.handle_status_id != 2)
                   //24小时未核查
                   .WhereIF(req.is_not_deal_hour24 == 1, c => c.handle_status_id == 0 && (c.is_jieshou == null || c.is_jieshou == 0) && c.identification_time < DateTime.Now.AddDays(-1))

                   //村名称
                   .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)
                   //地址
                   .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));

            //标签检索
            if (!string.IsNullOrEmpty(req.tagids))
            {
                var tags = req.tagids.Trim().Split(",").ToList();
                var ids = client.Queryable<DroneCaseInfoTag>().Where(a => req.tagids.Contains(a.tagid)).Select(a => a.caseid).ToList();
                query = query.Where(c => ids.Contains(c.Id));
            }

            //排序
            if (is_order == 1)
            {
                if (req.is_intact == 1 && req.handle_status_id == 0)
                    query = query.OrderBy(c => c.identification_time, OrderByType.Desc);
                else if (req.is_intact == 1 && req.handle_status_id == 1)
                    query = query.OrderBy(c => c.deal_time, OrderByType.Desc);
                else if (req.is_intact == 1 && req.handle_status_id == 2)
                    query = query.OrderBy(c => c.verifytime, OrderByType.Desc);
                else
                    query = query.OrderBy(c => c.createtime, OrderByType.Desc);
            }

            return query;
        }


        /// <summary>
        /// 查询案件和处理公共过滤方法
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        private ISugarQueryable<DroneCaseInfoSingle> GetCaseDealQueryable()
        {
            var query = client.Queryable<DroneCaseInfoSingle>()
                    .Where(c => c.is_delete == null || c.is_delete == 0)
                    .Where(c => c.is_intact == 1);
            return query;
        }

        /// <summary>
        /// 正式案件记录
        /// </summary>
        /// <returns></returns>
        public List<dynamic> LoadDroneCase(string streetid)
        {
            var list = GetCaseQueryable(new GetQueryCaseReq { streetid = streetid })
                .OrderBy(c => c.identification_time, OrderByType.Desc)
                .Select<dynamic>(c => new
                {
                    id = c.Id,
                    //c.streetname, 县级
                    streetname = c.countyname,
                    c.case_description,
                    c.identification_time
                })
                .Take(20).ToList();

            return list;
        }

        /// <summary>
        /// 最新案件处理
        /// </summary>
        /// <returns></returns>
        public object LoadDroneCaseDeal(int? istoday, string areaid)
        {
            DateTime? today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            var query = GetCaseDealQueryable()
                .WhereIF(istoday == 1, (c => c.examine_time >= today))
                .WhereIF(!string.IsNullOrEmpty(areaid), c => c.streetid == areaid || c.countyid == areaid || c.communityid == areaid)
                //.Where((d, c) => c.Id != null)
                .OrderBy(c => c.examine_time, OrderByType.Desc)
                .Select(c => new
                {
                    c.Id,
                    c.examine_time,
                    c.case_description,
                    c.typename,
                    c.countyid,
                    c.countyname,
                    c.streetid,
                    c.streetname,
                    c.communityid,
                    c.communityname,
                    c.result_name
                });
            if (istoday != 1)
                query = query.Take(20);
            else
                query = query.Take(100);
            var list = query.ToList();

            return list;
        }

        /// <summary>
        /// 上报和处理案件数量
        /// </summary>
        /// <returns></returns>
        public JObject GetTodayReportAndDealCount(string streetid)
        {
            var today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            var reportCount = GetCaseQueryable(new GetQueryCaseReq { streetid = streetid })
                .Where(c => c.identification_time > today)
                .Count();
            var dealCount = GetCaseQueryable(new GetQueryCaseReq { streetid = streetid })
                .Where(c => c.handle_status_id == 2)
                .Where(c => c.examine_time > today)
                .Count();
            JObject obj = new JObject();
            obj.Add("reportCount", reportCount);
            obj.Add("dealCount", dealCount);

            return obj;
        }

        /// <summary>
        /// 案件数量统计
        /// </summary>
        /// <returns></returns>
        public JObject GetDroneCaseCount()
        {
            var notIntactCount = client.Queryable<Sugar_Drone_caseinfo>().Where(c => c.is_intact == 0).Count();
            var intactCount = client.Queryable<Sugar_Drone_caseinfo>().Where(c => c.is_intact == 1).Count();

            JObject obj = new JObject();
            obj.Add("notIntactCount", notIntactCount);
            obj.Add("intactCount", intactCount);

            return obj;
        }

        /// <summary>
        /// 违建分类统计
        /// </summary>
        /// <returns></returns>
        public object GetDroneTypeCount(string areaid, int? is_dealer = null)
        {
            var list = GetCaseQueryable()
                .GroupBy(c => new { c.typename })
                .Select(c => new
                {
                    c.typename,
                    count = SqlFunc.AggregateCount(c.Id)
                }).ToList();

            var user = _auth.GetCurrentUser().User;

            //待核查
            var status0 = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = is_dealer, handle_status_id = 0, is_examine = 0, countyid = areaid }, user).Count();

            //合法
            var status1 = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = is_dealer, is_illegal = 0, countyid = areaid }, user).Count();

            //拆除
            var status2 = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = is_dealer, is_illegal = 1, measure_name_type = 0, countyid = areaid }, user).Count();

            //查处
            var status3 = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = is_dealer, is_illegal = 1, measure_name_type = 1, countyid = areaid }, user).Count();

            //完善手续
            var status4 = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = is_dealer, is_illegal = 1, measure_name_type = 2, countyid = areaid }, user).Count();

            //伪变化
            var status5 = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = is_dealer, is_illegal = 2, countyid = areaid }, user).Count();

            JArray array = new JArray();
            //for (int i = 0; i < list.Count; i++)
            //{
            //    var item = list[i];
            //    string typename = item.typename;
            //    int count = item.count;

            //    if (string.IsNullOrEmpty(typename))
            //        typename = "未知";

            //    JObject obj = new JObject();
            //    obj.Add("typename", typename);
            //    obj.Add("count", count);

            //    array.Add(obj);
            //}
            JObject obj0 = new JObject();
            obj0.Add("typename", "待核查");
            obj0.Add("count", status0);

            JObject obj1 = new JObject();
            obj1.Add("typename", "合法");
            obj1.Add("count", status1);

            JObject obj2 = new JObject();
            obj2.Add("typename", "拆除");
            obj2.Add("count", status2);

            JObject obj3 = new JObject();
            obj3.Add("typename", "查处");
            obj3.Add("count", status3);

            JObject obj4 = new JObject();
            obj4.Add("typename", "完善手续");
            obj4.Add("count", status4);

            JObject obj5 = new JObject();
            obj5.Add("typename", "伪变化");
            obj5.Add("count", status5);

            array.Add(obj0);
            array.Add(obj1);
            array.Add(obj2);
            array.Add(obj3);
            array.Add(obj4);
            array.Add(obj5);

            return array;

        }

        /// <summary>
        /// 按乡镇统计
        /// </summary>
        /// <param name="id">行政区划id</param>
        /// <returns></returns>
        public JArray GetDroneOrgCount(string id)
        {

            //string countyName = _configuration.GetSection("CountyName").Value;
            var areaid = id;
            if (string.IsNullOrEmpty(id))
            {
                areaid = _configuration.GetSection("AppSetting:TopAreaCode").Value;
            }

            JArray array = new JArray();
            var area = client.Queryable<SysOrg>().Where(c => c.Id.ToString() == areaid).First();
            if (area != null)
            {
                var childrenList = client.Queryable<SysOrg>().Where(c => c.ParentId == area.Id).OrderBy(c => c.SortNo, OrderByType.Asc).OrderBy(c => c.CreateTime, OrderByType.Asc).ToList();
                var today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));

                //案件上报数量
                var caseList = GetDatas(GetCaseQueryable(new GetQueryCaseReq { streetid = id }), area);
                //今日案件上报数量
                var caseTodayList = GetDatas(GetCaseQueryable(new GetQueryCaseReq { streetid = id }).Where(c => c.identification_time > today), area);
                //历史案件上报数量
                var caseHistoryList = GetDatas(GetCaseQueryable(new GetQueryCaseReq { streetid = id }).Where(c => c.identification_time < today), area);
                //未办理
                var statusFirst = GetDatas(GetCaseQueryable(new GetQueryCaseReq { streetid = id }).Where(c => c.handle_status_id == 0), area);
                //待审核
                var statusSecond = GetDatas(GetCaseQueryable(new GetQueryCaseReq { streetid = id }).Where(c => c.handle_status_id == 1), area);
                //已办结
                var statusThrid = GetDatas(GetCaseQueryable(new GetQueryCaseReq { streetid = id }).Where(c => c.handle_status_id == 2), area);

                //遍历乡镇
                for (int i = 0; i < childrenList.Count; i++)
                {
                    //当前乡镇
                    var _item = childrenList[i];

                    int _reportCount = 0;   //上报数量
                    int todayCount = 0;     //今日上报
                    int historyCount = 0;   //历史上报
                    int firstCount = 0;     //未办理
                    int secondCount = 0;    //待审核
                    int thridCount = 0;     //已办结

                    //当前乡镇上报的数量
                    var _caseModel = caseList.Where(c => c.areaid == _item.Id.ToString()).FirstOrDefault();
                    //今日案件数
                    var todayCaseModel = caseTodayList.Where(c => c.areaid == _item.Id.ToString()).FirstOrDefault();
                    //历史案件数
                    var historyCaseModel = caseHistoryList.Where(c => c.areaid == _item.Id.ToString()).FirstOrDefault();

                    //未办理
                    var firstCountModel = statusFirst.Where(c => c.areaid == _item.Id.ToString()).FirstOrDefault();
                    //待审核
                    var secondCountModel = statusSecond.Where(c => c.areaid == _item.Id.ToString()).FirstOrDefault();
                    //已办结
                    var thridCountModel = statusThrid.Where(c => c.areaid == _item.Id.ToString()).FirstOrDefault();

                    if (_caseModel != null)
                        _reportCount = _caseModel.count;
                    if (todayCaseModel != null)
                        todayCount = todayCaseModel.count;
                    if (historyCaseModel != null)
                        historyCount = historyCaseModel.count;

                    if (firstCountModel != null)
                        firstCount = firstCountModel.count;
                    if (secondCountModel != null)
                        secondCount = secondCountModel.count;
                    if (thridCountModel != null)
                        thridCount = thridCountModel.count;

                    JObject obj = new JObject();
                    obj.Add("name", _item.Name);
                    obj.Add("areaid", _item.Id.ToString());
                    obj.Add("reportCount", _reportCount);
                    obj.Add("todayCount", todayCount);
                    obj.Add("historyCount", historyCount);

                    obj.Add("firstCount", firstCount);
                    obj.Add("secondCount", secondCount);
                    obj.Add("thridCount", thridCount);

                    array.Add(obj);
                }
            }
            return array;

        }

        public List<CountRes> GetDatas(ISugarQueryable<DroneCaseInfoSingle> querys, SysOrg area)
        {
            var res = new List<CountRes>();
            var query = querys.Select(c => new
            {
                c.countyid,
                c.streetid,
                c.communityid,
                c.Id
            }).MergeTable();
            switch (area.Level)
            {
                case 0:

                    res = query.GroupBy(c => new { c.countyid })
                                       .Select(c => new CountRes
                                       {
                                           areaid = c.countyid,
                                           count = SqlFunc.AggregateCount(c.Id)
                                       })
                                       .ToList();
                    // Process result0
                    break;
                case 1:
                    res = query.GroupBy(c => new { c.streetid })
                                       .Select(c => new CountRes
                                       {
                                           areaid = c.streetid,
                                           count = SqlFunc.AggregateCount(c.Id)
                                       })
                                       .ToList();
                    // Process result1
                    break;
                case 2:
                    res = query.GroupBy(c => new { c.communityid })
                                       .Select(c => new CountRes
                                       {
                                           areaid = c.communityid,
                                           count = SqlFunc.AggregateCount(c.Id)
                                       })
                                       .ToList();
                    // Process result2
                    break;
                default:
                    // Handle default case
                    break;
            }
            return res;
        }

        /// <summary>
        /// 案件线索统计-费城街道工作区
        /// </summary>
        /// <returns></returns>
        public JArray GetDroneCityOrgCount()
        {
            string countyName = _configuration.GetSection("CountyName").Value;
            if (string.IsNullOrEmpty(countyName)) countyName = "费城街道";

            var countyid = client.Queryable<SysOrg>().Where(c => c.Name == countyName).Select(c => c.Id).First();
            var streetList = client.Queryable<SysOrg>().Where(c => c.ParentId == countyid).GroupBy(c => c.CustomCode).Select(c => c.CustomCode).ToList();

            #region 案件数量

            //费城街道
            var feicheng = GetCaseQueryable().Where(c => c.streetname.Contains("费城街道")).ToList();
            //今天
            var today = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            //案件上报数量
            var caseList = feicheng.Select(c => new { c.communityid }).ToList();
            //今日案件上报数量
            var caseTodayList = feicheng.Where(c => c.identification_time > today).Select(c => new { c.communityid }).ToList();
            //历史案件上报数量
            var caseHistoryList = feicheng.Where(c => c.identification_time < today).Select(c => new { c.communityid }).ToList();
            //未办理
            var statusFirst = feicheng.Where(c => c.handle_status_id == 0).Select(c => new { c.communityid }).ToList();
            //待审核
            var statusSecond = feicheng.Where(c => c.handle_status_id == 1).Select(c => new { c.communityid }).ToList();
            //已办结
            var statusThrid = feicheng.Where(c => c.handle_status_id == 2).Select(c => new { c.communityid }).ToList();

            #endregion

            JArray array = new JArray();
            for (int i = 0; i < streetList.Count; i++)
            {
                JObject obj = new JObject();
                int _reportCount = 0;   //上报数量
                int todayCount = 0;     //今日上报
                int historyCount = 0;   //历史上报
                int noCount = 0;     //未办理
                int auditCount = 0;    //待审核
                int finishCount = 0;     //已办结 

                var item = streetList[i];
                var org_id = client.Queryable<SysOrg>().Where(c => c.CustomCode == item).Select(c => c.Id).ToList();
                for (int k = 0; k < org_id.Count; k++)
                {
                    var _item = org_id[k];
                    var _caseModel = caseList.Where(c => c.communityid == _item.ToString()).Count();
                    if (_caseModel > 0)
                        _reportCount += _caseModel;
                    //今日案件数
                    var todayCaseModel = caseTodayList.Where(c => c.communityid == _item.ToString()).Count();
                    if (todayCaseModel > 0)
                        todayCount += todayCaseModel;
                    //历史案件数
                    var historyCaseModel = caseHistoryList.Where(c => c.communityid == _item.ToString()).Count();
                    if (historyCaseModel > 0)
                        historyCount += historyCaseModel;
                    //未办理
                    var firstCountModel = statusFirst.Where(c => c.communityid == _item.ToString()).Count();
                    if (firstCountModel > 0)
                        noCount += firstCountModel;
                    //待审核
                    var secondCountModel = statusSecond.Where(c => c.communityid == _item.ToString()).Count();
                    if (secondCountModel > 0)
                        auditCount += secondCountModel;
                    //已办结
                    var thridCountModel = statusThrid.Where(c => c.communityid == _item.ToString()).Count();
                    if (thridCountModel > 0)
                        finishCount += thridCountModel;
                }

                obj.Add("name", item);
                obj.Add("reportCount", _reportCount);
                obj.Add("todayCount", todayCount);
                obj.Add("historyCount", historyCount);

                obj.Add("noCount", noCount);
                obj.Add("auditCount", auditCount);
                obj.Add("finishCount", finishCount);

                array.Add(obj);
            }

            return array;

        }

        /// <summary>
        /// 数据统计，按天统计图表
        /// </summary>
        /// <returns></returns>
        public JArray GetDroneCaseDateCount(string type, string streetId)
        {

            DateTime begin = DateTime.Parse(DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd"));
            if (type == "week")
            {
                begin = DateTime.Parse(DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd"));
            }
            else if (type == "month")
            {
                begin = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01"));
            }

            //查询案件数据
            var reportList = GetCaseQueryable(new GetQueryCaseReq { streetid = streetId })
                .Where(c => c.identification_time > begin).Select(c => new { c.Id, identification_time = c.identification_time }).ToList();

            var dealList = GetCaseQueryable().Where(c => c.examine_time > begin)
                .WhereIF(!string.IsNullOrEmpty(streetId), c => c.streetid == streetId)
                .Select(c => new { c.Id, c.examine_time }).ToList();
            //var dealList = GetDealQueryable(db).Where(c => c.createtime > begin)
            //    .WhereIF(!string.IsNullOrEmpty(streetId), c => SqlFunc.Subqueryable<Sugar_Drone_caseinfo>().Where(it => it.streetid == streetId && it.Id == c.caseid).Any())
            //    .Select(c => new { c.Id, c.createtime }).ToList();

            JArray array = new JArray();
            while (begin < DateTime.Now)
            {
                JObject obj = new JObject();

                //日期
                obj.Add("day", begin.ToString("yyyy-MM-dd"));

                //过滤查询数量
                int reportCount = reportList.Where(c => c.identification_time >= begin && c.identification_time < begin.AddDays(1)).Count();
                int dealCount = dealList.Where(c => c.examine_time >= begin && c.examine_time < begin.AddDays(1)).Count();

                //数量
                obj.Add("reportCount", reportCount);
                obj.Add("dealCount", dealCount);

                array.Add(obj);

                //日期+1天
                begin = begin.AddDays(1);
            }

            return array;

        }

        /// <summary>
        /// 查询GeoJson
        /// </summary>
        /// <returns></returns>
        public JToken GetDroneGeoJson()
        {
            QueryGeoJsonCommonReq req = new QueryGeoJsonCommonReq();
            req.tablename = "view_drone_shp_data";
            req.pageIndex = 1;
            req.limit = 2000;

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

        /// <summary>
        /// 获取无人机的位置
        /// </summary>
        /// <returns></returns>
        public object GetDroneLocationPoints()
        {
            string time = DateTime.Now.AddMinutes(-3).ToString("yyyy-MM-dd HH:mm:ss");
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" select \"createuser\",\"createtime\", replace(replace(replace(st_astext(geom),'POINT(',''),')',''),' ',',') point from ");
            sql.AppendFormat($" (");
            sql.AppendFormat($"      SELECT \"createuser\",createtime,geom,\"row_number\"() OVER (PARTITION by \"createuser\" ORDER BY createtime desc) rownum FROM \"drone_point_data\" where createtime > '{time}' ");
            sql.AppendFormat($" ) aa where aa.rownum = 1");

            var list = client.SqlQueryable<dynamic>(sql.ToString()).ToList();
            return list;
        }
        /// <summary>
        /// 获取无人机的历史轨迹
        /// </summary>
        /// <returns></returns>
        public object GetDroneLocationPointsHistory(DateTime startTime, DateTime endTime, string userId)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" select \"createuser\",\"createtime\", replace(replace(replace(st_astext(geom),'POINT(',''),')',''),' ',',') point FROM \"drone_point_data\" where createtime > '{startTime}' and createtime < '{endTime}' and \"createuser\" = '{userId}' order by \"createtime\" desc");
            var list = client.SqlQueryable<dynamic>(sql.ToString()).ToList();
            return list;
        }

        /// <summary>
        /// 无人机飞行 假数据
        /// </summary>
        /// <returns></returns>
        public object GetDroneLocationPointsFalse()
        {
            JArray array = new JArray();

            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" select \"createuser\",\"createtime\", replace(replace(replace(st_astext(geom),'POINT(',''),')',''),' ',',') point from ");
            sql.AppendFormat($" drone_point_data where createtime > '2022-02-11' and createtime < '2022-02-12' order by createtime asc ");
            //var listFirst = db.SqlQueryable<dynamic>(sql.ToString()).ToList().ToJson();

            sql = new StringBuilder();
            sql.AppendFormat($" select \"createuser\",\"createtime\", replace(replace(replace(st_astext(geom),'POINT(',''),')',''),' ',',') point from ");
            sql.AppendFormat($" drone_point_data where createtime > '2022-02-15' and createtime < '2022-02-16' order by createtime asc ");
            //var listSecond = db.SqlQueryable<dynamic>(sql.ToString()).ToList().ToJson();

            JObject objA = new JObject();
            objA.Add("name", "listFirst");
            objA.Add("point", (JToken)JsonConvert.DeserializeObject("[{\"createuser\":\"13280580815\",\"createtime\":\"2022-04-22 14:22:22\",\"point\":\"117.72339712649222,35.05450202665419\"}]"));
            //117.72339712649222,35.05450202665419
            array.Add(objA);

            JObject objB = new JObject();
            objB.Add("name", "listSecond");
            objB.Add("point", (JToken)JsonConvert.DeserializeObject("[{\"createuser\":\"13280580815\",\"createtime\":\"2022-04-22 14:22:22\",\"point\":\"117.71858685321234,35.22679558236362\"}]"));
            //117.71858685321234,35.22679558236362
            array.Add(objB);

            JObject objC = new JObject();
            objC.Add("name", "listSecond");
            objC.Add("point", (JToken)JsonConvert.DeserializeObject("[{\"createuser\":\"13280580815\",\"createtime\":\"2022-04-22 14:22:22\",\"point\":\"118.07365607557824,35.20530775653663\"}]"));
            //118.07365607557824,35.20530775653663
            array.Add(objC);

            JObject objD = new JObject();
            objD.Add("name", "listSecond");
            objD.Add("point", (JToken)JsonConvert.DeserializeObject("[{\"createuser\":\"13280580815\",\"createtime\":\"2022-04-22 14:22:22\",\"point\":\"117.98160109200148,35.28244211798609\"}]"));
            //117.98160109200148,35.28244211798609
            array.Add(objD);

            JObject objE = new JObject();
            objE.Add("name", "listSecond");
            objE.Add("point", (JToken)JsonConvert.DeserializeObject("[{\"createuser\":\"13280580815\",\"createtime\":\"2022-04-22 14:22:22\",\"point\":\"117.97323242064601,35.521189135282015\"}]"));
            //117.97323242064601,35.521189135282015
            array.Add(objE);

            return array;

        }

        /// <summary>
        /// 获取无人机的在线率
        /// </summary>
        /// <returns></returns>
        public JObject GetDroneOnlinePercent()
        {

            string time = DateTime.Now.AddMinutes(-3).ToString("yyyy-MM-dd HH:mm:ss");
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat($" select \"createuser\",\"createtime\", replace(replace(replace(st_astext(geom),'POINT(',''),')',''),' ',',') point from ");
            sql.AppendFormat($" (");
            sql.AppendFormat($"      SELECT \"createuser\",createtime,geom,\"row_number\"() OVER (PARTITION by \"createuser\" ORDER BY createtime desc) rownum FROM \"drone_point_data\" where createtime > '{time}' ");
            sql.AppendFormat($" ) aa where aa.rownum = 1");

            //无人机在线数量
            var onlineCount = client.SqlQueryable<dynamic>(sql.ToString()).Count();

            //无人机的总数量
            var totalCount = client.SqlQueryable<dynamic>("select distinct(\"createuser\") \"name\" from drone_point_data").Count();

            onlineCount += 5;
            totalCount += 5;

            decimal onlinePercent = Decimal.Round(100 * Decimal.Parse(onlineCount.ToString()) / Decimal.Parse(totalCount.ToString()), 2);

            JObject obj = new JObject();
            obj.Add("onlineCount", onlineCount);
            obj.Add("offlineCount", totalCount - onlineCount);
            obj.Add("totalCount", totalCount);
            obj.Add("onlinePercent", onlinePercent);

            return obj;

        }

        /// <summary>
        /// 统计图表已完成未完成数量
        /// </summary>
        /// <returns></returns>
        public JObject GetDroneCaseCompleteCount(string areaid)
        {
            JObject obj = new JObject();

            //线索总数
            var cluesCount = GetCaseQueryable(new GetQueryCaseReq { streetid = areaid }).Count();
            //待核查 数量0
            var unHandCount = GetCaseQueryable(new GetQueryCaseReq { handle_status_id = 0, is_examine = 0, streetid = areaid }).Count();

            //待办理 数量0
            var unDealCount = GetCaseQueryable(new GetQueryCaseReq { handle_status_id = 0, is_examine = 1, streetid = areaid }).Count();

            //待审核 数量1
            var inHandCount = GetCaseQueryable(new GetQueryCaseReq { handle_status_id = 1, streetid = areaid }).Count();

            //已完成 数量2
            var completeCount = GetCaseQueryable(new GetQueryCaseReq { handle_status_id = 2, streetid = areaid }).Count();

            //全部
            obj.Add("cluesCount", cluesCount);
            //未核查 核查定性
            obj.Add("unHandCount", unHandCount);
            //待办理 处置办理--暂时没用
            obj.Add("unDealCount", unDealCount);
            //待审核 监督审核
            obj.Add("inHandCount", inHandCount);
            //已办结 查验归档
            obj.Add("completeCount", completeCount);

            return obj;

        }

        /// <summary>
        /// APP案件数量查询
        /// </summary>
        /// <returns></returns>
        public CaseProcessStatData GetCaseProcessStatData(QueryCaseProcessStatDataReq req)
        {

            var current = _auth.GetCurrentUser();
            var user = current.User;
            var roles = current.Roles.Select(c => c.Id.ToString()).ToList();

            CaseProcessStatData data = new CaseProcessStatData
            {
                // 核查定性
                proofread_confirm_new = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 0, is_drawback = 0 }, user).Count(),
                proofread_confirm_drawback = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 0, is_drawback = 1 }, user).Count(),
                // 处置办理
                handle_demolish = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 1, measure_name = "拟拆除" }, user).Count(),
                handle_detain = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 1, measure_name = "查处" }, user).Count(),
                handle_perfection = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 1, measure_name = "拟完善手续" }, user).Count(),
                handle_legal = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 0, is_examine = 1, is_illegal = 0 }, user).Count(),
                // 监督审核
                audit_demolish = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 1, measure_name = "拟拆除", is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_detain = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 1, measure_name = "查处", is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_perfection = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 1, measure_name = "拟完善手续", is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_legal = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 0, is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                audit_fakeChange = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 1, is_illegal = 2, is_verify_filter = req.is_verify_filter }, user, roles: roles).Count(),
                // 归档
                archive_demolish = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 1, measure_name = "拟拆除" }, user).Count(),
                archive_detain = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 1, measure_name = "查处" }, user).Count(),
                archive_perfection = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 1, measure_name = "拟完善手续" }, user).Count(),
                archive_legal = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 0 }, user).Count(),
                archive_fakeChange = QueryCaseInfoList(new QueryCaseInfoListReq { is_intact = 1, is_dealer = 1, handle_status_id = 2, is_illegal = 2 }, user).Count()
            };

            // 汇总
            //data.proofread_confirm_sum = data.proofread_confirm_drawback + data.proofread_confirm_new;
            //data.handle_sum = data.handle_demolish + data.handle_detain + data.handle_legal + data.handle_perfection;
            //data.audit_sum = data.audit_demolish + data.audit_detain + data.audit_fakeChange + data.audit_legal + data.audit_perfection;
            //data.archive_sum = data.archive_demolish + data.archive_detain + data.archive_fakeChange + data.archive_legal + data.archive_perfection;
            return data;

        }

        /// <summary>
        /// 基于乡镇的案件数量统计
        /// </summary>
        /// <returns></returns>
        public List<CaseStatDataPerTown> GetCaseProcessStatDataPerTown(QueryCaseInfoListReq req)
        {
            string countyName = _configuration.GetSection("CountyName").Value;
            if (string.IsNullOrEmpty(countyName)) countyName = "费县";
            var orgList = client.Queryable<SysOrg>().Where(c => c.ParentName == countyName).OrderBy(c => c.SortNo, OrderByType.Asc).ToList();

            var user = _auth.GetCurrentUser().User;

            List<CaseStatDataPerTown> statDataList = new List<CaseStatDataPerTown>();

            // 核查定性
            var reqBody = req.MapTo<QueryCaseInfoListReq>();
            reqBody.is_intact = 1;
            reqBody.handle_status_id = 0;
            reqBody.is_examine = 0;
            var list0 = QueryCaseInfoList(reqBody, user, 0)
                  .GroupBy(c => new { c.streetname, c.streetid })
                  .Select(c => new { c.streetname, c.streetid, count = SqlFunc.AggregateCount(c.Id) })
                  .OrderBy(c => c.streetname).ToList();

            // 处置办理
            reqBody = req.MapTo<QueryCaseInfoListReq>();
            reqBody.is_intact = 1;
            reqBody.handle_status_id = 0;
            reqBody.is_examine = 1;
            var list1 = QueryCaseInfoList(reqBody, user, 0)
                  .GroupBy(c => new { c.streetname, c.streetid })
                  .Select(c => new { c.streetname, c.streetid, count = SqlFunc.AggregateCount(c.Id) })
                  .OrderBy(c => c.streetname).ToList();

            // 监督审核
            reqBody = req.MapTo<QueryCaseInfoListReq>();
            reqBody.is_intact = 1;
            reqBody.handle_status_id = 1;
            var list2 = QueryCaseInfoList(reqBody, user, 0)
                  .GroupBy(c => new { c.streetname, c.streetid })
                  .Select(c => new { c.streetname, c.streetid, count = SqlFunc.AggregateCount(c.Id) })
                  .OrderBy(c => c.streetname).ToList();

            // 归档
            reqBody = req.MapTo<QueryCaseInfoListReq>();
            reqBody.is_intact = 1;
            reqBody.handle_status_id = 2;
            var list3 = QueryCaseInfoList(reqBody, user, 0)
                  .GroupBy(c => new { c.streetname, c.streetid })
                  .Select(c => new { c.streetname, c.streetid, count = SqlFunc.AggregateCount(c.Id) })
                  .OrderBy(c => c.streetname).ToList();

            foreach (var item in orgList)
            {
                //核查定性
                var count0 = list0.Where(c => c.streetid == item.Id.ToString()).Sum(c => c.count);

                //处置办理
                var count1 = list1.Where(c => c.streetid == item.Id.ToString()).Sum(c => c.count);

                //监督审核
                var count2 = list2.Where(c => c.streetid == item.Id.ToString()).Sum(c => c.count);

                //核验归档
                var count3 = list3.Where(c => c.streetid == item.Id.ToString()).Sum(c => c.count);

                CaseStatDataPerTown resultItem = new CaseStatDataPerTown
                {
                    TownId = item.Id.ToString(),
                    TownName = item.Name,
                    ProofreadCount = count0,
                    HandleCount = count1,
                    AuditCount = count2,
                    ArchiveCount = count3,
                };
                statDataList.Add(resultItem);
            }

            return statDataList;

        }

        /// <summary>
        /// 是否是费城街道
        /// </summary>
        /// <returns></returns>
        public int IsFeiChengStreet()
        {
            var user = _auth.GetCurrentUser().User;

            int res = 0;

            var count = client.Queryable<SysRelevance, SysOrg>((r, o) => new JoinQueryInfos(
                    JoinType.Left, r.SecondId == o.Id.ToString()
                 )).Where((r, o) => (o.Name.Contains("费城街道") || o.ParentName.Contains("费城街道")) && r.FirstId == user.Id.ToString() && r.Key == Define.USERORG).Count();
            if (count > 0)
            {
                res = 1;
            }

            return res;

        }

        /// <summary>
        /// 获取处理详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="caseid"></param>
        /// <returns></returns>
        public AddOrUpdateDroneCaseDealReq GetDroneCaseDeal(string id, string caseid)
        {
            AddOrUpdateDroneCaseDealReq res = new AddOrUpdateDroneCaseDealReq();
            res.Init();

            //详情
            var info = client.Queryable<DroneCaseDeal>()
                .WhereIF(!string.IsNullOrEmpty(id), c => c.Id == id)
                .WhereIF(!string.IsNullOrEmpty(caseid), c => c.caseid == caseid)
                .Where(c => c.is_delete == 0 || c.is_delete == null)
                .OrderBy(c => c.createtime, OrderByType.Desc)
                .First();
            if (info == null)
            {
                return res;
            }
            //文件
            var fileList = client.Queryable<DroneFiles>().Where(c => c.relid == info.Id && (c.is_delete == null || c.is_delete == 0) && c.tablename == "drone_case_deal").ToList();

            //图片
            List<PicInfo> picInfoList = fileList.Where(c => c.type == 0 && (c.tag == null || c.tag == "")).Select(c => new PicInfo
            {
                FilePath = c.path,
                Latitude = c.latitude,
                Longitude = c.longitude,
                Angle = c.angle,
            }).ToList();

            //整改后照片
            List<PicInfo> afterPicList = fileList.Where(c => c.type == 0 && c.tag == afterPicTag).Select(c => new PicInfo
            {
                FilePath = c.path,
                Latitude = c.latitude,
                Longitude = c.longitude,
                Angle = c.angle,
            }).ToList();

            //合法材料
            List<PicInfo> evidenceFileList = fileList.Where(c => c.type == 0 && c.tag == EvidenceFileTag).Select(c => new PicInfo
            {
                FilePath = c.path,
                Latitude = c.latitude,
                Longitude = c.longitude,
                Angle = c.angle,
            }).ToList();

            //处罚通知书
            var punish_pic_list = fileList.Where(c => c.type == 0 && c.tag == punishPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //交款通知书
            var payment_pic_list = fileList.Where(c => c.type == 0 && c.tag == paymentPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //政府同意完善手续证明
            var agree_checkout_pic_list = fileList.Where(c => c.type == 0 && c.tag == agreeCheckoutPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //办理手续
            var checkout_pic_list = fileList.Where(c => c.type == 0 && c.tag == checkoutPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //勘测定界图
            var boundary_pic_list = fileList.Where(c => c.type == 0 && c.tag == boundaryPicTag).GroupBy(c => c.path).Select(c => c.Key).ToList();

            //视频
            var video_list = fileList.Where(c => c.type == 1 && (c.tag == null || c.tag == "")).GroupBy(c => c.path).Select(c => c.Key).ToList();

            var remove_video_list = fileList.Where(c => c.type == 1 && (c.tag == "remove")).GroupBy(c => c.path).Select(c => c.Key).ToList();
            //详情
            res.info = info;
            //照片
            res.pic_info_list = picInfoList;
            //整改后照片
            res.after_pic_list = afterPicList;
            //合法材料
            res.evidence_file_list = evidenceFileList;
            //处罚通知书
            res.punish_pic_list = punish_pic_list;
            //交款通知书
            res.payment_pic_list = payment_pic_list;
            //政府同意完善手续证明
            res.agree_checkout_pic_list = agree_checkout_pic_list;
            //办理手续
            res.checkout_pic_list = checkout_pic_list;
            //勘测定界图
            res.boundary_pic_list = boundary_pic_list;
            //视频
            res.video_list = video_list;
            //拆除视频
            res.remove_video_list = remove_video_list;

            var caseModel = client.Queryable<Sugar_Drone_caseinfo>()
                .Where(c => c.Id == info.caseid)
                .First();
            res.handle_status_id = caseModel.handle_status_id.Value;
            res.is_illegal = caseModel.is_illegal;

            var current = _auth.GetCurrentUser();
            var roleList = current.Roles;
            //判断是否有审核权限
            var roles = roleList.Select(c => c.Id.ToString()).ToList();
            //查询用户角色绑定的流程有哪些
            var flowList = client.Queryable<DroneRelevance>().Where(c => roles.Contains(c.SecondId) && c.Key == Define.FLOW_ROLE).Select(c => c.FirstId).ToList();
            //查询用户绑定的流程Sort，用于判断用户是否有权限来审核
            var currentFlowList = client.Queryable<DroneFlowInstance>().Where(c => flowList.Contains(c.Id) && c.status == 0 && c.instance_name == "CaseVerify").Select(c => c.sort).ToList();

            //审核状态和处理状态
            var verifystatus = caseModel.verifystatus;
            var handle_status_id = caseModel.handle_status_id;

            //审核
            if (handle_status_id == 1)
            {
                //当前角色绑定的流程
                var count = currentFlowList.Where(c => c == verifystatus).Count();
                var hasVerifyRole = roleList.Where(c => c.Name == "案件审核").Count();
                if (count > 0 && hasVerifyRole > 0)
                {
                    res.can_verify = 1;
                }
            }

            return res;

        }

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

            //详情
            DroneCaseInfoSingle info = null;
            var flag = Infrastructure.Extensions.StringExtension.IsGuid(id);
            if (flag)
            {
                info = await client.Queryable<DroneCaseInfoSingle>().Where(c => c.Id == id).FirstAsync();
            }
            else
            {
                info = await client.Queryable<DroneCaseInfoSingle>().Where(c => c.case_no == id).FirstAsync();
            }

            ////工作区
            //var work_area = string.Empty;
            //if (info.streetname.Contains("费城街道") && !string.IsNullOrEmpty(info.communityid))
            //    work_area = await this.Repository.AsSugarClient().Queryable<SysOrg>().Where(c => c.Id.ToString() == info.communityid).Select(c => c.CustomCode).FirstAsync();

            //文件
            var fileList = await client.Queryable<DroneFiles>().Where(c => c.relid == info.Id && (c.is_delete == null || c.is_delete == 0) && c.tablename == "drone_caseinfo").ToListAsync();

            ////图片
            //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 = await client.Queryable<DroneCaseInfoRelation>().Where(a => a.caseid == info.Id).Select(a => a.relation_case_no).ToListAsync();

            //案件标签
            var tags = await client.Queryable<DroneCaseInfoTag>()
                .LeftJoin<SysCategory>((t, c) => t.tagid == c.Id.ToString())
                .Where((t, c) => t.caseid == info.Id && c.TypeId == "DRONE_CASE_TAG")
                .Select((t, c) => c.Name).ToListAsync();

            //图斑的中心点
            StringBuilder sql = new StringBuilder();
            if (!string.IsNullOrEmpty(info.geomid))
            {
                sql.AppendFormat($"SELECT st_astext(ST_Centroid(geom)) lnglat FROM \"drone_shp_data\" where gid in ({info.geomid}) and geom is not null");
                var dt = await client.Ado.GetDataTableAsync(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);
                }
                else
                {
                    res.lng = info.lng;
                    res.lat = info.lat;
                }
            }


            //res.work_area = work_area;
            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;

            return new Response<ScreenDroneCaseInfoReq>
            {
                Result = res,
                Message = "获取数据成功"
            };
        }
        #endregion

        #region  首页大屏
        public Response<List<dynamic>> GetTrendData(int datatype, string begindate, string enddate, string countyid, string type)
        {
            DateTime begin = DateTime.Now.AddDays(-10).Date;
            DateTime end = DateTime.Now;
            if (string.IsNullOrEmpty(begindate) || string.IsNullOrEmpty(enddate))
            {
                if (datatype == 1)
                {
                    begin = Convert.ToDateTime(DateTime.Now.AddMonths(-10).ToString("yyyy-MM-01"));
                    end = DateTime.Now;
                }
            }
            else
            {
                begin = Convert.ToDateTime(begindate);
                end = Convert.ToDateTime(enddate);
            }

            //聚合时间格式处理
            string format = "yyyy-MM-dd";
            if (datatype == 1)
            {
                format = "yyyy-MM";
            }
            var casetype = client.Queryable<SysDataItemDetail>()
              .Where(r => r.ItemName == type).First()?.ItemDetailId;

            //var caselistss = client.Queryable<DroneCaseInfoSingle>()
            //    .Where(r => r.createtime >= begin && r.createtime < end && r.createtime != null && r.typeid == casetype && r.is_closed == 0)
            //     .WhereIF(!string.IsNullOrEmpty(countyid), r => r.countyid == countyid)
            //    .OrderBy(r => r.createtime)
            //    .Select(r => new ChartCaseInfo
            //    {
            //        Id = r.Id,
            //        createtime = Convert.ToDateTime(r.createtime).ToString(format),
            //        is_illegal = r.is_illegal,
            //        measure_name = r.measure_name,
            //        handle_status_id = r.handle_status_id
            //    })
            //    .MergeTable()
            //    .GroupBy(it => it.createtime)
            //    .Select<dynamic>(it => new
            //    {
            //        //时间
            //        time = it.createtime,
            //        //违法
            //        illegal = SqlFunc.Subqueryable<DroneCaseInfoSingle>().Where(c => (c.is_illegal == 1 || c.handle_status_id != 5) && c.createtime != null && Convert.ToDateTime(c.createtime).ToString(format) == it.createtime && c.typeid == casetype && c.is_closed == 0&&c.countyid == countyid).Count(),
            //        //合法
            //        unillegal = SqlFunc.Subqueryable<DroneCaseInfoSingle>().Where(c => c.is_illegal == 0 && c.handle_status_id == 5 && c.createtime != null && Convert.ToDateTime(c.createtime).ToString(format) == it.createtime && c.typeid == casetype && c.is_closed == 0 && c.countyid == countyid).Count(),
            //        //其他
            //        other = SqlFunc.Subqueryable<DroneCaseInfoSingle>().Where(c => c.is_illegal == 2 && c.handle_status_id == 5 && c.createtime != null && Convert.ToDateTime(c.createtime).ToString(format) == it.createtime && c.typeid == casetype && c.is_closed == 0 && c.countyid == countyid).Count(),
            //        //复耕
            //        fugeng = SqlFunc.Subqueryable<DroneCaseInfoSingle>().Where(c => c.measure_name == "0" && c.handle_status_id == 5 && c.createtime != null && Convert.ToDateTime(c.createtime).ToString(format) == it.createtime && c.typeid == casetype && c.is_closed == 0 && c.countyid == countyid).Count(),
            //        //补办
            //        buban = SqlFunc.Subqueryable<DroneCaseInfoSingle>().Where(c => c.measure_name == "1" && c.handle_status_id == 5 && c.createtime != null && Convert.ToDateTime(c.createtime).ToString(format) == it.createtime && c.typeid == casetype && c.is_closed == 0 && c.countyid == countyid).Count(),
            //    }).ToList();



            //查询案件信息
            var caselistss = client.Queryable<DroneCaseInfoSingle>()
                .Where(r => r.createtime >= begin && r.createtime < end && r.createtime != null && r.typeid == casetype && r.is_closed == 0)
                 .WhereIF(!string.IsNullOrEmpty(countyid), c => c.countyid == countyid)
                .OrderBy(r => r.createtime)
                .Select(r => new ChartCaseInfo
                {
                    Id = r.Id,
                    createtime = Convert.ToDateTime(r.createtime).ToString(format),
                    is_illegal = r.is_illegal,
                    measure_name = r.measure_name,
                    handle_status_id = r.handle_status_id
                })
                .MergeTable()
                .GroupBy(it => it.createtime)
                .Select<dynamic>(it => new
                {
                    //时间
                    time = it.createtime,
                    //违法
                    illegal = SqlFunc.AggregateSum(SqlFunc.IIF((it.is_illegal == 1 || it.handle_status_id != 5), 1, 0)),
                    //合法
                    unillegal = SqlFunc.AggregateSum(SqlFunc.IIF(it.is_illegal == 0 && it.handle_status_id == 5, 1, 0)),
                    //其他
                    other = SqlFunc.AggregateSum(SqlFunc.IIF(it.is_illegal == 2 && it.handle_status_id == 5, 1, 0)),
                    //复耕
                    fugeng = SqlFunc.AggregateSum(SqlFunc.IIF(it.measure_name == "0" && it.handle_status_id == 5, 1, 0)),
                    //补办
                    buban = SqlFunc.AggregateSum(SqlFunc.IIF(it.measure_name == "1" && it.handle_status_id == 5, 1, 0)),
                }).ToList();

            return new Response<List<dynamic>>
            {
                Result = caselistss,
                Message = "获取数据成功"
            };
        }
        #endregion

        #region 新版大屏
        /// <summary>
        /// 总数与面积统计
        /// </summary>
        /// <param name="countyid">地区id</param>
        /// <param name="type">案件类型</param>
        /// <returns></returns>
        public JObject GetTotalAndArea(string countyid, string type)
        {
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }

            var casetype = client.Queryable<SysDataItemDetail>()
           .Where(r => r.ItemName == type).First()?.ItemDetailId;
            var caseList = client.Queryable<DroneCaseInfoSingle>()
            .Where(r => r.typeid == casetype && r.is_closed == 0)
            .WhereIF(!string.IsNullOrEmpty(countyid), c => c.countyid == countyid).ToList();
            //下发图斑总数
            var xfzs = caseList.Count();
            //下发图斑面积
            double xfmj = SumArea(caseList, r => r.area);
            //下发图斑耕地面积
            double xfgdmj = SumArea(caseList, r => r.gengdi_area);
            //合法用地宗数
            int hfzs = caseList.Count(r => r.is_illegal == 0 && r.handle_status_id == 5);
            //合法用地面积
            double hfmj = SumArea(caseList.Where(r => r.is_illegal == 0 && r.handle_status_id == 5), r => r.area);
            //违法用地宗数
            int wfzs = caseList.Count(r => r.is_illegal == 1 || r.handle_status_id != 5);
            //违法用地面积
            double wfmj = SumArea(caseList.Where(r => r.is_illegal == 1 || r.handle_status_id != 5), r => r.area);
            //其他用地宗数 
            int qtzs = caseList.Count(r => r.is_illegal == 2 && r.handle_status_id == 5);
            //其他用地面积
            double qtmj = SumArea(caseList.Where(r => r.is_illegal == 2 && r.handle_status_id == 5), r => r.area);
            //计算核实后新增违法面积
            double wfgdmj = SumArea(caseList.Where(r => r.is_illegal == 1 || r.handle_status_id != 5),
               r => r.gengdi_area);
            double flhgdmj = SumArea(caseList.Where(r => r.weifaleixing == 1 && r.handle_status_id == 5),
                r => r.gengdi_area);
            var hshxzwfgdgdmj = wfgdmj - flhgdmj;
            //计算整改后剩余耕地面积
            double bbsxgdmj = SumArea(caseList.Where(r => r.measure_name == "1" && r.handle_status_id == 5),
                r => r.gengdi_area);
            double ccgdmj = SumArea(caseList.Where(r => r.measure_name == "0" && r.handle_status_id == 5),
               r => r.gengdi_area);
            var zghsywfgdgdmj = wfgdmj - flhgdmj - bbsxgdmj - ccgdmj;
            JObject obj = new JObject
            {
                { "xfzs", xfzs },
                { "xfmj", xfmj },
                { "xfgdmj", xfgdmj },
                { "hfzs", hfzs },
                { "hfmj", hfmj },
                { "wfzs", wfzs },
                { "wfmj", wfmj },
                { "qtzs", qtzs },
                { "qtmj", qtmj },
                { "hshxzwfgdgdmj", hshxzwfgdgdmj },
                { "zghsywfgdgdmj", zghsywfgdgdmj },
            };

            return obj;
        }
        /// <summary>
        /// 案件类型查询宗数和面积
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public JObject GetTotalAndAreaByType(string countyid, string type)
        {
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }
            var casetype = client.Queryable<SysDataItemDetail>()
                                       .Where(r => r.ItemName == type).First()?.ItemDetailId;
            var caseList = client.Queryable<DroneCaseInfoSingle>()
                                       .Where(r => r.typeid == casetype && r.is_closed == 0)
                                       .WhereIF(!string.IsNullOrEmpty(countyid), c => c.countyid == countyid).ToList();
            var totalzs = caseList.Count();
            //已办结总数
            var ybjzs = caseList.Count(r => r.handle_status_id == 5);
            //已办结面积
            double ybjmj = SumArea(caseList.Where(r => r.handle_status_id == 5), r => r.area);
            //未办结总数
            int wbjzs = caseList.Count(r => r.handle_status_id != 5);
            //未办结面积
            double wbjmj = SumArea(caseList.Where(r => r.handle_status_id != 5), r => r.area);
            JObject obj = new JObject
            {
                { "totalzs", totalzs },
                { "ybjzs", ybjzs },
                { "ybjmj", ybjmj },
                { "wbjzs", wbjzs },
                { "wbjmj", wbjmj },
            };

            return obj;
        }
        /// <summary>
        /// 图斑汇总统计
        /// </summary>
        /// <param name="countyid"></param>
        /// <returns></returns>
        public Response<List<SummaryResp>> GetTuBanSummary(string countyid, string type)
        {
            List<SummaryResp> listResp = new List<SummaryResp>();
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }
            var casetype = client.Queryable<SysDataItemDetail>()
                                .Where(r => r.ItemName == type).First()?.ItemDetailId;
            var caseList = client.Queryable<DroneCaseInfoSingle>()
                                       .Where(r => r.typeid == casetype && r.is_closed == 0)
                                       .WhereIF(!string.IsNullOrEmpty(countyid), c => c.countyid == countyid).ToList();
            List<SysOrg> org = new List<SysOrg>();
            if (string.IsNullOrEmpty(countyid))
            {
                org = client.Queryable<SysOrg>().Where(r => r.Level == 1).ToList();
            }
            else
            {
                org = client.Queryable<SysOrg>().Where(r => r.Level == 2 && r.ParentId.ToString() == countyid).ToList();
            }
            foreach (var item in org)
            {
                var countyIdString = item.Id.ToString();
                var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();
                //下发宗数
                var xftbzs = casesForCounty.Count;
                //剩余违法耕地宗数
                var sywfgdtbzs = casesForCounty.Count(r => r.handle_status_id != 5 || r.is_illegal == 1);
                //面积
                double xfmj = SumArea(casesForCounty, r => r.area);
                //剩余违法耕地面积
                double sywfgdgdmj = SumArea(casesForCounty.Where(r => r.handle_status_id != 5 || r.is_illegal == 1), r => r.gengdi_area);
                SummaryResp summaryResp = new SummaryResp()
                {
                    countyname = item.Name,
                    countyid = item.Id,
                    xftbzs = xftbzs,
                    sywfgdtbzs = sywfgdtbzs,
                    xfmj = xfmj,
                    sywfgdgdmj = sywfgdgdmj
                };
                listResp.Add(summaryResp);
            }
            listResp = listResp.OrderByDescending(r => r.sywfgdgdmj).ToList();
            return new Response<List<SummaryResp>>
            {
                Result = listResp,
                Message = "获取数据成功"
            };
        }

        /// <summary>
        /// 获取图斑图例
        /// </summary>
        /// <param name="countyid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public Response<Dictionary<string, List<DroneShpDataResp>>> GetTuBanInfoByType(string countyid, string type)
        {
            // 获取案件类型ID
            var casetype = client.Queryable<SysDataItemDetail>()
                                 .Where(r => r.ItemName == type)
                                 .Select(r => r.ItemDetailId)
                                 .First();

            // 获取案件列表
            var caseList = client.Queryable<DroneCaseInfoSingle>()
                                 .Where(r => r.typeid == casetype && r.is_closed == 0)
                                 .WhereIF(!string.IsNullOrEmpty(countyid), c => c.countyid == countyid)
                                 .ToList();

            // 获取组织机构列表
            var org = string.IsNullOrEmpty(countyid)
                ? client.Queryable<SysOrg>().Where(r => r.Level == 1).ToList()
                : client.Queryable<SysOrg>().Where(r => r.Level == 2 && r.ParentId.ToString() == countyid).ToList();

            // 初始化结果字典
            var keyValuePairs = new Dictionary<string, List<DroneShpDataResp>>();

            // 分类案件列表
            var caseTypes = new Dictionary<string, Func<DroneCaseInfoSingle, bool>>
            {
                { "合法", r => r.is_illegal == 0 && r.handle_status_id == 5 },
                { "违法", r => r.is_illegal == 1 || r.handle_status_id != 5 },
                { "其他", r => r.is_illegal == 2 && r.handle_status_id == 5},
                { "拆除复耕", r => r.measure_name == "0" && r.handle_status_id == 5},
                { "补办手续", r => r.measure_name == "1"&& r.handle_status_id == 5}
            };

            foreach (var caseType in caseTypes)
            {
                // 获取分类案件列表
                var filteredCases = caseList.Where(caseType.Value).ToList();

                // 获取 GID 列表
                var gids = filteredCases.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();

                if (gids.Any())
                {
                    // 生成查询字符串
                    var gidsString = string.Join(",", gids);
                    var query = $"SELECT gid, ST_AsText(geom) AS geom FROM drone_shp_data WHERE gid IN ({gidsString})";

                    // 执行查询
                    var data = client.Ado.SqlQuery<DroneShpDataResp>(query);

                    // 添加到结果字典
                    keyValuePairs.Add(caseType.Key, data);
                }
                else
                {
                    keyValuePairs.Add(caseType.Key, new List<DroneShpDataResp>());
                }
            }

            // 返回结果
            return new Response<Dictionary<string, List<DroneShpDataResp>>>
            {
                Result = keyValuePairs
            };
        }

        #endregion

        #region 新版大屏2.0
        //右上角
        public Response<List<OffenceEChartResp>> CaseOffenceEchartsOld(int type, int month)
        {
            var (startTime, endTime) = GetMonthStartAndEnd(DateTime.Now.Year, month);
            var user = _auth.GetCurrentUser().User;
            var orgIds = base._auth.GetCurrentUser().Orgs;
            List<OffenceEChartResp> listechartResp = new List<OffenceEChartResp>();
            //只查询农用地案件
            var casetype = client.Queryable<SysDataItemDetail>()
                .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD").First()?.ItemDetailId;
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }
            List<SysOrg> org = new List<SysOrg>();
            List<DroneCaseInfoSingle> caseList = new List<DroneCaseInfoSingle>();
            if (orgIds.Any(r => r.Level == 0) || user.Id == -1) // 查询全部
            {
                org = client.Queryable<SysOrg>().Where(r => r.Level == 1).ToList();
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .WhereIF(month != 0, r => r.synchronoustime >= startTime && r.synchronoustime <= endTime)
                    .Where(r => r.typeid == casetype && r.is_closed == 0).ToList();
            }
            else if (orgIds.Any(r => r.Level == 1))
            {
                //县区数据
                org = client.Queryable<SysOrg>()
                   .Where(r => r.Level == 2 && orgIds.Select(a => a.Id).Contains(r.ParentId)).ToList();
                //caseList = client.Queryable<DroneCaseInfoSingle>()
                //    .WhereIF(month != 0, r => r.synchronoustime >= startTime && r.synchronoustime <= endTime)
                //    .Where(r => r.typeid == casetype && r.is_closed == 0).ToList();

            }

            caseList = client.Queryable<DroneCaseInfoSingle>()
                .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                .WhereIF(month != 0, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                .Where((a, b) => a.typeid == casetype && a.is_closed == 0)
                .Where((a, b) => !string.IsNullOrEmpty(b.Id)).ToList();

            if (type == 1)//下发图斑
            {
                foreach (var item in org)
                {
                    var countyIdString = item.Id.ToString();
                    var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();

                    double xfgdmj = SumArea(casesForCounty, r => r.gengdi_area);
                    var yongjiujibennongtianarea = SumArea(casesForCounty, r => r.yongjiujibennongtian_area);
                    double xfmj = SumArea(casesForCounty, r => r.area);
                    OffenceEChartResp offenceEchartResp = new OffenceEChartResp
                    {
                        countyid = item.Id,
                        countyname = item.Name,
                        tbzs = casesForCounty.Count,
                        tbmj = xfmj,
                        gdmj = xfgdmj,
                        yjjbntmj = yongjiujibennongtianarea
                    };
                    listechartResp.Add(offenceEchartResp);
                }
            }
            else if (type == 2)
            {
                foreach (var item in org)
                {
                    var countyIdString = item.Id.ToString();
                    var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();
                    int wfzs = casesForCounty.Count(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5);
                    int flhzs = casesForCounty.Count(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1);
                    int bzgdtbzs = casesForCounty.Count(r => (string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00")
                                          && r.handle_status_id == 5 && r.is_illegal == 1 && r.weifaleixing == 0);
                    double xfgdmj = SumArea(casesForCounty, r => r.gengdi_area);
                    double xfmj = SumArea(casesForCounty, r => r.area);
                    double wfmj = SumArea(casesForCounty.Where(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5),
                        r => r.area);
                    double wfgdmj = SumArea(casesForCounty.Where(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5),
                        r => r.gengdi_area);
                    double wfyjjbntmj = SumArea(casesForCounty.Where(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5),
                       r => r.yongjiujibennongtian_area);


                    //double yjjbntmj = SumArea(casesForCounty.Where(r => (r.weifaleixing == 0 && r.handle_status_id == 5) || r.handle_status_id != 5),
                    //    r => r.yongjiujibennongtian_area);//未判断

                    double flhmj = SumArea(casesForCounty.Where(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1),
                        r => r.area);
                    double flhgdmj = SumArea(casesForCounty.Where(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1),
                        r => r.gengdi_area);
                    double flhyjjbntmj = SumArea(casesForCounty.Where(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1),
                        r => r.yongjiujibennongtian_area);

                    OffenceEChartResp offenceEchartResp = new OffenceEChartResp
                    {
                        countyid = item.Id,
                        countyname = item.Name,
                        tbzs = (wfzs - flhzs - bzgdtbzs),
                        tbmj = Math.Round((wfmj - flhmj), 2),
                        gdmj = Math.Round((wfgdmj - flhgdmj), 2),
                        yjjbntmj = Math.Round(wfyjjbntmj - flhyjjbntmj, 2),
                    };
                    listechartResp.Add(offenceEchartResp);
                }
            }
            else
            {
                foreach (var item in org)
                {
                    var countyIdString = item.Id.ToString();
                    var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();
                    int wfzs = casesForCounty.Count(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5);
                    int flhzs = casesForCounty.Count(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1);
                    int bbsxzs = casesForCounty.Count(r => r.measure_name == "1" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1);
                    int cczs = casesForCounty.Count(r => r.measure_name == "0" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1);
                    int bzgdtbzs = casesForCounty.Count(r => (string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00")
                                          && r.handle_status_id == 5 && r.is_illegal == 1 && r.weifaleixing == 0);
                    double hfgdmj = SumArea(casesForCounty.Where(r => r.is_illegal == 0 && r.handle_status_id == 5),
                        r => r.gengdi_area);
                    double wfmj = SumArea(casesForCounty.Where(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5),
                        r => r.area);
                    double wfgdmj = SumArea(casesForCounty.Where(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5),
                        r => r.gengdi_area);
                    double wfyjjbntmj = SumArea(casesForCounty.Where(r => (r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5),
                      r => r.yongjiujibennongtian_area);
                    double flhmj = SumArea(casesForCounty.Where(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1),
                        r => r.area);
                    double flhgdmj = SumArea(casesForCounty.Where(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1),
                        r => r.gengdi_area);
                    double flhyjjbntmj = SumArea(casesForCounty.Where(r => r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1),
                        r => r.yongjiujibennongtian_area);
                    double bbsxmj = SumArea(casesForCounty.Where(r => r.measure_name == "1" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1),
                        r => r.area);
                    double bbsxgdmj = SumArea(casesForCounty.Where(r => r.measure_name == "1" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1),
                        r => r.gengdi_area);
                    double bbsxyjjbntmj = SumArea(casesForCounty.Where(r => r.measure_name == "1" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1),
                       r => r.yongjiujibennongtian_area);
                    double ccmj = SumArea(casesForCounty.Where(r => r.measure_name == "0" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1),
                        r => r.area);
                    double ccgdmj = SumArea(casesForCounty.Where(r => r.measure_name == "0" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1),
                        r => r.gengdi_area);
                    double ccyjjbntmj = SumArea(casesForCounty.Where(r => r.measure_name == "0" && r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1),
                        r => r.yongjiujibennongtian_area);
                    OffenceEChartResp offenceEchartResp = new OffenceEChartResp
                    {
                        countyid = item.Id,
                        countyname = item.Name,
                        tbzs = wfzs - flhzs - bbsxzs - cczs,
                        tbmj = Math.Round(wfmj - flhmj - bbsxmj - ccmj, 2),
                        gdmj = Math.Round(wfgdmj - flhgdmj - bbsxgdmj - ccgdmj, 2),
                        yjjbntmj = Math.Round(wfyjjbntmj - flhyjjbntmj - bbsxyjjbntmj - ccyjjbntmj, 2),
                    };
                    listechartResp.Add(offenceEchartResp);
                }
            }
            listechartResp = listechartResp.OrderByDescending(r => r.tbzs).ToList();
            return new Response<List<OffenceEChartResp>>
            {
                Result = listechartResp,
                Message = "获取数据成功"
            };
        }
        public Response<List<OffenceEChartResp>> CaseOffenceEcharts(int type, DateTime dateTime)
        {
            var (startTime, endTime) = GetMonthStartAndEnd(dateTime.Year, dateTime.Month);
            var user = _auth.GetCurrentUser().User;
            var orgIds = base._auth.GetCurrentUser().Orgs;
            List<OffenceEChartResp> listechartResp = new List<OffenceEChartResp>();
            ////只查询农用地案件
            //var casetype = client.Queryable<SysDataItemDetail>()
            //    .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD").First()?.ItemDetailId;
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }
            List<SysOrg> org = new List<SysOrg>();
            List<DroneCaseInfoSingle> caseList = new List<DroneCaseInfoSingle>();
            if (orgIds.Any(r => r.Level == 0) || user.Id == -1) // 查询全部
            {
                org = client.Queryable<SysOrg>().Where(r => r.Level == 1).ToList();
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .WhereIF(dateTime.Year != 0001, r => r.synchronoustime >= startTime && r.synchronoustime <= endTime)
                    .Where(r => r.typename == "农用地" && r.is_closed == 0).ToList();
            }
            else if (orgIds.Any(r => r.Level == 1))
            {
                //县区数据
                org = client.Queryable<SysOrg>()
                   .Where(r => r.Level == 2 && orgIds.Select(a => a.Id).Contains(r.ParentId)).ToList();
                //caseList = client.Queryable<DroneCaseInfoSingle>()
                //    .WhereIF(month != 0, r => r.synchronoustime >= startTime && r.synchronoustime <= endTime)
                //    .Where(r => r.typeid == casetype && r.is_closed == 0).ToList();

            }

            caseList = client.Queryable<DroneCaseInfoSingle>()
                .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                .WhereIF(dateTime.Year != 0001, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                .Where((a, b) => a.typename == "农用地" && a.is_closed == 0)
                .Where((a, b) => !string.IsNullOrEmpty(b.Id)).ToList();

            if (type == 1)//下发图斑
            {
                foreach (var item in org)
                {
                    var countyIdString = item.Id.ToString();
                    var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();

                    double xfgdmj = SumArea(casesForCounty, r => r.gengdi_area);
                    var yongjiujibennongtianarea = SumArea(casesForCounty, r => r.yongjiujibennongtian_area);
                    double xfmj = SumArea(casesForCounty, r => r.area);
                    OffenceEChartResp offenceEchartResp = new OffenceEChartResp
                    {
                        countyid = item.Id,
                        countyname = item.Name,
                        tbzs = casesForCounty.Count,
                        tbmj = xfmj,
                        gdmj = xfgdmj,
                        yjjbntmj = yongjiujibennongtianarea
                    };
                    listechartResp.Add(offenceEchartResp);
                }
            }
            else if (type == 2)
            {
                foreach (var item in org)
                {
                    var countyIdString = item.Id.ToString();
                    var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();
                    casesForCounty = casesForCounty.Where(r =>
               (!(string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00") &&
                r.handle_status_id != 5) ||
               (r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1 && !(string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00"))).ToList();
                    double xfgdmj = SumArea(casesForCounty, r => r.gengdi_area);
                    var yongjiujibennongtianarea = SumArea(casesForCounty, r => r.yongjiujibennongtian_area);
                    double xfmj = SumArea(casesForCounty, r => r.area);
                    OffenceEChartResp offenceEchartResp = new OffenceEChartResp
                    {
                        countyid = item.Id,
                        countyname = item.Name,
                        tbzs = casesForCounty.Count,
                        tbmj = xfmj,
                        gdmj = xfgdmj,
                        yjjbntmj = yongjiujibennongtianarea
                    };
                    listechartResp.Add(offenceEchartResp);
                }
            }
            else
            {
                foreach (var item in org)
                {
                    var countyIdString = item.Id.ToString();
                    var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();
                    casesForCounty = casesForCounty.Where(r =>
                    (!(string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00")) &&
                      r.handle_status_id != 5).ToList();
                    double xfgdmj = SumArea(casesForCounty, r => r.gengdi_area);
                    var yongjiujibennongtianarea = SumArea(casesForCounty, r => r.yongjiujibennongtian_area);
                    double xfmj = SumArea(casesForCounty, r => r.area);
                    OffenceEChartResp offenceEchartResp = new OffenceEChartResp
                    {
                        countyid = item.Id,
                        countyname = item.Name,
                        tbzs = casesForCounty.Count,
                        tbmj = xfmj,
                        gdmj = xfgdmj,
                        yjjbntmj = yongjiujibennongtianarea
                    };
                    listechartResp.Add(offenceEchartResp);
                }
            }
            listechartResp = listechartResp.OrderByDescending(r => r.tbzs).ToList();
            return new Response<List<OffenceEChartResp>>
            {
                Result = listechartResp,
                Message = "获取数据成功"
            };
        }
        public (DateTime startOfMonth, DateTime endOfMonth) GetMonthStartAndEnd(int year, int month)
        {
            if (month == 0)
            {
                return (DateTime.Now.AddMonths(-3), DateTime.Now);
            }
            // 获取该月的第一天
            DateTime startOfMonth = new DateTime(year, month, 1);

            // 获取该月的最后一天
            DateTime endOfMonth = startOfMonth.AddMonths(1).AddSeconds(-1);

            return (startOfMonth, endOfMonth);
        }
        /// <summary>
        /// 趋势图表
        /// </summary>
        /// <param name="datatype"></param>
        /// <param name="begindate"></param>
        /// <param name="enddate"></param>
        /// <param name="countyid"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public Response<List<dynamic>> GetTrendEchartsDataOld(int datatype, string begindate, string enddate, string countyid, int type)
        {
            // 计算开始和结束时间
            DateTime begin = DateTime.Now.AddDays(-10).Date;
            DateTime end = DateTime.Now;
            if (string.IsNullOrEmpty(begindate) || string.IsNullOrEmpty(enddate))
            {
                if (datatype == 1)
                {
                    begin = Convert.ToDateTime(DateTime.Now.AddMonths(-10).ToString("yyyy-MM-01"));
                    end = DateTime.Now;
                }
            }
            else
            {
                begin = Convert.ToDateTime(begindate);
                end = Convert.ToDateTime(enddate);
            }


            // 设置时间格式
            string format = datatype == 1 ? "yyyy-MM" : "yyyy-MM-dd";

            // 获取案件类型
            var casetype = client.Queryable<SysDataItemDetail>()
                .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD")
                .Select(r => r.ItemDetailId)
                .First();

            // 定义查询条件
            var query = client.Queryable<DroneCaseInfoSingle>()
                .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                .Where((a, b) => a.synchronoustime >= begin && a.synchronoustime < end && a.synchronoustime != null && a.typeid == casetype && a.is_closed == 0)
                .WhereIF(!string.IsNullOrEmpty(countyid), (a, b) => a.countyid == countyid || a.streetid == countyid)
                .Where((a, b) => !string.IsNullOrEmpty(b.Id))
                .OrderBy((a, b) => a.synchronoustime);
            // 根据类型添加额外的过滤条件
            if (type == 2)
            {
                //query = query.Where(a => (a.is_illegal == 1 || a.handle_status_id != 5) &&
                //                         !(a.weifaleixing == 1 && a.handle_status_id == 5) &&
                //                         !(string.IsNullOrEmpty(a.gengdi_area) &&a.handle_status_id == 5));
                query = query.Where(a => (!(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00") &&
                                                        a.handle_status_id != 5) ||
                                                       (!(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00") &&
                                                        a.handle_status_id == 5 && a.weifaleixing == 0 && a.is_illegal == 1));
            }
            else if (type == 3)
            {
                //query = query.Where(a => (a.is_illegal == 1 || a.handle_status_id != 5) &&
                //                         !(a.weifaleixing == 1 && a.handle_status_id == 5) &&
                //                         !(string.IsNullOrEmpty(a.gengdi_area) && a.handle_status_id == 5) &&
                //                         !(a.measure_name == "1" && a.handle_status_id == 5) &&
                //                         !(a.measure_name == "0" && a.handle_status_id == 5));
                query = query.Where(a => (!(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00")) &&
                                                         a.handle_status_id != 5);
            }

            // 查询并处理数据
            var caselistss = query
                .Select(a => new CaseInfoChartData
                {
                    Id = a.Id,
                    createtime = Convert.ToDateTime(a.synchronoustime).ToString(format),
                    is_illegal = a.is_illegal,
                    measure_name = a.measure_name,
                    handle_status_id = a.handle_status_id,
                    weifaleixing = a.weifaleixing,
                    gengdi_area = a.gengdi_area,
                    yongjiujibennongtian_area = a.yongjiujibennongtian_area,
                    area = a.area
                })
                .MergeTable()
                .GroupBy(it => it.createtime)
                .OrderBy(it => it.createtime)
                .Select(it => (dynamic)new
                {
                    time = it.createtime,
                    tnmj = SqlFunc.Round(SqlFunc.ToDouble(SqlFunc.AggregateSum(string.IsNullOrEmpty(it.area) ? 0.0 : SqlFunc.ToDouble(it.area))), 2),
                    gdmj = SqlFunc.Round(SqlFunc.ToDouble(SqlFunc.AggregateSum(string.IsNullOrEmpty(it.gengdi_area) ? 0.0 : SqlFunc.ToDouble(it.gengdi_area))), 2),
                    yjjbntmj = SqlFunc.Round(SqlFunc.ToDouble(SqlFunc.AggregateSum(string.IsNullOrEmpty(it.yongjiujibennongtian_area) ? 0.0 : SqlFunc.ToDouble(it.yongjiujibennongtian_area))), 2),
                    tbzs = SqlFunc.AggregateCount(it.Id),
                }).ToList();

            return new Response<List<dynamic>>
            {
                Result = caselistss,
                Message = "获取数据成功"
            };
        }

        public Response<List<dynamic>> GetTrendEchartsData(int datatype, string begindate, string enddate, string countyid, int type)
        {
            // 计算开始和结束时间
            DateTime begin = DateTime.Now.AddMonths(-3).Date;
            DateTime end = DateTime.Now;
            if (string.IsNullOrEmpty(begindate) || string.IsNullOrEmpty(enddate))
            {
                if (datatype == 1)
                {
                    begin = Convert.ToDateTime(DateTime.Now.AddMonths(-10).ToString("yyyy-MM-01"));
                    end = DateTime.Now;
                }
            }
            else
            {
                begin = Convert.ToDateTime(begindate);
                end = Convert.ToDateTime(enddate);
            }

            // 设置时间格式
            string format = datatype == 1 ? "yyyy-MM" : "yyyy-MM-dd";
            if (datatype == 0)
            {
                // 调整时间范围为整周
                begin = begin.AddDays(-(int)begin.DayOfWeek + 1); // 周一
                end = end.AddDays(7 - (int)end.DayOfWeek); // 周日
            }

            //// 获取案件类型
            //var casetype = client.Queryable<SysDataItemDetail>()
            //    .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD")
            //    .Select(r => r.ItemDetailId)
            //    .First();

            // 定义查询条件
            var query = client.Queryable<DroneCaseInfoSingle>()
                .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                .Where((a, b) => a.synchronoustime >= begin && a.synchronoustime < end && a.synchronoustime != null && a.typename == "农用地" && a.is_closed == 0)
                .WhereIF(!string.IsNullOrEmpty(countyid), (a, b) => a.countyid == countyid || a.streetid == countyid)
                .Where((a, b) => !string.IsNullOrEmpty(b.Id))
                .OrderBy((a, b) => a.synchronoustime);

            // 根据类型添加额外的过滤条件
            if (type == 2)
            {
                query = query.Where(a =>
               (!(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00") &&
                a.handle_status_id != 5) ||
               (a.handle_status_id == 5 && a.weifaleixing == 0 && a.is_illegal == 1 && !(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00")));
            }
            else if (type == 3)
            {
                query = query.Where(a => (!(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00")) &&
                                                         a.handle_status_id != 5);
            }

            // 查询并处理数据
            var caselistss = query
                .Select(a => new
                {
                    Id = a.Id,
                    rawCreatetime = a.synchronoustime, // 暂时存储为原始日期格式
                    is_illegal = a.is_illegal,
                    measure_name = a.measure_name,
                    handle_status_id = a.handle_status_id,
                    weifaleixing = a.weifaleixing,
                    gengdi_area = a.gengdi_area,
                    yongjiujibennongtian_area = a.yongjiujibennongtian_area,
                    area = a.area
                })
                .ToList() // 将查询结果加载到内存
                .Select(a => new
                {
                    a.Id,
                    createtime = datatype == 0 ? GetWeekFormat(Convert.ToDateTime(a.rawCreatetime)) : Convert.ToDateTime(a.rawCreatetime).ToString(format),
                    a.is_illegal,
                    a.measure_name,
                    a.handle_status_id,
                    a.weifaleixing,
                    a.gengdi_area,
                    a.yongjiujibennongtian_area,
                    a.area
                })
                .GroupBy(it => it.createtime) // 按时间分组
                .OrderBy(it => it.Key)
                .Select(it => (dynamic)new
                {
                    time = it.Key,
                    tnmj = Math.Round(it.Sum(x => string.IsNullOrEmpty(x.area) ? 0.0 : Convert.ToDouble(x.area)), 2),
                    gdmj = Math.Round(it.Sum(x => string.IsNullOrEmpty(x.gengdi_area) ? 0.0 : Convert.ToDouble(x.gengdi_area)), 2),
                    yjjbntmj = Math.Round(it.Sum(x => string.IsNullOrEmpty(x.yongjiujibennongtian_area) ? 0.0 : Convert.ToDouble(x.yongjiujibennongtian_area)), 2),
                    tbzs = it.Count()
                }).ToList();

            return new Response<List<dynamic>>
            {
                Result = caselistss,
                Message = "获取数据成功"
            };

            // 本地函数用于格式化周数
            string GetWeekFormat(DateTime date)
            {
                var calendar = System.Globalization.CultureInfo.CurrentCulture.Calendar;
                var dateTimeFormat = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
                int weekOfYear = calendar.GetWeekOfYear(date, dateTimeFormat.CalendarWeekRule, dateTimeFormat.FirstDayOfWeek);
                return $"{date.Year}年第{weekOfYear}周";
            }
        }


        /// <summary>
        /// 数据分析
        /// </summary>
        /// <param name="countyid">县区id</param>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public Response<dynamic> GetAnalysisData(string countyid, DateTime dateTime)
        {
            var (startTime, endTime) = GetMonthStartAndEnd(dateTime.Year, dateTime.Month);
            var (startTime2, endTime2) = dateTime.Month == 1 ? GetMonthStartAndEnd(dateTime.Year - 1, 12) : GetMonthStartAndEnd(dateTime.Year, dateTime.Month - 1);

            // 获取案件类型
            //var casetype = client.Queryable<SysDataItemDetail>()
            //    .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD")
            //    .Select(r => r.ItemDetailId)
            //    .First();

            // 查询本月数据
            var currentMonthQuery = client.Queryable<DroneCaseInfoSingle>()
                .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                .Where((a, b) => a.synchronoustime >= startTime && a.synchronoustime < endTime && a.synchronoustime != null && a.typename == "农用地" && a.is_closed == 0)
                .WhereIF(!string.IsNullOrEmpty(countyid), (a, b) => a.countyid == countyid || a.streetid == countyid)
                .Where((a, b) => !string.IsNullOrEmpty(b.Id));

            // 查询上月数据
            var previousMonthQuery = client.Queryable<DroneCaseInfoSingle>()
                .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                .Where((a, b) => a.synchronoustime >= startTime2 && a.synchronoustime < endTime2 && a.synchronoustime != null && a.typename == "农用地" && a.is_closed == 0)
                .WhereIF(!string.IsNullOrEmpty(countyid), (a, b) => a.countyid == countyid || a.streetid == countyid)
                .Where((a, b) => !string.IsNullOrEmpty(b.Id));

            // 本月数据统计
            var currentMonthCount = currentMonthQuery.Count();
            var currentMonthGdmj = currentMonthQuery.Sum(a => string.IsNullOrEmpty(a.gengdi_area) ? 0 : double.Parse(a.gengdi_area));

            // 上月数据统计
            var previousMonthCount = previousMonthQuery.Count();
            var previousMonthGdmj = previousMonthQuery.Sum(a => string.IsNullOrEmpty(a.gengdi_area) ? 0 : double.Parse(a.gengdi_area));

            // 计算环比，避免除以零
            var xftbhb = previousMonthCount != 0 ? (currentMonthCount - previousMonthCount) / (double)previousMonthCount * 100 : 100;
            var gdmjhb = previousMonthGdmj != 0 ? (currentMonthGdmj - previousMonthGdmj) / previousMonthGdmj * 100 : 100;

            // 新增违法数据统计
            var xzwfCurrentMonthQuery = currentMonthQuery.Where(a =>
            //(a.is_illegal == 1 && a.handle_status_id == 5) || a.handle_status_id != 5);
             (!(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00") &&
                a.handle_status_id != 5) ||
               (a.handle_status_id == 5 && a.weifaleixing == 0 && a.is_illegal == 1 && !(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00")));
            var xzwfPreviousMonthQuery = previousMonthQuery.Where(a =>
             (!(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00") &&
                a.handle_status_id != 5) ||
               (a.handle_status_id == 5 && a.weifaleixing == 0 && a.is_illegal == 1 && !(string.IsNullOrEmpty(a.gengdi_area) || a.gengdi_area == "0" || a.gengdi_area == "0.00")));
            //(a.is_illegal == 1 && a.handle_status_id == 5) || a.handle_status_id != 5);

            var xzwfCurrentMonthCount = xzwfCurrentMonthQuery.Count();
            var xzwfCurrentMonthGdmj = xzwfCurrentMonthQuery.Sum(a => string.IsNullOrEmpty(a.gengdi_area) ? 0 : double.Parse(a.gengdi_area));

            var xzwfPreviousMonthCount = xzwfPreviousMonthQuery.Count();
            var xzwfPreviousMonthGdmj = xzwfPreviousMonthQuery.Sum(a => string.IsNullOrEmpty(a.gengdi_area) ? 0 : double.Parse(a.gengdi_area));

            // 计算环比，避免除以零
            var wftbhb = xzwfPreviousMonthCount != 0 ? (xzwfCurrentMonthCount - xzwfPreviousMonthCount) / (double)xzwfPreviousMonthCount * 100 : 100;
            var xzwfGdmjhb = xzwfPreviousMonthGdmj != 0 ? (xzwfCurrentMonthGdmj - xzwfPreviousMonthGdmj) / xzwfPreviousMonthGdmj * 100 : 100;

            var result = new
            {
                xftb = currentMonthCount,
                gdmj = Math.Round(currentMonthGdmj, 2),
                xftbhb = Math.Round(xftbhb, 2),
                gdmjhb = Math.Round(gdmjhb, 2),
                xzwf = xzwfCurrentMonthCount,
                xzwfmj = Math.Round(xzwfCurrentMonthGdmj, 2),
                wftbhb = Math.Round(wftbhb, 2),
                xzwfgdmjhb = Math.Round(xzwfGdmjhb, 2),
            };

            return new Response<dynamic>
            {
                Result = result,
                Message = "获取数据成功"
            };
        }



        #endregion
        /// <summary>
        /// 下发图斑
        /// </summary>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public Response<dynamic> CaseOffenceXiaFa(DateTime dateTime)
        {
            int monthcount = 0;
            if (dateTime.Month == 0)
            {
                monthcount = 1;
            }
            else
            {
                monthcount = dateTime.Month;
            }

            var (startTime, endTime) = GetMonthStartAndEnd(dateTime.Year, dateTime.Month);
            var user = _auth.GetCurrentUser().User;
            var orgIds = base._auth.GetCurrentUser().Orgs;
            List<OffenceEChartResp> listechartResp = new List<OffenceEChartResp>();
            ////只查询农用地案件
            //var casetype = client.Queryable<SysDataItemDetail>()
            //    .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD").First()?.ItemDetailId;
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }
            List<SysOrg> org = new List<SysOrg>();
            List<DroneCaseInfoSingle> caseList = new List<DroneCaseInfoSingle>();
            if (orgIds.Any(r => r.Level == 0) || user.Id == -1) // 查询全部
            {
                org = client.Queryable<SysOrg>().Where(r => r.Level == 1).ToList();
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                    .WhereIF(dateTime.Year != 0001, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                    .Where((a, b) => (a.typename == "农用地" || a.typename == "建设用地" || a.typename == "推堆土") && a.is_closed == 0)
                    .Where((a, b) => !string.IsNullOrEmpty(b.Id)).ToList();
            }
            else if (orgIds.Any(r => r.Level == 1))
            {
                List<string> orgstr = new List<string>();
                //县区数据
                org = client.Queryable<SysOrg>()
                   .Where(r => r.Level == 2 && orgIds.Select(a => a.Id).Contains(r.ParentId)).ToList();
                foreach (var item in org)
                {
                    orgstr.Add(item.Id.ToString());

                }
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                    .WhereIF(dateTime.Year != 0001, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                    .Where((a, b) => orgstr.Contains(a.countyid) || orgstr.Contains(a.streetid))
                    .Where((a, b) => (a.typename == "农用地" || a.typename == "建设用地" || a.typename == "推堆土") && a.is_closed == 0)
                    .Where((a, b) => !string.IsNullOrEmpty(b.Id)).ToList();

            }
            int xiafaCount = caseList.Count;
            double tubanarea = SumArea(caseList, r => r.area);
            double gengdiarea = SumArea(caseList, r => r.gengdi_area);
            double jibenarea = SumArea(caseList, r => r.yongjiujibennongtian_area);
            int nongyongdicount = caseList.Where(r => r.typename == "农用地").ToList().Count;
            int jianshecount = caseList.Where(r => r.typename == "建设用地").ToList().Count;
            int tuiduitucount = caseList.Where(r => r.typename == "推堆土").ToList().Count;
            var result = new
            {
                xiafacount = xiafaCount,
                tubanarea = Math.Round(tubanarea, 2),
                gengdiarea = Math.Round(gengdiarea, 2),
                jibenarea = Math.Round(jibenarea, 2),
                nongyongdicount = nongyongdicount,
                jianshecount = jianshecount,
                tuiduitucount = tuiduitucount,

            };

            return new Response<dynamic>
            {
                Result = result,
                Message = "获取数据成功"
            };
        }

        /// <summary>
        /// 核实新增
        /// </summary>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public Response<dynamic> CaseOffenceCheckAdd(DateTime dateTime)
        {
            int monthcount = 0;
            if (dateTime.Month == 0)
            {
                monthcount = 1;
            }
            else
            {
                monthcount = dateTime.Month;
            }
            var (startTime, endTime) = GetMonthStartAndEnd(dateTime.Year, monthcount);
            var user = _auth.GetCurrentUser().User;
            var orgIds = base._auth.GetCurrentUser().Orgs;
            List<OffenceEChartResp> listechartResp = new List<OffenceEChartResp>();
            //只查询农用地案件
            //var casetype = client.Queryable<SysDataItemDetail>()
            //    .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD").First()?.ItemDetailId;
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }
            List<SysOrg> org = new List<SysOrg>();
            List<DroneCaseInfoSingle> caseList = new List<DroneCaseInfoSingle>();
            if (orgIds.Any(r => r.Level == 0) || user.Id == -1) // 查询全部
            {
                org = client.Queryable<SysOrg>().Where(r => r.Level == 1).ToList();
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                    .WhereIF(dateTime.Year != 0001, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                    .Where((a, b) => a.typename == "农用地" && a.is_closed == 0)
                    .Where((a, b) => !string.IsNullOrEmpty(b.Id)).ToList();
            }
            else if (orgIds.Any(r => r.Level == 1))
            {
                List<string> orgstr = new List<string>();
                //县区数据
                org = client.Queryable<SysOrg>()
                   .Where(r => r.Level == 2 && orgIds.Select(a => a.Id).Contains(r.ParentId)).ToList();
                foreach (var item in org)
                {
                    orgstr.Add(item.Id.ToString());

                }
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                    .WhereIF(dateTime.Year != 0001, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                    .Where((a, b) => orgstr.Contains(a.countyid) || orgstr.Contains(a.streetid))
                    .Where((a, b) => a.typename == "农用地" && a.is_closed == 0)
                    .Where((a, b) => !string.IsNullOrEmpty(b.Id)).ToList();

            }
            //var singlist = caseList.Where(r => ((r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5) &&
            //                                                           !(r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1) &&
            //                                                           !((string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00") && r.handle_status_id == 5
            //                                                           && (r.handle_status_id != 5 || (r.is_illegal == 1 && r.handle_status_id == 5)))).ToList();
            var singlist = caseList.Where(r =>
                (!(string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00") &&
                 r.handle_status_id != 5) ||
                (!(string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00") &&
                 r.handle_status_id == 5 && r.weifaleixing == 0 && r.is_illegal == 1)).ToList();
            int xinzengcount = singlist.Count;
            double gengdiarea = SumArea(singlist, r => r.gengdi_area);
            double jibenarea = SumArea(singlist, r => r.yongjiujibennongtian_area);
            int oneyixia = singlist.Where(r => !string.IsNullOrEmpty(r.gengdi_area) && double.Parse(r.gengdi_area) < 1).ToList().Count;
            int onetofive = singlist.Where(r => !string.IsNullOrEmpty(r.gengdi_area) && double.Parse(r.gengdi_area) >= 1 && double.Parse(r.gengdi_area) <= 5).ToList().Count;
            int fiveyishang = singlist.Where(r => !string.IsNullOrEmpty(r.gengdi_area) && double.Parse(r.gengdi_area) > 5).ToList().Count;
            var result = new
            {
                xinzengcount = xinzengcount,
                gengdiarea = Math.Round(gengdiarea, 2),
                jibenarea = Math.Round(jibenarea, 2),
                oneyixia = oneyixia,
                onetofive = onetofive,
                fiveyishang = fiveyishang,

            };

            return new Response<dynamic>
            {
                Result = result,
                Message = "获取数据成功"
            };
        }

        /// <summary>
        /// 整改剩余
        /// </summary>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public Response<dynamic> CaseOffenceModifyRemain(DateTime dateTime)
        {
            int monthcount = 0;
            if (dateTime.Month == 0)
            {
                monthcount = 1;
            }
            else
            {
                monthcount = dateTime.Month;
            }
            var (startTime, endTime) = GetMonthStartAndEnd(dateTime.Year, dateTime.Month);
            var user = _auth.GetCurrentUser().User;
            var orgIds = base._auth.GetCurrentUser().Orgs;
            List<OffenceEChartResp> listechartResp = new List<OffenceEChartResp>();
            ////只查询农用地案件
            //var casetype = client.Queryable<SysDataItemDetail>() dateTime.Year != 0001
            //    .Where(r => r.ItemCode == "DRONE_CASE_TYPE" && r.ItemValue == "DRONE_CASE_TYPE_NYD").First()?.ItemDetailId;
            double SumArea(IEnumerable<DroneCaseInfoSingle> cases, Func<DroneCaseInfoSingle, string> selector)
            {
                var sum = cases
                    .Select(selector)
                    .Where(area => !string.IsNullOrEmpty(area))
                    .Sum(area => double.TryParse(area, out var result) ? result : 0);
                return Math.Round(sum, 2); // 保留两位小数
            }
            List<SysOrg> org = new List<SysOrg>();
            List<DroneCaseInfoSingle> caseList = new List<DroneCaseInfoSingle>();
            if (orgIds.Any(r => r.Level == 0) || user.Id == -1) // 查询全部
            {
                org = client.Queryable<SysOrg>().Where(r => r.Level == 1).ToList();
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                    .WhereIF(dateTime.Year != 0001, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                    .Where((a, b) => a.typename == "农用地" && a.is_closed == 0)
                    .Where((a, b) => !string.IsNullOrEmpty(b.Id)).ToList();
            }
            else if (orgIds.Any(r => r.Level == 1))
            {
                List<string> orgstr = new List<string>();
                //县区数据
                org = client.Queryable<SysOrg>()
                   .Where(r => r.Level == 2 && orgIds.Select(a => a.Id).Contains(r.ParentId)).ToList();
                foreach (var item in org)
                {
                    orgstr.Add(item.Id.ToString());

                }
                caseList = client.Queryable<DroneCaseInfoSingle>()
                    .LeftJoin<WFProcess>((a, b) => SqlFunc.JsonField(b.InstanceInfo, "pkeyValue") == a.Id)
                    .WhereIF(dateTime.Year != 0001, (a, b) => a.synchronoustime >= startTime && a.synchronoustime <= endTime)
                    .Where((a, b) => orgstr.Contains(a.countyid) || orgstr.Contains(a.streetid))
                    .Where((a, b) => a.typename == "农用地" && a.is_closed == 0).ToList();

            }
            //var singlist = caseList.Where(r => ((r.is_illegal == 1 && r.handle_status_id == 5) || r.handle_status_id != 5) &&
            //                                      !(r.weifaleixing == 1 && r.handle_status_id == 5 && r.is_illegal == 1) &&
            //                                      !((string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00") && r.handle_status_id == 5 && (r.handle_status_id != 5 || (r.is_illegal == 1 && r.handle_status_id == 5))) &&
            //                                      !(r.measure_name == "1" && r.handle_status_id == 5 && r.weifaleixing == 0) &&
            //                                      !(r.measure_name == "0" && r.handle_status_id == 5 && r.weifaleixing == 0)).ToList();
            var singlist = caseList.Where(r =>
                (!(string.IsNullOrEmpty(r.gengdi_area) || r.gengdi_area == "0" || r.gengdi_area == "0.00")) &&
                r.handle_status_id != 5).ToList();
            int shengyucount = singlist.Count;
            double gengdiarea = SumArea(singlist, r => r.gengdi_area);
            double jibenarea = SumArea(singlist, r => r.yongjiujibennongtian_area);
            int oneyixia = singlist.Where(r => !string.IsNullOrEmpty(r.gengdi_area) && double.Parse(r.gengdi_area) < 1).ToList().Count;
            int onetofive = singlist.Where(r => !string.IsNullOrEmpty(r.gengdi_area) && double.Parse(r.gengdi_area) >= 1 && double.Parse(r.gengdi_area) <= 5).ToList().Count;
            int fiveyishang = singlist.Where(r => !string.IsNullOrEmpty(r.gengdi_area) && double.Parse(r.gengdi_area) > 5).ToList().Count;
            var result = new
            {
                shengyucount = shengyucount,
                gengdiarea = Math.Round(gengdiarea, 2),
                jibenarea = Math.Round(jibenarea, 2),
                oneyixia = oneyixia,
                onetofive = onetofive,
                fiveyishang = fiveyishang,

            };

            return new Response<dynamic>
            {
                Result = result,
                Message = "获取数据成功"
            };
        }

        public async Task<Response<PageInfo<List<DroneCaseInfoSingle>>>> ReFlyVerifyPage(PageReq req)
        {
            RefAsync<int> totalCount = 0;
            var data = await Repository.ChangeRepository<SugarRepositiry<DroneCaseInfoSingle>>()
                .AsQueryable()
                .Where(t => t.measure_name.Equals("0")) // 拆除复耕
                .Where(t => t.is_closed.Equals(0))
                .ToPageListAsync(req.page, req.limit, totalCount);
            return new Response<PageInfo<List<DroneCaseInfoSingle>>>
            {
                Result = new PageInfo<List<DroneCaseInfoSingle>>
                {
                    Items = data,
                    Total = totalCount
                }
            };
        }
    }

}
