using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.IRepositories.Call;
using System.IRepositories.Sys;
using System.Linq;
using System.Model;
using System.Model.Call;
using System.Model.Sys;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using Utility;

namespace TVShoppingCallCenter_ZLJ.Controllers.CallCenter
{
    /// <summary>
    /// 呼叫中心关联方法
    /// </summary>
  // [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class CallFunctionController : BaseController
    {
        private readonly IConfiguration config;
        private readonly ISys_MobileDataRepository busMobileDataRepository;
        private readonly ICall_CallRecordsRepository busCallRecordsRepository;
        private readonly ICall_CallOutboundRepository CallOutboundRecordsRepository;
        private readonly ICDRRepository busCdrRepository;
        private readonly Iauto_cdrRepository auto_cdrRepository;
        private readonly ItaskRepository taskRepository;
        private readonly ISys_AutoDialRepository sys_autodialrepository;
        private readonly ISys_SystemConfigRepository busSystemConfigRepository;
        private readonly ICus_VipInfoRepository _cus_vip_infoRepository;//客户
        private readonly Ipoint_agentRepository _point_agentrepository;
        public CallFunctionController(ISys_SystemConfigRepository _busSystemConfigRepository,ICDRRepository _busCdrRepository,ICall_CallRecordsRepository _busCallRecordsRepository,IConfiguration _configuration, ISys_MobileDataRepository _busMobileDataRepository, ICus_VipInfoRepository cus_vip_infoRepository,
            ICall_CallOutboundRepository _CallOutboundRecordsRepository, Iauto_cdrRepository _auto_cdrRepository
            , ItaskRepository _taskRepository, ISys_AutoDialRepository _sys_autodialrepository,
            Ipoint_agentRepository point_agentrepository)
        {
            busSystemConfigRepository = _busSystemConfigRepository;
            busCdrRepository = _busCdrRepository;
            busCallRecordsRepository = _busCallRecordsRepository;
            config = _configuration;
            busMobileDataRepository = _busMobileDataRepository;
            _cus_vip_infoRepository = cus_vip_infoRepository;
            CallOutboundRecordsRepository = _CallOutboundRecordsRepository;
            auto_cdrRepository = _auto_cdrRepository;
            taskRepository = _taskRepository;
            sys_autodialrepository = _sys_autodialrepository;
            _point_agentrepository = point_agentrepository;
        }
       
        /// <summary>
        /// 电话归属地查询
        /// </summary>
        /// <param name="tel"></param>
        /// <returns></returns>
        [HttpPost("GetTelLocation")]
        public async Task<IActionResult> GetTelLocation(string tel, int type = 0)
        {
            string location = await GetLocationFunc(tel, type);
            return Success("归属地加载成功", location);

        }
      

        /// <summary>
        /// 获取电话归属地
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [NonAction]
        internal async Task<string> GetLocationFunc(string tel, int type = 0)
        {

            string location = "未知";

            if (tel.Trim().Length == 11 && tel.Substring(0, 1) != "0")
            {
                T_Sys_MobileData mobile_Bll = new T_Sys_MobileData();
                T_Sys_MobileData mobileModel = await busMobileDataRepository.GetFirst(q => q.F_MobileNum == tel.Substring(0, 7));

                if (mobileModel != null)
                {

                    location = mobileModel.F_CityDes;
                    if (type == 0)
                    {
                        location += mobileModel.F_CardDes;
                    }
                }
            }
            else
            {
                T_Sys_MobileData mobile_Bll = new T_Sys_MobileData();
                T_Sys_MobileData mobileModel = await busMobileDataRepository.GetFirst(q => q.F_ZipCode == tel.Substring(0, 4));

                if (mobileModel == null)
                {
                    mobileModel = await busMobileDataRepository.GetFirst(q => q.F_ZipCode == tel.Substring(0, 3));
                }
                if (mobileModel != null)
                {
                    location = mobileModel.F_CityDes;
                    if (type == 0)
                    {
                        location += mobileModel.F_CardDes;
                    }
                }
            }

            return location;

        }




        #region  同步通话记录
        /// <summary>
        /// 同步通话记录
        /// </summary>
        /// <returns></returns>
        [NonAction]
        internal async Task<string> SyncCallRecord()
        {
            DateTime dtime = DateTime.Now.AddYears(-10);
            int maxid = 0;
            T_Call_CallRecords modelCallRecord = await busCallRecordsRepository.GetFirst(q => q.CdrId > 0, o => new { o.CdrId }, OrderByType.Desc);
            if (modelCallRecord != null)
            {
                maxid = modelCallRecord.CdrId;
            }
            modelCallRecord = await busCallRecordsRepository.GetFirst(q => q.CdrId > 0, o => new { o.EndTime }, OrderByType.Desc);
            if (modelCallRecord != null)
            {
                if (modelCallRecord.EndTime != null)
                    dtime = modelCallRecord.EndTime.GetValueOrDefault();
            }
            List<cdr> modellist = await busCdrRepository.GetListALL(q => q.id > maxid || q.end_time >= dtime);
            int totle = 0;
            int n = 0;
            int n1 = 0;
            if (modellist != null && modellist.Count > 0)
            {
                string url = "请配置videoURL/";
                T_Sys_SystemConfig   model =await busSystemConfigRepository.GetSingle(q=>q.F_ParamCode== "videoURL");
                if (model != null)
                {
                    url = model.F_ParamValue;
                }
                totle = modellist.Count;
                List<T_Call_CallRecords> modelRecordList = new List<T_Call_CallRecords>();
                foreach (cdr modelcdr in modellist)
                {

                    T_Call_CallRecords modelRecord = new T_Call_CallRecords();
                    modelRecord.ActionID = modelcdr.action_id;
                    modelRecord.TalkStartTime = modelcdr.answer_time;
                    modelRecord.Callee = modelcdr.callee;
                    if (modelcdr.call_type==0)
                    {
                      string tel = modelcdr.caller.TrimStart('0');
                        modelRecord.UserCode = modelcdr.callee_agent;
                        var cus = await _cus_vip_infoRepository.GetListALL(x => x.F_State == 1 && x.F_Phone
                       == modelcdr.caller || x.F_Phone
                       == tel);
                        if (cus!=null&&cus.Count >0 )
                        {
                            modelRecord.CusCode = cus.FirstOrDefault ().F_Name ;
                            modelRecord.CusId = cus.FirstOrDefault().F_ID ;
                            var point = await _point_agentrepository.GetListALL(x => x.agent == modelcdr.callee_agent);
                            if (point==null && point.Count ()<=0)
                            {
                                point_agent point_Agent = new point_agent();
                                point_Agent.caller = modelcdr.caller;
                                point_Agent.agent  = modelcdr.callee_agent;
                                var res = _point_agentrepository.Add(point_Agent);
                            }
                        }
                    }
                    else
                    {
                        modelRecord.UserCode = modelcdr.caller_agent;
                        string tel = modelcdr.callee.TrimStart('0');
                        modelRecord.UserCode = modelcdr.callee_agent;
                        var cus = await _cus_vip_infoRepository.GetListALL(x => x.F_State == 1 && x.F_Phone
                       == modelcdr.caller || x.F_Phone
                       == tel);
                        if (cus != null && cus.Count > 0)
                        {
                            modelRecord.CusCode = cus.FirstOrDefault().F_Name;
                            modelRecord.CusId = cus.FirstOrDefault().F_ID;
                        }
                    }
                    modelRecord.Caller = modelcdr.caller;
                    modelRecord.CallType = modelcdr.call_type;
                    modelRecord.BeginTime = modelcdr.create_time;
                    modelRecord.EndTime = modelcdr.end_time;
                    modelRecord.CallState = modelcdr.is_answer;
                    //  modelcdr.hangup_cause;挂机原因不赋值  HangUpReason
                    //  modelcdr.leave_path 留言 赋值给了FilePath
                    modelRecord.IvrEndTime = modelcdr.hangup_time;
                    modelRecord.Id = modelcdr.id;
                    modelRecord.MYD = modelcdr.myd;
                    modelRecord.Remark = modelcdr.note;
                    modelRecord.OperateType = modelcdr.op_type;
                    modelRecord.FilePath = url+ modelcdr.record_path;
                    if (string.IsNullOrEmpty(modelcdr.record_path) && !string.IsNullOrEmpty(modelcdr.leave_path))
                    {
                        modelRecord.FilePath = url+ modelcdr.leave_path;
                    }
                    modelRecord.RingStartTime = modelcdr.ring_time;
                    modelRecord.RelayNumber = modelcdr.trunk_num;
                    modelRecord.CallId = modelcdr.uuid;
                    modelRecord.CdrId = modelcdr.id;
                    modelRecord.Location = await GetLocationFunc(modelcdr.caller, 1);
                    #region 计算时长
                    modelRecord.LongTime = (int)DateTimeConvert.DateDiff(DateInterval.Second, modelcdr.create_time.GetValueOrDefault(), modelcdr.end_time.GetValueOrDefault());

                    if (modelcdr.answer_time != null)
                        modelRecord.TalkLongTime = (int)DateTimeConvert.DateDiff(DateInterval.Second, modelcdr.answer_time.GetValueOrDefault(), modelcdr.end_time.GetValueOrDefault());
                    else
                        modelRecord.TalkLongTime = 0;
                    #endregion
                    n++;
                    n1++;
                    modelRecordList.Add(modelRecord);
                    if (n >= 2000)
                    {
                        await busCallRecordsRepository.AddAndUpdateList(modelRecordList);
                        modelRecordList.Clear();
                        n = 0;
                    }

                }
                //T_Call_CallRecords modelreturn= await busCallRecordsRepository.AddAndUpdateList(modelRecordList,s=>new {s.EndTime,s.TalkEndTime,s.IvrEndTime });
                //T_Call_CallRecords modelreturn = 
                await busCallRecordsRepository.AddAndUpdateList(modelRecordList);
            }
            return $"同步情况  成功/总数 = {n1}/{totle}";
        }
        /// <summary>
        /// 同步自动外呼通话记录
        /// </summary>
        /// <returns></returns>
        [NonAction]
        internal async Task<string> SyncOutbound()
        {
            DateTime dtime = DateTime.Now.AddYears(-10);
            int maxid = 0;
            T_Call_CallOutbound modelCallRecord = await CallOutboundRecordsRepository.GetFirst(q => q.CdrId > 0, o => new { o.CdrId }, OrderByType.Desc);
            if (modelCallRecord != null)
            {
                maxid = modelCallRecord.CdrId;
            }
            modelCallRecord = await CallOutboundRecordsRepository.GetFirst(q => q.CdrId > 0, o => new { o.EndTime }, OrderByType.Desc);
            if (modelCallRecord != null)
            {
                if (modelCallRecord.EndTime != null)
                    dtime = modelCallRecord.EndTime.GetValueOrDefault();
            }
            List<auto_cdr > modellist = await auto_cdrRepository.GetListALL(q => q.id > maxid || q.end_time >= dtime);
            int totle = 0;
            int n = 0;
            int n1 = 0;
            if (modellist != null && modellist.Count > 0)
            {
                string url = "请配置videoURL/";
                T_Sys_SystemConfig model = await busSystemConfigRepository.GetSingle(q => q.F_ParamCode == "videoURL");
                if (model != null)
                {
                    url = model.F_ParamValue;
                }
                totle = modellist.Count;
                List<T_Call_CallOutbound> modelRecordList = new List<T_Call_CallOutbound>();
                foreach (auto_cdr modelcdr in modellist)
                {

                    T_Call_CallOutbound modelRecord = new T_Call_CallOutbound();
                    modelRecord.ActionID =1;
                    modelRecord.TalkStartTime = modelcdr.answer_time;
                    modelRecord.Callee = modelcdr.callee;
                     modelRecord.UserCode = modelcdr.agent;
                    modelRecord.Caller = modelcdr.caller;
                    modelRecord.CallType =1;
                    modelRecord.BeginTime = modelcdr.create_time;
                    modelRecord.EndTime = modelcdr.end_time;
                    //  modelRecord.CallState = modelcdr.is_answer;
                    modelRecord.Id =(int ) modelcdr.id;

                    modelRecord.FilePath = url + modelcdr.record_path;
                    if (string.IsNullOrEmpty(modelcdr.record_path) && !string.IsNullOrEmpty(modelcdr.record_path ))
                    {
                        modelRecord.FilePath = url + modelcdr.record_path;
                    }
                    modelRecord.RingStartTime = modelcdr.ring_time;
                    modelRecord.CallId = modelcdr.uuid;
                    modelRecord.CdrId = (int)modelcdr.id;
                    modelRecord.Location = await GetLocationFunc(modelcdr.caller, 1);
                    #region 计算时长
                    modelRecord.LongTime = (int)DateTimeConvert.DateDiff(DateInterval.Second, modelcdr.create_time.GetValueOrDefault(), modelcdr.end_time.GetValueOrDefault());

                    if (modelcdr.answer_time != null)
                        modelRecord.TalkLongTime = (int)DateTimeConvert.DateDiff(DateInterval.Second, modelcdr.answer_time.GetValueOrDefault(), modelcdr.end_time.GetValueOrDefault());
                    else
                        modelRecord.TalkLongTime = 0;
                    #endregion
                    n++;
                    n1++;
                    modelRecordList.Add(modelRecord);
                    if (n >= 2000)
                    {
                        await CallOutboundRecordsRepository.AddAndUpdateList(modelRecordList);
                        modelRecordList.Clear();
                        n = 0;
                    }

                }
                await CallOutboundRecordsRepository.AddAndUpdateList(modelRecordList);
            }
            return $"同步情况  成功/总数 = {n1}/{totle}";
        }

        /// <summary>
        /// 同步外呼状态
        /// </summary>
        /// <returns></returns>
        [NonAction]
        internal async Task<string> SyncAutodial()
        {
            List<task > modellist = await taskRepository.GetListALL(q => q.status  ==0 &&q .state ==1);
            int totle = 0;
            int n = 0;
            int n1 = 0;
            if (modellist != null && modellist.Count > 0)
            {
                List<T_Sys_AutoDial> modelAutoDial = new List<T_Sys_AutoDial>();
                List<task> taskList  = new List<task>();
                foreach (task  it  in modellist)
                {
                    var AutoDial = await sys_autodialrepository.GetSingle (q => q.F_ID  == it.outbound_id );
                    if (AutoDial!=null )
                    {
                        AutoDial.F_ISOutbound = 1;
                        modelAutoDial.Add(AutoDial);
                        n++;
                    }
                    it.status = 1;
                    taskList.Add(it);
                    #endregion
                    n1++;
                    if (n >= 2000)
                    {
                        await sys_autodialrepository.AddAndUpdateList(modelAutoDial);
                        modelAutoDial.Clear();
                        n = 0;
                    }
                    if (n1 >=2000)
                    {
                        await taskRepository.UpdateList(taskList);
                        taskList.Clear();
                        n1 = 0;
                    }
                }
                await sys_autodialrepository.AddAndUpdateList(modelAutoDial);
                await taskRepository.UpdateList (taskList);

            }
            return $"同步情况  成功/总数 = {n1}/{totle}";
        }
       

    }
}