using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenAuth.App.Interface;
using SqlSugar;
using Infrastructure;
using OpenAuth.App.ServiceApp.DroneSsnydManage.Export;
using OpenAuth.App.ServiceApp.DroneSsnydManage.Request;
using Org.BouncyCastle.Ocsp;
using DocumentFormat.OpenXml.Drawing;

namespace OpenAuth.App.ServiceApp.DroneSsnydManage
{
    public class DroneSsnyStatisticsApp : SqlSugarBaseApp<DroneSsnyd, SugarDbContext>
    {
        public DroneSsnyStatisticsApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<DroneSsnyd> repository, IAuth auth)
            : base(unitWork, repository, auth)
        {
        }
        #region 数据统计
        public Response<List<OffenceResp>> CaseOffence(string xiangmu_yt)
        {
            var user = _auth.GetCurrentUser().User;
            var orgIds = base._auth.GetCurrentUser().Orgs;
            List<OffenceResp> listResp = new List<OffenceResp>();
            double SumArea(IEnumerable<DroneSsnyd> cases, Func<DroneSsnyd, 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, 4); // 保留两位小数
            }
            List<SysOrg> org = new List<SysOrg>();
            List<DroneSsnyd> caseList = new List<DroneSsnyd>();
            //org = UnitWork.Db.Queryable<SysOrg>().Where(a => a.Level == 2 && a.ParentId == 371324).ToList();
            if (orgIds.Any(r => r.Level == 1) || user.Id == -1) // 查询全部
            {
                org = Repository.ChangeRepository<SugarRepositiry<SysOrg>>().AsQueryable().Where(r => r.Level == 2 && r.ParentId == 371312).ToList();
                caseList = Repository.AsQueryable().WhereIF(!string.IsNullOrEmpty(xiangmu_yt), (a) => a.xiangmu_yt == xiangmu_yt).ToList();
            }
            else if (orgIds.Any(r => r.Level == 2))
            {
                //县区数据
                //org = Repository.ChangeRepository<SugarRepositiry<SysOrg>>().AsQueryable().Where(r => r.Level == 2 && orgIds.Select(a => a.Id).Contains(r.ParentId)).ToList();
                org = Repository.ChangeRepository<SugarRepositiry<SysOrg>>().AsQueryable().Where(r => r.Level == 2 && orgIds.Select(a => a.Id).Contains(r.Id)).ToList();
                caseList = Repository.AsQueryable().WhereIF(!string.IsNullOrEmpty(xiangmu_yt), (a) => a.xiangmu_yt == xiangmu_yt).ToList();
            }
            //caseList = Repository.AsQueryable().WhereIF(!string.IsNullOrEmpty(xiangmu_yt), (a) => a.xiangmu_yt == xiangmu_yt).ToList();
            //总计
            int xmcount = 0;//项目个数
            double xmzydsum = 0.0,//项目总用地面积
                scydsum = 0.0,//生产用地面积
                fuydsum = 0.0,//辅助用地面积
                nydsum = 0.0,//农业用地面积
                gdsum = 0.0,//耕地面积
                yjjbntsum = 0.0;//永久基本农田面积
            foreach (var item in org)
            {
                var countyIdString = item.Id.ToString();
                var casesForCounty = caseList.Where(r => r.countyid == countyIdString || r.streetid == countyIdString).ToList();
                xmcount += casesForCounty.Count;
                var xmzydmj = SumArea(casesForCounty, r => r.shenqing_area.ToString());
                xmzydsum += xmzydmj;
                var scydmj = SumArea(casesForCounty, r => (r.shengchan_area ?? 0).ToString());
                scydsum += scydmj;
                var scfzydmj = SumArea(casesForCounty, r => (r.fuzhu_area ?? 0).ToString());
                fuydsum += scfzydmj;
                var nydmj = SumArea(casesForCounty, r => (r.nongyongdi_area ?? "0").ToString());
                nydsum += nydmj;
                var gdmj = SumArea(casesForCounty, r => (r.gengdi_area ?? "0").ToString());
                gdsum += gdmj;
                var yjjbntmj = SumArea(casesForCounty, r => (r.yongjiujibennongtian_area ?? "0").ToString());
                yjjbntsum += yjjbntmj;
                OffenceResp offenceResp = new OffenceResp
                {
                    countyid = item.Id,
                    countyname = item.Name,
                    xmcount = casesForCounty.Count,
                    xmzydmj = Math.Round(xmzydmj, 4),
                    scydmj = Math.Round(scydmj, 4),
                    scfzydmj = Math.Round(scfzydmj, 4),
                    nydmj = Math.Round(nydmj, 4),
                    gdmj = Math.Round(gdmj, 4),
                    yjjbntmj = Math.Round(yjjbntmj, 4)
                };
                listResp.Add(offenceResp);
            }
            listResp.Add(new OffenceResp
            {
                countyid = 0,
                countyname = "合计",
                xmcount = xmcount,
                xmzydmj = Math.Round(xmzydsum, 4),
                scydmj = Math.Round(scydsum, 4),
                scfzydmj = Math.Round(fuydsum, 4),
                nydmj = Math.Round(nydsum, 4),
                gdmj = Math.Round(gdsum, 4),
                yjjbntmj = Math.Round(yjjbntsum, 4)

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

        //项目信息
        public async Task<Response<PageInfo<List<QueryCaseOffenceListResp>>>> GetCaseInfo(QuerySsnyListReq req)
        {
            List<DroneSsnyd> caseList = new List<DroneSsnyd>();
            var baseQuery = Repository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(req.xiangmu_yt), (a) => a.xiangmu_yt == req.xiangmu_yt)
            .WhereIF(req.AreaId != "0", a => a.streetid == req.AreaId || a.countyid == req.AreaId || a.communityid == req.AreaId);
            List<QueryCaseOffenceListResp> baseList = new List<QueryCaseOffenceListResp>();
            RefAsync<int> totalcount = 0;
            // 获取分页结果
            var result = await baseQuery.Select(r => new QueryCaseOffenceListResp
            {
                Id = r.Id,
                xiangmu_no = r.xiangmu_no,
                xiangmu_name = r.xiangmu_name,
                streetname = r.streetname,
                communityname = r.communityname,
                quanliren = r.quanliren,
                xingzhengquhua = r.xingzhengquhua,
                beian_no = r.beian_no,
                start_time = r.start_time,
                end_time = r.end_time,
                xiangmu_yt = r.xiangmu_yt,
                shenqing_area = r.shenqing_area,
                shengchan_area = r.shengchan_area,
                fuzhu_area = r.fuzhu_area,
                xiafatime = r.xiafatime,
                handle_status_name = r.handle_status_name
            }).ToPageListAsync(req.page, req.limit, totalcount);
            return new Response<PageInfo<List<QueryCaseOffenceListResp>>>
            {
                Result = new PageInfo<List<QueryCaseOffenceListResp>>
                {
                    Items = result,
                    Total = totalcount
                },
                Message = "获取数据成功"
            };
        }
        #endregion
    }
}
