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

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// APP模块配置控制器
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]/[action]")]
    public class AppMenuInfoController : BaseController
    {
        private readonly ILogger<AppMenuInfoController> _logger;
        private readonly ISys_AppModule_InfoRepository _sys_appmoduleInfoRepository;

        public AppMenuInfoController(
            ILogger<AppMenuInfoController> logger, ISys_AppModule_InfoRepository sys_appmoduleInfoRepository
            )
        {
            _logger = logger;
            _sys_appmoduleInfoRepository = sys_appmoduleInfoRepository;
           
        }

        /// <summary>
        /// 获取分页
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetListByPage(string keyword, int ismenu = -1,int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_AppModule_Info>.Sort.Ascending("sort").Descending("create_time");
            var list = await _sys_appmoduleInfoRepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _sys_appmoduleInfoRepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listApp = new List<FilterDefinition<Sys_AppModule_Info>>();
            listApp.Add(Builders<Sys_AppModule_Info>.Filter.Ne("state_flag", 2));

            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Sys_AppModule_Info>.Filter.Where(s => s.module_code.Contains(keyword) || s.module_name.Contains(keyword)));
            if (ismenu >= 0) {
                listApp.Add(Builders<Sys_AppModule_Info>.Filter.Where(s => s.ismenu == ismenu));
            }
            #endregion
            int recordCount = 0;
            if (listApp.Count > 0)
            {
                var filter = Builders<Sys_AppModule_Info>.Filter.And(listApp);
                list = await _sys_appmoduleInfoRepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _sys_appmoduleInfoRepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = list,
                total = recordCount,
            };
            return Content(obj.ToJson());
        }


        /// <summary>
        /// 获取菜单实体
        /// </summary>
        /// <param name="mid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetModule(string mid)
        {
            var entity_ModuleInfo = await _sys_appmoduleInfoRepository.GetSingle(mid);
            if (entity_ModuleInfo != null)
            {
                return Success("加载菜单成功", new
                {
                    name = entity_ModuleInfo.module_name,
                    imgUrl = entity_ModuleInfo.img_url,
                    type= entity_ModuleInfo.ismenu,
                    code = entity_ModuleInfo.module_code,
                    enable = entity_ModuleInfo.state_flag,
                    remark = entity_ModuleInfo.remark,
                    sort = entity_ModuleInfo.sort
                });
            }
            else
            {
                return Error("加载菜单失败");
            }
        }

        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> AddModule(AppModuleInfoInput input)
        {
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入APP功能模块名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入APP功能菜单代码");

            //if (await _sys_appmoduleInfoRepository.Count(p => p.module_code == input.code && p.state_flag != 2) > 0)
            //{
            //    return Error("当前编码已经存在，请更换编码！");
            //}

            var entity_ModuleInfo = new Sys_AppModule_Info();

            entity_ModuleInfo.module_name = input.name;
            entity_ModuleInfo.img_url = input.imgurl == null ? new List<FileBaseModel>() : input.imgurl;
            entity_ModuleInfo.module_code = input.code;
            entity_ModuleInfo.remark = input.remark;
            entity_ModuleInfo.ismenu = input.type;
            entity_ModuleInfo.sort = input.sort;
            entity_ModuleInfo.state_flag = input.flag;
            entity_ModuleInfo.create_time = DateTime.Now.ToLocalTime();
            entity_ModuleInfo.create_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            if (await _sys_appmoduleInfoRepository.Add(entity_ModuleInfo))
            {
                return Success("APP功能模块添加成功");
            }
            else
            {
                return Error("App功能模块添加失败,请重试！");
            }

        }

        /// <summary>
        /// 删除App模块
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelModule(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                if (await _sys_appmoduleInfoRepository.DelModule(ids.ToArray()))
                {
                    return Success("删除APP模块成功");
                }
                else
                {
                    return Error("模块删除失败,请重试！");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 编辑菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> EditModule(AppModuleInfoInput input)
        {
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入模块名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入模块代码");


            //if(await _sys_appmoduleInfoRepository.Count(p => p.id != input.id && p.module_code == input.code && p.state_flag != 2)>0)
            //{
            //    return Error("当前编码已经存在，请更换编码！");
            //}

            var entity_ModuleInfo = await _sys_appmoduleInfoRepository.GetSingle(input.id);
            if (entity_ModuleInfo != null)
            {
                entity_ModuleInfo.module_name = input.name;
                entity_ModuleInfo.img_url = input.imgurl==null?new List<FileBaseModel>():input.imgurl;
                entity_ModuleInfo.module_code = input.code;
                entity_ModuleInfo.remark = input.remark;
                entity_ModuleInfo.ismenu = input.type;
                entity_ModuleInfo.sort = input.sort;
                entity_ModuleInfo.state_flag = Convert.ToInt32(input.flag);
                entity_ModuleInfo.lastmodify_time = DateTime.Now;
                entity_ModuleInfo.lastmodify_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

                if (await _sys_appmoduleInfoRepository.Update(entity_ModuleInfo))
                {
                    return Success("模块修改成功!");
                }
                else
                {
                    return Error("模块修改失败,请重试！");
                }
            }
            else
            {
                return Error("模块对象获取失败");
            }
        }







    }
}