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.Configuration;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;

namespace MessageApi.Controllers
{
    /// <summary>
    /// 公告管理
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class NoticeInfoController : BaseController
    {
        private readonly ILogger<NoticeInfoController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_Msg_NoticeInfoRepository _sys_msg_noticeinfoRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_Role_InfoRepository _sys_role_infoRepository;

        public NoticeInfoController(
            ILogger<NoticeInfoController> logger,
            IConfiguration configuration,
            ISys_Msg_NoticeInfoRepository sys_msg_noticeinfoRepository,
            ISys_User_AccountRepository sys_user_accountRepository,
            ISys_Role_InfoRepository sys_role_infoRepository
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_msg_noticeinfoRepository = sys_msg_noticeinfoRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
            _sys_role_infoRepository = sys_role_infoRepository;
        }

        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string keyword, string roleid, string userid,int iscus=-1,int isread=-1, int pageindex = 1, int pagesize = 10)
        {
            ////排序字段
            var sort = Builders<Sys_Msg_NoticeInfo>.Sort.Descending("createon");
            //根据条件查询集合
            var listApp = new List<FilterDefinition<Sys_Msg_NoticeInfo>>();
            listApp.Add(Builders<Sys_Msg_NoticeInfo>.Filter.Eq("isdelete", 0));

            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Sys_Msg_NoticeInfo>.Filter.Where(s => s.title.Contains(keyword) || s.content.Contains(keyword)));
            if (!string.IsNullOrEmpty(roleid))
                listApp.Add(Builders<Sys_Msg_NoticeInfo>.Filter.Eq("roleid", roleid));
            if (!string.IsNullOrEmpty(userid))
                listApp.Add(Builders<Sys_Msg_NoticeInfo>.Filter.Eq("typeid", userid));
            if (iscus >-1)
                listApp.Add(Builders<Sys_Msg_NoticeInfo>.Filter.Eq("iscus", iscus));
            if (isread > -1)
                listApp.Add(Builders<Sys_Msg_NoticeInfo>.Filter.Eq("isread", isread));

            int recordCount = 0;

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

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

        /// <summary>
        /// 获取公告列表 - 关联查询
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListByPageAsync(string keyword, string stime, string etime,int isread=-1, int pageindex = 1, int pagesize = 10)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            int recordCount = 0;
            var result = _sys_msg_noticeinfoRepository.GetListByPage(keyword, rolecode, usercode, stime, etime,isread , pageindex, pagesize, out recordCount);

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

        /// <summary>
        /// 获取新闻详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetails(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _sys_msg_noticeinfoRepository.GetSingle(id);

            return Success("获取成功！", model);
        }

        /// <summary>
        /// 添加公告
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="usercodes"></param>
        /// <param name="rolecodes"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string title, string content, string startdate, string enddate, string usercodes, string rolecodes)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            #region 验证判断
            if (string.IsNullOrEmpty(title))
                return Error("公告标题不能为空");
            if (string.IsNullOrEmpty(content))
                return Error("公告内容不能为空");
            #endregion            
            var model = new Sys_Msg_NoticeInfo();
            model.title = title;
            model.content = content;
            model.usercode = usercodes;
            model.rolecode = rolecodes;
            model.title = title;
            model.content = content;
            if(!string.IsNullOrEmpty(startdate))
                model.startdate = Convert.ToDateTime(startdate);
            if (!string.IsNullOrEmpty(enddate))
                model.enddate = Convert.ToDateTime(enddate);
            model.createby = usercode;
            model.isdelete = 0;

            bool bl = await _sys_msg_noticeinfoRepository.Add(model);
            if (bl)
            {
                return Success("添加成功");
            }
            return Error("添加失败");
        }


        /// <summary>
        /// 修改公告
        /// </summary>
        /// <param name="id"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="usercodes"></param>
        /// <param name="rolecodes"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string title, string content, string startdate, string enddate, string usercodes, string rolecodes,int isread=-1)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            #region 验证判断
            if (string.IsNullOrEmpty(title))
                return Error("公告标题不能为空");
            if (string.IsNullOrEmpty(content))
                return Error("公告内容不能为空");
            #endregion            
            var model = await _sys_msg_noticeinfoRepository.GetSingle(id);
            if (!string.IsNullOrEmpty(title))
            {
                model.title = title;
            }
            if (!string.IsNullOrEmpty(content))
            {
                model.content = content;
            }
            if (!string.IsNullOrEmpty(startdate))
            {
                model.startdate = Convert.ToDateTime(startdate);
            }
            if (!string.IsNullOrEmpty(startdate))
            {
                model.enddate = Convert.ToDateTime(enddate);
            }            
            if (!string.IsNullOrEmpty(usercodes))
            {
                model.usercode = usercodes;
            }
            if (!string.IsNullOrEmpty(rolecodes))
            {
                model.rolecode = rolecodes;
            }
            if (!string.IsNullOrEmpty(title))
            {
                model.title = title;
            }
            if (!string.IsNullOrEmpty(content))
            {
                model.content = content;
            }
            if (!string.IsNullOrEmpty(usercode))
            {
                model.createby = usercode;
            }
                model.isdelete = 0;
            
            if (isread > -1)
            { model.isread = isread; }

            bool bl = await _sys_msg_noticeinfoRepository.UpdateOne(model);
            if (bl)
            {
                return Success("添加成功");
            }
            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 _sys_msg_noticeinfoRepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteuser = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_msg_noticeinfoRepository.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("请选择要删除的记录");
        }

        #region 获取角色和人员 - 二级
        /// <summary>
        /// 获取角色和人员列表 - 二级
        /// </summary>
        [HttpGet("getroleusertree")]
        public async Task<IActionResult> GetRoleUserTreeListAsync(string id)
        {
            var model = new Sys_Msg_NoticeInfo();
            if(!string.IsNullOrEmpty(id))
                model = await _sys_msg_noticeinfoRepository.GetSingle(id);
            var listRole = (await _sys_role_infoRepository.Get(p => p.state_flag == 1)).ToList();
            var listUser = (await _sys_user_accountRepository.Get(p => p.delete_flag == false)).ToList();

            //string
            //if(model!=null && model.rolecode != "")


            var list = listRole.Select(p => new
            {
                id = p.id,
                code = p.role_code,
                name = p.role_name,
                parentid = "",
                ischeck = (model != null && model.rolecode != null) ? (model.rolecode.Contains(p.role_code) ? true : false) : false,
                children = listUser.Where(x => p.id.Equals(x.role_id)).Select(x => new
                {
                    id = x.id,
                    code = x.usercode,
                    name = x.username,
                    parentid = p.id,
                    ischeck = (model != null && model.usercode != null) ? (model.usercode.Contains(x.usercode) ? true : false) : false,
                    children = new List<string> { }
                })
            });
            return Success("获取成功", list);
        }
        #endregion


    }
}