using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using CallCenterApi.IRepositories;
using MadRunFabric.Model;
using MadRunFabric.Common;
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 CallDutyPhoneController : BaseController
    {
        private readonly ILogger<CallDutyPhoneController> _logger;
        private readonly ICall_DutyPhoneRepository _call_dutyphoneRepository;
        private readonly ISys_SeatGroupRepository _sys_seatgroupRepository;

        public CallDutyPhoneController(ILogger<CallDutyPhoneController> logger, 
            ICall_DutyPhoneRepository call_dutyphoneRepository, ISys_SeatGroupRepository sys_seatgroupRepository)
        {
            _logger = logger;
            _call_dutyphoneRepository = call_dutyphoneRepository;
            _sys_seatgroupRepository = sys_seatgroupRepository;
        }

        /// <summary>
        /// 获取值班电话列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string telphone,string groupid, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                //排序字段
                var sort = Builders<Call_DutyPhone>.Sort.Descending("createtime");

                //根据条件查询集合
                var flist = new List<FilterDefinition<Call_DutyPhone>>();
                flist.Add(Builders<Call_DutyPhone>.Filter.Eq("isdelete", false));
                if (!string.IsNullOrWhiteSpace(telphone))
                    flist.Add(Builders<Call_DutyPhone>.Filter.Where(s => s.zbdh.Contains(telphone)));
                if (!string.IsNullOrWhiteSpace(stime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(stime.Trim(), out dt2))
                        flist.Add(Builders<Call_DutyPhone>.Filter.Gt("createtime", stime + " 00:00:00"));
                }
                if (!string.IsNullOrWhiteSpace(etime))
                {
                    DateTime dt2 = new DateTime();
                    if (DateTime.TryParse(etime.Trim(), out dt2))
                        flist.Add(Builders<Call_DutyPhone>.Filter.Lt("createtime", etime + " 23:59:59"));
                }
                if (!string.IsNullOrWhiteSpace(groupid))
                    flist.Add(Builders<Call_DutyPhone>.Filter.Where(s => s.groupid.Equals(groupid)));
                var filter = Builders<Call_DutyPhone>.Filter.And(flist);
                var list = await _call_dutyphoneRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _call_dutyphoneRepository.CountAsync(filter);
                var obj = new
                {
                    state = "success",
                    message = "根据条件获取分页数据成功",
                    rows = list,
                    total = count,
                };
                return Content(obj.ToJson());
                //return Success("根据条件获取值班电话分页数据成功", list);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "根据条件获取值班电话分页数据异常");
                return Error("根据条件获取值班电话分页数据异常");
            }
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [Authorize]
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = await _call_dutyphoneRepository.GetSingle(id.Trim());

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

        }

        /// <summary>
        /// 添加值班电话
        /// </summary>
        [Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string telphone, string groupid, string des)
        {
            try
            {
                Call_DutyPhone clmodel = new Call_DutyPhone();
                var res = false;
                if (!string.IsNullOrWhiteSpace(telphone))
                    clmodel.zbdh = telphone;
                if (!string.IsNullOrWhiteSpace(des))
                    clmodel.remark = des;
                if(!string.IsNullOrWhiteSpace(groupid))
                {
                    clmodel.groupid = groupid.Trim();
                    var dModel = await _sys_seatgroupRepository.GetSingle(groupid.Trim());

                    if (dModel != null)
                    {
                        clmodel.groupname = dModel.zxzname;
                    }
                }
                clmodel.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                clmodel.createtime = DateTime.Now.ToLocalTime();
                clmodel.isdelete = false;

                res = await _call_dutyphoneRepository.Add(clmodel);
                if (res)
                    return Success("值班电话保存成功");
                else
                {
                    return Error("值班电话保存失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "值班电话保存异常");
                return Error("值班电话保存失败");
            }
        }

        /// <summary>
        /// 修改值班电话
        /// </summary>
        [Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> EditAsync(string id, string telphone, string groupid, string des)
        {
            var res = false;
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var clmodel = await _call_dutyphoneRepository.GetSingle(id);
                    if (clmodel != null)
                    {
                        if (!string.IsNullOrWhiteSpace(telphone))
                            clmodel.zbdh = telphone;
                        if (!string.IsNullOrWhiteSpace(des))
                            clmodel.remark = des;
                        if (!string.IsNullOrWhiteSpace(groupid))
                        {
                            clmodel.groupid = groupid.Trim();
                            var dModel = await _sys_seatgroupRepository.GetSingle(groupid.Trim());

                            if (dModel != null)
                            {
                                clmodel.groupname = dModel.zxzname;
                            }
                        }

                        res = _call_dutyphoneRepository.Update(clmodel).Result;
                    }
                }
                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_dutyphoneRepository.GetSingle(item);
                        ml.isdelete = true;
                        if (await _call_dutyphoneRepository.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("请选择要删除的记录");
        }
    }
}