.NETAdmin/ZR.Admin.WebApi/Controllers/CommonController.cs
2025-08-18 22:34:48 +08:00

297 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using MiniExcelLibs;
using ZR.Infrastructure.IPTools;
using ZR.Model.Business.Dto;
using ZR.Model.Business;
using ZR.Model.Dto;
using ZR.Model.System;
using ZR.ServiceCore.Resources;
using ZR.Service.Business.IBusinessService;
using ZR.Service.Business;
using System.Threading.Tasks;
namespace ZR.Admin.WebApi.Controllers
{
/// <summary>
/// 公共模块
/// </summary>
[Route("[controller]/[action]")]
[ApiExplorerSettings(GroupName = "sys")]
public class CommonController : BaseController
{
private OptionsSetting OptionsSetting;
private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
private IWebHostEnvironment WebHostEnvironment;
private ISysFileService SysFileService;
private readonly IStringLocalizer<SharedResource> _localizer;
public readonly ISysDeptService _deptService;
public readonly ISysDictDataService sysDictDataService;
/// <summary>
/// 工作记录接口
/// </summary>
private readonly ICamWorkrecordService _CamWorkrecordService;
/// <summary>
/// 工作人员记录接口
/// </summary>
private readonly ICamWorkerService _CamWorkerService;
/// <summary>
/// CommonController 构造函数
/// </summary>
/// <param name="stringLocalizer"></param>
/// <param name="options"></param>
/// <param name="webHostEnvironment"></param>
/// <param name="fileService"></param>
/// <param name="deptService"></param>
public CommonController(
IStringLocalizer<SharedResource> stringLocalizer,
IOptions<OptionsSetting> options,
IWebHostEnvironment webHostEnvironment,
ISysFileService fileService,
ISysDeptService deptService,
ISysDictDataService sysDictDataService,
ICamWorkrecordService _CamWorkrecordService,
ICamWorkerService camWorkerService)
{
WebHostEnvironment = webHostEnvironment;
SysFileService = fileService;
OptionsSetting = options.Value;
_localizer = stringLocalizer;
_deptService = deptService;
this.sysDictDataService = sysDictDataService;
this._CamWorkrecordService = _CamWorkrecordService;
_CamWorkerService = camWorkerService;
}
/// <summary>
/// home
/// </summary>
/// <returns></returns>
[Route("/")]
[HttpGet]
[AllowAnonymous]
public IActionResult Index()
{
var hello = _localizer["hello"].Value;
return Ok($"请求成功!=>" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}
/// <summary>
/// 查询IP信息
/// </summary>
/// <returns></returns>
[Route("/ip")]
[HttpGet]
[AllowAnonymous]
public IActionResult IPInfo(string ip)
{
if (ip.IsEmpty()) return ToResponse(ResultCode.CUSTOM_ERROR, "IP异常");
var region = IpTool.GetRegion(ip);
return SUCCESS(region);
}
/// <summary>
/// 企业消息测试
/// </summary>
/// <param name="msg">要发送的消息</param>
/// <param name="toUser">要发送的人@all所有xxx单独发送对个人</param>
/// <returns></returns>
[Route("/sendMsg")]
[HttpGet]
[Log(Title = "企业消息测试")]
public IActionResult SendMsg(string msg, string toUser = "")
{
WxNoticeHelper.SendMsg("消息测试", msg, toUser, WxNoticeHelper.MsgType.markdown);
return SUCCESS(msg);
}
#region
/// <summary>
/// 存储文件
/// </summary>
/// <param name="uploadDto">自定义文件名</param>
/// <param name="file"></param>
/// <param name="storeType">上传类型1、保存到本地 2、保存到阿里云</param>
/// <returns></returns>
[HttpPost]
[ActionPermissionFilter(Permission = "common")]
public async Task<IActionResult> UploadFile([FromForm] UploadDto uploadDto, IFormFile file, StoreType storeType = StoreType.ALIYUN)
{
if (file == null) throw new CustomException(ResultCode.PARAM_ERROR, "上传文件不能为空");
SysFile sysfile = new();
IFormFile formFile = file;
string fileExt = Path.GetExtension(formFile.FileName);//文件后缀
double fileSize = Math.Round(formFile.Length / 1024.0, 2);//文件大小KB
if (OptionsSetting.Upload.NotAllowedExt.Contains(fileExt))
{
return ToResponse(ResultCode.CUSTOM_ERROR, "上传失败,未经允许上传类型");
}
if (uploadDto.FileNameType == 1)
{
uploadDto.FileName = Path.GetFileNameWithoutExtension(formFile.FileName);
}
else if (uploadDto.FileNameType == 3)
{
uploadDto.FileName = SysFileService.HashFileName();
}
switch (storeType)
{
case StoreType.LOCAL:
string savePath = Path.Combine(WebHostEnvironment.WebRootPath);
if (uploadDto.FileDir.IsEmpty())
{
uploadDto.FileDir = OptionsSetting.Upload.LocalSavePath;
}
sysfile = await SysFileService.SaveFileToLocal(savePath, uploadDto, HttpContext.GetName(), formFile);
break;
case StoreType.REMOTE:
break;
case StoreType.ALIYUN:
int AlimaxContentLength = OptionsSetting.ALIYUN_OSS.MaxSize;
if (OptionsSetting.ALIYUN_OSS.REGIONID.IsEmpty())
{
return ToResponse(ResultCode.CUSTOM_ERROR, "配置文件缺失");
}
if ((fileSize / 1024) > AlimaxContentLength)
{
return ToResponse(ResultCode.CUSTOM_ERROR, "上传文件过大,不能超过 " + AlimaxContentLength + " MB");
}
sysfile = new(formFile.FileName, uploadDto.FileName, fileExt, fileSize + "kb", uploadDto.FileDir, HttpContext.GetName())
{
StoreType = (int)StoreType.ALIYUN,
FileType = formFile.ContentType,
ClassifyType = uploadDto.ClassifyType,
CategoryId = uploadDto.CategoryId,
};
sysfile = await SysFileService.SaveFileToAliyun(sysfile, uploadDto, formFile);
if (sysfile.Id <= 0) { return ToResponse(ApiResult.Error("阿里云连接失败")); }
break;
case StoreType.TENCENT:
break;
case StoreType.QINIU:
break;
default:
break;
}
return SUCCESS(new
{
url = sysfile.AccessUrl,
fileName = sysfile.FileName,
fileId = sysfile.Id.ToString()
});
}
#endregion
/// <summary>
/// 下载文件
/// </summary>
/// <param name="path"></param>
/// <param name="fileId"></param>
/// <returns></returns>
[HttpGet]
[ActionPermissionFilter(Permission = "common")]
[Log(Title = "下载文件", IsSaveResponseData = false)]
public IActionResult DownloadFile(string? path, long fileId = 0)
{
var tempPath = path;
if (fileId > 0)
{
var fileInfo = SysFileService.GetById(fileId);
if (fileInfo != null)
{
tempPath = fileInfo.FileUrl;
}
}
string fullPath = tempPath;
//if (tempPath.StartsWith("/"))
//{
// fullPath = Path.Combine(WebHostEnvironment.WebRootPath, tempPath.ReplaceFirst("/", ""));
//}
string fileName = Path.GetFileName(fullPath);
return DownFile(fullPath, fileName);
}
/// <summary>
/// home
/// </summary>
/// <returns></returns>
[Route("/config")]
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> GetConfig()
{
var file = await SysFileService.AsQueryable().Where(x => x.ClassifyType == "watermark").FirstAsync();
var topDept = await _deptService.AsQueryable().Where(it => it.ParentId == 0 && it.DelFlag == 0 && it.Status == 0).FirstAsync();
List<string> deptList = new List<string>();
if (topDept != null)
{
var children = await _deptService.AsQueryable().Where(it => it.ParentId == topDept.DeptId && it.DelFlag == 0 && it.Status == 0).Select(it => it.DeptName).ToListAsync();
deptList = children;
}
var list = await sysDictDataService.AsQueryable().Where(it => it.DictType == "sys_construction_status" && it.Status == "0").Select(it => it.DictValue).ToListAsync();
return SUCCESS(new { logo = file?.AccessUrl ?? "", deptList, construction = list });
}
/// <summary>
/// 添加工作记录
/// </summary>
/// <returns></returns>
[HttpPost]
[Route("/addworkrecord")]
public async Task<IActionResult> AddCamWorkRecord([FromBody] CamRecordWorkDto parm)
{
if (parm.Workers == null || parm.Workers.Count == 0)
{
return ToResponse(ResultCode.PARAM_ERROR, "请选择工作人员");
}
if (string.IsNullOrEmpty(parm.Image))
{
return ToResponse(ResultCode.PARAM_ERROR, "请上传图片");
}
// -当日所有照片
//- 当日根据【人名】分类的照片
//- 当日根据【工作内容】分类的照片
//- 当日根据【部门】分类的照片
var imageprx = ImageConverter.GetFileExtensionFromBase64(parm.Image);
var imageName = ImageConverter.GenerateImageFileName(imageprx);
var filePath = "gift/" + DateTime.Now.ToString("yyyy/MMdd/");
//备份一下本地
var modal = parm.Adapt<CamWorkrecord>().ToCreate(HttpContext);
modal.CreateTime = DateTime.Now;
modal.UpdateTime = DateTime.Now;
modal = await _CamWorkrecordService.Insertable(modal).ExecuteReturnEntityAsync();
var response = _CamWorkrecordService.AddCamWorkrecord(modal);
var workid = response.Id;
var workers = new List<CamWorker>();
foreach (var item in parm.Workers)
{
var worker = new CamWorker()
{
WorkrecordId = workid,
WorkerName = item,
CreateTime = DateTime.Now,
UpdateTime = DateTime.Now
};
workers.Add(worker);
}
_CamWorkerService.AsInsertable(workers).ExecuteCommand();
return SUCCESS(response);
}
}
}