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

namespace SignTokenApi.Controllers
{
    /// <summary>
    /// 意见反馈
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class FeedbackController : BaseController
    {
        private readonly ILogger<FeedbackController> _logger;
        private readonly ISys_User_FeedbackRepository _sys_user_feedbackRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        public FeedbackController(ILogger<FeedbackController> logger, ISys_User_FeedbackRepository sys_user_feedbackRepository, ISys_User_AccountRepository sys_user_accountRepository)
        {
            _logger = logger;
            _sys_user_feedbackRepository = sys_user_feedbackRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
        }

        /// <summary>
        /// 获取意见反馈分页
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string keyword, int apptype, string phone, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_User_Feedback>.Sort.Ascending("sort");

            //根据条件查询集合
            var listApp = new List<FilterDefinition<Sys_User_Feedback>>();
            listApp.Add(Builders<Sys_User_Feedback>.Filter.Eq("isdelete", 0));
            if (apptype > 0)
                listApp.Add(Builders<Sys_User_Feedback>.Filter.Eq("apptype", apptype));
            if (!string.IsNullOrEmpty(phone))
                listApp.Add(Builders<Sys_User_Feedback>.Filter.Where(s => s.phone.Contains(phone)));
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Sys_User_Feedback>.Filter.Where(s => s.title.Contains(keyword) || s.content.Contains(keyword)));

            if (!string.IsNullOrEmpty(stime))
                //listApp.Add(Builders<Sys_User_Feedback>.Filter.Where(s => DateTime.Compare(s.createtime, DateTime.Parse(stime + " 00:00:00")) >= 0));
                listApp.Add(Builders<Sys_User_Feedback>.Filter.Gte("createtime", DateTime.Parse(stime + " 00:00:00")));
            if (!string.IsNullOrEmpty(etime))
                //listApp.Add(Builders<Sys_User_Feedback>.Filter.Where(s => DateTime.Compare(s.createtime, DateTime.Parse(etime + " 23:59:59")) <= 0));
                listApp.Add(Builders<Sys_User_Feedback>.Filter.Lte("createtime", DateTime.Parse(etime + " 23:59:59")));
            #endregion
            int recordCount = 0;

            var filter = Builders<Sys_User_Feedback>.Filter.And(listApp);
            var list = await _sys_user_feedbackRepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _sys_user_feedbackRepository.CountAsync(filter);   //获取总数

            recordCount = int.Parse(redCount.ToString());

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

        /// <summary>
        /// 获取意见反馈
        /// </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_user_feedbackRepository.GetSingle(id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！", model);
        }

        /// <summary>
        /// 添加意见反馈
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(FeedbackInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.content))
                return Error("请输入内容");
            #endregion

            var model = new Sys_User_Feedback();
            model.apptype = input.apptype;
            model.phone = input.phone;
            model.title = input.title;
            model.content = input.content;
            model.files = input.files;
            model.remark = input.remark;
            model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //2018-8-4
            var modelu = await _sys_user_accountRepository.GetSingle(p => p.usercode == model.createby);
            if (modelu != null)
            {
                model.createbyname = modelu.username;
            }
            if (await _sys_user_feedbackRepository.Add(model))
            {
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }

        /// <summary>
        /// 修改意见反馈信息
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(FeedbackInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.content))
                return Error("请输入内容");
            #endregion

            var model = await _sys_user_feedbackRepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            model.apptype = input.apptype;
            model.phone = input.phone;
            model.title = input.title;
            model.content = input.content;
            model.files = input.files;
            model.remark = input.remark;
            bool b = await _sys_user_feedbackRepository.Update(model);
            if (b)
                return Success("修改成功");
            return Error("修改失败");
        }

        /// <summary>
        /// 删除意见反馈信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_user_feedbackRepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    ml.deleteby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (_sys_user_feedbackRepository.Update(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("请选择要删除的记录");
        }

    }
}