using AutoMapper;
using System;
using System.Collections.Generic;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using Model.ModelDto.SysDto;
using WMS.Entity.SysEntity;
using WMS.IBLL.ISysServer;
using WMS.IDAL.ISysInterface;
using Model.ModelVm.SysVm;
using System.Linq;
using SqlSugar;
using WMS.DAL;
using WMS.Entity.Context;

namespace WMS.BLL.SysServer
{
    /// <summary>
    /// 菜单服务实践
    /// </summary>
    public class MenuServer : DbHelper<SysFunctionMenu>,IMenuServer
    {
        private static readonly SqlSugarScope Db = DataContext.Db;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public IMenuRepository _menu { get; set; }
        readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="menu">菜单仓储</param>
        /// <param name="mapper">automapper</param>
        public MenuServer(IMenuRepository menu, IMapper mapper) : base(Db)
        {
            _menu = menu;
            _mapper = mapper;
        }


        /// <summary>
        /// 获取菜单信息列表
        /// </summary>
        /// <param name="menuDto">菜单Dto</param>
        /// <returns></returns>
        public List<FunctionMenuVm> GetMenuList(string MenuName, string pMenuNo, string MenuNo, string level = "")
        {
            string str = "select menu1.Id,menu1.MenuNo,menu1.MenuName,menu2.MenuName ParentName,menu1.ParentNo,menu1.Ord,menu1.Url,menu1.level,menu1.IsEnable,menu1.Demo,menu1.IsDel,menu1.CreateTime,menu1.CreateUser,menu1.UpdateTime,menu1.UpdateUser,user1.RealName CreateUserName from SysFunctionMenu menu1 left join sysfunctionmenu menu2 on menu1.parentNo = menu2.MenuNo join SysUserInfor user1 on menu1.CreateUser = user1.id  where menu1.IsDel = '0' and menu1.IsEnable = '0' ";

            //判断页面菜单
            if (!string.IsNullOrEmpty(MenuNo))
            {
                //判断层级是否为空
                if (!string.IsNullOrEmpty(level))
                {
                    //判断层级
                    if (level == "1")
                    {
                        //页面
                        str += $" and menu1.MenuNo = '{MenuNo}'";
                    }
                    if (level == "2")
                    {
                        //按钮
                        str += $" and menu1.ParentNo = '{MenuNo}'";
                    }
                    if (level == "0")
                    {
                        //模块
                        str += $" and menu1.ParentNo = '{MenuNo}'";
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(MenuName))
                    {
                        str += $" and menu1.ParentNo = '{MenuNo}'";
                    }
                    else
                    {
                        str += $" and menu1.ParentNo = '{MenuNo}' or menu1.MenuNo = '{MenuNo}'";

                    }
                }
            }
            //判断模块菜单
            if (!string.IsNullOrEmpty(pMenuNo))
            {
                //判断层级是否为空
                if (!string.IsNullOrEmpty(level))
                {
                    //判断层级
                    if (level == "1")
                    {
                        //页面
                        str += $" and menu1.ParentNo = '{pMenuNo}'";
                    }
                    if (level == "2")
                    {
                        //按钮
                        str += $" and menu1.ParentNo in (select MenuNo from SysFunctionMenu where ParentNo = '{pMenuNo}')";
                    }
                    if (level == "0")
                    {
                        //模块
                        str += $" and menu1.MenuNo= '{pMenuNo}'";
                    }
                }
                else
                {
                    //判断菜单名称是否为空
                    if (!string.IsNullOrEmpty(MenuName) && string.IsNullOrEmpty(MenuNo))
                    {
                        str += $" and menu1.ParentNo in (select MenuNo from SysFunctionMenu where ParentNo = '{pMenuNo}')";
                    }
                    else if (!string.IsNullOrEmpty(MenuNo))
                    {
                        str += $"  or menu1.MenuNo = '{MenuNo}'";
                    }
                    else
                    {
                        str += $" and  ( menu1.ParentNo = '{pMenuNo}' or menu1.MenuNo = '{pMenuNo}' or menu1.ParentNo in (select MenuNo from SysFunctionmenu where ParentNo = {pMenuNo}) )";
                    }
                }
            }
            //判断菜单名称与编号是否为空
            if (!string.IsNullOrEmpty(MenuName))
            {
                str += $" and menu1.MenuName like '%{MenuName}%'";
                //判断父级菜单是否为空
                if (!string.IsNullOrEmpty(pMenuNo) && string.IsNullOrEmpty(MenuNo))
                {
                    str += $" or menu1.MenuNo in (select MenuNo from SysFunctionMenu where ( ParentNo = '{pMenuNo}' or MenuNo='{pMenuNo}' ) and MenuName like '%{MenuName}%')";
                }
            }
            //判断菜单层级
            if (!string.IsNullOrEmpty(level))
            {
                str += $" and menu1.Level = '{level}'";
            }
            str += " order by menu1.MenuNo,menu1.Ord";
            List<FunctionMenuVm> menulist = _menu.GetMenuList(str);
            return menulist;
        }

