using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Datory;
using GxPress.Auth;
using GxPress.Common.Tools;
using GxPress.Entity.WorkMeeting;
using GxPress.Repository.Interface;
using GxPress.Repository.Interface.WorkMeeting;
using GxPress.Request.App.WorkMeeting;
using GxPress.Result;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using GxPress.Service.Interface.Meeting;
using GxPress.Repository.Interface.MeetingSummaryTodo;
using GxPress.Repository.Interface.FlowAttachment;
using GxPress.Service.Interface.UserMiddle;
using GxPress.Service.Interface.Analyze;
using GxPress.Request.Analyze;

namespace GxPress.Api.AppControllers
{
    /// <summary>
    /// 会议
    /// </summary>
    [Route("api/app/meeting")]
    [ApiController]
    [Authorize]
    public class AppMeetingController : ControllerBase
    {
        private readonly ILoginContext _loginContext;
        private readonly IMeetingLocationRepository _meetingLocationRepository;
        private readonly IMeetingOrderRepository _meetingOrderRepository;
        private readonly IMeetingRepository _meetingRepository;
        private readonly IMeetingRoomRepository _meetingRoomRepository;
        private readonly IMeetingSummaryRepository _meetingSummaryRepository;
        private readonly IUserRepository _userRepository;
        private readonly IMeetingService meetingService;
        private readonly IMeetingSummaryTodoRepository meetingSummaryTodoRepository;
        private readonly IFlowAttachmentRepository flowAttachmentRepository;
        private readonly IUserMiddleService _userMiddleService;
        private readonly IAnalyzeService _analyzeService;
        private readonly ICommentRepository _commentRepository;
        public AppMeetingController(ILoginContext loginContext, IMeetingLocationRepository meetingLocationRepository, IMeetingOrderRepository meetingOrderRepository, IMeetingRepository meetingRepository, IMeetingRoomRepository meetingRoomRepository, IMeetingSummaryRepository meetingSummaryRepository, IUserRepository userRepository, IMeetingService meetingService, IMeetingSummaryTodoRepository meetingSummaryTodoRepository, IFlowAttachmentRepository flowAttachmentRepository, IUserMiddleService userMiddleService, IAnalyzeService analyzeService, ICommentRepository commentRepository)
        {
            _loginContext = loginContext;
            _meetingLocationRepository = meetingLocationRepository;
            _meetingOrderRepository = meetingOrderRepository;
            _meetingRepository = meetingRepository;
            _meetingRoomRepository = meetingRoomRepository;
            _meetingSummaryRepository = meetingSummaryRepository;
            _userRepository = userRepository;
            this.meetingService = meetingService;
            this.meetingSummaryTodoRepository = meetingSummaryTodoRepository;
            this.flowAttachmentRepository = flowAttachmentRepository;
            _userMiddleService = userMiddleService;
            _analyzeService = analyzeService;
            _commentRepository = commentRepository;
        }

        /// <summary>
        /// 获取会议室列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("rooms")]
        [AllowAnonymous]
        public async Task<MeetingRoomsResult> ListRoom([FromQuery] MeetingRoomRequest request)
        {
            var locations = await _meetingLocationRepository.GetListAsync();
            var rooms = await _meetingRoomRepository.GetListAsync(request.LocationId);
            foreach (var room in rooms)
            {
                room.Address = await _meetingLocationRepository.GetAddress(room.LocationId);
            }

            return new MeetingRoomsResult
            {
                Locations = locations,
                Rooms = rooms
            };
        }

        /// <summary>
        /// 获取会议室
        /// </summary>
        /// <returns></returns>
        [HttpGet("rooms/{id}")]
        public async Task<MeetingRoomResult> RoomGet([FromRoute]int id)
        {
            var room = await _meetingRoomRepository.GetAsync(id);
            room.Address = await _meetingLocationRepository.GetAddress(room.LocationId);
            var orderList = await _meetingOrderRepository.GetListAsyncSinceNow(room.Id);
            var orders = new SortedDictionary<string, List<int>>();
            foreach (var meetingOrder in orderList)
            {

                var data = meetingOrder.Date.ToString().Insert(4, "-").Insert(7, "-");
                var key = StringUtils.GetDate(Convert.ToDateTime(data)).ToString();
                // var key = StringUtils.GetDate(meetingOrder.CreatedDate).ToString();

                if (orders.TryGetValue(key, out var hourList))
                {
                    hourList.Add(meetingOrder.Hour);

                }
                else
                {
                    orders[key] = new List<int>
                    {
                        meetingOrder.Hour
                    };
                }
            }
            var orderLists = new List<TimeDictionary>();
            //新版
            foreach (var item in orderList.Select(n => n.Date).Distinct())
            {
                var timeDictionary = new TimeDictionary();
                timeDictionary.TimeKey = item.ToString();
                timeDictionary.TimeValues = orderList.Where(n => n.Date == item).Select(n => n.Hour).Distinct().ToList();
                orderLists.Add(timeDictionary);
            }

            return new MeetingRoomResult
            {
                RoomName = room.Name,
                Disabled = room.Disabled,
                Orders = orders,
                OrderList = orderLists
            };
        }

