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 Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using OnLineChatApi.Class;
using OnLineChatApi.IRepositories;

namespace OnLineChatApi.Controllers
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class OnLineChatController : BaseController
    {
        private readonly ILogger<OnLineChatController> _logger;
        private readonly IChat_ProcessRepository _chatprocessRepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IMapper _mapper;

        public OnLineChatController(ILogger<OnLineChatController> logger, IChat_ProcessRepository chatprocessRepository,
            ISignTokenService signTokenService, IMapper mapper)
        {
            _logger = logger;
            _chatprocessRepository = chatprocessRepository;
            _signTokenService = signTokenService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取在线人员
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public IActionResult GetList()
        {
            var obj = new
            {
                ChatHub.ConnectionIds,
                ChatHub.Servicers,
                ChatHub.Customers
            };

            return Success("成功", obj);
        }

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

            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Chat_Process>.Filter.Where(s => s.content.Contains(keyword)));

            int recordCount = 0;

            var filter = Builders<Chat_Process>.Filter.And(listApp);
            var list = await _chatprocessRepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _chatprocessRepository.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 GetListsByPage(string keyword, int pageIndex = 1, int pageSize = 10)
        {
            int recordCount = 0;
            var result = _chatprocessRepository.GetListsByPage(keyword, 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 _chatprocessRepository.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 = _chatprocessRepository.GetDetails(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加步骤信息
        /// </summary>
        /// <param name="step"></param>
        /// <param name="content"></param>
        /// <param name="dictionarycode"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(int step, string content, int optiontype, string dictionarycode, List<string> options)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            #region 验证判断
            if (step == 0)
                return Error("步骤不能为空");
            if (string.IsNullOrEmpty(content))
                return Error("步骤内容不能为空");
            if (optiontype == 1 && string.IsNullOrEmpty(dictionarycode))
                return Error("字典项不能为空");
            if (optiontype == 2 && options != null && options.Count == 0)
                return Error("选择项不能为空");

            long n = await _chatprocessRepository.Count(x => x.step.Equals(step) && x.isdelete == 0);
            if (n > 0)
                return Error("步骤已存在");
            #endregion
            var model = new Chat_Process();
            model.step = step;
            model.content = content;
            model.optiontype = optiontype;
            model.dictionarycode = dictionarycode;
            if (options != null)
            {
                model.options = options;
            }
            else
            {
                model.options = new List<string>();
            }

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

            bool bl = await _chatprocessRepository.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, int step, string content, int optiontype, string dictionarycode, List<string> options)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            #region 验证判断
            if (step == 0)
                return Error("步骤不能为空");
            if (string.IsNullOrEmpty(content))
                return Error("步骤内容不能为空");
            if (optiontype == 1 && string.IsNullOrEmpty(dictionarycode))
                return Error("字典项不能为空");
            if (optiontype == 2 && options != null && options.Count == 0)
                return Error("选择项不能为空");

            long n = await _chatprocessRepository.Count(x => x.step == step && x.isdelete == 0 && x.id != id);
            if (n > 0)
                return Error("步骤已存在");
            #endregion
            var model = await _chatprocessRepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.step = step;
            model.optiontype = optiontype;
            model.content = content;
            model.dictionarycode = dictionarycode;
            if (options != null)
            {
                model.options = options;
            }
            else
            {
                model.options = new List<string>();
            }

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