using Edu.AOP.CustomerAttribute;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.Entity.User;
using Edu.Model.Public;
using Edu.Model.ViewModel.User;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;
using VT.FW.DB.Dapper;

namespace Edu.Module.User
{
    /// <summary>
    /// 公告处理类
    /// </summary>
    public class NoticeModule
    {
        /// <summary>
        /// 公告处理类对象
        /// </summary>
        private readonly RB_NoticeRepository noticeRepository = new RB_NoticeRepository();
        /// <summary>
        /// 公告基础
        /// </summary>
        private readonly RB_Notice_BaseRepository notice_BaseRepository = new RB_Notice_BaseRepository();
        /// <summary>
        /// 公告阅读
        /// </summary>
        private readonly RB_Notice_ReadRepository notice_ReadRepository = new RB_Notice_ReadRepository();
        /// <summary>
        /// 公告部门
        /// </summary>
        private readonly RB_Notice_DeptRepository notice_DeptRepository = new RB_Notice_DeptRepository();
        /// <summary>
        /// 部门
        /// </summary>
        private readonly RB_DepartmentRepository departmentRepository = new RB_DepartmentRepository();
        /// <summary>
        /// 账号
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();

        /// <summary>
        /// 公告日志记录表
        /// </summary>
        private readonly Repository.Log.RB_Notice_LogRepository noticeLogRepository = new Repository.Log.RB_Notice_LogRepository();
        /// <summary>
        /// 获取公告配置信息
        /// </summary>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public RB_Notice_Base_ViewModel GetNoticeBaseInfo(int group_Id)
        {
            var model = notice_BaseRepository.GetList(new RB_Notice_Base_ViewModel() { Group_Id = group_Id }).FirstOrDefault();
            return model;
        }

        /// <summary>
        /// 新增修改 公告配置信息
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public string SetNoticeBaseInfo(RB_Notice_Base_ViewModel dmodel)
        {
            bool flag;
            if (dmodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Notice_Base.Image),dmodel.Image},
                    { nameof(RB_Notice_Base.CopyPeople),dmodel.CopyPeople},
                    { nameof(RB_Notice_Base.From),dmodel.From},
                    { nameof(RB_Notice_Base.NumberRule),dmodel.NumberRule},
                    { nameof(RB_Notice_Base.UpdateBy),dmodel.UpdateBy},
                    { nameof(RB_Notice_Base.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                     new WhereHelper(nameof(RB_Notice_Base.Id), dmodel.Id)
                };
                flag = notice_BaseRepository.Update(keyValues, wheres);
            }
            else
            {
                var model = notice_BaseRepository.GetList(new RB_Notice_Base_ViewModel() { Group_Id = dmodel.Group_Id }).FirstOrDefault();
                if (model == null)
                {
                    flag = notice_BaseRepository.Insert(dmodel) > 0;
                }
                else
                {
                    return "已存在配置，无法新增";
                }
            }
            return flag ? "" : "出错了，请联系管理员";
        }