        /// <summary>
        /// 预定会议室 添加/编辑
        /// </summary>
        /// <returns></returns>
        [HttpPost("rooms/{id}/actions/order")]
        public async Task<DefaultResult> Order([FromRoute]int id, [FromBody] MeetingOrderRequest request)
        {
            var room = await _meetingRoomRepository.GetAsync(id);
            var meeting = new Meeting();
            if (request.MeetingId == 0)
            {
                meeting = new Meeting
                {
                    Name = request.Name,
                    LocationId = room.LocationId,
                    RoomId = room.Id,
                    Description = request.Description,
                    UserId = _loginContext.AccountId,
                    FileIds = request.FileIds,
                    UserIds = request.UserIds
                };
                meeting.Id = await _meetingRepository.InsertAsync(meeting);
            }
            else
            {
                meeting = await _meetingRepository.GetAsync(request.MeetingId);
                if (!string.IsNullOrWhiteSpace(request.Name))
                    meeting.Name = request.Name;
                if (!string.IsNullOrWhiteSpace(request.Description))
                    meeting.Description = request.Description;
                //删除参会人员
                await meetingSummaryTodoRepository.DeleteAsync(Q.Where(nameof(Entity.WorkMeeting.MeetingSummaryTodo.TypeId), 1).Where(nameof(Entity.WorkMeeting.MeetingSummaryTodo.MeetingSummaryId), request.MeetingId));
                //删除附件
                await flowAttachmentRepository.DeleteAsync(Q.Where(nameof(Entity.WorkFlow.FlowAttachment.TypeId), 2).Where(nameof(Entity.WorkFlow.FlowAttachment.FlowId), request.MeetingId));
                //删除会议时间
                if (request.Orders.Count > 0)
                    await _meetingOrderRepository.DeleteAsync(Q.Where(nameof(Entity.WorkMeeting.MeetingOrder.MeetingId), request.MeetingId));
            }
            //创建附件
            foreach (var item in request.flowAttachments)
            {
                item.FlowId = meeting.Id;
                item.TypeId = 2;
            }
            await flowAttachmentRepository.InsertsAsync(request.flowAttachments);
            //新增关联
            var meetingSummaryTodos = new List<Entity.WorkMeeting.MeetingSummaryTodo>();
            var meetingSummaryTodo = new MeetingSummaryTodo();
            meetingSummaryTodo.UserId = _loginContext.AccountId;
            meetingSummaryTodo.TypeId = 1;
            meetingSummaryTodo.IsAdmin = true;
            meetingSummaryTodo.MeetingSummaryId = meeting.Id;
            meetingSummaryTodos.Add(meetingSummaryTodo);
            foreach (var item in request.UserIds)
            {
                meetingSummaryTodo = new MeetingSummaryTodo();
                meetingSummaryTodo.UserId = item;
                meetingSummaryTodo.IsAdmin = false;
                meetingSummaryTodo.TypeId = 1;
                meetingSummaryTodo.MeetingSummaryId = meeting.Id;
                meetingSummaryTodos.Add(meetingSummaryTodo);
            }
            await meetingSummaryTodoRepository.InsertsAsync(meetingSummaryTodos);
            DateTime? startDate = null;
            DateTime? endDate = null;

            foreach (var requestOrder in request.Orders)
            {
                if (startDate.HasValue)
                {
                    if (requestOrder < startDate)
                    {
                        startDate = requestOrder;
                    }
                }
                else
                {
                    startDate = requestOrder;
                }

                if (endDate.HasValue)
                {
                    if (requestOrder > endDate)
                    {
                        endDate = requestOrder;
                    }
                }
                else
                {
                    endDate = requestOrder;
                }

                var order = new MeetingOrder
                {
                    RoomId = room.Id,
                    MeetingId = meeting.Id,
                    Date = StringUtils.GetDate(requestOrder),
                    Hour = requestOrder.Hour
                };
                await _meetingOrderRepository.InsertAsync(order);
            }

            meeting.StartDateTime = startDate;
            meeting.EndDateTime = endDate;

            await _meetingRepository.UpdateAsync(meeting);

            return new DefaultResult
            {
                Value = true
            };
        }
        /// <summary>
        /// 删除会议纪要
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("summary/{id}")]
        public async Task<bool> DeleteSummary(int id)
        {
            return await _meetingSummaryRepository.DeleteAsync(id);
        }

