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.CompanyManage.Request;
using OpenAuth.App.ServiceApp.TaxManage.Response;
using NPOI.SS.Formula.Functions;

namespace OpenAuth.App.ServiceApp.TaxManage
{
    public class TaxManagementApp : SqlSugarBaseApp<TaxTuceng, SugarDbContext>
    {
        private ISqlSugarClient client;

        #region 构造函数
        public TaxManagementApp(
            ISugarUnitOfWork<SugarDbContext> unitWork,
            ISimpleClient<TaxTuceng> repository,
            IAuth auth,
            ISqlSugarClient sqlSugarClient
            ) : base(unitWork, repository, auth)
        {
            this.client = sqlSugarClient;
        }
        #endregion

        #region 图层查询
        public async Task<List<TaxTuceng>> GetTucengInfo()
        {
            var list = await client.Queryable<TaxTuceng>().ToTreeAsync(it => it.Child, it => it.PId, 0);
            return list;
        }
        #endregion

        #region  用地、房屋图层相关企业查询
        public async Task<List<dynamic>> GetTaxBuildingInfo(string req)
        {
            string sql = "select * from view_building";
            if (!string.IsNullOrEmpty(req))
            {
                sql += "  where syrmc like '%" + req + "%' or zdbm='" + req + "'";
            }
            var list = await client.SqlQueryable<dynamic>(sql).ToListAsync();
            return list;
        }

        public async Task<List<dynamic>> GetTaxZongdiInfo(string req)
        {
            string sql = "select * from view_zongdi";
            if (!string.IsNullOrEmpty(req))
            {
                sql += "  where syrmc like '%" + req + "%' or zdbm='" + req + "'";
            }
            var list = await client.SqlQueryable<dynamic>(sql).ToListAsync();
            return list;
        }
        #endregion

        #region 图表数据查询
        /// <summary>
        /// 查询地图数据
        /// </summary>
        /// <returns></returns>
        public async Task<Response<dynamic>> LoadMapTotalData()
        {
            //区域面积
            decimal? qymj = await client.Queryable<TaxZongdi>()?.SumAsync(r => SqlFunc.IsNull(r.zdfzmj,0));
           
            decimal qymjtotal = 0;
            if (qymj != null)
            {
                qymjtotal = Math.Round((decimal)qymj / 1000, 2);
            }
            //地块总数
            int dkzs = await client.Queryable<TaxZongdi>().CountAsync();
            //企业数量
            int qysl=await client.Queryable<TaxCompany>().CountAsync();

            //年度利润总数
            decimal? ndlr = await client.Queryable<TaxGongxiandi>().Where(r=>r.tjnd==DateTime.Now.Year.ToString())?.SumAsync(r => SqlFunc.IsNull(r.ndgx, 0));


            return new Response<dynamic>
            {
                Code = 200,
                Message = "success",
                Result = new 
                {
                    qymj= qymjtotal,
                    dkzs=dkzs,
                    qysl=qysl,
                    ndlr=ndlr
                }
            };
        }

        /// <summary>
        /// 查询图表数据
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<TaxResponse>>> LoadChartData()
        {
            //获取行政区数据
            var xzq = await client.Queryable<TaxXzqh>()
                    .OrderBy(r => r.djqdm)
                    .GroupBy(r => new { r.djqdm, r.djqmc })
                    .Select(r => new XZQ
                    {
                        djqdm=r.djqdm,
                        djqmc=r.djqmc,
                    }).ToListAsync();
            //获取房屋面积数据
            var fw = await client.Queryable<TaxBuilding>()
                .LeftJoin<TaxZongdi>((r, z) => r.szzdbm == z.zdbm)
                .GroupBy((r, z) => z.djqdm)
                .Select((r, z) => new CompanyData
                {
                    name=z.djqdm,
                    data=(decimal)SqlFunc.AggregateSumNoNull(r.jzwfzmj)
                }).ToListAsync();

            //获取宗地面积
            var zd = await client.Queryable<TaxZongdi>()
                
                .GroupBy(r => r.djqdm)
                .Select(r => new CompanyData
                {
                    name = r.djqdm,
                    data = (decimal)SqlFunc.AggregateSumNoNull(r.zdfzmj)
                }).ToListAsync();
            List<TaxResponse> response = new List<TaxResponse>();
            foreach ( var x in xzq)
            {
                TaxResponse res = new TaxResponse();
                res.djqmc = x.djqmc;
                var fwdata=fw.Where(r=>r.name== x.djqdm).FirstOrDefault();
                if(fwdata != null)
                {
                    res.fcmj = Math.Round(fwdata.data,2);
                }
                var dkdata=zd.Where(r=>r.name==x.djqdm).FirstOrDefault();
                if (dkdata != null) 
                {
                    res.tdmj=Math.Round(dkdata.data,2);
                }
                response.Add(res);
            }

            return new Response<List<TaxResponse>>
            {
                Code = 200,
                Message = "success",
                Result = response
            };
        }

        /// <summary>
        /// 企业收入分乡镇情况
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<TaxgongxianResponse>>> LoadgongxianChartData()
        {
            //获取行政区数据
            var xzq = await client.Queryable<TaxXzqh>()
                    .OrderBy(r => r.djqdm)
                    .GroupBy(r => new { r.djqdm, r.djqmc })
                    .Select(r => new XZQ
                    {
                        djqdm = r.djqdm,
                        djqmc = r.djqmc,
                    }).ToListAsync();
            //获取房屋贡献
            var fw = await client.Queryable<TaxGongxianfang>()
                .Where(r=>r.tjnd==DateTime.Now.Year.ToString())
                .LeftJoin<TaxBuilding>((r, z) => r.zzwbm == z.jzwbm)
                .LeftJoin<TaxZongdi>((r,z,d)=>z.szzdbm==d.zdbm)
                .GroupBy((r, z, d) => d.djqdm)
                .Select((r, z, d) => new CompanyData
                {
                    name = d.djqdm,
                    data = (decimal)SqlFunc.AggregateSumNoNull(r.ndgx)
                }).ToListAsync();

            //获取宗地贡献
            var zd = await client.Queryable<TaxGongxiandi>()
                 .Where(r => r.tjnd == DateTime.Now.Year.ToString())
                 .LeftJoin<TaxZongdi>((r,z)=>r.sszdbm==z.zdbm)
                .GroupBy((r, z) => z.djqdm)
                .Select((r, z) => new CompanyData
                {
                    name = z.djqdm,
                    data = (decimal)SqlFunc.AggregateSumNoNull(r.ndgx)
                }).ToListAsync();
            List<TaxgongxianResponse> response = new List<TaxgongxianResponse>();
            foreach (var x in xzq)
            {
                TaxgongxianResponse res = new TaxgongxianResponse();
                res.djqmc = x.djqmc;
                var fwdata = fw.Where(r => r.name == x.djqdm).FirstOrDefault();
                if (fwdata != null)
                {
                    res.fcgx = Math.Round(fwdata.data, 2);
                }
                var dkdata = zd.Where(r => r.name == x.djqdm).FirstOrDefault();
                if (dkdata != null)
                {
                    res.tdgx = Math.Round(dkdata.data, 2);
                }
                response.Add(res);
            }

            return new Response<List<TaxgongxianResponse>>
            {
                Code = 200,
                Message = "success",
                Result = response
            };
        }
        #endregion

    }
}
