using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Authentication;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

using System.Security.Claims;
using System.Linq.Expressions;

using Newtonsoft;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using XHD.Core.IServices;
using XHD.Core.IRepository;
using XHD.Core.Common;
using XHD.Core.View;

using XHD.Core.Models;


namespace XHD.Core.View.Controllers
{
    public class SysMenuController : Controller
    {
        private readonly ILogger<SysMenuController> _logger;
        private readonly ISys_MenuService _service;
        private readonly ISys_ButtonService _serviceBtn;

        public SysMenuController(ILogger<SysMenuController> logger, ISys_MenuService service, ISys_ButtonService serviceBtn)
        {
            _service = service;
            _serviceBtn = serviceBtn;
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult MenuAdd()
        {
            return View();
        }

        public IActionResult ButtonAdd()
        {
            return View();
        }

        /// <summary>
        /// 按钮目录的混合表格
        /// </summary>
        /// <returns></returns>
        public async Task<string> Grid()
        {
            Expression<Func<Sys_Menu, bool>> expMenu = a => true;
            var MenuData = await _service.GridAsync(expMenu, "Menu_order");

            Expression<Func<Sys_Button, bool>> expBtn = a => true;
            var BtnData = await _serviceBtn.GridAsync(expBtn, "Btn_order");


            JArray arrapp = new JArray();

            foreach (var menu in MenuData.data)
            {
                JObject objapp = new JObject();

                objapp.Add("id", menu.id);
                objapp.Add("title", menu.Menu_name);
                objapp.Add("icon", $"fa { menu.Menu_icon }");
                objapp.Add("href", menu.Menu_url);
                objapp.Add("isMenu", 0);
                objapp.Add("parentid", menu.parentid);
                objapp.Add("order", menu.Menu_order);
                objapp.Add("auth", menu.id);

                arrapp.Add(objapp);
            }

            foreach (var button in BtnData.data)
            {
                JObject objapp = new JObject();

                objapp.Add("id", button.id);
                objapp.Add("title", button.Btn_name);
                objapp.Add("icon", $"fa { button.Btn_icon }");
                objapp.Add("href", "");
                objapp.Add("isMenu", 1);
                objapp.Add("parentid", button.Menu_id);
                objapp.Add("order", button.Btn_order);
                objapp.Add("auth", button.Btn_handler);

                arrapp.Add(objapp);
            }

            JObject obj = new JObject();
            obj.Add("code", 0);
            obj.Add("msg", "");
            obj.Add("count", 0);
            obj.Add("data", arrapp);

            return obj.ToString();
        }

        /// <summary>
        /// 目录树
        /// </summary>
        /// <returns></returns>
        public async Task<string> Tree()
        {
            var json = await _service.Tree();

            return json.ToString();
        }

        /// <summary>
        /// 目录的下拉
        /// </summary>
        /// <returns></returns>
        public async Task<string> Combo()
        {
            var json = await _service.Combo();

            return json.ToString();
        }

        /// <summary>
        /// 保存目录
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        public async Task<string> SaveMenu(Sys_Menu menu)
        {
            Expression<Func<Sys_Menu, bool>> expression = a => a.id == menu.id;
            var list = await _service.GridAsync(expression);

            var result = 0;
            if (list.count == 0)
            {
                result = await _service.AddAsync(menu);
            }
            else
            {
                result = await _service.UpdateAsync(menu);
            }

            return XHDResult.Success().ToString();
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <returns></returns>
        public async Task<string> SaveButton()
        {
            Sys_Button model = new Sys_Button();

            model.Menu_id = Request.Form["T_menu_id"];

            if (Request.Form["btn[add]"] == "on")
            {
                model.id = $"{model.Menu_id}|add";
                model.Btn_name = "新增";
                model.Btn_order = 10;
                model.Btn_handler = "add";
                model.Btn_icon = "fa-plus-circle";

                await _serviceBtn.AddAsync(model);
            }

            if (Request.Form["btn[edit]"] == "on")
            {
                model.id = $"{model.Menu_id}|edit";
                model.Btn_name = "修改";
                model.Btn_order = 20;
                model.Btn_handler = "edit";
                model.Btn_icon = "fa-pencil-square-o";

                await _serviceBtn.AddAsync(model);
            }

            if (Request.Form["btn[del]"] == "on")
            {
                model.id = $"{model.Menu_id}|del";
                model.Btn_name = "删除";
                model.Btn_order = 30;
                model.Btn_handler = "del";
                model.Btn_icon = "fa-minus-circle";

                await _serviceBtn.AddAsync(model);
            }

            if (Request.Form["btn[import]"] == "on")
            {
                model.id = $"{model.Menu_id}|import";
                model.Btn_name = "导入";
                model.Btn_order = 40;
                model.Btn_handler = "import";
                model.Btn_icon = "fa-sign-in";

                await _serviceBtn.AddAsync(model);
            }

            if (Request.Form["btn[export]"] == "on")
            {
                model.id = $"{model.Menu_id}|export";
                model.Btn_name = "导出";
                model.Btn_order = 50;
                model.Btn_handler = "export";
                model.Btn_icon = "fa-sign-out";

                await _serviceBtn.AddAsync(model);
            }


            if (Request.Form["btn[auth]"] == "on")
            {
                model.id = $"{model.Menu_id}|auth";
                model.Btn_name = "权限";
                model.Btn_order = 60;
                model.Btn_handler = "auth";
                model.Btn_icon = "fa-lock";

                await _serviceBtn.AddAsync(model);
            }

            if (Request.Form["btn[pwd]"] == "on")
            {
                model.id = $"{model.Menu_id}|pwd";
                model.Btn_name = "修改密码";
                model.Btn_order = 70;
                model.Btn_handler = "pwd";
                model.Btn_icon = "fa-lock";

                await _serviceBtn.AddAsync(model);
            }

            //if (Request.Form["btn[recharge]"] == "on")
            //{
            //    model.id = UUIDNext.Uuid.NewSequential().ToString();
            //    model.Btn_name = "充值";
            //    model.Btn_order = 60;
            //    model.Btn_handler = "recharge";
            //    model.Btn_icon = "fa-rmb";

            //    await _serviceBtn.Add(model);
            //}

            return XHDResult.Success().ToString();
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> DelMenu(string id)
        {
            //先检查此目录下是否有按钮
            Expression<Func<Sys_Button,bool>> exp=a=>a.Menu_id == id;

            var data = await _serviceBtn.GridAsync(exp);

            if (data.count > 0)
            {
                return XHDResult.Error("此目录下含有按钮，不能删除！").ToString();
            }

            await _service.DeleteAsync(id);

            return XHDResult.Success().ToString();
        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<string> DelButton(string id)
        {
            await _serviceBtn.DeleteAsync(id);

            return XHDResult.Success().ToString();
        }
    }
}
