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

namespace MessageApi.Controllers
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class NewsController : BaseController
    {
        private readonly ILogger<NewsController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_NewsRepository _sys_newsRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IMapper _mapper;

        public NewsController(
            ILogger<NewsController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            ISys_NewsRepository sys_newsRepository,
            ISignTokenService signTokenService, IMapper mapper)
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _sys_newsRepository = sys_newsRepository;
            _signTokenService = signTokenService;
            _mapper = mapper;
        }

        /// <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 projectid, string typeid, int level = 0, int pageindex = 1, int pagesize = 10)
        {
            ////排序字段
            var sort = Builders<Sys_News>.Sort.Ascending("sort");
            //根据条件查询集合
            var listApp = new List<FilterDefinition<Sys_News>>();
            listApp.Add(Builders<Sys_News>.Filter.Eq("isdelete", 0));

            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Sys_News>.Filter.Where(s => s.title.Contains(keyword) || s.content.Contains(keyword)));
            if (!string.IsNullOrEmpty(projectid))
                listApp.Add(Builders<Sys_News>.Filter.Eq("projectid", projectid));
            if (!string.IsNullOrEmpty(typeid))
                listApp.Add(Builders<Sys_News>.Filter.Eq("typeid", typeid));
            if (level != 0)
                listApp.Add(Builders<Sys_News>.Filter.Eq("level", level));

            int recordCount = 0;

            var filter = Builders<Sys_News>.Filter.And(listApp);
            var list = await _sys_newsRepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _sys_newsRepository.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 async Task<IActionResult> GetListsByPage(string keyword, string projectid, string typeid, int state = 0, int level = 0, 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;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            #region 定时发布
            DateTime dtnow = DateTime.Now;
            var lists = (await _sys_newsRepository.Get(x => x.state == 1 && x.publishtype == 1 && x.timingtime <= dtnow)).ToList();
            if (!string.IsNullOrEmpty(projectid))
                lists = lists.Where(x => x.projectid == projectid).ToList();
            if (lists.Count > 0)
            {
                foreach (var item in lists)
                {
                    item.state = 0;
                    item.createtime = DateTime.Now.ToLocalTime();
                    await _sys_newsRepository.UpdateOne(item);
                }
            }
            #endregion

            int recordCount = 0;
            var result = _sys_newsRepository.GetListsByPage(keyword, projectid, typeid, state, level, userinfo, rolecode,  pageIndex, pageSize, out recordCount);

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

        /// <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 _sys_newsRepository.GetSingle(id);

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

        /// <summary>
        /// 获取新闻详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public IActionResult GetDetails(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = _sys_newsRepository.GetDetails(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加新闻信息
        /// </summary>
        /// <param name="province"></param>
        /// <param name="city"></param>
        /// <param name="projectid"></param>
        /// <param name="typeid"></param>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="headimg"></param>
        /// <param name="headsmallimg"></param>
        /// <param name="files"></param>
        /// <param name="level"></param>
        /// <param name="sort"></param>
        /// <param name="state"></param>
        /// <param name="timingtime"></param>
        /// <param name="endtime"></param>
        /// <param name="rolecode"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string province, string city, string projectid, string typeid, string title, string content, string headimg,
            string headsmallimg, List<FileBaseModel> files, int level, int sort, int publishtype, string timingtime, string endtime, string rolecode)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            #region 验证判断
            //projectid为空时所有项目
            //if (string.IsNullOrEmpty(projectid))
            //    return Error("项目不能为空");
            if (string.IsNullOrEmpty(title))
                return Error("新闻标题不能为空");
            if (string.IsNullOrEmpty(title))
                return Error("新闻内容不能为空");
            #endregion            
            var model = new Sys_News();
            model.province = province;
            model.city = city;
            model.projectid = projectid;
            model.typeid = typeid;
            model.title = title;
            model.content = content;
            model.headimg = headimg;
            model.headsmallimg = headsmallimg;
            model.level = level;
            model.sort = sort;
            //model.state = 0;
            //新修改字段
            //发布类型(0立即发布、1定时发布)
            model.publishtype = publishtype;
            if (publishtype == 1)
            {
                model.state = 1;    //状态(0正常显示、1不显示)
                model.timingtime = DateTime.Parse(timingtime);
            }
            if (!string.IsNullOrEmpty(endtime))
                model.endtime = DateTime.Parse(endtime);
            model.rolecode = rolecode;

            if (files != null)
            {
                model.files = files;
            }
            else
            {
                model.files = new List<FileBaseModel>();
            }

            model.isdelete = 0;
            model.createuser = usercode;
            model.createtime = DateTime.Now;

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

        /// <summary>
        /// 修改新闻信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="step"></param>
        /// <param name="content"></param>
        /// <param name="dictionarycode"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string province, string city, string projectid, string typeid, string title, string content, 
            string headimg,string headsmallimg, List<FileBaseModel> files, int level, int sort, int publishtype, string timingtime, string endtime, string rolecode)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            #region 验证判断
            //projectid为空时所有项目
            //if (string.IsNullOrEmpty(projectid))
            //    return Error("项目不能为空");
            if (string.IsNullOrEmpty(title))
                return Error("新闻标题不能为空");
            if (string.IsNullOrEmpty(title))
                return Error("新闻内容不能为空");
            #endregion
            var model = await _sys_newsRepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.province = province;
            model.city = city;
            model.projectid = projectid;
            model.typeid = typeid;
            model.title = title;
            model.content = content;
            model.headimg = headimg;
            model.headsmallimg = headsmallimg;
            model.level = level;
            model.sort = sort;
            //新修改字段
            //发布类型(0立即发布、1定时发布)
            model.publishtype = publishtype;
            if (publishtype == 1)
            {
                model.state = 1;    //状态(0正常显示、1不显示)
                model.timingtime = DateTime.Parse(timingtime);
            }
            if (!string.IsNullOrEmpty(endtime))
                model.endtime = DateTime.Parse(endtime);
            model.rolecode = rolecode;

            if (files != null)
            {
                model.files = files;
            }
            else
            {
                model.files = new List<FileBaseModel>();
            }

            bool b = await _sys_newsRepository.UpdateOne(model);
            if (b)
            {
                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_newsRepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteuser = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_newsRepository.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("请选择要删除的记录");
        }
    }
}