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;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CallCenterApi.Controllers.trafficmanagement
{
    /// <summary>
    /// 号码归属地
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MobiledataController : BaseController
    {
        private readonly ILogger<MobiledataController> _logger;
        private readonly ICall_MobileDataRepository _call_mobiledataRepository;
        public MobiledataController(ILogger<MobiledataController> logger, ICall_MobileDataRepository call_mobiledataRepository)
        {
            _logger = logger;
            _call_mobiledataRepository = call_mobiledataRepository;
            
        }

        // GET: /<controller>/
        public IActionResult Index()
        {
            return View();
        }


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

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

        }

        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string key, int pageindex = 1, int pagesize = 10)
        {
            try
            {

                //排序字段
                var sort = Builders<Call_MobileData>.Sort.Ascending("id");// createtime

                //根据条件查询集合
                var list = new List<FilterDefinition<Call_MobileData>>();
                list.Add(Builders<Call_MobileData>.Filter.Eq("isdelete", 0));
                

                //模糊查询
                if (!string.IsNullOrWhiteSpace(key))
                    list.Add(Builders<Call_MobileData>.Filter.Where(s => s.mobilenum.Contains(key)|| s.carddes.Contains(key) || s.citydes.Contains(key) || s.zipcode.Contains(key)));

                var filter = Builders<Call_MobileData>.Filter.And(list);
                var blacklist = await _call_mobiledataRepository.GetByPage(filter, pageindex, pagesize, sort );//sort
                var count = await _call_mobiledataRepository.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]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string mobilenum,string zipcode, string citydes, string carddes)
        {
            try
            {
                
                Call_MobileData clmodel = new Call_MobileData();
                var res = false;
                if (!string.IsNullOrWhiteSpace(mobilenum))
                    clmodel.mobilenum = mobilenum;
                if (!string.IsNullOrWhiteSpace(zipcode))
                    clmodel.zipcode = zipcode;
                if (!string.IsNullOrWhiteSpace(citydes))
                    clmodel.citydes = citydes;
                if (!string.IsNullOrWhiteSpace(carddes))
                    clmodel.carddes = carddes;
                
                clmodel.createuser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                clmodel.isdelete = 0;
                clmodel.createtime = DateTime.Now.ToLocalTime();

                res = await _call_mobiledataRepository.Add(clmodel);

               
                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 mobilenum, string zipcode, string citydes, string carddes)
        {
            var res = false;
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var clmodel = await _call_mobiledataRepository.GetSingle(id);
                    if (clmodel != null)
                    {
                        if (!string.IsNullOrWhiteSpace(mobilenum))
                            clmodel.mobilenum = mobilenum;
                        if (!string.IsNullOrWhiteSpace(zipcode))
                            clmodel.zipcode = zipcode;
                        if (!string.IsNullOrWhiteSpace(citydes))
                            clmodel.citydes = citydes;
                        if (!string.IsNullOrWhiteSpace(carddes))
                            clmodel.carddes = carddes;
                        

                        res = await _call_mobiledataRepository.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_mobiledataRepository.GetSingle(item);
                        ml.isdelete = 1;
                        if (await _call_mobiledataRepository.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("请选择要删除的记录");
        }
    }
}
