using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using MadRunFabric.Common;
using MadRunFabric.Model.MessageApi;
using MessageApi.IRepositories;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace MessageApi.Controllers
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class ScheduleReminderController : BaseController
    {
        private readonly ILogger<ScheduleReminderController> _logger;
        private readonly ISchedule_ReminderRepository _schedule_reminderRepository;

        public ScheduleReminderController(
            ILogger<ScheduleReminderController> logger,
            ISchedule_ReminderRepository schedule_reminderRepository
            )
        {
            _logger = logger;
            _schedule_reminderRepository = schedule_reminderRepository;
        }

       /// <summary>
       /// 添加日程提醒
       /// </summary>
       /// <param name="srdate"></param>
       /// <param name="content"></param>
       /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string srdate,string enddate, string content)
        {
            try
            {
                string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                //string usercode = "8000";
                var model = new Schedule_Reminder();
                if (!string.IsNullOrEmpty(srdate))
                    model.srdate = Convert.ToDateTime(srdate);
                if (!string.IsNullOrEmpty(enddate))
                    model.enddate = Convert.ToDateTime(enddate);
                model.content = content;
                model.createuser = usercode;
                model.createtime = DateTime.Now;
                model.isdelete = 0;
                model.isread = 0;

                bool bl = await _schedule_reminderRepository.Add(model);
                if (bl)
                {
                    return Success("添加成功");
                }
                
                return Error("添加失败");
                
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加日程提醒异常");
                return Error("添加失败");
            }
        }

       /// <summary>
       /// 修改日程提醒
       /// </summary>
       /// <param name="id"></param>
       /// <param name="srdate"></param>
       /// <param name="content"></param>
       /// <param name="isread"></param>
       /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id,string srdate, string enddate, string content,int isread)
        {
            try
            {
                string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

                var model = await _schedule_reminderRepository.GetSingle(id);
                if (model == null)
                    return Error("操作失败");
                if (!string.IsNullOrEmpty(srdate))
                    model.srdate = Convert.ToDateTime(srdate);
                if (!string.IsNullOrEmpty(enddate))
                    model.enddate = Convert.ToDateTime(enddate);
                if (!string.IsNullOrEmpty(content))
                {
                    model.content = content;
                }
                if (isread > 0)
                {
                    model.isread = isread;
                }

                bool b = await _schedule_reminderRepository.UpdateOne(model);
                if (b)
                {
                    return Success("保存成功");
                }

                return Error("保存失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改日程提醒异常");
                return Error("保存失败");
            }
        }

        /// <summary>
        /// 删除信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _schedule_reminderRepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteuser = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_schedule_reminderRepository.UpdateOne(ml).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");

            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 日程提醒详情 by id
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _schedule_reminderRepository.GetSingle(id);
            // 处理已读
            if (model != null) {
                if (model.isread != 1)
                {
                    model.isread = 1;
                    await _schedule_reminderRepository.UpdateOne(model);
                }
            }
            return Success("获取成功！", model);
        }


        /// <summary>
        /// 获取日程提醒列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string stime, string etime, int isread=-1, int pageindex = 1, int pagesize = 10)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            ////排序字段
            var sort = Builders<Schedule_Reminder>.Sort.Ascending("srdate");
            //根据条件查询集合
            var listApp = new List<FilterDefinition<Schedule_Reminder>>();
            listApp.Add(Builders<Schedule_Reminder>.Filter.Eq("isdelete", 0));
            listApp.Add(Builders<Schedule_Reminder>.Filter.Eq("createuser",usercode));

            if (!string.IsNullOrWhiteSpace(stime))
            {
                DateTime dt2 = new DateTime();
                if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                    listApp.Add(Builders<Schedule_Reminder>.Filter.Gt("srdate", stime));
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                DateTime dt2 = new DateTime();
                if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                    listApp.Add(Builders<Schedule_Reminder>.Filter.Lt("srdate", etime));
            }           
            if (isread >= 0)
                listApp.Add(Builders<Schedule_Reminder>.Filter.Eq("isread", isread));

            int recordCount = 0;

            var filter = Builders<Schedule_Reminder>.Filter.And(listApp);
            var list = await _schedule_reminderRepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _schedule_reminderRepository.CountAsync(filter);   //获取总数
            recordCount = int.Parse(redCount.ToString());

            var obj = new
            {
                rows = list,
                total = recordCount
            };
            return Success("成功", obj);
        }

        /// <summary>
        /// 获取到期日程提醒
        /// </summary>
        /// <returns></returns>
        [HttpGet("gettxlist")]
        public async Task<IActionResult> GetTXListsAsync()
        {
            try
            {
                string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                //string usercode = "8000";
                ////排序字段
                var sort = Builders<Schedule_Reminder>.Sort.Ascending("srdate");

                //根据条件查询集合
                var flist = new List<FilterDefinition<Schedule_Reminder>>();
                flist.Add(Builders<Schedule_Reminder>.Filter.Eq("isdelete", false));

                flist.Add(Builders<Schedule_Reminder>.Filter.Where(s => s.createuser.Equals(usercode)));
                flist.Add(Builders<Schedule_Reminder>.Filter.Lt("srdate", DateTime .Now ));

                var filter = Builders<Schedule_Reminder>.Filter.And(flist);
                var vlist = await _schedule_reminderRepository.Get(filter, null, sort);
                var obj = new
                {
                    list = vlist
                };
                return Success("根据条件获取日程提醒数据成功", obj);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取到期日程提醒数据异常");
                return Error("获取到期日程提醒数据异常");
            }
        }
    }
}