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

namespace CallCenterApi.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<Cus_Customer_Project> _collection_cus_customer_project;
        protected readonly IMongoCollection<Sys_SystemConfig> _sys_systemconfigRepository;
        protected readonly IMongoCollection<Call_MobileData> _call_mobiledataRepository;
        protected readonly IMongoCollection<Bus_WorkOrder_Base> _bus_workorder_baseRepository;
       
        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>();
            _collection_cus_customer_project = _context.GetCollection<Cus_Customer_Project>();
            _sys_systemconfigRepository = _context.GetCollection<Sys_SystemConfig>();
            _call_mobiledataRepository = _context.GetCollection<Call_MobileData>();
            _bus_workorder_baseRepository = _context.GetCollection<Bus_WorkOrder_Base>();
        }


        //测试
        public object GetCallRecordTotalTime(string agentcode,string tag, string start, string end)//, UserInfoModel userinfo)
        {

            string bxwhere = "";
            if (!string.IsNullOrEmpty(tag))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{calltype:" + tag + "}";
                }
                else
                {
                    bxwhere = "{calltype:" + tag + "}";
                }
            }
            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 + "')}}";
                }

            }

            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\"}}}"));//UserId,UserCode,UserName
            //bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: {userid:\"$_id.userid\", usercode:\"$_id.usercode\",username:\"$_id. username\"}, count: {$sum: 1},totalcount:{$sum:\"$ longs_talk\"}}}"));//UserId,UserCode,UserName
            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"; }
            #region 
            var list = bxresult.Select(pro =>
            {
                var rts = pro.Values.ToArray();
                
                return new
                {
                    agentcode = rts[0].ToString(),
                    calloutcount = rts[1].ToString(),
                    talksummarytime = rts[2].ToString()
                };
            });
            return list;
            #endregion


            return bxresult;
            /*int[] hours = Enumerable.Range(0, 24).ToArray<int>();
            int[] bxcounts = new int[24];//报修数量
            int[] clcounts = new int[24];//处理数量

            for (int i = 0; i < hours.Length; i++)
            {
                bxcounts[i] = 0;
                clcounts[i] = 0;

                var bx = bxresult.Where(p => p.Values.ToArray()[0].ToString() == i.ToString()).FirstOrDefault();
                if (bx != null)
                {
                    bxcounts[i] = Int32.Parse(bx.Values.ToArray()[1].ToString());
                }

                var cl = clresult.Where(p => p.Values.ToArray()[0].ToString() == i.ToString()).FirstOrDefault();
                if (cl != null)
                {
                    clcounts[i] = Int32.Parse(cl.Values.ToArray()[1].ToString());
                }
            }

            var obj = new
            {
                hours,
                bxcounts,
                clcounts
            };

            return obj;*/
        }


        public object GetCallRecordRingTime(string agentcode, string start, string end)//, UserInfoModel userinfo)
        {

            string bxwhere = "{calltype:1},{callstate:0}";
            if (!string.IsNullOrEmpty(agentcode))
            {
                bxwhere = bxwhere + ",{agent_code:'" + agentcode + "'}";
            }

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

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

            }

            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},totalcount:{$sum:\"$longs_ring\"}}}"));//UserId,UserCode,UserName
            //bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: {userid:\"$_id.userid\", usercode:\"$_id.usercode\",username:\"$_id. username\"}, count: {$sum: 1},totalcount:{$sum:\"$ longs_talk\"}}}"));//UserId,UserCode,UserName
            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"; }
                      
        }

        public object GetHighChartData(string agentcode, string start, string end,string tag,string state)//, UserInfoModel userinfo)
        {

            //string bxwhere = "{calltype:1,callstate:0}";
            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 + "')}}";
                }

            }

            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}}}"));//UserId,UserCode,UserName
            //bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: {userid:\"$_id.userid\", usercode:\"$_id.usercode\",username:\"$_id. username\"}, count: {$sum: 1},totalcount:{$sum:\"$ longs_talk\"}}}"));//UserId,UserCode,UserName
            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="top"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <returns></returns>
        public object GetHWRank(int top, string stime, string etime)
        {
            var query = from p in _collection.AsQueryable()
                        join u in _collection_sys_user_account.AsQueryable() on p.agent_code  equals u.usercode into userinfo
                        where (p.agent_code!="0" && p.agent_code !=null )//1 == 1
                        select new
                        {
                            
                            usercode = p.agent_code,
                            username = userinfo.Count() > 0 ? userinfo.First().username : "",
                            p.begintime 
                        };
            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 ranklist = query.GroupBy(p => new { p.usercode, p.username }).Select(p => new
            {
                p.Key.usercode,
                p.Key.username,
                count = p.Count()
            }).OrderByDescending(p => p.count).ToList().Select((p, i) => new
            {
                p.usercode,
                p.username,
                p.count,
                rank = i + 1
            });

            return top == 0 ? ranklist : ranklist.Take(top);
        }

        /// <summary>
        /// 获取日周月年话务数据24小时统计
        /// </summary>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="optuser"></param>
        /// <returns></returns>
        public object GetHW24CountReport(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(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(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(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>
        /// Linq 关联查询 - App
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="provincecode"></param>
        /// <param name="citycode"></param>
        /// <param name="projectid"></param>
        /// <param name="protype"></param>
        /// <param name="systemid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="recordCount"></param>
        /// <returns></returns>
        public IEnumerable<object> GetLists(string stime, string etime, string keyword)
        {
            var query = from p in _collection.AsQueryable()
                        join u in _collection_cus_customer_project.AsQueryable() on p.callnumber equals u.mobilephone  into cusinfo
                        join w in _bus_workorder_baseRepository.AsQueryable() on p.callnumber equals w.phone into orderinfo//GetCallOutprefix()
                        where 1 == 1
                        orderby p.id descending //(p.agent_code != "0" && p.agent_code != null)

                        select new
                        {
                            p.id,
                            p.unique_id,
                            p.callnumber,
                            p.agent_code,
                            p.agent_extnumber,
                            p.calltype,
                            p.callstate,
                            p.dealtype,
                            p.opttype,
                            p.bussinesstype,
                            p.begintime,
                            p.begintime_ivr,
                            p.endtime_ivr,
                            p.begintime_queue,
                            p.endtime_queue,
                            p.begintime_ring,
                            p.endtime_ring,
                            p.begintime_talk,
                            p.endtime_talk,
                            p.endtime,
                            p.longs_ring,
                            p.longs_ivr,
                            p.longs_queue,
                            p.longs_talk,
                            p.longs,
                            p.turnstate,
                            p.begintime_opt,
                            p.begintime_talk_opt,
                            p.end_talk_opt,
                            p.agent_code_turn,
                            p.agent_extnumber_turn,
                            p.evaluation,
                            p.FilePath,
                            p.callopttype,
                            p.taskid,
                            p.taskphoneid,
                            cusname = cusinfo != null && cusinfo.Count() > 0 ? cusinfo.First().name : "",
                            existorder=orderinfo != null && orderinfo.Count() > 0 ? "有" : "无",

                        };


            #region 查询条件
            //query = query.Where(it => it.projectdelete == 0);
            if (!string.IsNullOrWhiteSpace(stime))
            {
                query = query.Where(s => s.begintime.CompareTo(DateTime.Parse(stime)) >= 0 || s.endtime.CompareTo(DateTime.Parse(stime)) >= 0);
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                query = query.Where(s => s.begintime.CompareTo(DateTime.Parse(etime)) <= 0 || s.endtime.CompareTo(DateTime.Parse(etime)) <= 0);
            }
            //模糊查询
            if (!string.IsNullOrWhiteSpace(keyword))
                query = query.Where(s => s.callnumber.Contains(keyword));

            #endregion

            return query;
        }

        //获取自动外呼前缀
        public string GetCallOutprefix(string phone)
        {
            int i;
            bool isnum = int.TryParse(phone.Substring(0, 1), out i);//判断是否为数字
            if (!isnum)
            {
                return "";
            }
            string phone1 = phone;
            string tophone = phone1;
            string zipcode = ""; string bfix = "0"; string wfix = ""; string fix = "";

            string bxwhere = "{isdelete:false},{paramcode:ZDWHQZ}";
            var bxstages = new List<IPipelineStageDefinition>();
            bxstages.Add(new JsonPipelineStageDefinition<Sys_SystemConfig, BsonDocument>("{$match:{$and:[" + bxwhere + "]}}"));
           
            var bxpipeline = new PipelineStagePipelineDefinition<Sys_SystemConfig, BsonDocument>(bxstages);
            var bxresult = _sys_systemconfigRepository.Aggregate(bxpipeline).ToList();
            string whqz = "";
            //var dModel = await _sys_systemconfigRepository.GetSingle(s => s.paramcode.Equals("ZDWHQZ") & s.isdelete == false, null);
            if (bxresult.Count > 0)
            {
                whqz = bxresult[0]["paramvalue"].ToString();
            }
            if (whqz != "")
            {
                var typearr = whqz.Split('#');
                if (typearr.Length > 2)
                {
                    zipcode = typearr[2];
                    bfix = typearr[1];
                    wfix = typearr[0];
                    int zip = 0;
                    #region
                    if (phone.Trim().Length >= 7)
                    {
                        //7位及7位以上是固定电话或手机
                        //判断是否手机
                        if (phone.Trim().Length == 11 && phone[0] == '1')
                        {//号码为11位，首位是1，为手机号
                         //BLL.T_Sys_MobileData mobile_Bll = new BLL.T_Sys_MobileData();
                         //Model.T_Sys_MobileData mobileModel = mobile_Bll.GetModelList("F_MobileNum='" + phone.Substring(0, 7) + "'").FirstOrDefault();
                         //_call_mobiledataRepository
                            string p = phone.Substring(0, 7);
                            string bxwhere1 = "{mobilenum:"+p+"}";
                            var bxstages1 = new List<IPipelineStageDefinition>();
                            bxstages1.Add(new JsonPipelineStageDefinition<Call_MobileData, BsonDocument>("{$match:{$and:[" + bxwhere1 + "]}}"));

                            var bxpipeline1 = new PipelineStagePipelineDefinition<Call_MobileData, BsonDocument>(bxstages1);
                            var bxresult1 = _call_mobiledataRepository.Aggregate(bxpipeline1).ToList();

                            //var mobileModel = await _call_mobiledataRepository.Get(x => x.mobilenum == phone.Substring(0, 7));
                            if (bxresult1!=null&&bxresult1.Count >0)
                            {
                                foreach (var items in bxresult1)
                                {
                                    if (items["zipcode"].Equals(zipcode))
                                    {
                                        zip = 1;
                                    }
                                    else
                                    {
                                        zip = 2;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (phone.Trim().Length == 11 && phone.Substring(0, 3).Equals(zipcode))
                            {//号码为11位
                             //截取前三位区号判断是否本地
                                bool resbd3 = phone.Substring(0, 3).Equals(zipcode);
                                //截取前四位区号判断是否本地
                                bool resbd4 = phone.Substring(0, 4).Equals(zipcode);
                                if (resbd3 || resbd4)
                                {
                                    zip = 3;
                                }
                                else
                                {
                                    zip = 4;
                                }
                            }
                            else if (phone.Trim().Length < 11)
                            {//号码小于11位，为本地
                                zip = 3;
                            }
                            else if (phone.Trim().Length > 11 && phone.Substring(0, 4).Equals(zipcode))
                            {//号码大于11位，截取前四位区号判断是否本地
                                zip = 3;
                            }
                            else
                            {
                                zip = 4;
                            }
                        }
                    }
                    #endregion
                    #region 
                    if (zip == 1)
                    {//手机本地号码
                        fix = bfix;
                    }
                    else if (zip == 2)
                    {//手机外地号码
                        fix = wfix;
                    }
                    else
                    {
                        tophone = phone1.TrimStart('0');
                        if (zip == 3)
                        {//本地固话去0加9 比如：988888517，937188888517
                            fix = bfix;
                        }
                        else if (zip == 4)
                        {//外地固话前加9 比如：9037188888517
                            fix = wfix;
                        }
                    }
                    #endregion
                    //var obj = new
                    //{
                    //    phone = fix + tophone,
                    //    fix = fix
                    //};
                    string y = fix + tophone;
                    return y;
                }
            }
            else//默认本地
            {
                fix = bfix;
                string y = fix + tophone;
                return y;
            }


            return "";


        }


        //添加获取省市报表
        public object GetPCCallRecordTotalTime(string agentcode, string tag, string start, string end,string province,string city)//, UserInfoModel userinfo)
        {

            string bxwhere = "";
            if (!string.IsNullOrEmpty(tag))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{calltype:" + tag + "}";
                }
                else
                {
                    bxwhere = "{calltype:" + tag + "}";
                }
            }
            if (!string.IsNullOrEmpty(province))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{city:/" + province + "/}";
                }
                else
                {
                    bxwhere = "{city:/" + province + "/}";
                }
            }
            if (!string.IsNullOrEmpty(city))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{city:/" + city + "/}";
                }
                else
                {
                    bxwhere = "{city:/" + city + "/}";
                }
            }
            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 + "')}}";
                }

            }

            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:\"$city\", count: {$sum: 1},totalcount:{$sum:\"$longs_talk\"}}}"));//UserId,UserCode,UserName
            //bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: {userid:\"$_id.userid\", usercode:\"$_id.usercode\",username:\"$_id. username\"}, count: {$sum: 1},totalcount:{$sum:\"$ longs_talk\"}}}"));//UserId,UserCode,UserName
            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"; }
            #region 
            var list = bxresult.Select(pro =>
            {
                var rts = pro.Values.ToArray();

                return new
                {
                    agentcode = rts[0].ToString(),
                    calloutcount = rts[1].ToString(),
                    talksummarytime = rts[2].ToString()
                };
            });
            return list;
            #endregion


            return bxresult;
            /*int[] hours = Enumerable.Range(0, 24).ToArray<int>();
            int[] bxcounts = new int[24];//报修数量
            int[] clcounts = new int[24];//处理数量

            for (int i = 0; i < hours.Length; i++)
            {
                bxcounts[i] = 0;
                clcounts[i] = 0;

                var bx = bxresult.Where(p => p.Values.ToArray()[0].ToString() == i.ToString()).FirstOrDefault();
                if (bx != null)
                {
                    bxcounts[i] = Int32.Parse(bx.Values.ToArray()[1].ToString());
                }

                var cl = clresult.Where(p => p.Values.ToArray()[0].ToString() == i.ToString()).FirstOrDefault();
                if (cl != null)
                {
                    clcounts[i] = Int32.Parse(cl.Values.ToArray()[1].ToString());
                }
            }

            var obj = new
            {
                hours,
                bxcounts,
                clcounts
            };

            return obj;*/
        }


        public object GetPCCallRecordRingTime(string agentcode, string start, string end, string province, string city)//, UserInfoModel userinfo)
        {

            string bxwhere = "{calltype:1},{callstate:0}";
            if (!string.IsNullOrEmpty(agentcode))
            {
                bxwhere = bxwhere + ",{agent_code:'" + agentcode + "'}";
            }
            if (!string.IsNullOrEmpty(province))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{city:/" + province + "/}";
                }
                else
                {
                    bxwhere = "{city:/" + province + "/}";
                }
            }
            if (!string.IsNullOrEmpty(city))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{city:/" + city + "/}";
                }
                else
                {
                    bxwhere = "{city:/" + city + "/}";
                }
            }
            if (!string.IsNullOrEmpty(start))
            {
                bxwhere = bxwhere + ",{begintime:{$gte:new Date('" + start + "')}}";

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

            }

            var bxstages = new List<IPipelineStageDefinition>();
            bxstages.Add(new JsonPipelineStageDefinition<mw_call_records, BsonDocument>("{$match:{$and:[" + bxwhere + "]}}"));
            bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id:\"$city\", count: {$sum: 1},totalcount:{$sum:\"$longs_ring\"}}}"));//UserId,UserCode,UserName
            //bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: {userid:\"$_id.userid\", usercode:\"$_id.usercode\",username:\"$_id. username\"}, count: {$sum: 1},totalcount:{$sum:\"$ longs_talk\"}}}"));//UserId,UserCode,UserName
            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"; }

        }

        public object GetPCHighChartData(string agentcode, string start, string end, string tag, string state, string province, string city)//, UserInfoModel userinfo)
        {

            //string bxwhere = "{calltype:1,callstate:0}";
            string bxwhere = "";
            if (!string.IsNullOrEmpty(tag))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{calltype:" + tag + "}";
                }
                else
                {
                    bxwhere = "{calltype:" + tag + "}";
                }
            }
            if (!string.IsNullOrEmpty(province))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{city:/" + province + "/}";
                }
                else
                {
                    bxwhere = "{city:/" + province + "/}";
                }
            }
            if (!string.IsNullOrEmpty(city))
            {
                if (bxwhere != "")
                {
                    bxwhere = bxwhere + ",{city:/" + city + "/}";
                }
                else
                {
                    bxwhere = "{city:/" + city + "/}";
                }
            }
            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 + "')}}";
                }

            }

            var bxstages = new List<IPipelineStageDefinition>();
            bxstages.Add(new JsonPipelineStageDefinition<mw_call_records, BsonDocument>("{$match:{$and:[" + bxwhere + "]}}"));
            bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id:\"$city\", count: {$sum: 1}}}"));//UserId,UserCode,UserName
            //bxstages.Add(new JsonPipelineStageDefinition<BsonDocument, BsonDocument>("{$group:{_id: {userid:\"$_id.userid\", usercode:\"$_id.usercode\",username:\"$_id. username\"}, count: {$sum: 1},totalcount:{$sum:\"$ longs_talk\"}}}"));//UserId,UserCode,UserName
            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="top"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <returns></returns>
        public object GetDataList(int top, string stime, string etime)
        {
            var query = from p in _collection.AsQueryable()
                        join u in _collection_sys_user_account.AsQueryable() on p.agent_code equals u.usercode into userinfo
                        where (p.agent_code != "0" && p.agent_code != null)//1 == 1
                        select new
                        {

                            usercode = p.agent_code,
                            username = userinfo.Count() > 0 ? userinfo.First().username : "",
                            p.begintime
                        };
            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 ranklist = query.GroupBy(p => new { p.usercode, p.username }).Select(p => new
            {
                p.Key.usercode,
                p.Key.username,
                count = p.Count()
            }).OrderByDescending(p => p.count).ToList().Select((p, i) => new
            {
                p.usercode,
                p.username,
                p.count,
                rank = i + 1
            });

            return top == 0 ? ranklist : ranklist.Take(top);
        }
    }
}
