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 SysConfigController : BaseController
    {
        private readonly ILogger<SysConfigController> _logger;
        private readonly ISys_SystemConfigRepository _sys_systemconfigRepository;

        public SysConfigController(ILogger<SysConfigController> logger, ISys_SystemConfigRepository sys_systemconfigRepository)
        {
            _logger = logger;
            _sys_systemconfigRepository = sys_systemconfigRepository;
        }

        /// <summary>
        /// 获取基础数据列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string value,string code, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                //排序字段
                var sort = Builders<Sys_SystemConfig>.Sort.Descending("createtime");
                
                //根据条件查询集合
                var flist = new List<FilterDefinition<Sys_SystemConfig>>();
                flist.Add(Builders<Sys_SystemConfig>.Filter.Eq("isdelete", false));

                if (!string.IsNullOrWhiteSpace(value))
                    flist.Add(Builders<Sys_SystemConfig>.Filter.Where(s => s.paramvalue.Contains(value)));
                if (!string.IsNullOrWhiteSpace(code))
                    flist.Add(Builders<Sys_SystemConfig>.Filter.Where(s => s.paramcode.Contains(code)));
                
                    var filter = Builders<Sys_SystemConfig>.Filter.And(flist);
                    var list = await _sys_systemconfigRepository.GetByPage(filter, pageindex, pagesize, sort);
                var count = await _sys_systemconfigRepository.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> GetSingle(string id)
        {
            if (id != null && id.Trim() != "")
            {
                try
                {
                    var dModel = await _sys_systemconfigRepository.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 code, string value, string des)
        {
            try
            {
                Sys_SystemConfig clmodel = new Sys_SystemConfig();
                if (await IsExistCodeAsync(code, ""))
                    return Error("参数名称不能重复，请修改后重新提交");
                var res = false;
                if (!string.IsNullOrWhiteSpace(code))
                    clmodel.paramcode = code;
                if (!string.IsNullOrWhiteSpace(value))
                    clmodel.paramvalue = value;
                if (!string.IsNullOrWhiteSpace(des))
                    clmodel.paramdes = des;
                clmodel.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //"8000";
                clmodel.createtime = DateTime.Now.ToLocalTime();
                clmodel.isdelete = false;

                res = await _sys_systemconfigRepository.Add(clmodel);
                if (res)
                    return Success("基础数据保存成功");
                else
                {
                    return Error("基础数据保存失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "基础数据保存异常");
                return Error("基础数据保存失败");
            }
        }
        //判断是否存在重复的Co编号
        private async Task<bool> IsExistCodeAsync(string code, string id)
        {
            var flist = new List<FilterDefinition<Sys_SystemConfig>>();
            flist.Add(Builders<Sys_SystemConfig>.Filter.Eq("paramcode", code));
            if (id != null && id != "")
                flist.Add(Builders<Sys_SystemConfig>.Filter.Ne("id", id));//sql += " and F_ParamId <>" + id;
            flist.Add(Builders<Sys_SystemConfig>.Filter.Where(con => con.isdelete == false));
            var filter = Builders<Sys_SystemConfig>.Filter.And(flist);
            long c = await _sys_systemconfigRepository.CountAsync(filter);
            return c > 0;
        }
        /// <summary>
        /// 修改基础数据
        /// </summary>
        [Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> Edit(string id, string code, string value, string des)
        {
            try
            {
                Sys_SystemConfig clmodel = new Sys_SystemConfig();
                if (await IsExistCodeAsync(code, id))
                    return Error("参数名称不能重复，请修改后重新提交");
                var res = false;
                if (id != null && id.Trim() != "")
                {
                    clmodel = await _sys_systemconfigRepository.GetSingle(id);
                    if (clmodel != null)
                    {
                        if (!string.IsNullOrWhiteSpace(code))
                            clmodel.paramcode = code;
                        if (!string.IsNullOrWhiteSpace(value))
                            clmodel.paramvalue = value;
                        if (!string.IsNullOrWhiteSpace(des))
                            clmodel.paramdes = des;

                        res = await _sys_systemconfigRepository.Update(clmodel);
                    }
                }
                if (res)
                    return Success("基础数据保存成功");
                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_systemconfigRepository.GetSingle(item);
                        ml.isdelete = true;
                        if (await _sys_systemconfigRepository.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("请选择要删除的记录");
        }
    }
}