using System;
using System.Collections.Generic;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class ModuleInfoController : BaseController
    {
        private readonly ISys_ModuleInfoRepository _sys_moduleinfoRepository;
        public ModuleInfoController(ISys_ModuleInfoRepository sys_moduleinfoRepository)
        {
            _sys_moduleinfoRepository = sys_moduleinfoRepository;
        }

        /// <summary>
        /// 返回树形下拉框 菜单数据 
        /// </summary>
        /// <returns></returns>
        [HttpGet("getall")]
        public async Task<IActionResult> GetALL()
        {
            var list_ModuleInfo = await _sys_moduleinfoRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled, o => o.F_Sort, SqlSugar.OrderByType.Asc);
            var treeList = new List<TreeModel>();
            foreach (var item in list_ModuleInfo)
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_Id;
                treeModel.iconcls = item.F_ImgUrl;
                treeModel.text = item.F_MenuName;
                treeModel.parentid = item.F_ParentId.Value;
                treeList.Add(treeModel);
            }
            return Success("获取菜单树成功", treeList.TreeRecursion(0));
        }

        /// <summary>
        /// 依据关键字获取相关菜单数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet("gettreegridjson")]
        public async Task<ActionResult> GetTreeGridJson(string keyword)
        {
            var list_ModuleInfo = await _sys_moduleinfoRepository.GetListALL(x => x.F_State < (int)EnumDelState.Delete);
            if (!string.IsNullOrEmpty(keyword))
            {
                list_ModuleInfo = list_ModuleInfo.ToList().TreeWhere(t => t.F_MenuName.Contains(keyword), "F_Id", "F_ParentId").ToList();
            }
            list_ModuleInfo = list_ModuleInfo.Where(x => x.F_State != (int)EnumDelState.Delete).OrderBy(x => x.F_Sort).ThenByDescending(x => x.F_LastModifyOn).ToList();//排序

            var treeList = new List<TreeGridModel>();
            foreach (var item in list_ModuleInfo)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = list_ModuleInfo.Count(t => t.F_ParentId == item.F_Id) == 0 ? false : true;
                treeModel.id = item.F_Id.ToString();
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.F_ParentId.ToString();
                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> GetModule(int mid)
        {
            var entity_ModuleInfo = await _sys_moduleinfoRepository.GetSingle(x=>x.F_Id==mid && x.F_State < (int)EnumDelState.Delete);
            if (entity_ModuleInfo != null)
            {
                return Success("加载菜单成功", new
                {
                    name = entity_ModuleInfo.F_MenuName,
                    imgUrl = entity_ModuleInfo.F_ImgUrl,
                    code = entity_ModuleInfo.F_MenuCode,
                    target = entity_ModuleInfo.F_Target,
                    url = entity_ModuleInfo.F_OptUrl,
                    enable = entity_ModuleInfo.F_State,
                    remark = entity_ModuleInfo.F_Remark,
                    sort = entity_ModuleInfo.F_Sort
                });
            }
            else
            {
                return Error("加载菜单失败");
            }
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addmodule")]
        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 T_Sys_ModuleInfo();
            entity_ModuleInfo.F_ParentId = input.parentid;
            entity_ModuleInfo.F_MenuName = input.name;
            entity_ModuleInfo.F_ImgUrl = HttpUtility.UrlDecode(input.imgurl);
            entity_ModuleInfo.F_MenuCode = input.code;
            entity_ModuleInfo.F_Target = input.target;
            entity_ModuleInfo.F_Remark = input.remark;
            entity_ModuleInfo.F_Sort = input.sort;
            entity_ModuleInfo.F_State = input.flag;
            entity_ModuleInfo.F_OptUrl = input.url;
            entity_ModuleInfo.F_CreateOn = DateTime.Now.ToLocalTime();
            entity_ModuleInfo.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

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

        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delmodule")]
        public async Task<IActionResult> DelModule(int[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                var res = 0;
                //获取选中的菜单下所有级联菜单id
                List<int> _ids = await GetTreeModuleId(new List<int>(ids));
                foreach (var item in _ids)
                {
                    var ml = await _sys_moduleinfoRepository.GetSingle(x => x.F_Id == item);
                    ml.F_State = (int)EnumDelState.Delete;
                    ml.F_DeleteOn = DateTime.Now.ToLocalTime();
                    ml.F_DeleteBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (_sys_moduleinfoRepository.Update(ml).Result)
                        res += 1;
                }
                if (res == _ids.Count )
                    return Success("删除菜单成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 编辑菜单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("editmodule")]
        public async Task<IActionResult> EditModule(ModuleInfoInput input)
        {
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入菜单名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入菜单代码");
            if (input.id == input.parentid)
            {
                return Error("父级ID不能是自己");
            }
            var entity_ModuleInfo = await _sys_moduleinfoRepository.GetSingle(x=>x.F_Id==input.id && x.F_State < (int)EnumDelState.Delete);
            if (entity_ModuleInfo != null)
            {
                entity_ModuleInfo.F_ParentId = input.parentid;
                entity_ModuleInfo.F_MenuName = input.name;
                entity_ModuleInfo.F_ImgUrl = HttpUtility.UrlDecode(input.imgurl);
                entity_ModuleInfo.F_MenuCode = input.code;
                entity_ModuleInfo.F_Target = input.target;
                entity_ModuleInfo.F_Remark = input.remark;
                entity_ModuleInfo.F_Sort = input.sort;
                entity_ModuleInfo.F_State = input.flag;
                entity_ModuleInfo.F_OptUrl = input.url;

                entity_ModuleInfo.F_LastModifyOn = DateTime.Now;
                entity_ModuleInfo.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

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

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