        /// <summary>
        /// 获取公告分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Notice_ViewModel> GetNoticePageList(int pageIndex, int pageSize, out long rowsCount, RB_Notice_ViewModel dmodel)
        {
            var list = noticeRepository.GetPageList(pageIndex, pageSize, out rowsCount, dmodel);
            if (list.Any())
            {
                //查询阅读人数
                string NoticeIds = string.Join(",", list.Select(x => x.Id));
                var readList = notice_ReadRepository.GetNoticeReadNumList(NoticeIds);
                foreach (var item in list)
                {
                    item.ReadNum = readList.Where(x => x.NoticeId == item.Id).FirstOrDefault()?.ReadNum ?? 0;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取我的公告分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Notice_ViewModel> GetMyNoticePageList(int pageIndex, int pageSize, out long rowsCount, RB_Notice_ViewModel dmodel)
        {
            #region 我的上级部门
            var dlist = departmentRepository.GetAllSuperiorDepartmentListRepository(dmodel.DeptId);
            if (dlist.Any())
            {
                dmodel.To = string.Join(",", dlist.Select(x => x.DeptId));
            }
            #endregion
            var list = noticeRepository.GetMyPageList(pageIndex, pageSize, out rowsCount, dmodel);
            if (list.Any())
            {
                //查询阅读人数
                string NoticeIds = string.Join(",", list.Select(x => x.Id));
                var readList = notice_ReadRepository.GetNoticeReadNumList(NoticeIds);
                foreach (var item in list)
                {
                    item.ReadNum = readList.Where(x => x.NoticeId == item.Id).FirstOrDefault()?.ReadNum ?? 0;
                }
            }
            return list;
        }



        /// <summary>
        /// 我审批的公告
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Notice_ViewModel> GetMyPageLogList(int pageIndex, int pageSize, out long count, RB_Notice_ViewModel demodel)
        {
            var list = noticeRepository.GetMyPageLogList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                //查询阅读人数
                string NoticeIds = string.Join(",", list.Select(x => x.Id));
                var readList = notice_ReadRepository.GetNoticeReadNumList(NoticeIds);
                foreach (var item in list)
                {
                    item.ReadNum = readList.Where(x => x.NoticeId == item.Id).FirstOrDefault()?.ReadNum ?? 0;
                }
            }
            return list;
        }



            /// <summary>
            /// 获取公告信息
            /// </summary>
            /// <param name="noticeId"></param>
            /// <returns></returns>
            public ApiResult GetNoticeInfo(int noticeId)
        {
            var model = noticeRepository.GetEntity<RB_Notice_ViewModel>(noticeId);
            if (model == null) { return ApiResult.ParamIsNull(); }
            var noticeBaseModel = notice_BaseRepository.GetList(new RB_Notice_Base_ViewModel() { Group_Id = model.Group_Id }).FirstOrDefault();
            var dList = notice_DeptRepository.GetList(new RB_Notice_Dept() { NoticeId = noticeId }, "");
            model.To = "-1";
            if (dList.Any())
            {
                model.To = string.Join(",", dList.Select(x => x.DeptId));
            }
            List<object> DepartmentList = new List<object>() { new { DepartmentId = -1, DeptName = "全公司" } };
            if (!string.IsNullOrEmpty(model.To) && model.To != "-1")
            {
                //查询所有的部门
                var dlist = departmentRepository.GetDepartmentListRepository(new RB_Department_ViewModel() { Group_Id = model.Group_Id, QDeptIds = model.To });
                DepartmentList = new List<object>();
                foreach (var item in dlist)
                {
                    DepartmentList.Add(new
                    {
                        DepartmentId = item.DeptId,
                        item.DeptName
                    });
                }
            }
            List<object> CopyPeopleList = new List<object>();
            if (!string.IsNullOrEmpty(model.CopyPeople) && model.CopyPeople != "-1")
            {
                //查询所有人
                var elist = accountRepository.GetEmployeeListRepository(new Employee_ViewModel() { Group_Id = model.Group_Id, QIds = model.CopyPeople });
                foreach (var item in elist)
                {
                    CopyPeopleList.Add(new
                    {
                        EmployeeId = item.Id,
                        EmName = item.EmployeeName
                    });
                }
            }
            //转换文件列表
            model.FileList = new List<FileModel>();
            if (!string.IsNullOrEmpty(model.File))
            {
                model.FileList = JsonHelper.DeserializeObject<List<FileModel>>(model.File);
            }
            string DayStr = "";
            if (model.UpdateTime != null)
            {
                DayStr = Common.Plugin.StringHelper.DateFormatToString(Convert.ToDateTime(model.UpdateTime));
            }
            var empModel = new RB_Account_ViewModel();
            if (model.UpdateBy > 0)
            {
                empModel = accountRepository.GetAccountListExtRepository(new Model.ViewModel.User.RB_Account_ViewModel()
                {
                    Id = model.UpdateBy
                })?.FirstOrDefault();
            }
            return ApiResult.Success("", new
            {
                model.Id,
                model.From,
                model.Number,
                model.Title,
                model.NoticeState,
                NoticeStateName = model.NoticeState.ToName(),
                model.Is_Top,
                model.To,
                toList = DepartmentList,
                model.CopyPeople,
                ccList = CopyPeopleList,
                model.Content,
                fileList = model.FileList.Select(x => new
                {
                    x.FileName,
                    x.FileUrl
                }),
                model.UpdateBy,
                UpdateByName = empModel?.AccountName ?? "",
                UpdateByIcon = empModel?.UserIcon ?? "",
                UpdateTime = model.UpdateTime.HasValue ? model.UpdateTime.Value.ToString("yyyy年MM月dd日") : "",
                DayStr,
                BgImage = noticeBaseModel?.Image ?? ""
            });
        }

        /// <summary>
        /// 公告操作
        /// </summary>
        /// <param name="noticeId"></param>
        /// <param name="type">类型 1置顶  2取消置顶  3撤回  4删除</param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool SetNoticeOperation(int noticeId, int type, UserInfo userInfo)
        {
            if (type == 5)
            {
                //公告阅读
                //查询该人是否已阅读
                var readModel = notice_ReadRepository.GetList(new RB_Notice_Read_ViewModel() { NoticeId = noticeId, AccountId = userInfo.Id }).FirstOrDefault();
                if (readModel == null)
                {
                    return notice_ReadRepository.Insert(new RB_Notice_Read()
                    {
                        Id = 0,
                        AccountId = userInfo.Id,
                        NoticeId = noticeId,
                        ReadTime = DateTime.Now
                    }) > 0;
                }
                else
                {
                    return true;
                }
            }
            else
            {
                var model = noticeRepository.GetEntity(noticeId);
                if (type == 3)
                {
                    if (model.NoticeState != Common.Enum.User.NoticeStateEnum.Publish)
                    {
                        return false;
                    }
                }
                if (type == 4)
                {
                    if (model.NoticeState == Common.Enum.User.NoticeStateEnum.Publish)
                    {
                        return false;
                    }
                }
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Notice.UpdateBy),userInfo.Id},
                    { nameof(RB_Notice.UpdateTime),DateTime.Now},
                };
                if (type == 1)
                {
                    keyValues.Add(nameof(RB_Notice.Is_Top), 1);
                }
                else if (type == 2)
                {
                    keyValues.Add(nameof(RB_Notice.Is_Top), 2);
                }
                else if (type == 3)
                {
                    keyValues.Add(nameof(RB_Notice.NoticeState), Common.Enum.User.NoticeStateEnum.Cancel);
                }
                else if (type == 4)
                {
                    keyValues.Add(nameof(RB_Notice.Status), Common.Enum.DateStateEnum.Delete);
                }
                return noticeRepository.Update(keyValues, new WhereHelper(nameof(RB_Notice.Id), noticeId));
            }
        }

        /// <summary>
        /// 获取公告实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Notice GetNoticeEntity(object Id)
        {
            return noticeRepository.GetEntity(Id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="demodel"></param>
        /// <param name="log"></param>
        /// <returns></returns>
        [TransactionCallHandler]
        public bool UpdateNotice(RB_Notice demodel, Model.Entity.Log.RB_Notice_Log log)
        {
            bool flag = false;
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Notice.NoticeState),(int)demodel.NoticeState},
                    { nameof(RB_Notice.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_Notice.UpdateTime),DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>()
                {
                     new WhereHelper(nameof(RB_Notice.Id), demodel.Id)
                };
                flag = noticeRepository.Update(keyValues, wheres);
                if (flag)
                {
                    noticeLogRepository.AddNoticeLogRepository(log);
                }
            }
            return flag;
        }




        /// <summary>
        /// 获取公告日志分页列表
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowsCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<Model.Entity.Log.RB_Notice_Log> GetNoticeLogPageListRepository(int pageIndex, int pageSize, out long rowsCount, Model.Entity.Log.RB_Notice_Log query)
        {
            return noticeLogRepository.GetNoticeLogPageListRepository( pageIndex,  pageSize, out  rowsCount,  query);
        }

        /// <summary>
        /// 新增修改公告
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetNoticeInfo(RB_Notice_ViewModel demodel)
        {
            if (demodel.Id > 0)
            {
                var oldModel = noticeRepository.GetEntity(demodel.Id);
                Dictionary<string, object> keyValues = new Dictionary<string, object>()
                {
                    { nameof(RB_Notice.From),demodel.From},
                    { nameof(RB_Notice.To),demodel.To},
                    { nameof(RB_Notice.CopyPeople),demodel.CopyPeople},
                    { nameof(RB_Notice.Title),demodel.Title},
                    { nameof(RB_Notice.Content),demodel.Content},
                    { nameof(RB_Notice.File),demodel.File},
                    { nameof(RB_Notice.NoticeState),(int)demodel.NoticeState},
                    { nameof(RB_Notice.Is_Top),demodel.Is_Top},
                    { nameof(RB_Notice.UpdateBy),demodel.UpdateBy},
                    { nameof(RB_Notice.UpdateTime),demodel.UpdateTime}
                };
                IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                {
                     new WhereHelper(nameof(RB_Notice.Id), demodel.Id)
                };
                bool flag = noticeRepository.Update(keyValues, whereHelpers);
                if (flag)
                {
                    //更新部门
                    var dList = notice_DeptRepository.GetList(new RB_Notice_Dept() { NoticeId = demodel.Id }, "");
                    if (demodel.To != "-1")
                    {
                        List<int> ToList = JsonHelper.DeserializeObject<List<int>>("[" + demodel.To + "]");
                        var insertList = ToList.Where(x => !dList.Select(z => z.DeptId).Contains(x)).ToList();
                        var delList = dList.Where(x => !ToList.Contains(x.DeptId)).ToList();
                        foreach (var item in insertList)
                        {
                            notice_DeptRepository.Insert(new RB_Notice_Dept()
                            {
                                Id = 0,
                                DeptId = item,
                                NoticeId = demodel.Id
                            });
                        }
                        foreach (var item in delList)
                        {
                            notice_DeptRepository.Delete(item);
                        }
                    }
                    else
                    {
                        //删除部门关联
                        foreach (var item in dList)
                        {
                            notice_DeptRepository.Delete(item);
                        }
                    }
                }
                if (flag && oldModel.NoticeState == Common.Enum.User.NoticeStateEnum.Draft && demodel.NoticeState == Common.Enum.User.NoticeStateEnum.Publish)
                {
                    //推送消息
                }
                return flag;
            }
            else
            {
                //查询生成规则
                var model = notice_BaseRepository.GetList(new RB_Notice_Base_ViewModel() { Group_Id = demodel.Group_Id }).FirstOrDefault();
                if (model == null)
                {
                    return false;
                }
                demodel.Number = "";
                demodel.NumberRule = model.NumberRule;
                if (model.NumberRule == Common.Enum.User.NoticeRuleEnum.One)
                {
                    //求出当前规则的最大一个
                    string MaxNumber = noticeRepository.GetNoticeNumberMax(model.NumberRule, demodel.Group_Id);
                    if (!string.IsNullOrEmpty(MaxNumber))
                    {
                        string[] NumberArr = MaxNumber.Split('-');
                        string Letter = NumberArr[1];
                        int Num = Convert.ToInt32(NumberArr[2]);
                        if (Num >= 999)
                        {
                            string LetterStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                            int Index = LetterStr.IndexOf(LetterStr);
                            Letter = LetterStr.Substring(Index, Index + 1);
                            Num = 1;
                        }
                        else
                        {
                            Num++;
                        }
                        demodel.Number = DateTime.Now.ToString("yyyy") + "-" + Letter + "-" + Num.ToString().PadLeft(3, '0');
                    }
                    else
                    {
                        demodel.Number = DateTime.Now.ToString("yyyy") + "-A-001";
                    }
                }
                int Id = noticeRepository.Insert(demodel);
                bool flag = Id > 0;
                if (flag)
                {
                    //更新部门
                    if (demodel.To != "-1")
                    {
                        List<int> ToList = JsonHelper.DeserializeObject<List<int>>("[" + demodel.To + "]");
                        foreach (var item in ToList)
                        {
                            notice_DeptRepository.Insert(new RB_Notice_Dept()
                            {
                                Id = 0,
                                DeptId = item,
                                NoticeId = Id
                            });
                        }
                    }
                }
                if (flag && demodel.NoticeState == Common.Enum.User.NoticeStateEnum.Publish)
                {
                    //推送消息
                }
                return flag;
            }
        }

    }
}