using MadRunFabric.Common;
using MadRunFabric.Common.Options;
using MadRunFabric.Model;
using MadRunFabric.Model.CallCenterApi;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using WechatApi.IRepositories;

namespace WechatApi.Repositories
{
    public class Call_RecordsRepository : BaseRepository<mw_call_records, string>, ICall_RecordsRepository
    {
        protected readonly ILogger<BaseRepository<mw_call_records, string>> _logger;
        protected readonly IMongoCollection<mw_call_records> _collection_mw_call_records;
        protected readonly IMongoCollection<Sys_User_Account> _collection_sys_user_account;
        protected readonly IMongoCollection<MW_Agent_State_Record> _collection_mw_agent_state_record;
        public Call_RecordsRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<mw_call_records, string>> logger) : base(settings, logger)
        {
            _logger = logger;
            _collection_mw_call_records = _context.GetCollection<mw_call_records>();
            _collection_sys_user_account = _context.GetCollection<Sys_User_Account>();
        }

        /// <summary>
        /// 获取坐席总数
        /// </summary>
        /// <returns></returns>
        public int GetUserCount()
        {
            var users = from sysuser in _collection_sys_user_account.AsQueryable()
                        where sysuser.delete_flag == false
                        select sysuser;

            return users.Count();
        }
        /// <summary>
        /// 获取通话量
        /// </summary>
        /// <param name="agentcode">坐席工号</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="tag">呼叫类型</param>
        /// <param name="state">呼叫状态</param>
        public object GetHighChartData(string agentcode, string start, string end, string tag, string state)
        {
            #region 条件搜索
            string bxwhere = "";
            if (!string.IsNullOrEmpty(tag))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{calltype:" + tag + "}";
                }
                else
                {
                    bxwhere = "{calltype:" + tag + "}";
                }
            }
            if (!string.IsNullOrEmpty(state))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{callstate:" + state + "}";
                }
                else
                {
                    bxwhere = "{callstate:" + state + "}";
                }
            }
            if (!string.IsNullOrEmpty(agentcode))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{agent_code:'" + agentcode + "'}";
                }
                else
                {
                    bxwhere = "{agent_code:'" + agentcode + "'}";
                }
            }

            if (!string.IsNullOrEmpty(start))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{begintime:{$gte:new Date('" + start + "')}}";
                }
                else
                {
                    bxwhere = "{begintime:{$gte:new Date('" + start + "')}}";
                }

            }
            if (!string.IsNullOrEmpty(end))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{begintime:{$lte:new Date('" + end + "')}}";
                }
                else
                {
                    bxwhere = "{begintime:{$lte:new Date('" + end + "')}}";
                }

            }
            #endregion
            var bxstages = new List<IPipelineStageDefinition>();
            bxstages.Add(new JsonPipelineStageDefinition<mw_call_records, BsonDocument>("{$match:{$and:[" + bxwhere + "]}}"));
            bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id:\"$id\", count: {$sum: 1}}}"));
            var bxpipeline = new PipelineStagePipelineDefinition<mw_call_records, BsonDocument>(bxstages);
            var bxresult = _collection_mw_call_records.Aggregate(bxpipeline).ToList();
            if (bxresult.Count > 0)
            {
                return bxresult[0]["count"];
            }
            else
            { return "0"; }

        }
        /// <summary>
        /// 获取通话时长
        /// </summary>
        /// <param name="agentcode">坐席工号</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="tag">呼叫类型</param>
        /// <param name="state">呼叫状态</param>
        public object GetCallRecordTotalTime(string agentcode, string tag, string start, string end, string state)
        {
            #region 条件搜索
            string bxwhere = "";
            if (!string.IsNullOrEmpty(tag))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{calltype:" + tag + "}";
                }
                else
                {
                    bxwhere = "{calltype:" + tag + "}";
                }
            }
            if (!string.IsNullOrEmpty(state))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{callstate:" + state + "}";
                }
                else
                {
                    bxwhere = "{callstate:" + state + "}";
                }
            }
            if (!string.IsNullOrEmpty(agentcode))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{agent_code:'" + agentcode + "'}";
                }
                else
                {
                    bxwhere = "{agent_code:'" + agentcode + "'}";
                }
            }

            if (!string.IsNullOrEmpty(start))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{begintime:{$gte:new Date('" + start + "')}}";
                }
                else
                {
                    bxwhere = "{begintime:{$gte:new Date('" + start + "')}}";
                }

            }
            if (!string.IsNullOrEmpty(end))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{begintime:{$lte:new Date('" + end + "')}}";
                }
                else
                {
                    bxwhere = "{begintime:{$lte:new Date('" + end + "')}}";
                }

            }
            #endregion
            var bxstages = new List<IPipelineStageDefinition>();
            bxstages.Add(new JsonPipelineStageDefinition<mw_call_records, BsonDocument>("{$match:{$and:[" + bxwhere + "]}}"));//agent_code
            bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id:\"$id\", count: {$sum: 1},totalcount:{$sum:\"$longs_talk\"}}}"));
            var bxpipeline = new PipelineStagePipelineDefinition<mw_call_records, BsonDocument>(bxstages);
            var bxresult = _collection_mw_call_records.Aggregate(bxpipeline).ToList();
            if (bxresult.Count > 0)
            {
                return bxresult[0]["count"] + "," + bxresult[0]["totalcount"];
            }
            else
            { return "0,0"; }
        }

        /// <summary>
        /// 获取日周月年话务数据24小时统计
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <returns></returns>
        public object GetHW24CountReport(string agentcode, string stime, string etime)
        {
            int[] hours = Enumerable.Range(0, 24).ToArray<int>();
            int[] counts = new int[24];
            int[] yjrcounts = new int[24];
            int[] wjrcounts = new int[24];

            var query = from p in _collection.AsQueryable() where 1 == 1 select p;
            if (!string.IsNullOrEmpty(agentcode))
                query = query.Where(it => it.agent_code.Equals(agentcode));
            if (!string.IsNullOrEmpty(stime))
                query = query.Where(it => it.begintime >= Convert.ToDateTime(stime));
            if (!string.IsNullOrEmpty(etime))
                query = query.Where(it => it.begintime <= Convert.ToDateTime(etime));

            var list = query.ToList();
            for (int i = 0; i < hours.Length; i++)
            {
                counts[i] = list.Where(it => it.begintime.Hour == i).Count();
            }

            #region 已接入
            var query1 = from p in _collection.AsQueryable() where p.callstate == 1 select p;
            if (!string.IsNullOrEmpty(agentcode))
                query1 = query1.Where(it => it.agent_code.Equals(agentcode));
            if (!string.IsNullOrEmpty(stime))
                query1 = query1.Where(it => it.begintime >= Convert.ToDateTime(stime));
            if (!string.IsNullOrEmpty(etime))
                query1 = query1.Where(it => it.begintime <= Convert.ToDateTime(etime));

            var list1 = query1.ToList();
            for (int i = 0; i < hours.Length; i++)
            {
                yjrcounts[i] = list1.Where(it => it.begintime.Hour == i).Count();
            }
            #endregion

            #region 未接入
            var query2 = from p in _collection.AsQueryable() where p.callstate == 0 select p;
            if (!string.IsNullOrEmpty(agentcode))
                query2 = query2.Where(it => it.agent_code.Equals(agentcode));
            if (!string.IsNullOrEmpty(stime))
                query2 = query2.Where(it => it.begintime >= Convert.ToDateTime(stime));
            if (!string.IsNullOrEmpty(etime))
                query2 = query2.Where(it => it.begintime <= Convert.ToDateTime(etime));

            var list2 = query2.ToList();
            for (int i = 0; i < hours.Length; i++)
            {
                wjrcounts[i] = list2.Where(it => it.begintime.Hour == i).Count();
            }
            #endregion

            var result = new
            {
                hours,
                counts,
                yjrcounts,
                wjrcounts
            };
            return result;
        }

        /// <summary>
        /// 坐席状态统计
        /// </summary>
        /// <param name="agentcode"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public object GetAgentState(string agentcode, string start, string end)
        {
            #region 条件搜索
            string bxwhere = "";
            if (!string.IsNullOrEmpty(agentcode))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{agent_id:" + agentcode + "}";
                }
                else
                {
                    bxwhere = "{agent_id:" + agentcode + "}";
                }
            }

            if (!string.IsNullOrEmpty(start))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{time_login:{$gte:new Date('" + start + "')}}";
                }
                else
                {
                    bxwhere = "{time_login:{$gte:new Date('" + start + "')}}";
                }

            }
            if (!string.IsNullOrEmpty(end))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{time_login:{$lte:new Date('" + end + "')}}";
                }
                else
                {
                    bxwhere = "{time_login:{$lte:new Date('" + end + "')}}";
                }

            }
            #endregion
            
            var bxstages = new List<IPipelineStageDefinition>();
            bxstages.Add(new JsonPipelineStageDefinition<MW_Agent_State_Record, BsonDocument>("{$match:{$and:[" + bxwhere + "]}}"));//agent_code
            bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id:\"$id\", logintimes:{$sum:\"$login_times\"}, freetimes:{$sum:\"free_times\"}, reposetimes:{$sum:\"repose_times\"}, talktimes:{$sum:\"talk_times\"}, reposenum:{$sum:\"repose_num\"}, answernum:{$sum:\"answer_num\"}}}"));
            var bxpipeline = new PipelineStagePipelineDefinition<MW_Agent_State_Record, BsonDocument>(bxstages);
            var bxresult = _collection_mw_agent_state_record.Aggregate(bxpipeline).ToList();
            if (bxresult.Count > 0)
            {
                var obj = new {
                    logintimes = bxresult[0]["logintimes"],
                    freetimes = bxresult[0]["freetimes"],
                    reposetimes = bxresult[0]["reposetimes"],
                    talktimes = bxresult[0]["talktimes"],
                    reposenum = bxresult[0]["reposenum"],
                    answernum = bxresult[0]["answernum"],
                };
                return obj;
            }
            else
            { return null; }
        }
            #region
            ///// <summary>
            ///// 获取24小时通话情况
            ///// </summary>
            ///// <param name="agentcode">坐席工号</param>
            ///// <param name="start">开始时间</param>
            ///// <param name="end">结束时间</param>
            ///// <param name="tag">呼叫类型</param>
            ///// <param name="state">呼叫状态</param>
            //public object Get24HourCall(string agentcode, string tag, string start, string end, string state)
            //{
            //    #region 条件搜索
            //    string bxwhere = ""; 
            //    if (!string.IsNullOrEmpty(tag))
            //    {
            //        if (bxwhere != "")
            //        {
            //            bxwhere = bxwhere + ",{calltype:" + tag + "}";
            //        }
            //        else
            //        {
            //            bxwhere = "{calltype:" + tag + "}";
            //        }
            //    }
            //    if (!string.IsNullOrEmpty(state))
            //    {
            //        if (bxwhere != "")
            //        {
            //            bxwhere = bxwhere + ",{callstate:" + state + "}";
            //        }
            //        else
            //        {
            //            bxwhere = "{callstate:" + state + "}";
            //        }
            //    }
            //    if (!string.IsNullOrEmpty(agentcode))
            //    {
            //        if (bxwhere != "")
            //        {
            //            bxwhere = bxwhere + ",{agent_code:'" + agentcode + "'}";
            //        }
            //        else
            //        {
            //            bxwhere = "{agent_code:'" + agentcode + "'}";
            //        }
            //    }

            //    if (!string.IsNullOrEmpty(start))
            //    {
            //        if (bxwhere != "")
            //        {
            //            bxwhere = bxwhere + ",{begintime:{$gte:new Date('" + start + "')}}";
            //        }
            //        else
            //        {
            //            bxwhere = "{begintime:{$gte:new Date('" + start + "')}}";
            //        }

            //    }
            //    if (!string.IsNullOrEmpty(end))
            //    {
            //        if (bxwhere != "")
            //        {
            //            bxwhere = bxwhere + ",{begintime:{$lte:new Date('" + end + "')}}";
            //        }
            //        else
            //        {
            //            bxwhere = "{begintime:{$lte:new Date('" + end + "')}}";
            //        }

            //    }
            //    #endregion

            //    var bxstages = new List<IPipelineStageDefinition>();
            //    bxstages.Add(new JsonPipelineStageDefinition<mw_call_records, BsonDocument>("{$match:{$and:[" + bxwhere + "]}}"));//agent_code
            //    bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id:{$hour: {$add:[\"begintime\",28800000]} }, count: {$sum: 1},longs:{$sum:\"$longs_talk\"}}}"));
            //    var bxpipeline = new PipelineStagePipelineDefinition<mw_call_records, BsonDocument>(bxstages);
            //    var bxresult = _collection_mw_call_records.Aggregate(bxpipeline).ToList();

            //    int[] hours = Enumerable.Range(0, 24).ToArray<int>();
            //    string[] counts = new string[24];//数量
            //    string[] longs = new string[24];//时长

            //    for (int i = 0; i < hours.Length; i++)
            //    {
            //        counts[i] = "0";
            //        longs[i] = "0";

            //        var bx = bxresult.Where(p => p.Values.ToArray()[0].ToString() == i.ToString()).FirstOrDefault();
            //        if (bx != null)
            //        {
            //            counts[i] = bx.Values.ToArray()[1].ToString();
            //            longs[i] = bx.Values.ToArray()[2].ToString();
            //        }
            //    }

            //    var obj = new
            //    {
            //        hours,
            //        counts,
            //        longs,
            //    };

            //    return obj;
            //}
            #endregion
        }
}