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

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CallCenterApi.Controllers.telbusiness
{
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MWAgentStateRecordController : BaseController
    {
        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }

        private readonly ILogger<MWAgentStateRecordController> _logger;
        private readonly IMW_Agent_State_RecordRepository _mw_agent_state_recordRepository;

        public MWAgentStateRecordController(ILogger<MWAgentStateRecordController> logger, IMW_Agent_State_RecordRepository mw_agent_state_recordRepository)
        {
            _logger = logger;
            _mw_agent_state_recordRepository = mw_agent_state_recordRepository;
        }

        [Authorize]
        [HttpGet("getall")]
        public async Task<IActionResult> GetAllListsAsync()
        {
            try
            {
                var recordlist = await _mw_agent_state_recordRepository.GetAll();
                return Success("获取全部数据成功", recordlist);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取坐席状态全部数据异常");
                return Error("获取坐席状态全部数据失败");
            }
        }

        /// <summary>
        /// 获取列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListByPageAsync(string keyword, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            //排序字段
            var sort = Builders<MW_Agent_State_Record>.Sort.Descending("id");
            var list = await _mw_agent_state_recordRepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _mw_agent_state_recordRepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<MW_Agent_State_Record>>();
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listfilter.Add(Builders<MW_Agent_State_Record>.Filter.Where(s => s.agent_id.ToString ().Contains (keyword)));
            #endregion
            int recordCount = 0;
            if (listfilter.Count > 0)
            {
                var filter = Builders<MW_Agent_State_Record>.Filter.And(listfilter);
                list = await _mw_agent_state_recordRepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _mw_agent_state_recordRepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

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

        /// <summary>
        /// 获取列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string stime,string etime,string agentid,string keyword, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            //排序字段
            var sort = Builders<MW_Agent_State_Record>.Sort.Descending("id");
            var list = await _mw_agent_state_recordRepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _mw_agent_state_recordRepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listfilter = new List<FilterDefinition<MW_Agent_State_Record>>();
            //模糊查询
            //if (!string.IsNullOrEmpty(keyword))
                //listfilter.Add(Builders<MW_Agent_State_Record>.Filter.Where(s => s.agent_id.Equals(keyword)));
            #endregion
            if (!string.IsNullOrEmpty(agentid))
            {
                listfilter.Add(Builders<MW_Agent_State_Record>.Filter.Where(s => s.agent_id.Equals(keyword)));
            }
            
            if (!string.IsNullOrWhiteSpace(stime))
            {
                DateTime dt2 = new DateTime();
                if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                {

                    //时间戳转换
                    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
                    long timeStamp = (long)(dt2 - startTime).TotalSeconds; // 相差秒数
                    listfilter.Add(Builders<MW_Agent_State_Record>.Filter.Gt("time_login", timeStamp));
                }
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                DateTime dt2 = new DateTime();
                if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                {
                    //时间戳转换
                    System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
                    long timeStamp = (long)(dt2 - startTime).TotalSeconds; // 相差秒数
                    listfilter.Add(Builders<MW_Agent_State_Record>.Filter.Lt("time_login", timeStamp));
                }
            }

            int recordCount = 0;
            if (listfilter.Count > 0)
            {
                var filter = Builders<MW_Agent_State_Record>.Filter.And(listfilter);
                list = await _mw_agent_state_recordRepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _mw_agent_state_recordRepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

            //根据日期汇总
            var listt = list.ToList();
            foreach (var item in listt)
            {

            }

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