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 MadRunFabric.Model;
using ConfigurationApi.Models.Input;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;
using ConfigurationApi.Models.Dto;

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 菜单按钮管理
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class ModuleButtonInfoController : BaseController
    {
        private readonly ILogger<DictionaryController> _logger;
        private readonly ISys_Module_InfoRepository _sys_moduleInfoRepository;
        private readonly ISys_ModuleButton_InfoRepository _sys_modulebuttonInfoRepository;
        public ModuleButtonInfoController(
            ILogger<DictionaryController> logger,
            ISys_Module_InfoRepository sys_moduleInfoRepository, ISys_ModuleButton_InfoRepository sys_modulebuttonInfoRepository
            )
        {
            _logger = logger;
            _sys_moduleInfoRepository = sys_moduleInfoRepository;
            _sys_modulebuttonInfoRepository = sys_modulebuttonInfoRepository;
        }

        /// <summary>
        /// 通过菜单的moduleId获取对应菜单下的所有按钮信息
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListAsync(string moduleId= "000000000000000000000000")
        {
            //TODO:计划使用缓存
            var list_ModuleInfoButton = (await _sys_modulebuttonInfoRepository.GetAll()).ToList();//DataSet  不在此处添加搜素条件，是因为计划改为缓存

            list_ModuleInfoButton = list_ModuleInfoButton.FindAll(t => t.moudle_id == moduleId && t.state_flag==1);

            List<ModuleInfoButtonDto> list_ModuleInfoButtonDto = new List<ModuleInfoButtonDto>();

            foreach (var entity in list_ModuleInfoButton)
            {
                ModuleInfoButtonDto _dto = new ModuleInfoButtonDto
                {
                    id = entity.id,
                    moduleid = entity.moudle_id,
                    name = entity.full_name,
                    jsevent = entity.jsevent,
                    icon = entity.icon,
                    url = entity.url_address,
                    flag = entity.state_flag,
                    remark = entity.remark,
                    sort = entity.sort
                };
                list_ModuleInfoButtonDto.Add(_dto);
            }

            list_ModuleInfoButton.Sort((x, y) => x.sort - y.sort);//排序
            return Success("获取按钮", list_ModuleInfoButton);
        }

        /// <summary>
        /// 通过菜单的moduleId获取对应菜单下的所有按钮信息  V6.0全盘优化
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        [HttpGet("gettreegridjson")]
        public async Task<ActionResult> GetTreeGridJsonAsync(string moduleId = "000000000000000000000000")
        {
            //TODO:计划使用缓存
            var list_ModuleInfoButton = (await _sys_modulebuttonInfoRepository.GetAll()).ToList();//DataSet  不在此处添加搜素条件，是因为计划改为缓存

            list_ModuleInfoButton = list_ModuleInfoButton.FindAll(t => t.moudle_id == moduleId && t.state_flag <2);

            list_ModuleInfoButton.Sort((x, y) => x.sort - y.sort);//排序

            var treeList = new List<TreeGridModel>();


            foreach (var item in list_ModuleInfoButton)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = list_ModuleInfoButton.Count(t => t.parent_id == item.id.ToString()) == 0 ? false : true;
                treeModel.id = item.id.ToString();
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.parent_id;
                treeModel.expanded = hasChildren;
                treeModel.entityJson = item.ToJson();
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeGridJson());
        }


        /// <summary>
        /// 获取菜单按钮实体
        /// </summary>
        /// <param name="mId"></param>
        /// <returns></returns>
        [HttpGet("getmodule")]
        public async Task<IActionResult> GetModuleAsync(string mid = "000000000000000000000000")
        {
            var entity = (await _sys_modulebuttonInfoRepository.GetSingle(mid));//DataSet  不在此处添加搜素条件，是因为计划改为缓存

            if (entity != null)
            {
                ModuleInfoButtonDto _dto = new ModuleInfoButtonDto
                {
                    id = entity.id,
                    moduleid = entity.moudle_id,
                    name = entity.full_name,
                    jsevent = entity.jsevent,
                    code = entity.encode,
                    icon = entity.icon,
                    url = entity.url_address,
                    flag = entity.state_flag,
                    remark = entity.remark,
                    sort = entity.sort
                };
                return Success("加载按钮成功", _dto);
            }
            else
            {
                return Error("加载按钮失败");
            }
        }


        /// <summary>
        /// 添加按钮
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addmodule")]
        public async Task<IActionResult> AddModule(ModuleInfoButtonDto input)
        {
            if (string.IsNullOrEmpty(input.moduleid))
                return Error("参数错误");
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入按钮名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入按钮代码");

            var entity_ModuleInfoButton = new Sys_ModuleButton_Info();
            entity_ModuleInfoButton.moudle_id = input.moduleid;
            entity_ModuleInfoButton.encode = input.code;
            entity_ModuleInfoButton.full_name = input.name;
            entity_ModuleInfoButton.jsevent = input.jsevent;
            entity_ModuleInfoButton.icon = input.icon;
            entity_ModuleInfoButton.url_address = System.Web.HttpUtility.UrlDecode(input.url);
            entity_ModuleInfoButton.parent_id = "000000000000000000000000";
            entity_ModuleInfoButton.state_flag = Convert.ToInt32(input.flag);
            entity_ModuleInfoButton.remark = input.remark;

            entity_ModuleInfoButton.sort = input.sort;
            entity_ModuleInfoButton.create_time = DateTime.Now.ToLocalTime();
            entity_ModuleInfoButton.create_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            if (await _sys_modulebuttonInfoRepository.Add(entity_ModuleInfoButton))
            {
                return Success("按钮添加成功");
            }
            else
            {
                return Error("菜单按钮添加失败,请重试！");
            }
        }


        /// <summary>
        /// 更新按钮
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatemodule")]
        public async Task<IActionResult> UpdateModule(ModuleInfoButtonDto input)
        {
            if (string.IsNullOrEmpty(input.moduleid))
                return Error("参数错误");
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入按钮名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入按钮代码");

            var entity_ModuleInfoButton = new Sys_ModuleButton_Info();
            entity_ModuleInfoButton.id = input.id;
            entity_ModuleInfoButton.moudle_id = input.moduleid;
            entity_ModuleInfoButton.encode = input.code;
            entity_ModuleInfoButton.full_name = input.name;
            entity_ModuleInfoButton.jsevent = input.jsevent;
            entity_ModuleInfoButton.icon = input.icon;
            entity_ModuleInfoButton.url_address = System.Web.HttpUtility.UrlDecode(input.url);
            entity_ModuleInfoButton.parent_id = "000000000000000000000000";
            entity_ModuleInfoButton.state_flag = Convert.ToInt32(input.flag);
            entity_ModuleInfoButton.remark = input.remark;

            entity_ModuleInfoButton.sort = input.sort;
            entity_ModuleInfoButton.create_time = DateTime.Now.ToLocalTime();
            entity_ModuleInfoButton.create_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
           
            if (await _sys_modulebuttonInfoRepository.Update(entity_ModuleInfoButton))
            {
                return Success("按钮修改成功");
            }
            else
            {
                return Error("按钮修改失败,请重试！");
            }
            

        }

        /// <summary>
        /// 删除菜单按钮
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delmodule")]
        public async Task<IActionResult> DelModuleAsync(string[] ids)
        {
            if (await _sys_modulebuttonInfoRepository.DelModuleButton(ids))
            {
                return Success("删除按钮成功");
            }
            else
            {
                return Error("按钮修改失败,请重试！");
            }
        }

        /// <summary>
        /// 编辑菜单按钮
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("editmodule")]
        public async Task<IActionResult> EditModuleAsync(ModuleInfoButtonDto input)
        {
            if (string.IsNullOrEmpty(input.moduleid))
                return Error("参数错误");
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入按钮名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入按钮代码");

            var entity_ModuleInfoButton = await _sys_modulebuttonInfoRepository.GetSingle(input.id);
            if (entity_ModuleInfoButton != null)
            {
                entity_ModuleInfoButton.moudle_id = input.moduleid;
                entity_ModuleInfoButton.encode = input.code;
                entity_ModuleInfoButton.full_name = input.name;
                entity_ModuleInfoButton.jsevent = input.jsevent;
                entity_ModuleInfoButton.icon = input.icon;
                entity_ModuleInfoButton.url_address = System.Web.HttpUtility.UrlDecode(input.url);

                entity_ModuleInfoButton.state_flag = Convert.ToInt32(input.flag);
                entity_ModuleInfoButton.remark = input.remark;

                entity_ModuleInfoButton.sort = input.sort;

                entity_ModuleInfoButton.lastmodify_time = DateTime.Now;
                entity_ModuleInfoButton.lastmodify_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

                if (await _sys_modulebuttonInfoRepository.Update(entity_ModuleInfoButton))
                {
                    return Success("按钮修改成功");
                }
                else
                {
                    return Error("按钮修改失败,请重试！");
                }
            }
            else
            {
                return Error("菜单对象获取失败");
            }
        }

    }
}