        /// <summary>
        /// 新增会议纪要
        /// </summary>
        /// <returns></returns>
        [HttpPost("summary")]
        public async Task<MeetingSummary> AddSummary([FromBody] MeetingSummaryRequest request)
        {
            var meeting = await _meetingRepository.GetAsync(request.MeetingId);
            var summary = new MeetingSummary
            {
                MeetingId = meeting.Id,
                RoomId = meeting.RoomId,
                UserId = _loginContext.AccountId,
                Title = request.Title,
                Content = request.Content,
                UserIds = request.UserIds
            };
            summary.Id = await _meetingSummaryRepository.InsertAsync(summary);
            //判断是不是新版通知
            if (request.AddresseeUserMiddles.Count > 0)
            {
                foreach (var item in request.AddresseeUserMiddles)
                {
                    item.DataSourceId = summary.Id;
                    item.MiddleType = 400;
                }
                await _userMiddleService.AddUserMiddleAsync(request.AddresseeUserMiddles);
                //获取用户
                var users = await _userMiddleService.FindUsersAsync(request.AddresseeUserMiddles, _loginContext.AccountId);
                request.UserIds = users.Select(n => n.Id).ToList();
            }
            //新增关联
            var meetingSummaryTodos = new List<Entity.WorkMeeting.MeetingSummaryTodo>();
            var meetingSummaryTodo = new MeetingSummaryTodo();
            meetingSummaryTodo.UserId = _loginContext.AccountId;
            meetingSummaryTodo.IsAdmin = true;
            meetingSummaryTodo.TypeId = 2;
            meetingSummaryTodo.MeetingSummaryId = summary.Id;
            meetingSummaryTodos.Add(meetingSummaryTodo);
            foreach (var item in request.UserIds)
            {
                if (_loginContext.AccountId == item)
                    continue;
                meetingSummaryTodo = new MeetingSummaryTodo();
                meetingSummaryTodo.UserId = item;
                meetingSummaryTodo.IsAdmin = false;
                meetingSummaryTodo.TypeId = 2;
                meetingSummaryTodo.MeetingSummaryId = summary.Id;
                meetingSummaryTodos.Add(meetingSummaryTodo);
            }
            await meetingSummaryTodoRepository.InsertsAsync(meetingSummaryTodos);
            return summary;
        }