        /// <summary>
        /// 根据层级获取菜单列表
        /// </summary>
        /// <param name="level"></param>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<FunctionMenuVm> GetMenuListForRight(string level, string UserId)
        {
            var userEntry = Db.Ado.SqlQuery<SysUserInfor>($"select * from SysUserInfor where Id ={UserId}").FirstOrDefault();
            string sqlStr = "select * from SysFunctionMenu where IsDel='0' ";
            if (!string.IsNullOrEmpty(level))
            {
                sqlStr += $" and level='{level}' ";
            }
            //分配权限只能分配当前登录用户有的权限
            if (userEntry != null && userEntry.UserName.ToUpper() != "ADMIN")
            {
                sqlStr += $"and MenuNo in (select MenuNo from SysRoleRight where RoleNo='{userEntry.RoleNo}') ";
            }
            List<FunctionMenuVm> menulist = Db.Ado.SqlQuery<FunctionMenuVm>(sqlStr);
            return menulist;
        }

        /// <summary>
        /// 获取模块菜单
        /// </summary>
        /// <returns></returns>
        public List<SysFunctionMenu> GetParentMenuList()
        {
            List<SysFunctionMenu> menulist = _menu.GetParentMenuList();
            return menulist;
        }

        /// <summary>
        ///  根据id获取菜单信息列表
        /// </summary>
        /// <param name="menuid">菜单id</param>
        /// <returns></returns>
        public SysFunctionMenu GetMenuListById(int menuid)
        {
            SysFunctionMenu menu = _menu.GetMenuListById(menuid);
            return menu;
        }

        /// <summary>
        ///  根据编号获取菜单信息列表
        /// </summary>
        /// <param name="menuno">菜单编号</param>
        /// <returns></returns>
        public int GetMenuListByNo(string menuno)
        {
            string str = $"select * from SysFunctionMenu where MenuNo = '{menuno}'";
            List<SysFunctionMenu> menulist = _menu.GetMenuListByNo(str);
            return menulist.Count;
        }

