using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Exceptions;
using Siger.ApiTPM.Result;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;
using Siger.Middlelayer.TpmRepository.Response;

namespace Siger.ApiTPM.Controllers
{
    public class AppMsgController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IRepairRepository _repairRepository;
        private readonly ISigerAppMessageRepository _messageRepository;
        private readonly ISigerAppMuteRepository _appMuteRepository;
        public AppMsgController(IUnitOfWork unitOfWork, ISparepartRepository projectSparepartRepository,
            IRepairRepository repairRepository, ISigerAppMessageRepository messageRepository,
            ISigerAppMuteRepository appMuteRepository)
        {
            _unitOfWork = unitOfWork;
            _repairRepository = repairRepository;
            _messageRepository = messageRepository;
            _appMuteRepository = appMuteRepository;
        }

        /// <summary>
        /// 未读消息数量
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UnreadMsgNum()
        {
            int etime = UnixTimeHelper.GetNow();
            int stime = UnixTimeHelper.GetTodayUnix() - 86400 * 4;
            var repairnum = _messageRepository.GetList(t =>
                    t.tomid == UserId && t.projectid == ProjectId && t.create_time <= etime && t.create_time >= stime &&
                    t.type == (int) RepairOrPlanStatus.Repair).OrderByDescending(q=>q.create_time).Take(200).Count(q => q.read_sign == 0);
            var plannum = _messageRepository.GetList(t => t.tomid == UserId && t.projectid == ProjectId && t.create_time <= etime && t.create_time >= stime &&
                t.type == (int) RepairOrPlanStatus.Plan).OrderByDescending(q=>q.create_time).Take(200).Count(q => q.read_sign == 0);
            var res = new RepsonseMsgNum
            {
                repairnum = repairnum,
                plannum = plannum,
                all = repairnum + plannum
            };
            return new ObjectResult(res);
        }

        /// <summary>
        /// 消息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MsgList([FromBody]RequestMsgList req)
        {
            var time = UnixTimeHelper.GetNow();
            var stime = UnixTimeHelper.GetTodayUnix() - 86400 * 4;

            var msgs = _messageRepository.GetList(t => t.tomid == UserId && t.projectid == ProjectId
                                                                         && t.create_time <= time &&
                                                                         t.create_time >= stime && t.type == req.type)
                .OrderByDescending(x => x.create_time).Take(200).ToList();

            var res = new List<MsgModel>();
            foreach(var msg in msgs)
            {
                res.Add(new MsgModel
                {
                    id = msg.id,
                    tomid = msg.tomid,
                    repairid = msg.repairid,
                    type = msg.type,
                    title = msg.title,
                    content = msg.content,
                    read_sign = msg.read_sign,
                    status = msg.status,
                    yeartime = UnixTimeHelper.ConvertIntDateTime(msg.create_time)
                });
            }
            return new AppMsgResultResult
            {
                total = res.Count,
                data = res
            };
        }

        /// <summary>
        /// 设置/取消 消息免打扰
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult MsgMute([FromBody]RequestMsgMute req)
        {
            var appMute = _repairRepository.GetAppMuteByRepairId(req.repairid, ProjectId, UserId);
            if (appMute != null)
            {
                appMute.status = req.status;
                var res = _appMuteRepository.UpdateMute(appMute);
                if (res > 0)
                    return new ObjectResult(CommonEnum.Succefull);
                throw new BadRequestException(CommonEnum.Fail);
            }
            var model = new siger_app_mute
            {
                mid = UserId,
                projectid = ProjectId,
                status = req.status,
                repairid = req.repairid
            };
            var result = _appMuteRepository.InsertMute(model);
            if (result > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 读取消息取消设置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ReadMsgMute([FromBody]RequestMsgMute req)
        {
            var appMute = _repairRepository.GetAppMuteByRepairId(req.repairid, ProjectId, UserId);
            if (appMute != null)
            {
                return new ObjectResult(appMute.status);
            }

            return new ObjectResult((int) MuteStatus.Close);
        }


        /// <summary>
        /// 根据MsgID 将相关信息置为已读
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ReadMsgById([FromBody]RequestReadMsgByID req)
        {
            if (req.msgid == 0 && (req.msgarr == null || !req.msgarr.Any()))
            {
                throw new ServerException(900027);
            }

            if (req.msgid > 0)
            {
                var msg = _messageRepository.Get(t => t.id == req.msgid);
                if (msg != null)
                {
                    msg.read_sign = 1;
                    if (_messageRepository.UpdateMessage(msg) > 0)
                    {
                        return new ObjectResult(CommonEnum.Succefull);
                    }
                }
            }
            else if (req.msgarr != null && req.msgarr.Any())
            {
                var msgs = _messageRepository.GetList(t => req.msgarr.Contains(t.id)).ToList();
                var msgList = new List<siger_app_project_message>();
                foreach (var msg in msgs)
                {
                    msg.read_sign = 1;
                    msgList.Add(msg);
                }

                if (_messageRepository.UpdateMessageRange(msgList) > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 将工单内所有该人员相关的信息置为已读
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ReadMsgByRepairId([FromBody]RequestDataByRepairId req)
        {
            if (req.repairid == 0)
            {
                throw new ServerException(900027);
            }

            var msgs = _messageRepository.GetList(t =>
                t.repairid == req.repairid && t.projectid == ProjectId && t.tomid == UserId);
            foreach (var msg in msgs)
            {
                msg.read_sign = 1;
                _messageRepository.UpdateMessage(msg);
            }

            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);
            throw new BadRequestException(CommonEnum.Fail);
        }
    }
}