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;

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

        /// <summary>
        /// 返回树形下拉框 菜单数据 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetALL()
        {
            var list_ModuleInfo =(await _sys_moduleInfoRepository.GetAll()).Where(x=> x.state_flag == 1).OrderBy(x => x.sort);
            var treeList = new List<TreeModel>();
            foreach (var item in list_ModuleInfo)
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.id;
                treeModel.iconcls = item.img_url;
                treeModel.text = item.module_name;
                treeModel.parentid = item.parent_id;
                treeList.Add(treeModel);
            }
            return Success("获取菜单树成功", treeList.TreeRecursion("000000000000000000000000"));
        }


        ///// <summary>
        ///// 依据关键字获取相关菜单数据 
        ///// </summary>
        ///// <param name="keyword"></param>
        ///// <returns></returns>
        //[HttpGet]
        //public async Task<IActionResult> GetAllGrid(string keyword)
        //{
        //    //TODO:计划使用缓存
        //    var list_ModuleInfo = await _sys_moduleInfoRepository.GetAll();//不在此处添加搜素条件，是因为计划改为缓存
        //    if (!string.IsNullOrEmpty(keyword))
        //    {
        //        list_ModuleInfo = list_ModuleInfo.ToList().TreeWhere(t => t.module_name.Contains(keyword), "id", "parent_id").ToList();
        //    }

        //    list_ModuleInfo.OrderByDescending(x => x.sort);
        //    return Success("获取菜单", list_ModuleInfo);
        //}

        /// <summary>
        /// 依据关键字获取相关菜单数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult> GetTreeGridJson(string keyword)
        {
            var list_ModuleInfo = (await _sys_moduleInfoRepository.GetAll()).Where(x=>x.state_flag<2);//DataSet  不在此处添加搜素条件，是因为计划改为缓存
            if (!string.IsNullOrEmpty(keyword))
            {
                list_ModuleInfo = list_ModuleInfo.ToList().TreeWhere(t => t.module_name.Contains(keyword), "id", "parent_id").ToList();
            }
            list_ModuleInfo =list_ModuleInfo.Where(x=>x.state_flag!=2).OrderBy(x => x.sort).ThenByDescending(x=>x.lastmodify_time);//排序

            var treeList = new List<TreeGridModel>();
            foreach (var item in list_ModuleInfo)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = list_ModuleInfo.Count(t => t.parent_id == item.id) == 0 ? false : true;
                treeModel.id = item.id;
                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]
        public async Task<IActionResult> GetModule(string mid)
        {
            var entity_ModuleInfo = await _sys_moduleInfoRepository.GetSingle(mid);
            if (entity_ModuleInfo != null)
            {
                return Success("加载菜单成功", new
                {
                    name = entity_ModuleInfo.module_name,
                    imgUrl = entity_ModuleInfo.img_url,
                    code = entity_ModuleInfo.module_code,
                    target = entity_ModuleInfo.target,
                    url = entity_ModuleInfo.opt_url,
                    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(ModuleInfoInput input)
        {
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入菜单名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入菜单代码");

            var entity_ModuleInfo = new Sys_Module_Info();
            entity_ModuleInfo.parent_id = string.IsNullOrEmpty(input.parentid) ? "000000000000000000000000" : input.parentid;
            entity_ModuleInfo.module_name = input.name;
            entity_ModuleInfo.img_url = System.Web.HttpUtility.UrlDecode(input.imgurl);
            entity_ModuleInfo.module_code = input.code;
            entity_ModuleInfo.target = input.target;
            entity_ModuleInfo.remark = input.remark;
            entity_ModuleInfo.sort = input.sort;
            entity_ModuleInfo.state_flag = input.flag;
            entity_ModuleInfo.opt_url = input.url;
            entity_ModuleInfo.create_time = DateTime.Now.ToLocalTime();
            entity_ModuleInfo.create_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

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

        }

        /// <summary>
        /// 获取所有子节点的Id
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        private async Task<List<string>> GetTreeModuleId(List<string> ids)
        {
            List<string> _moduleIdlist = null;
            List<string> _list = new List<string>(ids);
            var list_ModuleInfo = await _sys_moduleInfoRepository.GetAll();//DataSet  不在此处添加搜素条件，是因为计划改为缓存
            for (int i = 0; i < ids.Count; i++)
            {
                _moduleIdlist = list_ModuleInfo.Where(x => x.parent_id == ids[i]).Select(x => x.id).ToList();
                if (_moduleIdlist.Count > 0)
                {
                    _list.AddRange(_moduleIdlist);
                    _list.AddRange(await GetTreeModuleId(_moduleIdlist));
                    _list = _list.Distinct().ToList();
                }
            }
            return _list;
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> DelModule(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                //获取选中的菜单下所有级联菜单id
                List<string> _ids = await GetTreeModuleId(new List<string>(ids));
                if (await _sys_moduleInfoRepository.DelModule(_ids.ToArray()))
                {
                    return Success("删除菜单按钮成功");
                }
                else
                {
                    return Error("按钮修改失败,请重试！");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

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

            var entity_ModuleInfo =await _sys_moduleInfoRepository.GetSingle(input.id);
            if (entity_ModuleInfo != null)
            {
                entity_ModuleInfo.parent_id = string.IsNullOrEmpty(input.parentid) ? "000000000000000000000000" : input.parentid;
                entity_ModuleInfo.module_name = input.name;
                entity_ModuleInfo.img_url = System.Web.HttpUtility.UrlDecode(input.imgurl);
                entity_ModuleInfo.module_code = input.code;
                entity_ModuleInfo.remark = input.remark;
                entity_ModuleInfo.target = input.target;
                entity_ModuleInfo.sort = input.sort;
                entity_ModuleInfo.state_flag = Convert.ToInt32(input.flag);
                entity_ModuleInfo.opt_url = input.url;
                entity_ModuleInfo.lastmodify_time = DateTime.Now;
                entity_ModuleInfo.lastmodify_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

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

    }
}