        /// <summary>
        /// 获取会议纪要
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="typeId">0 是全部 1我发起 2 别人 </param>
        /// <param name="meetingId">会议ID</param>
        /// <param name="page">页码数</param>
        /// <param name="perPage">数量</param>
        /// <returns></returns>
        [HttpGet("summary/list")]
        [AllowAnonymous]
        public async Task<IEnumerable<MeetingSummaryResult>> ListSummary(string keyword, int typeId, int meetingId, int page = 1, int perPage = 10)
        {
            // var summaries = await _meetingSummaryRepository.GetListAsync(keyword, _loginContext.AccountId, typeId, meetingId, page, perPage);
            // var userId = _loginContext.AccountId;
            // var list = new List<MeetingSummaryResult>();
            // foreach (var summary in summaries)
            // {
            //     var meeting = await _meetingRepository.GetAsync(summary.MeetingId);
            //     if (meeting == null) continue;
            //     var address = await _meetingLocationRepository.GetAddress(meeting.LocationId);
            //     if (address == null) continue;
            //     var userName = await _userRepository.GetNameAsync(summary.UserId);

            //     if (!string.IsNullOrEmpty(keyword))
            //     {
            //         if (!summary.Title.Contains(keyword) && !summary.Content.Contains(keyword) &&
            //             !userName.Contains(keyword) && !address.Contains(keyword))
            //         {
            //             continue;
            //         }
            //     }
            //     var orderList = await _meetingOrderRepository.GetListByMeetingIdAsync(meeting.Id);
            //     var meetingTimeDictionary = meetingService.GetMeetingTimeDictionary(orderList);

            //     var meetingSummaryResult = new MeetingSummaryResult()
            //     {
            //         Id = summary.Id,
            //         UserId = summary.UserId,
            //         UserName = userName,
            //         Title = summary.Title,
            //         Content = summary.Content,
            //         MeetingId = summary.MeetingId,
            //         UserIds = summary.UserIds,
            //         MeetingName = meeting.Name,
            //         Address = address,
            //         CreatedDate = summary.CreatedDate,
            //         MeetingTimes = meetingTimeDictionary.Values.First()
            //     };
            //     list.Add(meetingSummaryResult);
            // }
            var summaries = await _meetingSummaryRepository.GetListMeetingSummaryResultAsync(keyword, _loginContext.AccountId, typeId, meetingId, page, perPage);
            foreach (var item in summaries)
            {
                var orderList = await _meetingOrderRepository.GetListByMeetingIdAsync(item.MeetingId);
                var meetingTimeDictionary = meetingService.GetMeetingTimeDictionary(orderList);
                item.MeetingTimes = meetingTimeDictionary.Values.First();
            }
            return summaries;
        }

        /// <summary>
        /// 修改会议纪要
        /// </summary>
        /// <returns></returns>
        [HttpPut("summary/{id}")]
        public async Task<MeetingSummary> EditSummary([FromRoute] int id, [FromBody] MeetingSummaryRequest request)
        {
            var summary = await _meetingSummaryRepository.GetAsync(id);
            summary.Title = request.Title;
            summary.Content = request.Content;
            summary.UserIds = request.UserIds;
            //获取新版
            if (request.AddresseeUserMiddles.Count > 0)
            {
                await _userMiddleService.DeleteAsync(Q.Where(nameof(Entity.UserMiddle.UserMiddle.MiddleType), 400).Where(nameof(Entity.UserMiddle.UserMiddle.DataSourceId), id));
                foreach (var item in request.AddresseeUserMiddles)
                {
                    item.DataSourceId = id;
                    item.MiddleType = 400;
                }
                await _userMiddleService.AddUserMiddleAsync(request.AddresseeUserMiddles);
                var users = await _userMiddleService.FindUsersAsync(request.AddresseeUserMiddles, summary.UserId);
                request.UserIds = users.Select(n => n.Id).ToList();
                request.UserIds.Remove(summary.UserId);
            }
            //删除会议纪要关联用户
            await meetingSummaryTodoRepository.DeleteAsync(Q.Where(nameof(Entity.WorkMeeting.MeetingSummaryTodo.TypeId), 2).Where(nameof(Entity.WorkMeeting.MeetingSummaryTodo.MeetingSummaryId), id));
            //新增关联
            var meetingSummaryTodos = new List<Entity.WorkMeeting.MeetingSummaryTodo>();
            var meetingSummaryTodo = new MeetingSummaryTodo();
            meetingSummaryTodo.UserId = _loginContext.AccountId;
            meetingSummaryTodo.IsAdmin = true;
            meetingSummaryTodo.TypeId = 2;
            meetingSummaryTodo.MeetingSummaryId = summary.Id;
            meetingSummaryTodos.Add(meetingSummaryTodo);
            foreach (var item in request.UserIds)
            {
                meetingSummaryTodo = new MeetingSummaryTodo();
                meetingSummaryTodo.UserId = item;
                meetingSummaryTodo.IsAdmin = false;
                meetingSummaryTodo.TypeId = 2;
                meetingSummaryTodo.MeetingSummaryId = summary.Id;
                meetingSummaryTodos.Add(meetingSummaryTodo);
            }
            await meetingSummaryTodoRepository.InsertsAsync(meetingSummaryTodos);
            await _meetingSummaryRepository.UpdateAsync(summary);

            return summary;
        }

