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

namespace CallCenterApi.Controllers.trafficmanagement
{
    /// <summary>
    /// 黑名单管理控制器，存储需拦截的黑名单号码
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class CallBlackListController : BaseController
    {
        private readonly ILogger<CallBlackListController> _logger;
        private readonly ICall_BlacklistRepository _call_blacklistRepository;

        public CallBlackListController(ILogger<CallBlackListController> logger, ICall_BlacklistRepository call_blacklistRepository)
        {
            _logger = logger;
            _call_blacklistRepository = call_blacklistRepository;
        }

        [Authorize]
        [HttpGet("getall")]
        public async Task<IActionResult> GetAllListsAsync()
        {
            try
            {
                var blacklist = await _call_blacklistRepository.GetAll();
                return Success("获取全部数据成功", blacklist);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取黑名单全部数据异常");
                return Error("获取黑名单全部数据失败");
            }
        }

        [Authorize]
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListsAsync(string phone,string stime,string etime)
        {
            try
            {
                //排序字段
                var sort = Builders<Call_Blacklist>.Sort.Descending("createtime");

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_Blacklist>>();
                list.Add(Builders<Call_Blacklist>.Filter.Eq("isdelete", false));
                if (stime != null)
                    list.Add(Builders<Call_Blacklist>.Filter.Gt("settime", stime));
                if (etime != null)
                    list.Add(Builders<Call_Blacklist>.Filter.Lt("settime", etime));
                if (phone != null)
                    list.Add(Builders<Call_Blacklist>.Filter.Where(s => s.telphone.Contains(phone)));
                
                    var filter = Builders<Call_Blacklist>.Filter.And(list);
                    var blacklist = await _call_blacklistRepository.Get(filter, null, sort);

                return Success("根据条件获取数据成功", blacklist);
                //return blacklist.Result.ToJson();
                //return "初始化数据成功";
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取黑名单数据异常");
                return Error("根据条件获取黑名单数据失败");
            }
        }

        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string phone, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            try
            {
               
                //排序字段
                var sort = Builders<Call_Blacklist>.Sort.Descending("createtime");

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_Blacklist>>();
                list.Add(Builders<Call_Blacklist>.Filter.Eq("isdelete", false));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim() + " 00:00:00", out dt2))
                        list.Add(Builders<Call_Blacklist>.Filter.Gt("settime", stime));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim() + " 23:59:59", out dt2))
                        list.Add(Builders<Call_Blacklist>.Filter.Lt("settime", etime));
                }

                //号码模糊查询
                if (!string.IsNullOrWhiteSpace(phone))
                    list.Add(Builders<Call_Blacklist>.Filter.Where(s => s.telphone.Contains(phone)));

                var filter = Builders<Call_Blacklist>.Filter.And(list);
                var blacklist = await _call_blacklistRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _call_blacklistRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = blacklist,
                    total = count,
                };
                return Content(obj.ToJson());
                //return Success("根据条件获取分页数据成功", blacklist);
                //return blacklist.Result.ToJson();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取黑名单分页数据异常");
                return Error("根据条件获取黑名单分页数据失败");
            }
        }

        [Authorize]
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = await _call_blacklistRepository.GetSingle(id.Trim());

                    if (dModel != null)
                    {
                        return Success("获取黑名单成功", dModel);
                    }
                    else
                    {
                        return Error("获取黑名单失败");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "获取黑名单实体异常");
                    return Error("获取黑名单失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        [Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string phone, string settime, string removetime, string des)
        {
            try
            {
                Call_Blacklist clmodel = new Call_Blacklist();
                var res = false;
                if(!string.IsNullOrWhiteSpace(phone))
                    clmodel.telphone = phone;
                if (!string.IsNullOrWhiteSpace(settime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(settime.Trim(), out dt2))
                        clmodel.settime = dt2;
                }
                if (!string.IsNullOrWhiteSpace(removetime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(removetime.Trim(), out dt2))
                        clmodel.removetime = dt2;
                }
                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("update")]
        public async Task<IActionResult> UpdateAsync(string id, string phone, string settime, string removetime, string des)
        {
            var res = false;
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var clmodel = await _call_blacklistRepository.GetSingle(id);
                    if (clmodel != null)
                    {
                        if (!string.IsNullOrWhiteSpace(phone))
                            clmodel.telphone = phone;
                        if (!string.IsNullOrWhiteSpace(settime))
                        {
                            DateTime dt2 = new DateTime();
                            if (DateTime.TryParse(settime.Trim(), out dt2))
                                clmodel.settime = dt2;
                        }
                        if (!string.IsNullOrWhiteSpace(removetime))
                        {
                            DateTime dt2 = new DateTime();
                            if (DateTime.TryParse(removetime.Trim(), out dt2))
                                clmodel.removetime = dt2;
                        }
                        if (!string.IsNullOrWhiteSpace(des))
                            clmodel.describe = des.Trim();
                        //clmodel.interceptnum += 1;//2018-7-26clmodel.interceptnum += 1;

                        res = await _call_blacklistRepository.Update(clmodel);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "黑名单保存异常");
                    return Error("黑名单保存失败");
                }
            }
            if (res)
                return Success("黑名单保存成功");
            else
                return Error("黑名单保存失败");
        }

        [Authorize]
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _call_blacklistRepository.GetSingle(item);
                        ml.isdelete = true;
                        if (await _call_blacklistRepository.Update(ml))
                            res += 1;
                    }
                    if (res == ids.Length)
                        return Success("黑名单删除成功");
                    else if (res > 0 && res < ids.Length)
                        return Error("部分黑名单删除失败");
                    else
                        return Error("黑名单删除失败");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "黑名单删除异常");
                    return Error("黑名单删除失败");
                }
            }
            else
                return Error("请选择要删除的记录");
        }
    }
}