GeneratorController.cs 7.05 KB
using Hh.Mes.Common.Reflect;
using Hh.Mes.Common.Request;
using Hh.Mes.POJO.Entity;
using Hh.Mes.POJO.Response;
using Hh.Mes.POJO.ViewModel;
using Hh.Mes.POJO.WebEntity.tool;
using Hh.Mes.Service.SystemAuth;
using Hh.Mes.Service.WebService.Tool;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace WebMvc.Areas.Planned.Controllers
{
    /// <summary>
    /// 代码生成器
    /// </summary>
    [Area("Planned")]
    public class GeneratorController : BaseController
    {
        private readonly CodeGeneratorService _generatorService;
        private readonly IHostingEnvironment env;

        public GeneratorController(IAuth authUtil, CodeGeneratorService generatorService, IHostingEnvironment environment) : base(authUtil)
        {
            _generatorService = generatorService;
            env = environment;
        }

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

        /// <summary>
        /// 代码预览
        /// </summary>
        /// <param name="areaName"></param>
        /// <param name="entityName"></param>
        /// <returns></returns>
        public IActionResult CodePreview(string entityName, string areaName = "")
        {
            if (env.IsDevelopment())
            {
                if (string.IsNullOrWhiteSpace(areaName))
                {
                    areaName = string.Empty;
                    ModelState.AddModelError(string.Empty, "请填写区域名称");
                }
                var code = _generatorService.GetCode(entityName, areaName, GetAreaSelectItems());
                return View(code);
            }
            else
            {
                return Redirect("/Error");
            }
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult CodePreview(CodePreviewVM codePreview)
        {
            string areaName = codePreview.AreaName;
            string entityName = codePreview.EntityName;
            if (string.IsNullOrWhiteSpace(areaName))
            {
                areaName = string.Empty;
                ModelState.AddModelError(string.Empty, "区域名称不能为空!");
            }
            var result = _generatorService.GetCode(entityName, areaName, GetAreaSelectItems());
            return View(result);
        }

        /// <summary>
        /// 文件保存路径预览
        /// </summary>
        /// <param name="entityName"></param>
        /// <param name="areaName"></param>
        /// <returns></returns>
        public IActionResult SaveCodeFile(string entityName, string areaName)
        {
            var fileName = _generatorService.ConvertToControllerName(entityName);
            var path = new CodeSavePath
            {
                JavaScriptPath = Path.GetFullPath($"./wwwroot/productjs/{areaName}/{fileName}.js"),
                CshtmlPath = Path.GetFullPath($"./Areas/{areaName}/Views/{fileName}/Index.cshtml"),
                ControllerPath = Path.GetFullPath($"./Areas/{areaName}/Controllers/{fileName}Controller.cs"),
                ModelPath = Path.GetFullPath($"../../sys/Hh.Mes.POJO/WebEntity/{areaName}/{entityName}.cs"),
                ServicePath = Path.GetFullPath($"../../sys/Hh.Mes.Service/WebService/{areaName}/{fileName}Service.cs"),
                EntityName = entityName,
                AreaName = areaName,
            };
            return View(path);
        }

        /// <summary>
        /// 代码文件保存
        /// </summary>
        /// <param name="path">文件保存路径</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult SaveCodeFile(CodeSavePath path)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var code = _generatorService.GetCode(path.EntityName, path.AreaName, GetAreaSelectItems());
                    var result = new Dictionary<string, Response>
                    {
                        { path.JavaScriptPath, _generatorService.SaveFile(path.JavaScriptPath, code.JavaScriptTemp) },
                        { path.ModelPath, _generatorService.SaveFile(path.ModelPath, code.ModelTemp) },
                        { path.ControllerPath, _generatorService.SaveFile(path.ControllerPath, code.ControllerTemp) },
                        { path.CshtmlPath, _generatorService.SaveFile(path.CshtmlPath, code.CshtmlTemp) },
                        { path.ServicePath, _generatorService.SaveFile(path.ServicePath, code.ServiceTemp) },
                    };
                    if (result.All(x => x.Value.Status))
                    {
                        var tableInfo = _generatorService.GetTableDescription(path.EntityName);
                        var module = new SysModule()
                        {
                            Code = path.EntityName,
                            Name = string.IsNullOrWhiteSpace(tableInfo.TableName) ? tableInfo.TableCode : tableInfo.TableName,
                            Url = $"/{path.AreaName}/{path.EntityName}/Index",
                            IconName = "&#xe663;",
                            SortNo = 10,
                            IsShow = 1,
                        };
                        var addBtnsResult = _generatorService.InsertModelAndButton(module, path.AreaName);
                        result.Add("MenusAndBtns", addBtnsResult);
                    }
                    var json = JsonConvert.SerializeObject(result);
                    return RedirectToAction(nameof(ResultView), new { json });
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
            }
            return View();
        }

        /// <summary>
        /// 结果预览
        /// </summary>
        /// <returns></returns>
        public IActionResult ResultView(string json)
        {
            var result = new Dictionary<string, Response>();
            ViewBag.ErrorMessage = "";
            try
            {
                result = JsonConvert.DeserializeObject<Dictionary<string, Response>>(json);
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
            }
            return View(result);
        }

        /// <summary>
        /// 加载及分页查询
        /// </summary>
        /// <param name="pageRequest">表单请求信息</param>
        /// <param name="entity">实体信息</param>
        /// <returns></returns>
        [HttpPost]
        public string Load(PageReq pageRequest, TableInfo entity)
        {
            return Serialize(_generatorService.Load(pageRequest, entity));
        }

        /// <summary>
        /// 获取所有Area的集合
        /// </summary>
        /// <returns></returns>
        private IEnumerable<string> GetAreaSelectItems()
        {
            return ReflectHelper.GetControlAreas<Controller>().Select(x => x.Key);
        }
    }
}