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

namespace CallCenterApi.Repositories
{
    public class MW_Autocall_Call_RecordRepository : BaseRepository<MW_Autocall_Call_Record, string>, IMW_Autocall_Call_RecordRepository
    {
        protected readonly IMongoCollection<Call_OutTask> _collection_outtask;
        
        protected readonly ILogger<BaseRepository<MW_Autocall_Call_Record, string>> _logger;
        public MW_Autocall_Call_RecordRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<MW_Autocall_Call_Record, string>> logger) : base(settings, logger)
        {
            _collection_outtask = _context.GetCollection<Call_OutTask>();
            
            _logger = logger;
        }

        //public MW_Autocall_Call_RecordRepository(IOptions<MongodbOptions> settings, ILogger<BaseRepository<MW_Autocall_Call_Record, string>> logger) : base(settings, logger)
        //{
        //}


        /// <summary>
        /// Linq 关联查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public object GetDetails(string key)
        {

            if (!string.IsNullOrWhiteSpace(key))
            {


                //关联查询
                var query =
                from re in _collection.AsQueryable()
                join tasks in _collection_outtask.AsQueryable() on re.task_icon equals tasks.id into taskinfo
                where re.callee == key
                orderby re.id descending
                select new
                {
                    re.id,
                    re.unique_id,
                    re.timestamp,
                    re.task_icon,
                    taskname = taskinfo.Count() > 0 ? taskinfo.First().taskname : null,
                    re.callee,
                    re.start_time,
                    re.end_time,
                    re.connect_time,
                    re.agent_id,
                    re.record_path,
                    re.is_call_out_ok,
                    re.is_want_agent,
                    re.is_want_agent_ok,
                    re.is_turn_agent,
                    re.is_turn_agent_ok

                };
                var model = query.ToList().Select(re =>
                {

                    return new
                    {
                        re.id,
                        re.unique_id,
                        re.timestamp,
                        re.task_icon,
                        re.taskname,
                        re.callee,
                        re.start_time,
                        re.end_time,
                        re.connect_time,
                        re.agent_id,
                        re.record_path,
                        re.is_call_out_ok,
                        re.is_want_agent,
                        re.is_want_agent_ok,
                        re.is_turn_agent,
                        re.is_turn_agent_ok
                    };
                }).FirstOrDefault();
                if (model != null)
                {
                    return model;
                }
            }
            else
            {
                //关联查询
                var query =
                from re in _collection.AsQueryable()
                join tasks in _collection_outtask.AsQueryable() on re.task_icon equals tasks.id into taskinfo
                where 1 == 1
                orderby re.id descending
                select new
                {
                    re.id,
                    re.unique_id,
                    re.timestamp,
                    re.task_icon,
                    taskname = taskinfo.Count() > 0 ? taskinfo.First().taskname : null,
                    re.callee,
                    re.start_time,
                    re.end_time,
                    re.connect_time,
                    re.agent_id,
                    re.record_path,
                    re.is_call_out_ok,
                    re.is_want_agent,
                    re.is_want_agent_ok,
                    re.is_turn_agent,
                    re.is_turn_agent_ok

                };
                var model = query.ToList().Select(re =>
                {

                    return new
                    {
                        re.id,
                        re.unique_id,
                        re.timestamp,
                        re.task_icon,
                        re.taskname,
                        re.callee,
                        re.start_time,
                        re.end_time,
                        re.connect_time,
                        re.agent_id,
                        re.record_path,
                        re.is_call_out_ok,
                        re.is_want_agent,
                        re.is_want_agent_ok,
                        re.is_turn_agent,
                        re.is_turn_agent_ok
                    };
                }).FirstOrDefault();
                if (model != null)
                {
                    return model;
                }
            }
            return null;
        }

        /// <summary>
        /// Linq 关联查询 分页
        /// </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> GetListsByPage(string key, int pageindex, int pagesize, out int recordCount)
        {

            //关联查询
            var query =
                 from re in _collection.AsQueryable()
                 join tasks in _collection_outtask.AsQueryable() on re.task_icon equals tasks.id into taskinfo
                 where 1 == 1
                 orderby re.id descending
                 select new
                {
                     re.id,
                     re.unique_id,
                     re.timestamp,
                     re.task_icon,
                     taskname = taskinfo.Count() > 0 ? taskinfo.First().taskname : null,
                     re.callee,
                     re.start_time,
                     re.end_time,
                     re.connect_time,
                     re.agent_id,
                     re.record_path,
                     re.is_call_out_ok,
                     re.is_want_agent,
                     re.is_want_agent_ok,
                     re.is_turn_agent,
                     re.is_turn_agent_ok
                 };
            #region 查询条件
            if (!string.IsNullOrEmpty(key))
                query = query.Where(s => s.callee .Contains(key) );
            
            #endregion
            recordCount = query.Count();
            var list = query.Skip((pageindex - 1) * pagesize).Take(pagesize);

            var querys = list.ToList().Select(re =>
            {
            var filter = Builders<Call_OutTask>.Filter.Eq("id", re.task_icon);// "5bce8756876d23c7d429891f");
                var clmodel = _collection_outtask.Find(filter ).FirstOrDefaultAsync();//关联查询没获取到taskname
                if (clmodel!=null&& clmodel.Result !=null )
                {
                    return new
                    {
                        re.id,
                        re.unique_id,
                        re.timestamp,
                        re.task_icon,
                        taskname =clmodel.Result.taskname,//re.taskname,
                        re.callee,
                        re.start_time,
                        re.end_time,
                        re.connect_time,
                        re.agent_id,
                        re.record_path,
                        re.is_call_out_ok,
                        re.is_want_agent,
                        re.is_want_agent_ok,
                        re.is_turn_agent,
                        re.is_turn_agent_ok
                    };
                } else 
                return new
                {
                    re.id,
                    re.unique_id,
                    re.timestamp,
                    re.task_icon,
                    re.taskname,
                    re.callee,
                    re.start_time,
                    re.end_time,
                    re.connect_time,
                    re.agent_id,
                    re.record_path,
                    re.is_call_out_ok,
                    re.is_want_agent,
                    re.is_want_agent_ok,
                    re.is_turn_agent,
                    re.is_turn_agent_ok
                };
            });

            return querys;
        }

        
    }
}
