using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ZR.CodeGenerator.CodeGenerator;
using ZR.CodeGenerator.Service;
using ZR.Model;
namespace ZR.CodeGenerator
{
///
/// 代码生成器。
///
/// 根据指定的实体域名空间生成Repositories和Services层的基础代码文件。
///
///
public class CodeGeneratorTool
{
///
/// 代码生成器配置
///
private static CodeGenerateOption _option = new CodeGenerateOption();
///
/// InputDto输入实体是不包含字段
///
private static string inputDtoNoField = "DeleteMark,CreatorTime,CreatorUserId,CompanyId,DeptId,LastModifyTime,LastModifyUserId,DeleteTime,DeleteUserId,";
///
/// 代码生成器入口方法
///
///
/// 要生成代码的表
///
///
/// 要删除表名称的字符
/// 是否替换现有文件,为true时替换
public static void Generate(string dbName, string baseNamespace, List listTable, string replaceTableNameStr, bool ifExsitedCovered = false)
{
_option.DtosNamespace = baseNamespace + ".Dtos";
_option.ModelsNamespace = baseNamespace + ".Model";
_option.IRepositoriesNamespace = baseNamespace + ".IRepositories";
_option.RepositoriesNamespace = baseNamespace + ".Repositories";
_option.IServicsNamespace = baseNamespace + ".IServices";
_option.ServicesNamespace = baseNamespace + ".Services";
_option.ApiControllerNamespace = baseNamespace + "Api";
_option.ReplaceTableNameStr = replaceTableNameStr;
//_option.TableList = listTable;
_option.BaseNamespace = baseNamespace;
CodeGeneraterService codeGeneraterService = new CodeGeneraterService();
//List listTable = dbExtractor.GetWhereTables(_option.TableList);
string profileContent = string.Empty;
foreach (DbTableInfo dbTableInfo in listTable)
{
List listField = codeGeneraterService.GetColumnInfo(dbName, dbTableInfo.TableName);
GenerateSingle(listField, dbTableInfo, ifExsitedCovered);
string tableName = dbTableInfo.TableName;
if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr))
{
string[] rel = _option.ReplaceTableNameStr.Split(';');
for (int i = 0; i < rel.Length; i++)
{
if (!string.IsNullOrEmpty(rel[i].ToString()))
{
tableName = tableName.Replace(rel[i].ToString(), "");
}
}
}
tableName = tableName.Substring(0, 1).ToUpper() + tableName.Substring(1);
profileContent += string.Format(" CreateMap<{0}, {0}OutputDto>();\n", tableName);
profileContent += string.Format(" CreateMap<{0}InputDto, {0}>();\n", tableName);
}
//GenerateDtoProfile(_option.ModelsNamespace, profileContent, ifExsitedCovered);
}
///
/// 单表生成代码
///
/// 表字段集合
/// 表信息
/// 如果目标文件存在,是否覆盖。默认为false
public static void GenerateSingle(List listField, DbTableInfo tableInfo, bool ifExsitedCovered = false)
{
var modelsNamespace = _option.ModelsNamespace;
var modelTypeName = tableInfo.TableName;//表名
var modelTypeDesc = tableInfo.Description;//表描述
if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr))
{
string[] rel = _option.ReplaceTableNameStr.Split(';');
for (int i = 0; i < rel.Length; i++)
{
if (!string.IsNullOrEmpty(rel[i].ToString()))
{
modelTypeName = modelTypeName.Replace(rel[i].ToString(), "");
}
}
}
modelTypeName = modelTypeName.Substring(0, 1).ToUpper() + modelTypeName.Substring(1);
string keyTypeName = "string";//主键数据类型
string modelcontent = "";//数据库模型字段
string InputDtocontent = "";//输入模型
string outputDtocontent = "";//输出模型
string vueViewListContent = string.Empty;//Vue列表输出内容
string vueViewFromContent = string.Empty;//Vue表单输出内容
string vueViewEditFromContent = string.Empty;//Vue变量输出内容
string vueViewEditFromBindContent = string.Empty;//Vue显示初始化输出内容
string vueViewSaveBindContent = string.Empty;//Vue保存时输出内容
string vueViewEditFromRuleContent = string.Empty;//Vue数据校验
foreach (SqlSugar.DbColumnInfo dbFieldInfo in listField)
{
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName.Substring(1);
modelcontent += " /// \n";
modelcontent += ($" /// {dbFieldInfo.ColumnDescription}\n");
modelcontent += " /// \n";
if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey)
{
modelcontent += $" [SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPrimarykey}, IsIdentity = {dbFieldInfo.IsIdentity})]\n";
}
modelcontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r";
//主键
if (dbFieldInfo.IsIdentity)
{
keyTypeName = dbFieldInfo.DataType;
//outputDtocontent += " /// \n";
//outputDtocontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
//outputDtocontent += " /// \n";
//outputDtocontent += string.Format(" [SqlSugar.SugarColumn(IsIdentity = true, IsPrimaryKey = true)]\n");
//outputDtocontent += string.Format(" public {0} {1}", TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType), columnName);
//outputDtocontent += " { get; set; }\n\r";
}
else //非主键
{
modelcontent += " /// \n";
modelcontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
modelcontent += " /// \n";
//if (dbFieldInfo.DataType == "string")
//{
// modelcontent += string.Format(" [MaxLength({0})]\n", dbFieldInfo.FieldMaxLength);
//}
modelcontent += string.Format(" public {0} {1}", TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType), columnName);
modelcontent += " { get; set; }\n\r";
//outputDtocontent += " /// \n";
//outputDtocontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
//outputDtocontent += " /// \n";
//if (dbFieldInfo.DataType == "string")
//{
// outputDtocontent += string.Format(" [MaxLength({0})]\n", dbFieldInfo.FieldMaxLength);
//}
//outputDtocontent += string.Format(" public {0} {1}", dbFieldInfo.DataType, columnName);
//outputDtocontent += " { get; set; }\n\r";
//if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint")
//{
// vueViewListContent += string.Format(" \n", columnName, dbFieldInfo.ColumnDescription);
// vueViewListContent += " \n";
// vueViewListContent += string.Format(" ", columnName);
// vueViewListContent += "{{ ";
// vueViewListContent += string.Format("scope.row.{0}===true?'启用':'禁用' ", columnName);
// vueViewListContent += "}}\n";
// vueViewListContent += " \n";
// vueViewListContent += " \n";
// vueViewFromContent += string.Format(" ", dbFieldInfo.ColumnDescription, columnName);
// vueViewFromContent += string.Format(" \n", columnName);
// vueViewFromContent += " 是\n";
// vueViewFromContent += " 否\n";
// vueViewFromContent += " \n";
// vueViewFromContent += " \n";
// vueViewEditFromContent += string.Format(" {0}: 'true',\n", columnName);
// vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}+''\n", columnName);
//}
//else
//{
// vueViewListContent += string.Format(" \n", columnName, dbFieldInfo.ColumnDescription);
// vueViewFromContent += string.Format(" \n", dbFieldInfo.ColumnDescription, columnName);
// vueViewFromContent += string.Format(" \n", columnName, dbFieldInfo.ColumnDescription);
// vueViewFromContent += " \n";
// vueViewEditFromContent += string.Format(" {0}: '',\n", columnName);
// vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}\n", columnName);
//}
//vueViewSaveBindContent += string.Format(" '{0}':this.editFrom.{0},\n", columnName);
//if (!dbFieldInfo.IsNullable)
//{
// vueViewEditFromRuleContent += string.Format(" {0}: [\n", columnName);
// vueViewEditFromRuleContent += " {";
// vueViewEditFromRuleContent += string.Format("required: true, message:\"请输入{0}\", trigger: \"blur\"", dbFieldInfo.ColumnDescription);
// vueViewEditFromRuleContent += "},\n { min: 2, max: 50, message: \"长度在 2 到 50 个字符\", trigger:\"blur\" }\n";
// vueViewEditFromRuleContent += " ],\n";
//}
}
//if (!inputDtoNoField.Contains(columnName) || columnName == "Id")
//{
// InputDtocontent += " /// \n";
// InputDtocontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
// InputDtocontent += " /// \n";
// //if (dbFieldInfo.FieldType == "string")
// //{
// // InputDtocontent += string.Format(" [MaxLength({0})]\n", dbFieldInfo.FieldMaxLength);
// //}
// InputDtocontent += string.Format(" public {0} {1}", dbFieldInfo.DataType, columnName);
// InputDtocontent += " { get; set; }\n\r";
//}
//
}
GenerateModels(modelsNamespace, modelTypeName, tableInfo.TableName, modelcontent, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateRepository(modelTypeName, modelTypeDesc, tableInfo.TableName, keyTypeName, ifExsitedCovered);
//GenerateIService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateOutputDto(modelTypeName, modelTypeDesc, outputDtocontent, ifExsitedCovered);
//GenerateInputDto(modelsNamespace, modelTypeName, modelTypeDesc, InputDtocontent, keyTypeName, ifExsitedCovered);
//GenerateControllers(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateVueViews(modelTypeName, modelTypeDesc, vueViewListContent, vueViewFromContent, vueViewEditFromContent, vueViewEditFromBindContent, vueViewSaveBindContent, vueViewEditFromRuleContent, ifExsitedCovered);
}
#region 生成Model
///
/// 生成Models文件
///
/// 命名空间
/// 类名
/// 表名称
/// 表描述
/// 数据库表实体内容
/// 主键数据类型
/// 如果目标文件存在,是否覆盖。默认为false
private static void GenerateModels(string modelsNamespace, string modelTypeName, string tableName, string modelContent, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Substring(0, path.IndexOf("\\bin"));
var parentPath = path.Substring(0, path.LastIndexOf("\\"));
var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + modelsNamespace;
if (!Directory.Exists(servicesPath))
{
servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\Models";
Directory.CreateDirectory(servicesPath);
}
var fullPath = servicesPath + "\\" + modelTypeName + ".cs";
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
var content = ReadTemplate("ModelTemplate.txt");
content = content
.Replace("{ModelsNamespace}", modelsNamespace)
.Replace("{ModelTypeName}", modelTypeName)
.Replace("{TableNameDesc}", modelTypeDesc)
.Replace("{KeyTypeName}", keyTypeName)
.Replace("{ModelContent}", modelContent)
.Replace("{TableName}", tableName);
WriteAndSave(fullPath, content);
}
#endregion
#region 帮助方法
///
/// 从代码模板中读取内容
///
/// 模板名称,应包括文件扩展名称。比如:template.txt
///
private static string ReadTemplate(string templateName)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
string fullName = $"{path}\\Template\\{templateName}";
string temp = fullName;
string str = "";
if (!File.Exists(temp))
{
return str;
}
StreamReader sr = null;
try
{
sr = new StreamReader(temp);
str = sr.ReadToEnd(); // 读取文件
}
catch { }
sr?.Close();
sr?.Dispose();
return str;
}
///
/// 写文件
///
///
///
private static void WriteAndSave(string fileName, string content)
{
//实例化一个文件流--->与写入文件相关联
using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
//实例化一个StreamWriter-->与fs相关联
using var sw = new StreamWriter(fs);
//开始写入
sw.Write(content);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
#endregion
}
}