        /// <summary>
        /// 新增菜单信息
        /// </summary>
        /// <param name="menudto">菜单DTO模型</param>
        /// <param name="userId">当前操作用户id</param>
        /// <returns></returns>
        /// <exception cref="Exception">捕获异常</exception>
        public async Task<int> InsertMenu(FunctionMenuDto menudto)
        {
            //捕获异常
            try
            {
                //模型映射
                SysFunctionMenu menu = _mapper.Map<SysFunctionMenu>(menudto);
                //是否可用
                menu.IsEnable = "0";
                int i = 0;
                int count = GetMenuListByNo(menu.MenuNo);
                //判断菜单号是否唯一
                if (count > 0)
                {
                    i = 3;
                }
                else if (count == 0)
                {
                    //验证层级 0:模块、1:页面、2:按钮
                    switch (menu.Level)
                    {
                        case "0":
                            if (!string.IsNullOrWhiteSpace(menu.ParentNo))
                            {
                                throw new Exception("模块类型为模块,父级菜单应为空");
                            }
                            break;
                        case "1":
                            if (string.IsNullOrWhiteSpace(menu.ParentNo))
                            {
                                throw new Exception("模块类型为页面,父级菜单不能为空");
                            }

                            var menuData = Db.Queryable<SysFunctionMenu>().First(m => m.MenuNo == menu.ParentNo);
                            if (menuData == null)
                            {
                                throw new Exception("未查询到父级菜单信息,请核实");
                            }

                            if (menuData.Level != "0")
                            {
                                throw new Exception("当前模块类型是页面,父级菜单类型应为模块");
                            }
                            break;
                        case "2":
                            if (string.IsNullOrWhiteSpace(menu.ParentNo))
                            {
                                throw new Exception("模块类型为页面,父级菜单不能为空");
                            }

                            var menuData2 = Db.Queryable<SysFunctionMenu>().First(m => m.MenuNo == menu.ParentNo);
                            if (menuData2 == null)
                            {
                                throw new Exception("未查询到父级菜单信息,请核实");
                            }

                            if (menuData2.Level != "1")
                            {
                                throw new Exception("当前模块类型是按钮,父级菜单类型应为页面");
                            }
                            break;
                        default:
                            throw new Exception("模块类型异常");
                    }
                    i = await _menu.InsertMenu(menu);
                }
                return i;
            }
            catch (Exception ex)
            {
                //抛出异常
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 删除菜单信息
        /// </summary>
        /// <param name="id">菜单id</param>
        /// <returns></returns>
        /// <exception cref="Exception">捕获异常</exception>
        public async Task<int> DeleteMenu(SysFunctionMenu menu)
        {
            //捕获异常
            try
            {
                int i = await _menu.DeleteMenu(menu);
                return i;
            }
            catch (Exception ex)
            {
                //抛出异常
                throw new Exception("删除菜单信息异常", ex);
            }

        }

        /// <summary>
        /// 编辑菜单信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception">捕获异常</exception>
        public async Task<int> UpdateMenu(FunctionMenuVm menuvm)
        {
            //捕获异常
            try
            {
                SysFunctionMenu menu = _mapper.Map<SysFunctionMenu>(menuvm);
                //验证层级 0:模块、1:页面、2:按钮
                switch (menu.Level)
                {
                    case "0":
                        if (!string.IsNullOrWhiteSpace(menu.ParentNo))
                        {
                            throw new Exception("模块类型为模块,父级菜单应为空");
                        }
                        break;
                    case "1":
                        if (string.IsNullOrWhiteSpace(menu.ParentNo))
                        {
                            throw new Exception("模块类型为页面,父级菜单不能为空");
                        }

                        var menuData = Db.Queryable<SysFunctionMenu>().First(m => m.MenuNo == menu.ParentNo);
                        if (menuData == null)
                        {
                            throw new Exception("未查询到父级菜单信息,请核实");
                        }

                        if (menuData.Level != "0")
                        {
                            throw new Exception("当前模块类型是页面,父级菜单类型应为模块");
                        }
                        break;
                    case "2":
                        if (string.IsNullOrWhiteSpace(menu.ParentNo))
                        {
                            throw new Exception("模块类型为页面,父级菜单不能为空");
                        }

                        var menuData2 = Db.Queryable<SysFunctionMenu>().First(m => m.MenuNo == menu.ParentNo);
                        if (menuData2 == null)
                        {
                            throw new Exception("未查询到父级菜单信息,请核实");
                        }

                        if (menuData2.Level != "1")
                        {
                            throw new Exception("当前模块类型是按钮,父级菜单类型应为页面");
                        }
                        break;
                    default:
                        throw new Exception("模块类型异常");
                }
                int i = await _menu.UpdateMenu(menu);
                return i;
            }
            catch (Exception ex)
            {
                //抛出异常
                throw new Exception(ex.Message);
            }

        }

        /// <summary>
        /// 根据父级菜单号获取菜单信息
        /// </summary>
        /// <param name="MenuNo">菜单号</param>
        /// <returns></returns>
        public List<FunctionMenuVm> GetMenuByParentNo(string MenuNo)
        {
            List<FunctionMenuVm> menulist = _menu.GetMenuByParentNo(MenuNo);
            return menulist;
        }
    }
}