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.systemmanagement
{
    /// <summary>
    /// 坐席组管理
    /// </summary>
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SysSeatGroupController : BaseController
    {
        private readonly ILogger<SysSeatGroupController> _logger;
        private readonly ISys_SeatGroupRepository _sys_seatgroupRepository;

        public SysSeatGroupController(ILogger<SysSeatGroupController> logger, ISys_SeatGroupRepository sys_seatgroupRepository)
        {
            _logger = logger;
            _sys_seatgroupRepository = sys_seatgroupRepository;
        }
        /// <summary>
        /// 获取坐席组列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string key, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                //排序字段
                var sort = Builders<Sys_SeatGroup>.Sort.Descending("createtime");
                
                //根据条件查询集合
                var flist = new List<FilterDefinition<Sys_SeatGroup>>();
                flist.Add(Builders<Sys_SeatGroup>.Filter.Eq("isdelete", false));

                if (!string.IsNullOrWhiteSpace(key))
                    flist.Add(Builders<Sys_SeatGroup>.Filter.Where(s => s.zxzcode.Contains(key)
                        || s.zxzname.Contains(key) || s.zxatt.Contains(key)
                        || s.whbdkey.Contains(key) || s.whwdkey.Contains(key) || s.outcallnum.Contains(key) || s.des.Contains(key)));

                
                    var filter = Builders<Sys_SeatGroup>.Filter.And(flist);
                    var list = await _sys_seatgroupRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _sys_seatgroupRepository.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("获取坐席组分页数据失败");
            }
        }

        [Authorize]
        [HttpGet("getlist")]
        public async Task<IActionResult> GetList(string key)
        {
            //排序字段
            var sort = Builders<Sys_SeatGroup>.Sort.Descending("createtime");

            var list = await _sys_seatgroupRepository.Get(null, null, sort);

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

            if (!string.IsNullOrWhiteSpace(key))
                flist.Add(Builders<Sys_SeatGroup>.Filter.Where(s => s.zxzcode.Contains(key)
                    || s.zxzname.Contains(key) || s.zxatt.Contains(key)
                    || s.whbdkey.Contains(key) || s.whwdkey.Contains(key) || s.des.Contains(key)));


            if (flist.Count > 0)
            {
                var filter = Builders<Sys_SeatGroup>.Filter.And(flist);
                list = await _sys_seatgroupRepository.Get(filter, null, sort);
            }
            return Success("根据条件获取数据成功", list);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [Authorize]
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingle(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = await _sys_seatgroupRepository.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> Add(string zxzcode, string zxzname, string zxatt,
            string whwdkey,string whbdkey, int ivrkey,string outcallnum, string des)
        {
            try
            {
                Sys_SeatGroup clmodel = new Sys_SeatGroup();
                if (await GetExistByCodeAsync(zxzcode, "") || await GetExistByNameAsync(zxzname, ""))
                {
                    return Error("坐席组编号和名称必须唯一，请重新输入！");
                }
                var res = false;

                if (!string.IsNullOrWhiteSpace(zxzcode))
                    clmodel.zxzcode = zxzcode.Trim();
                else
                {
                    return Error("编号不能为空");
                }
                if (!string.IsNullOrWhiteSpace(zxzname))
                    clmodel.zxzname = zxzname.Trim();
                else
                {
                    return Error("名称不能为空");
                }
                if (!string.IsNullOrWhiteSpace(zxatt))
                    clmodel.zxatt = zxatt.Trim();
                else
                {
                    return Error("坐席地区号不能为空");
                }
                if (!string.IsNullOrWhiteSpace(whwdkey))
                    clmodel.whwdkey = whwdkey.Trim();
                else
                {
                    return Error("外呼外地前缀不能为空");
                }
                if (!string.IsNullOrWhiteSpace(whbdkey))
                    clmodel.whbdkey = whbdkey.Trim();
                else
                {
                    return Error("外呼本地前缀不能为空");
                }
                if (!string.IsNullOrWhiteSpace(outcallnum))
                {
                    if (!ValidateString.IsNumberStr(outcallnum.Trim().ToString()))
                    {
                        return Error("坐席组号码必须为数字");
                    }
                    clmodel.outcallnum = outcallnum.Trim();
                }
                if (!ValidateString.IsNumberStr(whwdkey.Trim().ToString()))
                {
                    return Error("外呼外地前缀必须为数字");
                }
                if (!ValidateString.IsNumberStr(whbdkey.Trim().ToString()))
                {
                    return Error("外呼本地前缀必须为数字");
                }
               
                clmodel.ivrkey = ivrkey;
                clmodel.des = des;
                clmodel.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                clmodel.createtime = DateTime.Now.ToLocalTime();
                clmodel.isdelete = false;

                res = await _sys_seatgroupRepository.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> Edit(string id, string zxzcode, string zxzname, string zxatt,
            string whwdkey, string whbdkey, int ivrkey,string outcallnum, string des)
        {
            try
            {
                if (id != null && id.Trim() != "")
                {


                    if (await GetExistByCodeAsync(zxzcode, id) || await GetExistByNameAsync(zxzname, id))
                    {
                        return Error("坐席组编号和名称必须唯一，请重新输入！");
                    }
                    if (string.IsNullOrWhiteSpace(whwdkey))
                        return Error("外呼外地前缀不能为空");
                    if (string.IsNullOrWhiteSpace(whbdkey))
                        return Error("外呼本地前缀不能为空");

                    if (!ValidateString.IsNumberStr(whwdkey.Trim().ToString()))
                    {
                        return Error("外呼外地前缀必须为数字");
                    }
                    if (!ValidateString.IsNumberStr(whbdkey.Trim().ToString()))
                    {
                        return Error("外呼本地前缀必须为数字");
                    }

                    var res = false;
                    if (id != null && id.Trim() != "")
                    {
                        var clmodel = await _sys_seatgroupRepository.GetSingle(id);
                        if (clmodel != null)
                        {
                            if (!string.IsNullOrWhiteSpace(zxzcode))
                                clmodel.zxzcode = zxzcode.Trim();
                            if (!string.IsNullOrWhiteSpace(zxzname))
                                clmodel.zxzname = zxzname.Trim();
                            if (!string.IsNullOrWhiteSpace(zxatt))
                                clmodel.zxatt = zxatt.Trim();
                            if (!string.IsNullOrWhiteSpace(whwdkey))
                                clmodel.whwdkey = whwdkey.Trim();
                            if (!string.IsNullOrWhiteSpace(whbdkey))
                                clmodel.whbdkey = whbdkey.Trim();
                            if (!string.IsNullOrWhiteSpace(outcallnum))
                                clmodel.outcallnum = outcallnum.Trim();

                            clmodel.ivrkey = ivrkey;
                            if (!string.IsNullOrWhiteSpace(des))
                                clmodel.des = des;

                            res = await _sys_seatgroupRepository.Update(clmodel);
                        }
                    }
                    if (res)
                        return Success("坐席组保存成功");
                    else
                    {
                        return Error("坐席组保存失败");
                    }
                }
                else
                    return Error("请选择要编辑的坐席组");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "坐席组保存异常");
                return Error("坐席组保存失败");
            }
        }

        [Authorize]
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _sys_seatgroupRepository.GetSingle(item);
                        ml.isdelete = true;
                        if (await _sys_seatgroupRepository.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("请选择要删除的记录");
        }

        #region 私有方法
        /// <summary>
        /// 根据坐席组编号查询是否存在此坐席组编号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task<bool> GetExistByCodeAsync(string code, string id)
        {
            var flist = new List<FilterDefinition<Sys_SeatGroup>>();
            flist.Add(Builders<Sys_SeatGroup>.Filter.Eq("zxzcode", code));
            if (id != null && id != "")
                flist.Add(Builders<Sys_SeatGroup>.Filter.Ne("id", id));//sql += " and F_ParamId <>" + id;

            var filter = Builders<Sys_SeatGroup>.Filter.And(flist);
            long c = await _sys_seatgroupRepository.CountAsync(filter);
            return c > 0;
        }
        /// <summary>
        /// 根据坐席组名称查询是否存在此坐席组编号
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        private async Task<bool> GetExistByNameAsync(string name, string id)
        {
            var flist = new List<FilterDefinition<Sys_SeatGroup>>();
            flist.Add(Builders<Sys_SeatGroup>.Filter.Eq("zxzname", name));
            if (id != null && id != "")
                flist.Add(Builders<Sys_SeatGroup>.Filter.Ne("id", id));//sql += " and F_ParamId <>" + id;

            var filter = Builders<Sys_SeatGroup>.Filter.And(flist);
            long c = await _sys_seatgroupRepository.CountAsync(filter);
            return c > 0;
        }
        #endregion
    }
}