        /// <summary>
        /// 获取会议纪要详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("summary/{id}")]
        public async Task<MeetingSummaryResult> GetSummary([FromRoute] int id)
        {
            var summary = await _meetingSummaryRepository.GetAsync(id);
            if (summary == null)
                throw new Common.Exceptions.BusinessException("会议纪要不存在");
            var meeting = await _meetingRepository.GetAsync(summary.MeetingId);
            var address = await _meetingLocationRepository.GetAddress(meeting.LocationId);
            //获取新版
            var addresseeUserMiddles = await _userMiddleService.FindUserMiddlesAsync(400, id);
            var meetingSummaryResult = new MeetingSummaryResult
            {
                Id = summary.Id,
                UserId = summary.UserId,
                UserName = await _userRepository.GetNameAsync(summary.UserId),
                Title = summary.Title,
                Content = summary.Content,
                MeetingId = summary.MeetingId,
                UserIds = summary.UserIds,
                MeetingName = meeting.Name,
                Address = address,
                CreatedDate = summary.CreatedDate,
                AddresseeUserMiddles = addresseeUserMiddles.ToList()
            };
            //是否是自己创建
            meetingSummaryResult.IsAdmin = _loginContext.AccountId == summary.UserId;
            var analyzeRequest = new Request.App.Analyze.AnalyzeRequest();
            analyzeRequest.TypeValue = 10;
            analyzeRequest.AnalyzeType = 1;
            analyzeRequest.SourceId = meetingSummaryResult.Id;
            analyzeRequest.UserId = _loginContext.AccountId;
            //点赞数量
            meetingSummaryResult.PraiseCount = await _analyzeService.CountAsync(analyzeRequest);
            //获取话题的评论数量
            var commentCount =
                await _commentRepository.CountAsync(Q.Where(nameof(Entity.Comment.ArticleId), meetingSummaryResult.Id).Where(nameof(Entity.Comment.TypeValue), analyzeRequest.TypeValue).Where(nameof(Entity.Comment.Pid), 0));
            meetingSummaryResult.CommentCount = commentCount;
            //获取话题的转发数量
            analyzeRequest.AnalyzeType = 4;
            var retransmissionCount = await _analyzeService.CountAsync(analyzeRequest);
            meetingSummaryResult.RetransmissionCount = retransmissionCount;
            meetingSummaryResult.IsRetransmission = await _analyzeService.ExistsAsync(analyzeRequest);
            //获取话题的收藏数量
            analyzeRequest.AnalyzeType = 3;
            var collectCount = await _analyzeService.CountAsync(analyzeRequest);
            meetingSummaryResult.CollectCount = collectCount;
            //是否收藏
            meetingSummaryResult.IsCollect = await _analyzeService.ExistsAsync(analyzeRequest);
            //获取话题的点赞数量
            analyzeRequest.AnalyzeType = 1;
            var praiseCount = await _analyzeService.CountAsync(analyzeRequest);
            meetingSummaryResult.PraiseCount = praiseCount;
            //是否点赞
            meetingSummaryResult.IsPraise = await _analyzeService.ExistsAsync(analyzeRequest);
            //获取点赞数据
            var request = new PraisePageSearchRequest { SourceId = id, TypeValue = analyzeRequest.TypeValue, Page = 1, PerPage = 3 };
            meetingSummaryResult.PraisePagedList = await _analyzeService.GetPraisePageAsync(request);
            return meetingSummaryResult;
        }
        /// <summary>
        /// 获取会议纪要详情 web专属
        /// </summary>
        /// <returns></returns>
        [HttpGet("summary/web/{id}")]
        [AllowAnonymous]
        public async Task<MeetingSummaryResult> GetWebSummary([FromRoute] int id)
        {
            var summary = await _meetingSummaryRepository.GetAsync(id);
            var meeting = await _meetingRepository.GetAsync(summary.MeetingId);
            var address = await _meetingLocationRepository.GetAddress(meeting.LocationId);
            //获取新版
            var addresseeUserMiddles = await _userMiddleService.FindUserMiddlesAsync(400, id);
            var meetingSummaryResult = new MeetingSummaryResult
            {
                Id = summary.Id,
                UserId = summary.UserId,
                UserName = await _userRepository.GetNameAsync(summary.UserId),
                Title = summary.Title,
                Content = summary.Content,
                MeetingId = summary.MeetingId,
                UserIds = summary.UserIds,
                MeetingName = meeting.Name,
                Address = address,
                CreatedDate = summary.CreatedDate,
                AddresseeUserMiddles = addresseeUserMiddles.ToList()
            };
            var analyzeRequest = new Request.App.Analyze.AnalyzeRequest();
            return meetingSummaryResult;
        }
        /// <summary>
        /// 获取我的会议
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet("current")]
        public async Task<IEnumerable<MeetingResult>> ListCurrentMeeting([FromQuery] string keyword)
        {
            var meetings = await _meetingRepository.GetCurrentListAsync(_loginContext.AccountId, keyword);
            var list = new List<MeetingResult>();
            foreach (var meeting in meetings)
            {
                //获取会议房间
                var room = await _meetingRoomRepository.GetAsync(meeting.RoomId);
                var address = await _meetingLocationRepository.GetAddress(meeting.LocationId);
                var orderList = await _meetingOrderRepository.GetListByMeetingIdAsync(meeting.Id);
                var orders = new SortedDictionary<string, List<int>>();
                foreach (var meetingOrder in orderList)
                {
                    var data = meetingOrder.Date.ToString().Insert(4, "-").Insert(7, "-");
                    var key = StringUtils.GetDate(Convert.ToDateTime(data)).ToString();

                    if (orders.TryGetValue(key, out var hourList))
                    {
                        hourList.Add(meetingOrder.Hour);
                    }
                    else
                    {
                        orders[key] = new List<int>
                        {
                            meetingOrder.Hour
                        };
                    }
                }
                var meetingTimeDictionary = meetingService.GetMeetingTimeDictionary(orderList);
                //状态
                var status = 0;
                var meetingTimeList = meetingTimeDictionary.Keys.First();
                if (meetingTimeList.Count > 0)
                {
                    var meetingTime = meetingTimeList.FirstOrDefault();
                    var TimeValuelast = meetingTime.TimeValues.Last();
                    var data = meetingTime.TimeKey.ToString().Insert(4, "-").Insert(7, "-");
                    var key = Convert.ToDateTime(data).AddHours(TimeValuelast);
                    if (key < DateTime.Now)
                        status = 1;
                }
                list.Add(new MeetingResult
                {
                    Id = meeting.Id,
                    UserId = meeting.UserId,
                    UserName = await _userRepository.GetNameAsync(meeting.UserId),
                    Name = meeting.Name,
                    Description = meeting.Description,
                    UserIds = meeting.UserIds,
                    Address = address,
                    OrderList = meetingTimeDictionary.Keys.First(),
                    MeetingTimes = meetingTimeDictionary.Values.First(),
                    Status = status,
                    CreatedDate = meeting.CreatedDate,
                    RoomName = room == null ? "" : room.Name,
                    Orders = orders
                });
            }

            return list;
        }

        /// <summary>
        /// 获取历史会议
        /// </summary>
        /// <returns></returns>
        [HttpGet("history")]
        public async Task<IEnumerable<MeetingResult>> ListHistoryMeeting([FromQuery] string keyword, int page = 1, int perPage = 10)
        {
            var meetings = await _meetingRepository.GetHistoryListAsync(_loginContext.AccountId, keyword, page, perPage);
            var list = new List<MeetingResult>();
            foreach (var meeting in meetings)
            {
                var address = await _meetingLocationRepository.GetAddress(meeting.LocationId);
                //获取会议房间
                var room = await _meetingRoomRepository.GetAsync(meeting.RoomId);
                var orderList = await _meetingOrderRepository.GetListByMeetingIdAsync(meeting.Id);
                var orders = new SortedDictionary<string, List<int>>();
                foreach (var meetingOrder in orderList)
                {
                    var key = StringUtils.GetDate(meetingOrder.CreatedDate).ToString();

                    if (orders.TryGetValue(key, out var hourList))
                    {
                        hourList.Add(meetingOrder.Hour);
                    }
                    else
                    {
                        orders[key] = new List<int>
                        {
                            meetingOrder.Hour
                        };
                    }
                }
                var meetingTimeDictionary = meetingService.GetMeetingTimeDictionary(orderList);
                var meetingTimes = meetingTimeDictionary.Values.First();
                //状态
                var status = 0;
                var meetingTimeList = meetingTimeDictionary.Keys.First();
                if (meetingTimeList.Count > 0)
                {
                    var meetingTime = meetingTimeList.FirstOrDefault();
                    var TimeValuelast = meetingTime.TimeValues.Last();
                    var data = meetingTime.TimeKey.ToString().Insert(4, "-").Insert(7, "-");
                    var key = Convert.ToDateTime(data).AddHours(TimeValuelast);
                    if (key < DateTime.Now)
                        status = 1;
                }
                list.Add(new MeetingResult
                {
                    Id = meeting.Id,
                    UserId = meeting.UserId,
                    UserName = await _userRepository.GetNameAsync(meeting.UserId),
                    Name = meeting.Name,
                    Description = meeting.Description,
                    UserIds = meeting.UserIds,
                    Address = address,
                    CreatedDate = meeting.CreatedDate,
                    MeetingTimes = meetingTimes,
                    RoomName = room == null ? "" : room.Name,
                    Orders = orders,
                    Status = 1
                });
            }

            return list;
        }

        /// <summary>
        /// 获取会议详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<MeetingResult> GetMeeting([FromRoute] int id)
        {
            var meeting = await _meetingRepository.GetAsync(id);
            var room = await _meetingRoomRepository.GetAsync(meeting.RoomId);
            var address = await _meetingLocationRepository.GetAddress(meeting.LocationId);
            //获取当前会议时间段
            var orderList = await _meetingOrderRepository.GetListByMeetingIdAsync(id);
            var orders = new SortedDictionary<string, List<int>>();
            foreach (var meetingOrder in orderList)
            {
                var key = StringUtils.GetDate(meetingOrder.CreatedDate).ToString();

                if (orders.TryGetValue(key, out var hourList))
                {
                    hourList.Add(meetingOrder.Hour);
                }
                else
                {
                    orders[key] = new List<int>
                    {
                        meetingOrder.Hour
                    };
                }
            }
            //获取会议上传的文件流
            var flowAttachments = await flowAttachmentRepository.GetAllAsync(Q.Where(nameof(Entity.WorkFlow.FlowAttachment.TypeId), 2).Where(nameof(Entity.WorkFlow.FlowAttachment.FlowId), id).OrderByDesc(nameof(Entity.WorkFlow.FlowAttachment.CreatedDate)));
            var meetingTimeDictionary = meetingService.GetMeetingTimeDictionary(orderList);
            #region   //获取当前房间的所有时间
            var orderLists = new List<TimeDictionary>();
            var orderAllList = await _meetingOrderRepository.GetListAsyncSinceNow(room.Id);
            //新版
            foreach (var item in orderAllList.Select(n => n.Date).Distinct())
            {
                var timeDictionary = new TimeDictionary();
                timeDictionary.TimeKey = item.ToString();
                timeDictionary.TimeValues = orderAllList.Where(n => n.Date == item).OrderBy(n => n.Hour).Select(n => n.Hour).Distinct().ToList();
                orderLists.Add(timeDictionary);
            }
            #endregion
            #region  参会人员
            var meetingUsersRequest = new MeetingUsersRequest();
            meetingUsersRequest.MeetingId = id;
            var meetingUserResults = await _meetingRepository.GetUserByMeeting(meetingUsersRequest);
            #endregion
            return new MeetingResult
            {
                Id = meeting.Id,
                UserId = meeting.UserId,
                UserName = await _userRepository.GetNameAsync(meeting.UserId),
                Name = meeting.Name,
                Description = meeting.Description,
                UserIds = meeting.UserIds,
                Address = address,
                CreatedDate = meeting.CreatedDate,
                ImageUrl = room.ImageUrl,
                OrderList = meetingTimeDictionary.Keys.First(),
                OrderAllList = orderLists,
                Orders = orders,
                MeetingRoom = room,
                FlowAttachments = flowAttachments.ToList(),
                MeetingTimes = meetingTimeDictionary.Values.First(),
                MeetingUserResults = meetingUserResults,
                Disabled = room.Disabled,
                Status = meeting.EndDateTime < DateTime.Now ? 1 : 0
            };
        }

        /// <summary>
        /// 取消预定
        /// </summary>
        /// <returns></returns>
        [HttpPost("{id}/actions/cancel")]
        public async Task<DefaultResult> Cancel([FromRoute]int id)
        {
            await _meetingRepository.DeleteAsync(id);

            return new DefaultResult
            {
                Value = true
            };
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("actions/users")]
        public async Task<IEnumerable<MeetingUserResult>> GetUsers([FromBody]MeetingUsersRequest request)
        {
            return await _meetingRepository.GetUserByMeeting(request);
        }
    }
}