using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain.DataMaintenance;
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 OpenAuth.Repository.Domain.FireManagement;
using Infrastructure;
using OpenAuth.App.ServiceApp.FireManagement.Request;
using Yitter.IdGenerator;
using OpenAuth.App.Const;
using DocumentFormat.OpenXml.Spreadsheet;
using OpenAuth.Repository.Domain;
using OpenAuth.App.ServiceApp.FireManagement.Response;
using DocumentFormat.OpenXml.EMMA;

namespace OpenAuth.App.ServiceApp.FireManagement
{
    public class FireManagementApp : SqlSugarBaseApp<FmFireclueTask, SugarDbContext>
    {
        public FireManagementApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<FmFireclueTask> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            _auth = auth;
        }
        /// <summary>
        /// 下发防火线索任务
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> IssuedFireClueTask(FmFireclueTask info)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                info.Id = YitIdHelper.NextId();
                info.State = (int)TaskState.待接收;
                info.TaskTime = DateTime.Now;
                info.IsDelete = false;
                await db.FmFireclueTask.InsertAsync(info);
                List<FmFireTaskUser> fftuList = new List<FmFireTaskUser>();
                if (info.RecipientUsers == null || info.RecipientUsers.Count == 0)
                {
                    var userList = await db.User.AsQueryable().Where(r => r.Status == 0).ToListAsync();
                    userList.ForEach(user =>
                    {
                        FmFireTaskUser fftu = new FmFireTaskUser
                        {
                            Id = YitIdHelper.NextId(),
                            UserId = user.Id.ToString(),
                            TaskId = info.Id,
                            ReceiveTime = DateTime.Now,
                            State = (int)TaskState.待接收
                        };
                        fftuList.Add(fftu);
                    });
                }
                else
                {
                    info.RecipientUsers.ForEach(user =>
                    {
                        FmFireTaskUser fftu = new FmFireTaskUser
                        {
                            Id = YitIdHelper.NextId(),
                            UserId = user,
                            TaskId = info.Id,
                            ReceiveTime = DateTime.Now,
                            State = (int)TaskState.待接收
                        };
                        fftuList.Add(fftu);
                    });
                }
                await db.FmFireTaskUser.InsertRangeAsync(fftuList);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }

        /// <summary>
        /// 查询下发人员
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task<Response<List<SysUserResp>>> LoadFireClueUser(string username, string unitname)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var users = await db.User.AsQueryable()
                    .WhereIF(!string.IsNullOrEmpty(username), r => r.Name.Contains(username))
                    .WhereIF(!string.IsNullOrEmpty(unitname), r => r.UnitName.Contains(username))
                    .Where(r => r.Status == 0)
                    .Select(r => new SysUserResp
                    {
                        Id = r.Id,
                        Name = r.Name
                    }).ToListAsync();
                return new Response<List<SysUserResp>> { Result = users };
            }
        }
        /// <summary>
        /// 查询任务列表
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<FmFireclueTask>>> GetTaskList()
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var tasks = await db.FmFireclueTask.AsQueryable()
                    .Where(r => r.IsDelete == false)
                    .ToListAsync();
                return new Response<List<FmFireclueTask>> { Result = tasks };
            }
        }
        /// <summary>
        /// 查询人员单位信息
        /// </summary>
        /// <returns></returns>
        public async Task<Response<List<FmUserUnit>>> GetUserUnit()
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var userunit = await db.FmUserUnit.AsQueryable().ToListAsync();
                return new Response<List<FmUserUnit>> { Result = userunit };
            }
        }
        #region 单位管理
        //添加人员单位
        public async Task<Response<bool>> AddUserUnit(FmUserUnit info)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                info.Id = YitIdHelper.NextId();
                await db.FmUserUnit.InsertAsync(info);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
        //编辑人员单位
        public async Task<Response<bool>> EditUserUnit(FmUserUnit info)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                await db.FmUserUnit.UpdateAsync(info);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
        //获取单个人员单位
        public async Task<Response<FmUserUnit>> LoadUserUnitById(long id)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var info = await db.FmUserUnit.AsQueryable().FirstAsync(r => r.Id == id);
                return new Response<FmUserUnit> { Result = info };
            }
        }
        //删除人员单位
        public async Task<Response<bool>> DeleteUserUnit(long id)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                await db.FmUserUnit.DeleteAsync(r => r.Id == id);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
        #endregion
        #region 火情线索
        public async Task<Response<bool>> AddFireClueInfo(FmFireclueInfo info)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                info.Id = YitIdHelper.NextId();
                info.State = (int)State.上报;
                info.ReportTime = DateTime.Now;
                var exitinfo = db.FmFireclueInfo.AsQueryable().Where(a => a.ReportTime.ToString("yyyy-MM-dd") == DateTime.Now.ToString("yyyy-MM-dd")).Count();
                info.ClueNo = "H" + DateTime.Now.ToString("yyyyMMdd") + (exitinfo == 0 ? "01" : "0" + (exitinfo + 1));
                await db.FmFireclueInfo.InsertAsync(info);
                if (db.Commit())
                {
                    return new Response<bool> { Result = true, Message = "操作成功" };
                }
                else
                {
                    return new Response<bool> { Result = false, Message = "操作失败" };
                }
            }
        }
        /// <summary>
        /// 查询火情线索
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<FmFireclueInfo>> LoadClueInfoById(long id)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var info = await db.FmFireclueInfo.AsQueryable()
                    .FirstAsync(r => r.Id == id);
                return new Response<FmFireclueInfo> { Result = info };
            }
        }
        //查询火情线索列表
        public async Task<Response<List<FmFireclueInfo>>> GetFireClueList()
        {
            using (var db = base.UnitWork.CreateContext())
            {
                var list = await db.FmFireclueInfo.AsQueryable().Where(r => r.State == 1).ToListAsync();
                return new Response<List<FmFireclueInfo>> { Result = list };
            }
        }
        //按月统计火情线索
        public async Task<Response<List<FireInfoForChart>>> GetFireClueStatistics(int type)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                if (type == 1)
                {
                    DateTime firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    var list = await db.FmFireclueInfo.AsQueryable()
                        //.Where(r => r.State == 1)
                        .Where(r => r.ReportTime >= firstDayOfMonth)
                        .GroupBy(r => new { r.ReportTime.Day })
                        .Select(r => new FireInfoForChart
                        {
                            DateTime = r.ReportTime.Day.ToString() + "日",
                            Count = SqlFunc.AggregateCount(r.Id)
                        }).ToListAsync();
                    return new Response<List<FireInfoForChart>> { Result = list };
                }
                else
                {
                    DateTime firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);
                    var list = await db.FmFireclueInfo.AsQueryable()
                    //.Where(r => r.State == 1)
                     .Where(r => r.ReportTime >= firstDayOfYear)
                    .GroupBy(r => new { r.ReportTime.Month })
                    .Select(r => new FireInfoForChart
                    {
                        DateTime = r.ReportTime.Month.ToString() + "月",
                        Count = SqlFunc.AggregateCount(r.Id)
                    }).ToListAsync();
                    return new Response<List<FireInfoForChart>> { Result = list };
                }
            }
        }

        public async Task<Response<List<FireInfoStateForChart>>> GetFireClueStatisticsByState(int type)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                if (type == 1)
                {
                    DateTime firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    var list = await db.FmFireclueInfo.AsQueryable()
                        .Where(r => r.ReportTime >= firstDayOfMonth)
                        .GroupBy(r => new { r.ReportTime.Day })
                        .Select(r => new FireInfoStateForChart
                        {
                            DateTime = r.ReportTime.Day.ToString() + "日",
                            TreatedCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.State >= 3, 1, 0)),
                            UntreatedCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.State < 3, 1, 0))
                        }).ToListAsync();
                    return new Response<List<FireInfoStateForChart>> { Result = list };
                }
                else if (type == 2)
                {
                    DateTime firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);
                    var list = await db.FmFireclueInfo.AsQueryable()
                     .Where(r => r.ReportTime >= firstDayOfYear)
                    .GroupBy(r => new { r.ReportTime.Month })
                    .Select(r => new FireInfoStateForChart
                    {
                        DateTime = r.ReportTime.Month.ToString() + "月",
                        TreatedCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.State >= 3, 1, 0)),
                        UntreatedCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.State < 3, 1, 0))
                    }).ToListAsync();
                    return new Response<List<FireInfoStateForChart>> { Result = list };
                }
                else
                {
                    DateTime firstDayOfYear = DateTime.Now.AddYears(-3);
                    var list = await db.FmFireclueInfo.AsQueryable()
                     .Where(r => r.ReportTime >= firstDayOfYear)
                    .GroupBy(r => new { r.ReportTime.Year })
                    .Select(r => new FireInfoStateForChart
                    {
                        DateTime = r.ReportTime.Year.ToString() + "年",
                        TreatedCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.State >= 3, 1, 0)),
                        UntreatedCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.State < 3, 1, 0))
                    }).ToListAsync();
                    return new Response<List<FireInfoStateForChart>> { Result = list };
                }
            }
        }
        public async Task<Response<List<FireInfoDegreeForChart>>> GetFireClueStatisticsByDegreeType(int type)
        {
            using (var db = base.UnitWork.CreateContext())
            {
                if (type == 1)
                {
                    DateTime firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                    var list = await db.FmFireclueInfo.AsQueryable()
                        .Where(r => r.ReportTime >= firstDayOfMonth)
                        .GroupBy(r => new { r.ReportTime.Day })
                        .Select(r => new FireInfoDegreeForChart
                        {
                            DateTime = r.ReportTime.Day.ToString() + "日",
                            ExtraLargeCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.DegreeType == 1, 1, 0)),
                            LargeCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.DegreeType == 2, 1, 0))
                        }).ToListAsync();
                    return new Response<List<FireInfoDegreeForChart>> { Result = list };
                }
                else if (type == 2)
                {
                    DateTime firstDayOfYear = new DateTime(DateTime.Now.Year, 1, 1);
                    var list = await db.FmFireclueInfo.AsQueryable()
                     .Where(r => r.ReportTime >= firstDayOfYear)
                    .GroupBy(r => new { r.ReportTime.Month })
                    .Select(r => new FireInfoDegreeForChart
                    {
                        DateTime = r.ReportTime.Month.ToString() + "月",
                        ExtraLargeCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.DegreeType == 1, 1, 0)),
                        LargeCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.DegreeType == 2, 1, 0))
                    }).ToListAsync();
                    return new Response<List<FireInfoDegreeForChart>> { Result = list };
                }
                else
                {
                    DateTime firstDayOfYear = DateTime.Now.AddYears(-3);
                    var list = await db.FmFireclueInfo.AsQueryable()
                     .Where(r => r.ReportTime >= firstDayOfYear)
                    .GroupBy(r => new { r.ReportTime.Year })
                    .Select(r => new FireInfoDegreeForChart
                    {
                        DateTime = r.ReportTime.Year.ToString() + "年",
                        ExtraLargeCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.DegreeType == 1, 1, 0)),
                        LargeCount = SqlFunc.AggregateSum(SqlFunc.IIF(r.DegreeType == 2, 1, 0))
                    }).ToListAsync();
                    return new Response<List<FireInfoDegreeForChart>> { Result = list };
                }
            }
        }
        #endregion
    }
}
