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.Dtos;
using System.Linq.Expressions;

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class ModuleButtonInfoController : BaseController
    {
        private readonly ISys_ModuleButtonInfoRepository _sys_modulebuttoninfoRepository;
        public ModuleButtonInfoController(ISys_ModuleButtonInfoRepository sys_modulebuttoninfoRepository)
        {
            _sys_modulebuttoninfoRepository = sys_modulebuttoninfoRepository;
        }

        [HttpGet("getlist")]
        public async Task<IActionResult> GetListAsync(int menuid = 0)
        {
            var list_ModuleInfoButton= new List<T_Sys_ModuleButtonInfo>();
            Expression<Func<T_Sys_ModuleButtonInfo, bool>> eq = a => a.F_State != (int)EnumDelState.Delete;
            if (menuid>0)
                eq = eq.And(b => b.F_MenuId == menuid);

            list_ModuleInfoButton = await _sys_modulebuttoninfoRepository.GetListALL(eq, o => o.F_Sort, SqlSugar.OrderByType.Asc);

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

            foreach (var entity in list_ModuleInfoButton)
            {
                ModuleInfoButtonDto _dto = new ModuleInfoButtonDto
                {
                    id = entity.F_Id,
                    moduleid = entity.F_MenuId.Value,
                    name = entity.F_ButtonName,
                    jsevent = entity.F_JSEvent,
                    icon = entity.F_Icon,
                    url = entity.F_UrlAddress,
                    flag = entity.F_State.Value,
                    remark = entity.F_Remark,
                    sort = entity.F_Sort.Value
                };
                list_ModuleInfoButtonDto.Add(_dto);
            }

            return Success("获取按钮", list_ModuleInfoButtonDto);
        }

        /// <summary>
        /// 通过菜单的moduleId获取对应菜单下的所有按钮信息  V6.0全盘优化
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        [HttpGet("gettreegridjson")]
        public async Task<ActionResult> GetTreeGridJsonAsync(int moduleId = 0)
        {
            var list_ModuleInfoButton = new List<T_Sys_ModuleButtonInfo>();

            Expression<Func<T_Sys_ModuleButtonInfo, bool>> eq = a => a.F_State != (int)EnumDelState.Delete;
            if (moduleId > 0)
                eq = eq.And(b => b.F_MenuId == moduleId);

            list_ModuleInfoButton = await _sys_modulebuttoninfoRepository.GetListALL(eq, o => o.F_Sort, SqlSugar.OrderByType.Asc);

            var treeList = new List<TreeGridModel>();

            foreach (var item in list_ModuleInfoButton)
            {
                TreeGridModel treeModel = new TreeGridModel();
                treeModel.id = item.F_Id.ToString();
                treeModel.isLeaf = false;
                treeModel.parentId = "0";
                treeModel.expanded = false;
                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(int mid = 0)
        {
            var entity = (await _sys_modulebuttoninfoRepository.GetSingle(x => x.F_Id == mid && x.F_State != (int)EnumDelState.Delete));

            if (entity != null)
            {
                ModuleInfoButtonDto _dto = new ModuleInfoButtonDto
                {
                    id = entity.F_Id,
                    moduleid = entity.F_MenuId.Value,
                    name = entity.F_ButtonName,
                    jsevent = entity.F_JSEvent,
                    code = entity.F_ButtonCode,
                    icon = entity.F_Icon,
                    url = entity.F_UrlAddress,
                    flag = entity.F_State.Value,
                    remark = entity.F_Remark,
                    sort = entity.F_Sort.Value
                };
                return Success("加载按钮成功", _dto);
            }
            else
            {
                return Error("加载按钮失败");
            }
        }


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

            var entity_ModuleInfoButton = new T_Sys_ModuleButtonInfo();
            entity_ModuleInfoButton.F_MenuId = input.moduleid;
            entity_ModuleInfoButton.F_ButtonCode = input.code;
            entity_ModuleInfoButton.F_ButtonName = input.name;
            entity_ModuleInfoButton.F_JSEvent = input.jsevent;
            entity_ModuleInfoButton.F_Icon = input.icon;
            entity_ModuleInfoButton.F_UrlAddress = HttpUtility.UrlDecode(input.url);
            entity_ModuleInfoButton.F_State = Convert.ToInt32(input.flag);
            entity_ModuleInfoButton.F_Remark = input.remark;

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

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


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

            var entity_ModuleInfoButton = await _sys_modulebuttoninfoRepository.GetSingle(x => x.F_Id == input.id && x.F_State != (int)EnumDelState.Delete);
            if (entity_ModuleInfoButton == null)
                return Error("获取信息失败");
            entity_ModuleInfoButton.F_Id = input.id;

            entity_ModuleInfoButton.F_MenuId = input.moduleid;
            entity_ModuleInfoButton.F_ButtonCode = input.code;
            entity_ModuleInfoButton.F_ButtonName = input.name;
            entity_ModuleInfoButton.F_JSEvent = input.jsevent;
            entity_ModuleInfoButton.F_Icon = input.icon;
            entity_ModuleInfoButton.F_UrlAddress = HttpUtility.UrlDecode(input.url);
            entity_ModuleInfoButton.F_State = Convert.ToInt32(input.flag);
            entity_ModuleInfoButton.F_Remark = input.remark;

            entity_ModuleInfoButton.F_Sort = input.sort;
            entity_ModuleInfoButton.F_LastModifyOn = DateTime.Now.ToLocalTime();
            entity_ModuleInfoButton.F_LastModifyBy = 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(int[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_modulebuttoninfoRepository.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_modulebuttoninfoRepository.Update(ml).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    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> EditModuleAsync(ModuleInfoButtonDto input)
        {
            if (input.id <= 0)
                return Error("参数错误");
            if (input.moduleid <= 0)
                return Error("菜单参数错误");
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入按钮名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入按钮代码");

            var entity_ModuleInfoButton = await _sys_modulebuttoninfoRepository.GetSingle(x=>x.F_Id==input.id && x.F_State != (int)EnumDelState.Delete);
            if (entity_ModuleInfoButton != null)
            {
                entity_ModuleInfoButton.F_MenuId = input.moduleid;
                entity_ModuleInfoButton.F_ButtonCode = input.code;
                entity_ModuleInfoButton.F_ButtonName = input.name;
                entity_ModuleInfoButton.F_JSEvent = input.jsevent;
                entity_ModuleInfoButton.F_Icon = input.icon;
                entity_ModuleInfoButton.F_UrlAddress = HttpUtility.UrlDecode(input.url);
                entity_ModuleInfoButton.F_State = Convert.ToInt32(input.flag);
                entity_ModuleInfoButton.F_Remark = input.remark;
                entity_ModuleInfoButton.F_Sort = input.sort;

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

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