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

namespace CallCenterApi.Controllers
{
    /// <summary>
    /// IVR使用控制器，IVR文件需要使用的接口
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class IVRUseController : BaseController
    {
        private readonly ILogger<IVRUseController> _logger;
        #region
        private readonly ICall_BlacklistRepository _call_blacklistRepository;
        private readonly ISys_IVRWordsRepository _sys_ivrwordsRepository;
        private readonly ISys_WorkOFFDaysRepository _sys_workoffdaysRepository;
        private readonly ISys_WorkTimesRepository _sys_worktimesRepository;
        private readonly ISys_SeatGroupRepository _sys_seatgroupRepository;
        private readonly ICall_DutyPhoneRepository _call_dutyphoneRepository;
        private readonly ICall_RecordsRepository _call_recordsRepository;
        #endregion
        public IVRUseController(ILogger<IVRUseController> logger,
            ICall_BlacklistRepository call_blacklistRepository,
                ISys_IVRWordsRepository sys_ivrwordsRepository, 
                ISys_WorkOFFDaysRepository sys_workoffdaysRepository,
                ISys_WorkTimesRepository sys_worktimesRepository, 
                ICall_DutyPhoneRepository call_dutyphoneRepository,
                ISys_SeatGroupRepository sys_seatgroupRepository,
                ICall_RecordsRepository call_recordsRepository)
        {
            _logger = logger;
            _call_blacklistRepository = call_blacklistRepository;
            _sys_ivrwordsRepository = sys_ivrwordsRepository;
            _sys_workoffdaysRepository = sys_workoffdaysRepository;
            _sys_worktimesRepository = sys_worktimesRepository;
            _call_dutyphoneRepository = call_dutyphoneRepository;
            _sys_seatgroupRepository = sys_seatgroupRepository;
            _call_recordsRepository = call_recordsRepository;
        }

        #region 黑名单
        /// <summary>
        /// 根据主叫号码获取是否是黑名单
        /// 如果是根据callid更新通话记录中的数据
        /// </summary>
        [HttpGet("getblack")]
        public async Task<IActionResult> IsBlackListAsync(string caller, string callid)
        {
            var list = new List<FilterDefinition<Call_Blacklist>>();
            if (caller != null)
                list.Add(Builders<Call_Blacklist>.Filter.Where(s => s.telphone.Contains(caller)));

            var time = DateTime.Now.ToLocalTime();
            list.Add(Builders<Call_Blacklist>.Filter.Gt("removetime", time));
            list.Add(Builders<Call_Blacklist>.Filter.Lt("settime", time));
            list.Add(Builders<Call_Blacklist>.Filter.Eq("isdelete", false));

            var filter = Builders<Call_Blacklist>.Filter.And(list);
            var res = false;
            try
            {   
                var blacklist = await _call_blacklistRepository.Get(filter, null, null);
                if (blacklist.Count() > 0)
                {
                    //Call_Blacklist m_blacklist = blacklist.Result.FirstOrDefault();
                    // 根据callid更新通话记录中的数据
                    res = true;
                }
            }
            catch(Exception ex)
            {
                return Error("程序异常，异常信息为：" + ex.Message);
            }

            if (res)
                return Success("当前号码为黑名单号码");
            else
                return Error("当前号码为正常号码");
        }
        #endregion

        #region 欢迎词
        /// <summary>
        /// 欢迎词
        /// </summary>
        /// <param name="caller">主叫号码</param>
        /// <param name="callee">被叫号码</param>
        /// <returns></returns>
        [HttpGet("getivr")]
        public async Task<IActionResult> GetIVRWel(string caller, string callee)
        {
            var date = DateTime.Now.ToLocalTime();
            var list = new List<FilterDefinition<Sys_IVRWords>>();
            list.Add(Builders<Sys_IVRWords>.Filter.Eq("isdelete", false));
            list.Add(Builders<Sys_IVRWords>.Filter.Eq("isstate", 1));//isnull(F_IsState,0)=1
            list.Add(Builders<Sys_IVRWords>.Filter.Lt("startdate", date) & Builders<Sys_IVRWords>.Filter.Gt("enddate", date));//(F_StartDate<=getdate() and F_EndDate>=getdate())

            var filter = Builders<Sys_IVRWords>.Filter.And(list);
            var ilist = await _sys_ivrwordsRepository.Get(filter);

            var text = "";var type = 0;
            if (ilist!=null&&ilist.Count() > 0)
            {
                var model = ilist.FirstOrDefault();
                type = model.type;
                if (type == 1)
                    text = model.content;
                else if (type == 2)
                    text = model.wavfile.FirstOrDefault().fileurl;
            }

            var obj = new
            {
                TTSText = text,
                type = type
                //TTSText="欢迎致电河南华谊网络科技有限公司"
            };
            
            return Success("获取欢迎词", obj);
        }
        #endregion

        #region 节假日
        [HttpGet("getholiday")]
        public async Task<IActionResult> IsHoliday(string caller, string callee)
        {
            var date = DateTime.Now.ToString("yyyy-MM-dd");
            #region 获取当日是否为休息日
            var wdlist = await _sys_workoffdaysRepository.Get(x => x.isdelete == false && x.offstate == 0);
            var isoffday = false;
            foreach (var item in wdlist)
            {
                if (item.offdate.ToString("yyyy-MM-dd").Equals(date))
                {
                    isoffday = true;
                    break;
                }
            }
            #endregion

            #region 获取当前时间是否为下班时间 暂时不区分休息日的上下班时间
            //获取对应坐席组
            var zxzmodel = await getseatgroupAsync(caller, callee);
            var zxzcode = "";
            if (zxzmodel!=null)
                zxzcode = zxzmodel.zxzcode;
            var isworktime = false;
            var wtlist = await _sys_worktimesRepository.Get(x => x.isdelete == false && x.groupcode == zxzcode);
            var timenow = DateTime.Now;
            foreach (var item in wtlist)
            {
                var starttime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + item.workstarttimes);
                var endtime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " " + item.workendtimes);
                if (DateTime.Compare(timenow, starttime) > 0 && DateTime.Compare(timenow, endtime) < 0)
                {
                    isworktime = true;
                    break;
                }
            }
            #endregion
            
