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

namespace CallCenterApi.Controllers.trafficmanagement
{
    /// <summary>
    /// 来电弹屏
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class CallInScreenController : BaseController
    {
        public IActionResult Index()
        {
            return View();
        }

        private readonly ILogger<CallInScreenController> _logger;
        private readonly ICall_BlacklistRepository _call_blacklistRepository;
        private readonly ICall_MobileDataRepository _call_mobiledataRepository;
        private readonly ISys_TelTitleDataRepository _sys_telltitledataRepository;

        public CallInScreenController(ILogger<CallInScreenController> logger, ICall_BlacklistRepository call_blacklistRepository, ICall_MobileDataRepository call_mobiledataRepository, ISys_TelTitleDataRepository sys_telltitledataRepository)
        {
            _logger = logger;
            _call_blacklistRepository = call_blacklistRepository;
            _call_mobiledataRepository = call_mobiledataRepository;
            _sys_telltitledataRepository = sys_telltitledataRepository;
        }

        [Authorize]
        [HttpPost("addblack")]
        public async Task<IActionResult> AddAsync(string phone, string des,int num,int type)
        {
            try
            {
                Call_Blacklist clmodel = new Call_Blacklist();
                var res = false;
                var date = DateTime.Now;
                var enddate = date;
                if (!string.IsNullOrWhiteSpace(phone))
                    clmodel.telphone = phone;
                
                clmodel.settime = date;

                switch (type)
                {
                    case 1: enddate = enddate.AddDays(num); break;
                    case 2: enddate = enddate.AddHours(num); break;
                    case 3: enddate = enddate.AddMinutes(num); break;
                    case 4: enddate = DateTime.MaxValue; break;
                }
                clmodel.removetime = enddate;
                if (!string.IsNullOrWhiteSpace(des))
                    clmodel.describe = des.Trim();
                clmodel.interceptnum = 0;//2018-7-26将1改为0
                clmodel.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                clmodel.isdelete = false;
                clmodel.createtime = DateTime.Now.ToLocalTime();

                res = await _call_blacklistRepository.Add(clmodel);

                #region 测试
                //var c=_call_blacklistRepository.Add(new Call_Blacklist()
                //{
                //    telphone = "13825698521",
                //    callid = "",
                //    isdelete = false,
                //    settime = DateTime.Now,
                //    describe = "",
                //    removetime = DateTime.Now.AddDays(7),
                //    usercode = "8000",
                //    blacktype = 0,
                //    interceptnum = 0
                //});
                //return c.Result.ToString();
                #endregion
                if (res)
                    return Success("黑名单保存成功");
                else
                    return Error("黑名单保存失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "黑名单保存异常");
                return Error("黑名单保存失败");
            }
        }

        [Authorize]
        [HttpPost("delblack")]
        public async Task<IActionResult> RemoveAsync(string phone)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复

            #region
            Call_Blacklist imodel = new Call_Blacklist();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("isdelete", "true");

            var list = new List<FilterDefinition<Call_Blacklist>>();
            var filterBuilder = Builders<Call_Blacklist>.Filter;
            list.Add(filterBuilder.Eq("telphone", phone));
            long n = await _call_blacklistRepository.Count(x => x.telphone == phone);
            if (n > 0)
            {
                var filter = Builders<Call_Blacklist>.Filter.And(list);
                var tt = await _call_blacklistRepository.UpdateManay(imodel, dic, filter);
                if (tt)
                { return Success("黑名单删除成功"); }
                else
                { return Error("黑名单删除失败"); }
            }
            else
            {
                return Error("黑名单中没有此电话号码");
            }
            #endregion

               
        }

        /// <summary>
        /// 获取号码的归属地 - RecordServer调用（不需要登录验证）
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="serveruse"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("getphonelocation")]
        public async Task<IActionResult> GetPhoneLocation(string tel, int serveruse = 0)
        {
            if (tel != null && tel.Trim() != "")
            {
                try
                {
                    string location = "未知";

                    if (tel.Trim().Length == 11 && tel.Substring(0, 1) != "0")
                    {
                        
                        var dModel = await _call_mobiledataRepository.GetSingle(p => p.mobilenum == tel.Substring(0, 7));
                        
                        if (dModel != null)
                        {
                            location = dModel.citydes + dModel.carddes ;
                            if (serveruse == 1)
                            {
                                return Success("获取号码归属地成功", dModel.citydes);
                            }
                            else
                            {
                                return Success("获取号码归属地成功", location);
                            }
                        }
                    }
                    else
                    {
                        if (tel.Length > 3)
                        {
                            var dModel = await _sys_telltitledataRepository.GetSingle(p => p.keyphonenum == tel.Substring(0, 4));
                            if (dModel == null)
                            {
                                dModel = await _sys_telltitledataRepository.GetSingle(p => p.keyphonenum == tel.Substring(0, 3));
                            }
                            if (dModel != null)
                            {
                                location = dModel.titlename;
                                return Success("获取号码归属地成功", location);
                            }
                        }
                        else if (tel.Length > 2)
                        {
                            var dModel = await _sys_telltitledataRepository.GetSingle(p => p.keyphonenum == tel.Substring(0, 3));

                            if (dModel != null)
                            {
                                location = dModel.titlename;
                                return Success("获取号码归属地成功", location);
                            }
                        }
                        
                    }

                                        
                    return Success("获取号码归属地成功", location);

                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取号码归属地实体异常");
                    return Error("获取号码归属地失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        
    }
}