using Ewide.Core;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DataEncryption.Extensions;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.RemoteRequest.Extensions;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Vote.Services.Dto;
using Vote.Services.Entities;
namespace Vote.Services.ApiController
{
///
/// 外墙调查问卷
///
[ApiDescriptionSettings("outsidewall", Order = 0)]
[Route("/gb/yjb/api/outsidewall")]
public class OutsideWallService : IDynamicApiController
{
private readonly SqlSugarRepository _repoutsideExperts;
private readonly SqlSugarRepository repoutside_wall;
private readonly SqlSugarRepository repoutside_wall_building;
private readonly SqlSugarRepository repoutside_wall_building_photo;
private readonly SqlSugarRepository repoutside_wall_photo;
private readonly SqlSugarRepository rep_SysFile;
private readonly IMemoryCache _memoryCache;
readonly IOptions _options;
///
///
///
///
///
///
///
///
public OutsideWallService(SqlSugarRepository repoutsideExperts, SqlSugarRepository _repoutside_wall, SqlSugarRepository _repoutside_wall_building, SqlSugarRepository _repoutside_wall_building_photo, SqlSugarRepository _repoutside_wall_photo, IMemoryCache memoryCache, SqlSugarRepository _rep_SysFile, IOptions options)
{
_repoutsideExperts = repoutsideExperts;
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;
}
///
/// 导出Excel
///
///
[HttpPost]
[UnitOfWork]
[Route("export_excel")]
public async Task ExportExcel(OutsideWallQueryInput args)
{
var list = await QueryBuildings(args);
//var list = await repoutside_wall.AsQueryable().Where(a => !a.IsDeleted).OrderByDescending(a => a.CreatedTime).ToListAsync();
var filepath = Tools.ExcelHelper.WriteExcelOutsideWallBuilding(list);
return new FileStreamResult(new FileStream(filepath, FileMode.Open), "application/octet-stream") { FileDownloadName = filepath };
return 1;
}
[HttpPost("querybuildings")]
public async Task> QueryBuildings(OutsideWallQueryInput args)
{
var entity = await repoutside_wall_building.AsQueryable().LeftJoin((a, b) => a.outsidewallId == b.Id)
.WhereIF(!string.IsNullOrWhiteSpace(args.communityId), (a, b) => b.communityId == args.communityId)
.WhereIF(!string.IsNullOrWhiteSpace(args.submitCode), (a, b) => b.submitCode == args.submitCode)
.Select((a, b) => new OutsideWallBuildingsOutput
{
communityId = b.Id,
createtime = b.createtime,
communityName = b.communityName,
submitCode = b.submitCode,
Address = a.Address,
BuildingId = a.BuildingId,
BuildingName = a.BuildingName,
BuildingUnit = a.BuildingUnit,
ConstructionUnit = a.ConstructionUnit,
curwallproblemother = a.curwallproblemother,
curwallproblems = a.curwallproblems,
DesingerUnit = a.DesingerUnit,
diaoluowu = a.diaoluowu,
firstproblemdate = a.firstproblemdate,
MonitorUnit = a.MonitorUnit,
Households = a.Households,
Id = a.Id,
LevelCount = a.LevelCount,
outsidewallId = a.outsidewallId,
problemfanwei = a.problemfanwei,
problemfrequency = a.problemfanwei,
problemheight = a.problemheight,
problemseason = a.problemseason,
wallproblemsfirst = a.wallproblemsfirst,
wallproblemtoward = a.wallproblemtoward,
WuYeUnit = a.WuYeUnit
})
.OrderByDescending(a => a.createtime)//.OrderBy((a, b) => b.communityName)
.WithCache(60 * 60).ToListAsync();
var ids = entity.Select(a => a.Id).ToArray();
var photos = await repoutside_wall_building_photo.AsQueryable()
.Where(a => ids.Contains(a.outsidewallBuildingId)).WithCache(60 * 60).ToListAsync();
foreach (var building in entity)
{
var _ps = photos.Where(a => a.outsidewallBuildingId == building.Id).OrderBy(a => a.toward).ToList();
var _ps2 = new List();
_ps2.AddRange(_ps.Where(a => a.toward == "东"));
_ps2.AddRange(_ps.Where(a => a.toward == "西"));
_ps2.AddRange(_ps.Where(a => a.toward == "南"));
_ps2.AddRange(_ps.Where(a => a.toward == "北"));
building.outside_wall_building_photos = _ps2;
}
//var result = entity.Adapt>();
//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 entity;
}
[HttpPost("query")]
public async Task Query(OutsideWallQueryInput args)
{
//repoutside_wall.Ado.SqlQuery("")
var entity = await repoutside_wall.AsQueryable()
.WhereIF(!string.IsNullOrWhiteSpace(args.communityId), a => a.communityId == args.communityId)
.WhereIF(!string.IsNullOrWhiteSpace(args.submitCode), a => a.submitCode == args.submitCode)
.OrderByDescending(a => a.createtime).OrderBy(a => a.communityName)
.WithCache(60 * 60).ToListAsync();
var ids = entity.Select(a => a.Id).ToArray();
var photos = await repoutside_wall_photo.AsQueryable()
.Where(a => ids.Contains(a.outsidewallId)).WithCache(60 * 60).ToListAsync();
foreach (var wall in entity)
{
wall.outside_wall_photos = photos.Where(a => a.outsidewallId == wall.Id).ToList();
}
//var result = entity.Adapt>();
//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 entity;
}
[HttpPost("querybuilding")]
public async Task QueryBuilding(OutsideWallQueryBuildingInput args)
{
var entity = await repoutside_wall_building.AsQueryable().Where(a => a.outsidewallId == args.wallId).WithCache(60 * 60).ToListAsync();
var ids = entity.Select(a => a.Id).ToArray();
var photos = await repoutside_wall_building_photo.AsQueryable().Where(a => ids.Contains(a.outsidewallBuildingId)).WithCache(60 * 60).ToListAsync();
foreach (var building in entity)
{
var _ps = photos.Where(a => a.outsidewallBuildingId == building.Id).OrderBy(a => a.toward).ToList();
var _ps2 = new List();
_ps2.AddRange(_ps.Where(a => a.toward == "东"));
_ps2.AddRange(_ps.Where(a => a.toward == "西"));
_ps2.AddRange(_ps.Where(a => a.toward == "南"));
_ps2.AddRange(_ps.Where(a => a.toward == "北"));
building.outside_wall_building_photos = _ps2;
}
//var result = entity.Adapt>();
//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 entity;
}
///
/// 获取时间戳
///
///
private string GetTimeStamp()
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalMilliseconds).ToString();
}
///
/// 上传文件
///
///
///
[AllowAnonymous]
[HttpPost("sysFileInfo/upload")]
public async Task UploadFileDefault(IFormFile file)
{
return await UploadFile(file, _options.Value.Default);
}
///
/// 删除文件
///
///
///
[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);
}
///
/// 预览文件
///
///
///
[AllowAnonymous]
[HttpGet("sysFileInfo/preview/{id}")]
public async Task 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);
}
///
/// 上传文件
///
///
///
///
private static async Task 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;
}
///
/// 生成随机字母与数字
///
/// 生成长度
/// 是否要在生成前将当前线程阻止以避免重复
public string GetCode(int Length, bool Sleep)
{
if (Sleep) System.Threading.Thread.Sleep(3);
char[] Pattern = new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
string result = "";
int n = Pattern.Length;
System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks));
for (int i = 0; i < Length; i++)
{
int rnd = random.Next(0, n);
result += Pattern[rnd];
}
return result;
}
#region 调查页
///
/// 授权验证
///
///
[HttpPost("VerifyKey")]
[AllowAnonymous]
public async Task VerifyKey([FromQuery] string key)
{
return await _repoutsideExperts.IsExistsAsync(f => f.login_code.ToUpper() == key.ToUpper());
//return await Task.FromResult(false);
}
///
/// 获取三居系统中的社区
///
///
[AllowAnonymous]
[HttpGet("communitys")]
public async Task> GetCommunitys(string searchkey)
{
var cacheKey = "cache_GetCommunitys";
List Communitys = null;
Communitys = _memoryCache.Get>(cacheKey);
if (Communitys == null || Communitys.Count == 0)
{
//var aaaaaaaaaaaaaa = repoutside_wall.AsQueryable().ToList();
var SanjuKey = App.GetConfig("OutsideWallSetting:SanjuKey");
var timeStamp = GetTimeStamp();
var sign = (SanjuKey + timeStamp).ToMD5Encrypt();
var GetCommunitysUrl = App.GetConfig("OutsideWallSetting:GetCommunitys");
var GetHouseInfoCitysByCommunityUrl = App.GetConfig("OutsideWallSetting:GetHouseInfoCitysByCommunity");
Communitys = await string.Format(GetCommunitysUrl, "")
.SetHeaders(new Dictionary { { "sign", sign }, { "timeStamp", timeStamp } })
.GetAsAsync>();
_memoryCache.Set(cacheKey, Communitys, DateTime.Now.AddHours(1));
}
if (!string.IsNullOrEmpty(searchkey))
return Communitys.Where(a => a.Name.Contains(searchkey)).ToList();
return Communitys;
}
///
/// 获取三居系统中的社区
///
///
[AllowAnonymous]
[HttpGet("communitys/{id}")]
public async Task> GetCommunityInfo(string id)
{
var cacheKey = "cache_building_" + id;
List building = _memoryCache.Get>(cacheKey);
if (building == null)
{
var SanjuKey = App.GetConfig("OutsideWallSetting:SanjuKey");
var timeStamp = GetTimeStamp();
var sign = (SanjuKey + timeStamp).ToMD5Encrypt();
var GetHouseInfoCitysByCommunityUrl = App.GetConfig("OutsideWallSetting:GetHouseInfoCitysByCommunity");
building = await string.Format(GetHouseInfoCitysByCommunityUrl, id)
.SetHeaders(new Dictionary { { "sign", sign }, { "timeStamp", timeStamp } })
.GetAsAsync>();
_memoryCache.Set(cacheKey, building, DateTime.Now.AddHours(1));
}
return building;
}
///
/// 获取三居系统中的社区
///
///
[AllowAnonymous]
[HttpGet("community/{id}")]
public async Task GetCommunityInfo(string id, string querystring)
{
if (string.IsNullOrWhiteSpace(querystring))
return new List();
return (await GetCommunityInfo(id)).Where(a => a.Address.Contains(querystring)).ToList();
}
///
/// 提交
///
///
[Consumes("application/json", "multipart/form-data")]
[HttpPost("submit")]
[AllowAnonymous]
public async Task Submit([FromForm] OutsideWallInput args, [FromQuery] string key)
{
var verifyKey = await _repoutsideExperts.IsExistsAsync(f => f.login_code.ToUpper() == key.ToUpper());
if (!verifyKey)
{
throw Oops.Oh("授权码错误");
}
try
{
//string key = GetCode(6, true);
repoutside_wall.Ado.BeginTran();
var wall = args.Adapt();
wall.submitCode = key;
wall.Id = Guid.NewGuid().ToString();
wall.createtime = DateTime.Now;
wall.isdeleted = 0;
await repoutside_wall.InsertAsync(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)
{
if (!item.curwallproblems.Any())
continue;
var build = item.Adapt();
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 key;
}
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("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() // 加密
//{
// { "UserId", model.Id },
// { "Account",model.phone }
//});
//return new { success = true, token };
return 1;
}
#endregion 调查页
}
}