            var obj = new {
                isoffday,
                isworktime
            };
            return Success("获取休息日和上班时间", obj);
        }
        #endregion

        #region 坐席组
        /// <summary>
        /// 获取坐席组
        /// 预留参数可为空
        /// </summary>
        /// <param name="caller">主叫号码</param>
        /// <param name="callee">被叫号码</param>
        /// <returns></returns>
        [HttpGet("getseatgroup")]
        public async Task<IActionResult> GetSeatGroup(string caller, string callee)
        {
            var zxzmodel = await getseatgroupAsync(caller, callee);
            var zxzid = "";
            if (zxzmodel != null)
                zxzid = zxzmodel.id;

            var obj = new
            {
                groupid = zxzid
            };
            return Success("获取坐席组ID", obj);
        }
        #endregion

        #region 值班电话
        /// <summary>
        /// 获取值班电话
        /// 预留参数可为空
        /// </summary>
        /// <param name="caller">主叫号码</param>
        /// <param name="callee">被叫号码</param>
        /// <returns></returns>
        [HttpGet("getdutyphone")]
        public async Task<IActionResult> GetDutyPhone(string caller,string callee)
        {
            //获取对应坐席组
            var zxzmodel = await getseatgroupAsync(caller, callee);
            var zxzid = "";
            if (zxzmodel != null)
                zxzid = zxzmodel.id;
            #region
            //根据条件查询集合
            var flist = new List<FilterDefinition<Call_DutyPhone>>();
            flist.Add(Builders<Call_DutyPhone>.Filter.Eq("isdelete", false));
            flist.Add(Builders<Call_DutyPhone>.Filter.Eq("groupid", zxzid));
            #endregion
            var list = await _call_dutyphoneRepository.Get(Builders<Call_DutyPhone>.Filter.And(flist));
            var phone = "";
            if (list.Count() > 0)
            {
                var model = list.FirstOrDefault();
                phone = model.zbdh;

                #region 更新最后呼入时间
                model.callintime = DateTime.Now.ToLocalTime();
                await _call_dutyphoneRepository.Update(model);
                #endregion
            }

            var obj = new
            {
                dutyphone = phone
            };
            return Success("获取值班电话", obj);
        }
        #endregion


        #region 获取最近沟通的坐席
        /// <summary>
        /// 根据号码通话记录，优先自动匹配最近一次沟通的坐席
        /// </summary>
        /// <param name="caller">主叫号码</param>
        /// <returns></returns>
        [HttpGet("getlatelyseat")]
        public async Task<IActionResult> GetLatelySeat(string caller)
        {
            // 条件如下：
            // 1、坐席不为0；
            // 2、呼叫状态：1已接通；
            // 3、处理方式：2自助服务和6人工处理；
            // 4、主叫号码（获取主叫号码最近一次沟通记录）
            var list = await _call_recordsRepository.Get(x => x.agent_code != "0" && x.callstate == 1 && (x.dealtype == 2 || x.dealtype == 6) && x.callnumber.Contains(caller));
            // 排序按照 通话开始时间
            list = list.OrderByDescending(x => x.begintime_talk);
            var lists = list.ToList();
            var seatcode = "";
            if (list.Count() > 0)
            {
                var model = list.FirstOrDefault();
                seatcode = model != null ? model.agent_code : "";
            }
            var obj = new
            {
                seatcode = seatcode
            };
            return Success("获取最近沟通的坐席", obj);
        }
        #endregion


        /// <summary>
        /// 获取对应坐席组 - 方法
        /// </summary>
        /// <param name="caller"></param>
        /// <param name="callee">被叫</param>
        /// <param name="ivrkey">按键之</param>
        /// <returns></returns>
        private async Task<Sys_SeatGroup> getseatgroupAsync(string caller, string callee,string ivrkey="")
        {
            #region 获取坐席组
            var zxzlist = await _sys_seatgroupRepository.Get(x => x.isdelete == false);
            //if (!string.IsNullOrEmpty(callee))
            //    zxzlist = zxzlist.Where(x => x.outcallnum.Equals(callee));
            //if (!string.IsNullOrEmpty(ivrkey))
            //    zxzlist = zxzlist.Where(x => x.ivrkey.Equals(ivrkey));

            if (zxzlist.Count() > 0)
            {
                var model = zxzlist.FirstOrDefault();
                return model;
            }
            else
                return null;
            #endregion
        }
    }
}