<%-- 
Name: Database Table Properties
Author: yubaolee
Description: Create a list of properties from a database table
--%>
<%@ CodeTemplate Language="C#" Encoding="utf-8" TargetLanguage="C#" Debug="True" Description="应用层" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="Table"
             Type="SchemaExplorer.TableSchema"  %>
<%@ Property Name="HeaderModel" 
Type="System.Boolean" 
Category="1.Database"
Default="true"
Description="是否为启用头表模式，即类似‘入库订单’界面" %>
<%@ Assembly Src="../Web/Util.cs" %>
<%@ Import Namespace="Util" %>
using System;
using System.Linq;
using Infrastructure;
using OpenAuth.App.Interface;
using OpenAuth.App.Request;
using OpenAuth.App.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository.Interface;
namespace OpenAuth.App
{
    public class <%=Table.Name%>App : BaseStringApp<<%=Table.Name%>, OpenAuthDBContext>
    {
        private RevelanceManagerApp _revelanceApp;
        /// <summary>
        /// 加载列表
        /// </summary>
        public TableData Load(Query<%=Table.Name%>ListReq request)
        {
            var loginContext = _auth.GetCurrentUser();
            if (loginContext == null)
            {
                throw new CommonException("登录已过期", Define.INVALID_TOKEN);
            }
           //如果是WebAPI,请务必改为loginContext.GetTableColumns("<%=Table.Name%>");
           var columnFields = loginContext.GetTableColumnsFromDb("<%=Table.Name%>");
            if (columnFields == null || columnFields.Count == 0)
            {
                throw new Exception("请在代码生成界面配置Category表的字段属性");
            }
            var result = new TableData();
            var objs = UnitWork.Find<<%=Table.Name%>>(null);
            if (!string.IsNullOrEmpty(request.key))
            {
                objs = objs.Where(u => u.Id.Contains(request.key));
            }
             var propertyStr = string.Join(',', columnFields.Select(u =>u.ColumnName));
            result.columnFields = columnFields;
            result.data = objs.OrderBy(u => u.Id)
                .Skip((request.page - 1) * request.limit)
                .Take(request.limit).Select($"new ({propertyStr})");
            result.count = objs.Count();
            return result;
        }
        <%
        if(Table.Name.Contains("Tbl") && (!Table.Name.Contains("Dtbl")) && this.HeaderModel){
            var dtblName = Table.Name.Replace("Tbl","Dtbl");  //明细表的表名    
        %>
        public void Add(AddOrUpdate<%=Table.Name%>Req req)
        {
            var obj = req.MapTo<<%=Table.Name%>>();
            //todo:根据自己的业务场景，补充或调整字段
            obj.CreateTime = DateTime.Now;
            var user = _auth.GetCurrentUser().User;
            obj.CreateUserId = user.Id;
            obj.CreateUserName = user.Name;
            UnitWork.Add(obj);
            if (req.<%=dtblName%>Reqs != null && req.<%=dtblName%>Reqs.Any())
            {
                foreach (var detail in req.<%=dtblName%>Reqs)
                {
                    detail.ForeignKeyId = obj.Id;  //todo:调整自己的明细表外键
                    _<%=dtblName%>App.AddNoSave(detail);
                }
            }
            UnitWork.Save();
        }
         public void Update(AddOrUpdate<%=Table.Name%>Req obj)
        {
            var user = _auth.GetCurrentUser().User;
            if (obj.<%=dtblName%>Reqs != null && obj.<%=dtblName%>Reqs.Any())
            {
                //id为空的添加
                foreach (var detail in obj.<%=dtblName%>Reqs.Where(u =>string.IsNullOrEmpty(u.Id)))
                {
                    detail.ForeignKeyId = obj.Id; //todo:调整自己的明细表外键
                    _<%=dtblName%>App.AddNoSave(detail);
                }
                //id比数据库少的，删除
                var containids = obj.<%=dtblName%>Reqs.Select(u => u.Id)
                    .Where(u =>!string.IsNullOrEmpty(u)).ToList();
                if (containids.Any())
                {
                    UnitWork.Delete<<%=dtblName%>>(u =>(!containids.Contains(u.Id)) && u.ForeignKeyId == obj.Id);  //todo:调整自己的明细表外键
                }
                //更新id相同的
                foreach (var detail in obj.<%=dtblName%>Reqs.Where(u =>!string.IsNullOrEmpty(u.Id)))
                {
                    _<%=dtblName%>App.Update(detail);
                }
            }
            <%CreateUpdate();%>
            UnitWork.Save();
        }
        <%
        }else{     %>
        public void Add(AddOrUpdate<%=Table.Name%>Req req)
        {
            var obj = req.MapTo<<%=Table.Name%>>();
            //todo:根据自己的业务场景，补充或调整字段
            //比如：obj.CreateTime = DateTime.Now;
            // var user = _auth.GetCurrentUser().User;
            // obj.CreateUserId = user.Id;
            // obj.CreateUserName = user.Name;
            Repository.Add(obj);
        }
         public void Update(AddOrUpdate<%=Table.Name%>Req obj)
        {
             <%CreateUpdate();%>
        }
        <%
        }
        %>
        public <%=Table.Name%>App(IUnitWork<OpenAuthDBContext> unitWork, IRepository<<%=Table.Name%>, OpenAuthDBContext> repository,
            RevelanceManagerApp app, IAuth auth) : base(unitWork, repository,auth)
        {
            _revelanceApp = app;
        }
    }
}
<script runat="template">
/// <summary>
/// 创建更新字段
/// </summary>
public void CreateUpdate() {
    var updatestr = Tools.CreateBlank(1) + "UnitWork.Update<" + Table.Name + ">(u => u.Id == obj.Id, u => new " + Table.Name + "\r\n";
    updatestr +=Tools.CreateBlank(1) + "{\r\n";
    var columnstr = "";
    foreach (ColumnSchema p in Table.Columns) {
        if (p.IsPrimaryKeyMember) continue ;
        columnstr += Tools.CreateBlank(2)+ p.Name + " = obj." + p.Name + ", \r\n";
    }
    columnstr = columnstr.Substring(0, columnstr.Length - 4);  //删除最后一个逗号
    updatestr += columnstr;
    updatestr +=  "\r\n" +Tools.CreateBlank(2) +"//todo:根据自己的业务场景，补充或调整字段";
    updatestr += "\r\n" +Tools.CreateBlank(1) +"});";
    Response.WriteLine(updatestr);
}
</script>