using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RMYY_CallCenter_Api.DB;

namespace RMYY_CallCenter_Api.Controllers.System
{
    public class MenuController : BaseController
    {
        private Bll.T_Sys_Menu menuBLL = new Bll.T_Sys_Menu();

        // GET: Menu
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(string keyword)
        {
            string sql = "";
            if (!string.IsNullOrEmpty(keyword)) 
                sql += $"and F_MenuName like '%{keyword}%'";
            List<Model.T_Sys_Menu> list =menuBLL.GetModelList($"F_State=1 and (F_Type=1 or F_Type=2)"+ sql);
            List<Model.T_Sys_Menu> listitem = menuBLL.GetModelList($" F_ParentId in (select F_MenuId from T_Sys_Menu where F_Type=2 group by F_MenuId )"+ sql);
            //foreach (var item in list)
            //{
            //    if (item.F_Type == 2)
            //    {
            //         item.button=listitem.Where(p => p.F_ParentId == item.F_MenuId).ToList();
            //    }
            //}
            list.Sort((x, y) => x.F_Sort ?? 0 - y.F_Sort ?? 0);
            return Success("成功", list);
        }

        /// <summary>
        /// 获取按钮列表
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <returns></returns>
        public ActionResult GetListButton(int pid,string keyword, int pagesize = 10, int pageindex = 1,int menutype=0)
        {
            DataTable dt = new DataTable();
            if (pid > 0)
            {
                string sql = "and F_State=1";
                var model = menuBLL.GetModel(pid);
                if (model != null)
                {
                    sql=$" and F_Type=3 and F_ParentId=" + pid;
                }
                if (!string.IsNullOrEmpty(keyword))
                {
                    sql += $" and F_MenuName like'%" + keyword.Trim() + "%'";
                }
                if (menutype>0)
                {
                    sql += $" and F_MenuType=" + menutype;
                }
                int recordCount = 0;
                dt = Bll.PagerBll.GetListPager
                    (
                    "T_Sys_Menu",
                    "F_MenuId",
                    "*",
                    sql,
                    "ORDER BY F_Sort asc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount
                    );
                var modelist = menuBLL.DataTableToList(dt);
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = modelist,
                    total = recordCount
                };
                return Content(obj.ToJson());
            }
             return Error("参数错误！");
          
        }
        /// <summary>
        /// 返回树形下拉框 菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetTreeList()
        {
            var ds_ModuleInfo = menuBLL.GetModelList("F_State=1 and (F_Type=1 or F_Type=2)");
            ds_ModuleInfo.Sort((x, y) => x.F_Sort??0 - y.F_Sort??0);//排序
            var treeList = new List<TreeModel>();
            foreach (var item in ds_ModuleInfo.Where(p=>p.F_ParentId==0))
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_MenuId.ToString();
                treeModel.IconCls = item.F_Icon;
                treeModel.text = item.F_MenuName;
                treeModel.parentid = item.F_ParentId.ToString();
                treeModel.children = TreeRecursion(ds_ModuleInfo, item.F_MenuId.ToString());
                treeList.Add(treeModel);
            }
            //return Content(treeList.ToJson());
            return Success("获取菜单树成功", treeList);
        }

        private List<TreeModel> TreeRecursion(List<Model.T_Sys_Menu> data, string parentId = "0")
        {
            List<TreeModel> newList = new List<TreeModel>();
            List<Model.T_Sys_Menu> item = data.FindAll(t => t.F_ParentId.ToString() == parentId);//data建议在调用此扩展方法前已经排序过
            if (item.Count > 0)
            {
                foreach (Model.T_Sys_Menu entity in item)
                {
                    TreeModel treeModel = new TreeModel();
                    treeModel.id = entity.F_MenuId.ToString();
                    treeModel.IconCls = entity.F_Icon;
                    treeModel.text = entity.F_MenuName;
                    treeModel.parentid = entity.F_ParentId.ToString();
                    if (entity.F_Type == 1)
                    {
                        treeModel.children = TreeRecursion(data, entity.F_MenuId.ToString());
                    }
                    else if (entity.F_Type == 2)
                    {
                        treeModel.children = TreeRecursion(data, entity.F_MenuId.ToString());
                    }
                    newList.Add(treeModel);
                }
            }
            return newList;
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="menuid"></param>
        /// <param name="menucode"></param>
        /// <returns></returns>
        public ActionResult GetModel(int menuid = 0, string menucode = "")
        {
            string sql = " 1=1 ";
            if (menuid > 0)
            {
                sql += " and F_MenuId=" + menuid;
            }
            if (!string.IsNullOrWhiteSpace(menucode))
            {
                sql += " and F_MenuCode='" + menucode + "'";
            }
            if (string.IsNullOrEmpty(menucode)&& menuid==0)
                return Error("获取失败");

            var role = menuBLL.GetModelList(sql).FirstOrDefault();
            if (role != null)
                return Success("获取成功", role);
            else return Error("不存在此菜单信息！");
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(int pid, string code, string name, int sort, int type, string url, string function,string icon,string remark,int menutype=0, int state = 1, string workState = "")
        {
            if (menuBLL.Exists(code))
            {
                return Error("已经存在此编码");
            }
            else
            {
                Model.T_Sys_Menu dModel = new Model.T_Sys_Menu();
                dModel.F_ParentId = pid;
                dModel.F_Sort = sort;
                dModel.F_MenuCode = code;
                dModel.F_MenuName = name;
                dModel.F_Type = type;
                dModel.F_Url = url;
                dModel.F_Action = function;
                dModel.F_Icon = icon;
                dModel.F_State = state;
                dModel.F_Remark = remark;
                dModel.F_CreateTime = DateTime.Now;
                dModel.F_MenuType = menutype;
                dModel.F_WorkState = workState;
                dModel.F_CreateUser = User.F_UserCode;

                int n = menuBLL.Add(dModel);
                if (n > 0)
                {
                    return Success("添加成功", n);
                }

                else
                    return Error("添加失败");
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int id, int pid, string code, string name, int sort, int type, string url, string function, string icon,string remark, int menutype=0, int state=1, string workState = "")
        {
            Model.T_Sys_Menu dModel = menuBLL.GetModel(id);
            if (dModel != null)
            {
                var list = menuBLL.GetModelList(" F_MenuCode='" + code + "' and F_MenuId!= "+ id);
                if (list.Count > 0)
                {
                    return Error("已经存在此编码");
                }
                else
                {
                    dModel.F_ParentId = pid;
                    dModel.F_Sort = sort;
                    dModel.F_MenuCode = code;
                    dModel.F_MenuName = name;
                    dModel.F_Type = type;
                    dModel.F_Url = url;
                    dModel.F_Action = function;
                    dModel.F_Icon = icon;
                    dModel.F_State = state;
                    dModel.F_Remark = remark;
                    dModel.F_MenuType = menutype;
                    dModel.F_WorkState = workState ?? "";
                    if (menuBLL.Update(dModel))
                    {
                        return Success("修改成功");
                    }
                    else
                        return Error("修改失败");
                }
            }
            else
            {
                return Error("修改失败");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (id > 0)
            {
                int menucount =(int) DbHelperSQL.GetSingle("  select COUNT(1) from T_Sys_RoleMenu where F_MenuId='"+id+"'");
              //  var list = menuBLL.GetList("F_ParentId='" + id + "'").Tables[0];
                if (menucount > 0)
                {
                    return Error("正在被使用，不能删除");
                }

                if (menuBLL.Delete(id))
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("删除失败");
            }

        }

        /// <summary>
        /// 获取工单对应的操作按钮
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult GetButtonList(int type)
        {
            if (type > 0)
            {
                string sql = $" F_State=1 and F_Type=3 and F_MenuType={type}";
                var modelist = menuBLL.GetModelList(sql);
                var rows = modelist.Select(p =>
                {
                    return new
                    {
                        F_MenuId=p.F_MenuId,
                        F_MenuName=p.F_MenuName,
                        F_Action=p.F_Action
                    };
                }
                );
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = rows
                };
                return Content(obj.ToJson());
            }
            else
                return Error("参数错误！");
        }
    }
}