using System.ComponentModel.DataAnnotations;
using Dpz.Core.Public.ViewModel.DynamicPages;
using Dpz.Core.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Dpz.Core.Web.Controllers;
[CheckAuthorize]
public class DynamicController(IDynamicPageService dynamicPageService) : Controller
{
[HttpGet]
public async Task<IActionResult> MyDynamicPages(int pageIndex = 1, int pageSize = 10, string name = "")
{
var userInfo = User.GetIdentity() ?? throw new Exception("login has expired");
var source = await dynamicPageService.GetPageAsync(pageIndex, pageSize, name, userInfo.Id);
var data = Pagination<VmDynamicPage>.Create(source);
return Json(new ResultInfo(data));
}
/// <summary>
/// 创建动态页
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Create([FromBody][Required]VmCreateDynamicPage model)
{
if (!ModelState.IsValid)
{
var errors = ModelState
.Select(x => x.Value?.Errors ?? new ModelErrorCollection())
.SelectMany(x => x)
.Select(x => x.ErrorMessage)
.ToArray();
return Json(new ResultInfo(string.Join("\n", errors)));
}
model.Creator = User.GetIdentity() ?? throw new Exception("login has expired");
await dynamicPageService.CreateAsync(model);
return Json(new ResultInfo(true));
}
public async Task<IActionResult> Find(string id = "")
{
var userInfo = User.GetIdentity() ?? throw new Exception("login has expired");
var pageInformation = await dynamicPageService.FindAsync(id, userInfo.Id);
return Json(new ResultInfo(pageInformation));
}
public async Task<IActionResult> Save([FromBody][Required] VmEditDynamicPage model)
{
if (!ModelState.IsValid)
{
var errors = ModelState
.Select(x => x.Value?.Errors ?? new ModelErrorCollection())
.SelectMany(x => x)
.Select(x => x.ErrorMessage)
.ToArray();
return Json(new ResultInfo(string.Join("\n", errors)));
}
model.CreatorId = (User.GetIdentity() ?? throw new Exception("login has expired")).Id;
await dynamicPageService.EditContentAsync(model);
return Json(new ResultInfo(true));
}
}