Files
number_zj/20220330_Vote/Vote.Services/ApiController/OutsideWallService.cs
2023-06-28 23:07:04 +08:00

327 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Ewide.Core;
using Ewide.Core.Service;
using Furion;
using Furion.ClayObject.Extensions;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DataEncryption;
using Furion.DataEncryption.Extensions;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.RemoteRequest.Extensions;
using Google.Protobuf.Reflection;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using NPOI.HPSF;
using Vote.Services.Dto;
using Vote.Services.Entities;
namespace Vote.Services.ApiController
{
/// <summary>
/// 外墙调查问卷
/// </summary>
[ApiDescriptionSettings("outsidewall", Order = 0)]
[Route("/gb/yjb/api/outsidewall")]
public class OutsideWallService : IDynamicApiController
{
private readonly SqlSugarRepository<Entities.outside_wall> repoutside_wall;
private readonly SqlSugarRepository<Entities.outside_wall_building> repoutside_wall_building;
private readonly SqlSugarRepository<Entities.outside_wall_building_photo> repoutside_wall_building_photo;
private readonly SqlSugarRepository<Entities.outside_wall_photo> repoutside_wall_photo;
private readonly SqlSugarRepository<SysFile> rep_SysFile;
private readonly IMemoryCache _memoryCache;
readonly IOptions<UploadFileOptions> _options;
/// <summary>
///
/// </summary>
/// <param name="_repoutside_wall"></param>
/// <param name="_repoutside_wall_building"></param>
/// <param name="_repoutside_wall_building_photo"></param>
/// <param name="_repoutside_wall_photo"></param>
/// <param name="memoryCache"></param>
public OutsideWallService(SqlSugarRepository<Entities.outside_wall> _repoutside_wall, SqlSugarRepository<Entities.outside_wall_building> _repoutside_wall_building, SqlSugarRepository<Entities.outside_wall_building_photo> _repoutside_wall_building_photo, SqlSugarRepository<Entities.outside_wall_photo> _repoutside_wall_photo, IMemoryCache memoryCache, SqlSugarRepository<SysFile> _rep_SysFile, IOptions<UploadFileOptions> options)
{
repoutside_wall = _repoutside_wall;
repoutside_wall_building = _repoutside_wall_building;
repoutside_wall_building_photo = _repoutside_wall_building_photo;
repoutside_wall_photo = _repoutside_wall_photo;
_memoryCache = memoryCache;
_options = options;
rep_SysFile = _rep_SysFile;
}
/// <summary>
/// 获取三居系统中的社区
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("query/{id}")]
public async Task<dynamic> Query(string id)
{
var entity = await repoutside_wall.AsQueryable().FirstAsync(a => a.communityId == id);
if (entity != null)
{
var outside_wall_photos = await repoutside_wall_photo.AsQueryable().Where(a => a.outsidewallId == entity.Id).ToListAsync();
entity.outside_wall_photos = outside_wall_photos;
var outside_wall_buildings = await repoutside_wall_building.AsQueryable().Where(a => a.outsidewallId == entity.Id).ToListAsync();
entity.outside_wall_buildings = outside_wall_buildings;
return entity;
}
return null;
}
/// <summary>
/// 获取三居系统中的社区
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("communitys")]
public async Task<List<SanjuCommunity>> GetCommunitys(string searchkey)
{
var cacheKey = "cache_GetCommunitys";
List<SanjuCommunity> Communitys = null;
Communitys = _memoryCache.Get<List<SanjuCommunity>>(cacheKey);
if (Communitys == null || Communitys.Count == 0)
{
//var aaaaaaaaaaaaaa = repoutside_wall.AsQueryable().ToList();
var SanjuKey = App.GetConfig<string>("OutsideWallSetting:SanjuKey");
var timeStamp = GetTimeStamp();
var sign = (SanjuKey + timeStamp).ToMD5Encrypt();
var GetCommunitysUrl = App.GetConfig<string>("OutsideWallSetting:GetCommunitys");
var GetHouseInfoCitysByCommunityUrl = App.GetConfig<string>("OutsideWallSetting:GetHouseInfoCitysByCommunity");
Communitys = await string.Format(GetCommunitysUrl, "")
.SetHeaders(new Dictionary<string, object> { { "sign", sign }, { "timeStamp", timeStamp } })
.GetAsAsync<List<SanjuCommunity>>();
_memoryCache.Set(cacheKey, Communitys, DateTime.Now.AddHours(1));
}
if (!string.IsNullOrEmpty(searchkey))
return Communitys.Where(a => a.Name.Contains(searchkey)).ToList();
return Communitys;
}
/// <summary>
/// 获取三居系统中的社区
/// </summary>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("community/{id}")]
public async Task<dynamic> GetCommunityInfo(string id)
{
var cacheKey = "cache_building_" + id;
List<SanjuBuilding> building = _memoryCache.Get<List<SanjuBuilding>>(cacheKey);
if (building == null)
{
var SanjuKey = App.GetConfig<string>("OutsideWallSetting:SanjuKey");
var timeStamp = GetTimeStamp();
var sign = (SanjuKey + timeStamp).ToMD5Encrypt();
var GetHouseInfoCitysByCommunityUrl = App.GetConfig<string>("OutsideWallSetting:GetHouseInfoCitysByCommunity");
building = await string.Format(GetHouseInfoCitysByCommunityUrl, id)
.SetHeaders(new Dictionary<string, object> { { "sign", sign }, { "timeStamp", timeStamp } })
.GetAsAsync<List<SanjuBuilding>>();
_memoryCache.Set(cacheKey, building, DateTime.Now.AddHours(1));
}
return building;
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
private string GetTimeStamp()
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpPost("sysFileInfo/upload")]
public async Task<string> UploadFileDefault(IFormFile file)
{
return await UploadFile(file, _options.Value.Default);
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("sysFileInfo/delete/{id}")]
public async Task DeleteFile(string id)
{
var entity = await rep_SysFile.AsQueryable().FirstAsync(a => a.Id == id);
_ = entity == null ? throw Oops.Oh("参数异常") : "";
var pathType = _options.Value.Default.path;
var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, pathType);
File.Delete(Path.Combine(filePath, entity.FileObjectName));
await rep_SysFile.DeleteAsync(id);
}
/// <summary>
/// 预览文件
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[AllowAnonymous]
[HttpGet("sysFileInfo/preview/{id}")]
public async Task<IActionResult> PreviewFileInfo(string id)
{
var file = await rep_SysFile.AsQueryable().FirstAsync(a => a.Id == id);
_ = file == null ? throw Oops.Oh("参数异常") : "";
var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, file.FileBucket, file.FileObjectName);
var fileName = HttpUtility.UrlEncode(file.FileOriginName?.Replace(" ", null).Replace("\"", null), Encoding.UTF8);
return new FileStreamResult(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Ewide.Core.Util.MimeMapping.GetMimeMapping(filePath)) { FileDownloadName = fileName };
//return await DownloadFileInfo(input);
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="file"></param>
/// <param name="pathType"></param>
/// <returns></returns>
private static async Task<string> UploadFile(IFormFile file, FileDescription fileOption)
{
var pathType = fileOption.path;
var mimeType = Ewide.Core.Util.MimeMapping.GetMimeMapping(file.FileName);
if (!fileOption.contentType.Contains(mimeType))
{
throw Oops.Oh("上传文件mimeType错误!");
}
var fileId = Guid.NewGuid().ToString();
var fileSizeKb = (long)(file.Length / 1024.0); // 文件大小KB
if (fileSizeKb > fileOption.maxSize)
{
throw Oops.Oh("文件大小超过最大限制!");
}
var originalFilename = file.FileName; // 文件原始名称
var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀
var finalName = fileId + fileSuffix; // 生成文件的最终名称
var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, pathType);
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
using (var stream = File.Create(Path.Combine(filePath, finalName)))
{
await file.CopyToAsync(stream);
}
var sysFileInfo = new SysFile
{
Id = fileId,
FileLocation = (int)FileLocation.LOCAL,
FileBucket = pathType,
FileObjectName = finalName,
FileOriginName = originalFilename,
FileSuffix = fileSuffix.TrimStart('.'),
FileSizeKb = fileSizeKb
};
//await rep_SysFile.InsertAsync(sysFileInfo);
await sysFileInfo.InsertAsync();
return fileId;
}
/// <summary>
/// 提交
/// </summary>
/// <returns></returns>
[Consumes("application/json", "multipart/form-data")]
[HttpPost("submit")]
[AllowAnonymous]
public async Task<dynamic> Submit([FromForm] OutsideWallInput args)
{
try
{
repoutside_wall.Ado.BeginTran();
var wall = args.Adapt<outside_wall>();
wall.Id = Guid.NewGuid().ToString();
wall.createtime = DateTime.Now;
wall.isdeleted = 0;
wall = await repoutside_wall.InsertReturnEntityAsync(wall);
if (args.fileList != null)
{
foreach (var item in args.fileList)
{
await repoutside_wall_photo.InsertReturnEntityAsync(new outside_wall_photo
{
outsidewallId = wall.Id,
sysfileid = item
});
}
}
foreach (var item in args.buildings)
{
var build = item.Adapt<outside_wall_building>();
build.Id = Guid.NewGuid().ToString();
build.outsidewallId = wall.Id;
build.BuildingId = build.Id;
build.createtime = DateTime.Now;
build = await repoutside_wall_building.InsertReturnEntityAsync(build);
if (item.problemfiles != null)
{
foreach (var item1 in item.problemfiles)
{
await repoutside_wall_building_photo.InsertReturnEntityAsync(new outside_wall_building_photo
{
outsidewallBuildingId = build.Id,
sysfileid = item1.file,
toward = item1.Toward
});
}
}
}
repoutside_wall.Ado.CommitTran();
return "提交成功";
}
catch (Exception ex)
{
repoutside_wall.Ado.RollbackTran();
throw Oops.Oh(ex.Message + ex.StackTrace);
}
//var lastSend = await repSmsCode.DetachedEntities.Where(p => p.phone == args.phone && !p.IsDeleted).OrderByDescending(a => a.CreatedTime).FirstOrDefaultAsync();
//_ = (lastSend == null || lastSend.code != args.code || lastSend.expire_time < DateTime.Now) ? throw Oops.Oh("验证码错误或已失效") : 1;
//var totalCount = await repPerson.DetachedEntities.Where(a => !a.IsDeleted && a.date == args.date).CountAsync();
//_ = totalCount >= App.GetConfig<int>("NingboZhiChun:TotalCount") ? throw Oops.Oh("提交失败,名额已满。") : 1;
//_ = (await repPerson.DetachedEntities.Where(a => !a.IsDeleted && (a.phone == args.phone || a.cardno == args.cardno)).CountAsync() > 0) ? throw Oops.Oh("您已提交,无需再次提交") : 1;
//var now = DateTime.Now;
//var model = new Entities.nbzc_person
//{
// address = args.address,
// phone = args.phone,
// cardno = args.cardno,
// CreatedTime = DateTime.Now,
// date = args.date,
// hangye = args.hangye,
// IsDeleted = false,
// line = args.line,
// name = args.name,
// weixin_number = args.weixin_number
//};
//model = await model.InsertOrUpdate();
//lastSend.IsDeleted = true;
//await repSmsCode.UpdateIncludeAsync(lastSend, new string[] { nameof(lastSend.IsDeleted) });
//var token = JWTEncryption.Encrypt(new Dictionary<string, object>() // 加密
//{
// { "UserId", model.Id },
// { "Account",model.phone }
//});
//return new { success = true, token };
return 1;
}
}
}