using Aspose.Cells;
using Aspose.Words;
using Aspose.Words.Tables;
using EyeSoft.Extensions;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using OASystem.API.OAMethodLib;
using OASystem.API.OAMethodLib.HunYuanAPI;
using OASystem.API.OAMethodLib.QiYeWeChatAPI;
using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
using OASystem.Domain.AesEncryption;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Domain.ViewModels.QiYeWeChat;
using OASystem.Infrastructure.Repositories.Groups;
using Quartz.Logging;
using Quartz.Util;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Diagnostics;
using TencentCloud.Common;
using static OASystem.API.OAMethodLib.GeneralMethod;
using static OASystem.API.OAMethodLib.JWTHelper;
using static OpenAI.GPT3.ObjectModels.Models;
namespace OASystem.API.Controllers
{
///
/// 资料相关
///
//[Authorize]
[Route("api/[controller]/[action]")]
public class ResourceController : ControllerBase
{
private readonly IMapper _mapper;
private readonly ILogger _logger;
private readonly IConfiguration _config;
private readonly IHunyuanService _hunyuanService;
private readonly IQiYeWeChatApiService _qiYeWeChatApiService;
private readonly SqlSugarClient _sqlSugar;
private readonly CarDataRepository _carDataRep;
private readonly LocalGuideDataRepository _localGuideDataRep;
private readonly ThreeCodeRepository _ThreeCodeRep;
private readonly HotelDataRepository _hotelDataRep;
private readonly ResItemInfoRepository _resItemInfoRep;
private readonly SetDataRepository _setDataRepository;
private readonly CountryFeeRepository _countryFeeRep;
private readonly SetDataTypeRepository _setDataTypeRep;
private readonly AirTicketAgentRepository _airTicketAgentRep;
private readonly InvitationOfficialActivityDataRepository _InvitationOfficialActivityDataRep;
private readonly OfficialActivitiesRepository _officialActivitiesRep;
private readonly AskDataRepository _askDataRep;
private readonly TicketBlackCodeRepository _ticketBlackCodeRep;
private readonly TourClientListRepository _tourClientListRep;
private readonly DelegationInfoRepository _delegationInfoRep;
private readonly TranslatorLibraryRepository _translatorRep;
private readonly MediaSuppliersRepository _mediaSupplierRep;
private readonly List _portIds;
private readonly BasicInsuranceCostRepository _insuranceCostRep;
private readonly GamesBudgetMasterRepository _gamesBudgetMasterRep;
private readonly OverseaVehicleRepository _overseaVehicleRep;
private readonly MaterialCostRepository _materialCostRep;
///
/// 签证费用归属省份静态数据
///
private static readonly List> _provinceData = new()
{
new(122, "四川"),
new(132, "云南"),
new(103, "重庆"),
new(108, "贵州")
};
public ResourceController(
IMapper mapper,
IConfiguration config,
ILogger logger,
IHunyuanService hunyuanService,
IQiYeWeChatApiService qiYeWeChatApiService,
SqlSugarClient sqlSugar,
CarDataRepository carDataRep,
LocalGuideDataRepository localGuideDataRep,
ThreeCodeRepository threeCodeRep,
HotelDataRepository hotelDataRep,
ResItemInfoRepository resItemInfoRep,
SetDataRepository setDataRepository,
CountryFeeRepository countryFeeRep,
SetDataTypeRepository setDataTypeRep,
AirTicketAgentRepository airTicketAgentRep,
InvitationOfficialActivityDataRepository invitationOfficialActivityDataRep,
OfficialActivitiesRepository officialActivitiesRep,
AskDataRepository askDataRep,
TicketBlackCodeRepository ticketBlackCodeRep,
TourClientListRepository tourClientListRep,
DelegationInfoRepository delegationInfoRep,
TranslatorLibraryRepository translatorRep,
MediaSuppliersRepository mediaSupplierRep,
BasicInsuranceCostRepository insuranceCostRep,
GamesBudgetMasterRepository gamesBudgetMasterRep,
OverseaVehicleRepository overseaVehicleRep,
MaterialCostRepository materialCostRep
)
{
_mapper = mapper;
_config = config;
_logger = logger;
_hunyuanService = hunyuanService;
_qiYeWeChatApiService = qiYeWeChatApiService;
_sqlSugar = sqlSugar;
_carDataRep = carDataRep;
_localGuideDataRep = localGuideDataRep;
_ThreeCodeRep = threeCodeRep;
_hotelDataRep = hotelDataRep;
_resItemInfoRep = resItemInfoRep;
_setDataRepository = setDataRepository;
_countryFeeRep = countryFeeRep;
_setDataTypeRep = setDataTypeRep;
_airTicketAgentRep = airTicketAgentRep;
_InvitationOfficialActivityDataRep = invitationOfficialActivityDataRep;
_officialActivitiesRep = officialActivitiesRep;
_askDataRep = askDataRep;
_ticketBlackCodeRep = ticketBlackCodeRep;
_tourClientListRep = tourClientListRep;
_delegationInfoRep = delegationInfoRep;
_translatorRep = translatorRep;
_mediaSupplierRep = mediaSupplierRep;
_portIds = new List { 1, 2, 3 };
_insuranceCostRep = insuranceCostRep;
_gamesBudgetMasterRep = gamesBudgetMasterRep;
_overseaVehicleRep = overseaVehicleRep;
_materialCostRep = materialCostRep;
}
#region 车公司资料板块
///
/// 车公司信息查询
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryCarData(QueryCarDataDto dto)
{
Result LocalGuide = await _carDataRep.QueryCarData(dto);
if (LocalGuide.Code == 0)
{
return Ok(JsonView(true, "查询成功", LocalGuide.Data));
}
else
{
return Ok(JsonView(false, LocalGuide.Msg));
}
}
///
/// 车公司资料下拉框数据
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryCarSelect()
{
var carData = _carDataRep.QueryDto().ToList();
if (carData.Count == 0)
{
return Ok(JsonView(false, "暂无数据!"));
}
foreach (var item in carData) EncryptionProcessor.DecryptProperties(item);
carData.Add(new CarDataSelectView { Id = 0, UnitArea = "全部" });
carData = carData.Where((x, i) => carData.FindIndex(z => z.UnitArea == x.UnitArea) == i).ToList();
carData = carData.OrderBy(x => x.Id).ToList();
var data = new List();
foreach (CarDataSelectView car in carData)
{
if (!string.IsNullOrWhiteSpace(car.UnitArea))
{
data.Add(car);
}
}
return Ok(JsonView(true, "查询成功", data));
}
///
/// 根据Id查询车公司详细数据
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QuerCarDataDetailById(QueryCarDataDetailDto dto)
{
string sql = string.Format(@" Select * From Res_CarData With(Nolock) Where Id = {0} ", dto.Id);
var info = _resItemInfoRep._sqlSugar.SqlQueryable(sql).First();
if (info == null)
{
return Ok(JsonView(false, "未找到相关数据!"));
}
EncryptionProcessor.DecryptProperties(info);
return Ok(JsonView(true, "查询成功", info));
}
///
/// 车公司信息添加
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task AddCarData(AddCarDataDto dto)
{
if (string.IsNullOrEmpty(dto.UnitArea)) return Ok(JsonView(false, "请检查单位区域是否填写!"));
if (string.IsNullOrEmpty(dto.UnitName)) return Ok(JsonView(false, "请检查单位名称是否填写!"));
if (string.IsNullOrEmpty(dto.Contact)) return Ok(JsonView(false, "请检查单位联系人是否填写!"));
if (string.IsNullOrEmpty(dto.ContactTel)) return Ok(JsonView(false, "请检查联系方式是否填写正确!"));
var carDadaInfo = _carDataRep
.QueryDto(a => a.UnitArea == dto.UnitArea &&
a.UnitName == dto.UnitName &&
a.Contact == dto.Contact &&
a.ContactTel == dto.ContactTel
)
.First();
if (carDadaInfo != null) return Ok(JsonView(false, "该信息已存在,请勿重复添加!"));
var carData = _mapper.Map(dto);
carData.LastUpdateUserId = dto.CreateUserId;
carData.LastUpdateTime = DateTime.Now;
EncryptionProcessor.EncryptProperties(carData);
int id = await _carDataRep.AddAsyncReturnId(carData);
if (id < 1) return Ok(JsonView(false, "添加失败!"));
return Ok(JsonView(true, "添加成功", new { Id = id }));
}
///
/// 车公司信息修改
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task UpCarData(UpCarDataDto dto)
{
if (string.IsNullOrEmpty(dto.UnitArea)) return Ok(JsonView(false, "请检查单位区域是否填写!"));
if (string.IsNullOrEmpty(dto.UnitName)) return Ok(JsonView(false, "请检查单位名称是否填写!"));
if (string.IsNullOrEmpty(dto.Contact)) return Ok(JsonView(false, "请检查单位联系人是否填写!"));
if (string.IsNullOrEmpty(dto.ContactTel)) return Ok(JsonView(false, "请检查联系方式是否填写正确!"));
var carData = _mapper.Map(dto);
carData.LastUpdateTime = DateTime.Now;
EncryptionProcessor.EncryptProperties(carData);
var res = await _sqlSugar.Updateable(carData)
.IgnoreColumns(x => new { x.CreateUserId, x.CreateTime, x.DeleteTime, x.DeleteUserId, x.IsDel })
.ExecuteCommandAsync();
if (res < 1) { return Ok(JsonView(false, "修改失败!")); }
return Ok(JsonView(true, "修改成功"));
}
///
/// 车公司信息删除
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelCarData(DelCarDataDto dto)
{
bool res = await _carDataRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res) { return Ok(JsonView(false, "删除失败!")); }
return Ok(JsonView(true, "删除成功"));
}
#endregion
#region 导游地接资料板块
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task LocalGuideBatchEncryption()
{
var infos = await _sqlSugar.Queryable().ToListAsync();
foreach (var item in infos) EncryptionProcessor.EncryptProperties(item);
await _sqlSugar.Updateable(infos).ExecuteCommandAsync();
return Ok(JsonView(true));
}
///
/// 导游地接资料查询
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryLocalGuide(QueryLocalGuide dto)
{
Stopwatch stopwatch = Stopwatch.StartNew();
Result LocalGuide = await _localGuideDataRep.QueryLocalGuide(dto);
if (LocalGuide.Code == 0)
{
stopwatch.Stop();
return Ok(JsonView(true, $"查询成功!耗时:{stopwatch.ElapsedMilliseconds} 毫秒", LocalGuide.Data));
}
stopwatch.Stop();
return Ok(JsonView(false, LocalGuide.Msg + $" 耗时:{stopwatch.ElapsedMilliseconds} 毫秒"));
}
///
/// 导游地接资料下拉框数据
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryLocalGuideSelect()
{
var localGuides = _carDataRep.QueryDto().ToList();
if (localGuides.Count == 0)
{
return Ok(JsonView(false, "暂无数据!"));
}
foreach (var item in localGuides) EncryptionProcessor.DecryptProperties(item);
localGuides.Add(new QueryLocalGuideSelectView { Id = 0, UnitArea = "全部" });
localGuides = localGuides.Where((x, i) => localGuides.FindIndex(z => z.UnitArea == x.UnitArea && !string.IsNullOrEmpty(z.UnitArea)) == i).ToList();
localGuides = localGuides.OrderBy(x => x.Id).ToList();
var data = new List();
foreach (QueryLocalGuideSelectView Local in localGuides)
{
if (!string.IsNullOrWhiteSpace(Local.UnitArea))
{
data.Add(Local);
}
}
return Ok(JsonView(true, "查询成功", data));
}
///
/// 根据Id查询地接详细数据
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryLocalGuideDetailById(QueryLocalGuideDetailDto dto)
{
string sql = string.Format(@" Select * From Res_LocalGuideData With(Nolock) Where Id = {0} ", dto.Id);
var info = _resItemInfoRep._sqlSugar.SqlQueryable(sql).First();
if (info == null)
{
return Ok(JsonView(false, "未找到相关数据!"));
}
EncryptionProcessor.DecryptProperties(info);
return Ok(JsonView(true, "查询成功", info));
}
///
/// 导游地接信息操作(Status:1.新增,2.修改)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OperationLocalGuide(LocalGuideOperationDto dto)
{
if (string.IsNullOrEmpty(dto.UnitArea)) return Ok(JsonView(false, "请检查单位区域是否填写!"));
if (string.IsNullOrEmpty(dto.UnitName)) return Ok(JsonView(false, "请检查单位名称是否填写!"));
if (string.IsNullOrEmpty(dto.Contact)) return Ok(JsonView(false, "请检查单位联系人是否填写!"));
if (string.IsNullOrEmpty(dto.ContactTel)) return Ok(JsonView(false, "请检查联系方式是否填写正确!"));
Result result = await _localGuideDataRep.LocalGuideOperation(dto);
if (result.Code != 0)
{
return Ok(JsonView(false, result.Msg));
}
return Ok(JsonView(true, result.Msg));
}
///
/// 导游地接信息操作(删除)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelLocalGuide(LocalGuideDelDto dto)
{
var res = await _localGuideDataRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res)
{
return Ok(JsonView(false, "删除失败"));
}
return Ok(JsonView(true, "删除成功!"));
}
#endregion
#region 机场三字码信息
///
/// 机场三字码查询
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryThreeCode(QueryThreeCodeDto dto)
{
try
{
Result LocalGuide = await _ThreeCodeRep.QueryThreeCode(dto);
if (LocalGuide.Code == 0)
{
return Ok(JsonView(true, "查询成功", LocalGuide.Data));
}
else
{
return Ok(JsonView(false, LocalGuide.Msg));
}
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 机场三字码数据城市下拉框数据
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryThreeCodeSelect()
{
try
{
var ThreeCode = _carDataRep.QueryDto().ToList();
if (ThreeCode.Count == 0)
{
return Ok(JsonView(false, "暂无数据!"));
}
ThreeCode.Add(new ThreeCodeSelectView { Id = 0, City = "全部" });
ThreeCode = ThreeCode.Where((x, i) => ThreeCode.FindIndex(z => z.City == x.City && z.City != "") == i).ToList();
ThreeCode = ThreeCode.OrderBy(x => x.Id).ToList();
List data = new List();
foreach (ThreeCodeSelectView _ThreeCode in ThreeCode)
{
if (!string.IsNullOrWhiteSpace(_ThreeCode.City))
{
data.Add(_ThreeCode);
}
}
return Ok(JsonView(true, "查询成功", data));
}
catch (Exception)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 机场三字码资料操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OperationThreeCode(ThreeCodeOperationDto dto)
{
try
{
if (dto.Three == "")
{
return Ok(JsonView(false, "请检查三字码是否填写!"));
}
if (dto.Country == "")
{
return Ok(JsonView(false, "请检查国家是否填写!"));
}
if (dto.City == "")
{
return Ok(JsonView(false, "请检查城市是否填写正确!"));
}
if (dto.AirPort == "")
{
return Ok(JsonView(false, "请检查机场是否填写正确!"));
}
Result result = await _ThreeCodeRep.ThreeCodeOperation(dto);
if (result.Code != 0)
{
return Ok(JsonView(false, result.Msg));
}
return Ok(JsonView(true, result.Msg));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 机场三字码资料操作(删除)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelThreeCode(ThreeCodeDelDto dto)
{
try
{
var res = await _ThreeCodeRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res)
{
return Ok(JsonView(false, "删除失败"));
}
return Ok(JsonView(true, "删除成功!"));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
///根据ID查询三字码信息
///
///
[HttpPost]
public IActionResult QuerySingleThreeCode(QuerySingleThreeCode dto)
{
var jw = JsonView(false);
var single = _sqlSugar.Queryable().First(x => x.Id == dto.ID && x.IsDel == 0);
if (single != null)
{
jw = JsonView(true, "获取成功!", new
{
single.Three,
Four = single.Four?.Trim(),
single.AirPort,
single.AirPort_En,
single.City,
single.Country,
single.Remark
});
}
else
{
jw.Msg = "暂无!";
}
return Ok(jw);
}
#endregion
#region 代理出票合作方资料
///
/// 代理出票合作方资料
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryAirTicketAgent(DtoBase dto)
{
var res_AirTicketAgents = _airTicketAgentRep.Query(a => a.IsDel == 0).ToList();
if (res_AirTicketAgents.Count > 1)
{
res_AirTicketAgents = res_AirTicketAgents.OrderByDescending(a => a.CreateTime).ToList();
if (dto.PageSize == 0 && dto.PageIndex == 0)
{
foreach (var item in res_AirTicketAgents) EncryptionProcessor.DecryptProperties(item);
return Ok(JsonView(true, "查询成功!", res_AirTicketAgents));
}
else
{
int count = res_AirTicketAgents.Count;
float totalPage = (float)count / dto.PageSize;//总页数
if (totalPage == 0) totalPage = 1;
else totalPage = (int)Math.Ceiling((double)totalPage);
var _AirTicketAgent = new List();
for (int i = 0; i < dto.PageSize; i++)
{
var RowIndex = i + (dto.PageIndex - 1) * dto.PageSize;
if (RowIndex < res_AirTicketAgents.Count)
{
EncryptionProcessor.DecryptProperties(res_AirTicketAgents[RowIndex]);
_AirTicketAgent.Add(res_AirTicketAgents[RowIndex]);
}
else break;
}
return Ok(JsonView(true, "查询成功!", new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = _AirTicketAgent }));
}
}
return Ok(JsonView(false, "暂无数据!"));
}
///
/// 代理出票合作方资料操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OpAirTicketAgent(OpAirTicketAgentDto dto)
{
if (string.IsNullOrEmpty(dto.Account)) return Ok(JsonView(false, "请检查代理商账户是否填写!"));
if (string.IsNullOrEmpty(dto.Bank)) return Ok(JsonView(false, "请检查代理商银行是否填写!"));
if (string.IsNullOrEmpty(dto.Name)) return Ok(JsonView(false, "请检查代理商名称是否填写正确!"));
Result result = await _airTicketAgentRep.OpAirTicketAgent(dto);
if (result.Code != 0) return Ok(JsonView(false, result.Msg));
return Ok(JsonView(true, result.Msg));
}
///
/// 代理出票合作方资料操作(删除)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelAirTicketAgent(DelBaseDto dto)
{
var res = await _airTicketAgentRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res) return Ok(JsonView(false, "删除失败"));
return Ok(JsonView(true, "删除成功!"));
}
#endregion
#region 酒店资料数据
///
/// 酒店信息查询 Page
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryHotelData(QueryHotelDataDto dto)
{
string sqlWhere = string.Empty;
if (!string.IsNullOrWhiteSpace(dto.Name))
{
sqlWhere += string.Format(@" And hd.Name like '%{0}%'", AesEncryptionHelper.Encrypt(dto.Name));
}
if (!string.IsNullOrWhiteSpace(dto.City) && dto.City != "全部")
{
sqlWhere += string.Format(@" And hd.City like '%{0}%'", AesEncryptionHelper.Encrypt(dto.City));
}
if (!string.IsNullOrWhiteSpace(dto.Contact))
{
sqlWhere += string.Format(@" And hd.Contact like '%{0}%'", AesEncryptionHelper.Encrypt(dto.Contact));
}
if (!string.IsNullOrWhiteSpace(dto.ContactPhone))
{
sqlWhere += string.Format(@" And hd.ContactPhone like '%{0}%'", AesEncryptionHelper.Encrypt(dto.ContactPhone));
}
sqlWhere += string.Format(@" And hd.IsDel={0}", 0);
if (!string.IsNullOrEmpty(sqlWhere.Trim()))
{
Regex r = new Regex("And");
sqlWhere = r.Replace(sqlWhere, "Where", 1);
}
string sql = string.Format(@"SELECT
*
FROM
(
SELECT
ROW_NUMBER() OVER (
ORDER BY
hd.CreateTime DESC
) AS Row_Number,
hd.Id,
hd.City,
hd.[Name],
hd.Tel,
hd.Fax,
hd.Contact,
hd.ContactPhone,
u.CnName AS CreateUserName,
hd.CreateTime
FROM
Res_HotelData hd
WITH
(NoLock)
LEFT JOIN Sys_Users u
WITH
(NoLock) ON hd.CreateUserId = u.Id {0}
) Temp
", sqlWhere);
if (dto.PortType == 1)
{
var HotelDataData = await _sqlSugar.SqlQueryable(sql).ToListAsync();
if (HotelDataData.Count == 0)
{
return Ok(JsonView(false, "暂无数据"));
}
foreach (var item in HotelDataData)
{
EncryptionProcessor.DecryptProperties(item);
}
return Ok(JsonView(true, "操作成功", HotelDataData));
}
else if (dto.PortType == 2 || dto.PortType == 3)
{
RefAsync total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
var data = await _sqlSugar.SqlQueryable(sql).ToPageListAsync(dto.PageIndex, dto.PageSize, total); //ToPageAsync
foreach (var item in data) EncryptionProcessor.DecryptProperties(item);
return Ok(JsonView(true, "操作成功", data, total));
}
else return Ok(JsonView(false, "请传入PortType参数!1:Web,2:Android,3:IOS"));
}
///
/// 酒店资料
/// 详情
/// add time:2024-05-14 11:57:10
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryHotelDataInfo(QueryHotelDataInfoDto dto)
{
var _view = await _hotelDataRep._Info(dto.PortType, dto.Id);
if (_view.Code == 0)
{
return Ok(JsonView(true, _view.Msg, _view.Data));
}
return Ok(JsonView(false, _view.Msg));
}
///
/// 酒店资料下拉框数据
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryHotelDataSelect()
{
try
{
var HotelData = _carDataRep.QueryDto().ToList();
if (HotelData.Count == 0)
{
return Ok(JsonView(false, "暂无数据!"));
}
//解密
foreach (var item in HotelData)
{
EncryptionProcessor.DecryptProperties(item);
}
HotelData.Add(new QueryHotelDataSelect { Id = 0, City = "全部" });
HotelData = HotelData.Where((x, i) => HotelData.FindIndex(z => z.City == x.City && z.City != "") == i).ToList();
HotelData = HotelData.OrderBy(x => x.Id).ToList();
var data = new List();
foreach (var Hotel in HotelData)
{
if (!string.IsNullOrWhiteSpace(Hotel.City))
{
data.Add(Hotel);
}
}
return Ok(JsonView(true, "查询成功", data));
}
catch (Exception)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 酒店资料操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OperationHotelData(OperationHotelDto dto)
{
if (string.IsNullOrEmpty(dto.City)) return Ok(JsonView(false, "请检查酒店所在城市是否填写!"));
if (string.IsNullOrEmpty(dto.Name)) return Ok(JsonView(false, "请检查酒店名称是否填写!"));
if (string.IsNullOrEmpty(dto.Address)) return Ok(JsonView(false, "请检查酒店地址是否填写正确!"));
if (string.IsNullOrEmpty(dto.Tel)) return Ok(JsonView(false, "请检查酒店联系方式是否填写正确!"));
Result result = await _hotelDataRep.OperationHotelData(dto);
if (result.Code != 0) return Ok(JsonView(false, result.Msg));
return Ok(JsonView(true, result.Msg));
}
///
/// 酒店资料操作(删除)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelHotelData(DelHotelDataDto dto)
{
try
{
var res = await _hotelDataRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res)
{
return Ok(JsonView(false, "删除失败"));
}
return Ok(JsonView(true, "删除成功!"));
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
#endregion
#region 签证费用资料
///
/// 签证费用资料查询
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryCountryFeeCost(DtoBase dto)
{
var portType = dto.PortType;
if (portType != 1 && portType != 2 && portType != 3)
return Ok(JsonView(false, "请传入PortType参数!1:Web,2:Android,3:IOS"));
var countryVisaFees = await _countryFeeRep
.QueryDto()
.OrderByDescending(x => x.CreateTime)
.ToListAsync();
if (countryVisaFees == null || countryVisaFees.Count == 0)
return Ok(JsonView(false, "暂无数据!"));
return Ok(JsonView(true, "查询成功", countryVisaFees));
}
///
/// 签证费用资料查询 Page New
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryVisaCountryFeeCosts(QueryVisaCountryFeeCostsDto dto)
{
// 校验端口类型
if (dto.PortType != 1 && dto.PortType != 2 && dto.PortType != 3)
return Ok(JsonView(false, "请传入PortType参数!1:Web,2:Android,3:IOS"));
var portType = dto.PortType;
RefAsync total = 0;
var query = _countryFeeRep._sqlSugar
.Queryable()
.Where(x => x.IsDel == 0)
.WhereIF(dto.VisaFeeType >= 0, x => x.VisaFeeType == dto.VisaFeeType)
.WhereIF(!string.IsNullOrEmpty(dto.CountryName), x => x.VisaCountry.Contains(dto.CountryName))
.OrderByDescending(x => x.CreateTime);
var countryVisaFees = await query.ToPageListAsync(dto.PageIndex, dto.PageSize, total);
if (!countryVisaFees.Any()) return Ok(JsonView(true, "暂无数据!"));
var view = _mapper.Map>(countryVisaFees);
return Ok(JsonView(true, "查询成功", view, total));
}
///
/// 签证费用资料操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OperationCountryFeeCost(OperationCountryFeeCostDto dto)
{
if (string.IsNullOrWhiteSpace(dto.VisaContinent) || string.IsNullOrWhiteSpace(dto.VisaCountry))
return Ok(JsonView(false, "请检查州名和国家名是否填写!"));
return Ok(await _countryFeeRep.OperationCountryFeeCost(dto));
}
///
/// 签证费用资料操作(删除)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelCountryFeeCost(DelCountryFeeCostDto dto)
{
var res = await _countryFeeRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res) return Ok(JsonView(false, "删除失败"));
return Ok(JsonView(true, "删除成功!"));
}
#endregion
#region 签证费用资料 New
///
/// 签证费用标准 Init
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task VisaFeeStandardInit()
{
//签证费用类型数据
var visaFeeTypeData = new List>
{
new(0, "因公"),
new(1, "因私")
};
//签证费用归属省份
var data = new
{
VisaFeeType = visaFeeTypeData.Select(x => new { Id = x.Key, Text = x.Value }),
Province = _provinceData.Select(x => new { Id = x.Key, Text = x.Value })
};
return Ok(JsonView(data));
}
///
/// 签证费用标准 Info
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task VisaFeeStandardInfo(VisaFeeStandardInfoDto dto)
{
var portType = dto.PortType;
if (portType != 1 && portType != 2 && portType != 3)
return Ok(JsonView(false, "请传入PortType参数!1:Web,2:Android,3:IOS"));
return Ok(await _countryFeeRep.InfoAsync(dto.Id));
}
///
/// 签证费用标准 List
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task VisaFeeStandardList(VisaFeeStandardListDto dto)
{
return Ok(await _countryFeeRep.PageListAsync(dto));
}
///
/// 签证费用标准 Save
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task VisaFeeStandardSave(VisaFeeStandardSaveDto dto)
{
return Ok(await _countryFeeRep.SaveAsync(dto));
}
///
/// 签证费用标准 SoftDel
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task VisaFeeStandardSoftDel(VisaFeeStandardSoftDelDto dto)
{
return Ok(await _countryFeeRep.SoftDelAsync(dto.CurrUserId, dto.Id));
}
///
/// 根据省份获取签证费用报价
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task VisaFeeQuoteByProvince(VisaFeesByProvinceDto dto)
{
//省份验证
var provinceIds = _provinceData.Select(x => x.Key).ToList();
if (!provinceIds.Contains(dto.ProvinceId))
{
return Ok(JsonView(false, "请选择有效的省份!"));
}
return Ok(await _countryFeeRep.VisaFeeQuoteAsync(dto.ProvinceId, dto.CountryName));
}
#endregion
#region 物料信息、供应商维护
#region 供应商
///
/// 物料供应商查询
///
/// Json序列化
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostSearchItemVendor(JsonDtoBase _jsonDto)
{
if (string.IsNullOrEmpty(_jsonDto.Paras))
{
return Ok(JsonView(false, "参数为空"));
}
Search_ResItemVendorDto _ItemVendorDto = System.Text.Json.JsonSerializer.Deserialize(_jsonDto.Paras);
if (_ItemVendorDto != null)
{
if (_ItemVendorDto.SearchType == 2) //获取列表
{
Res_ItemVendorListView rstList = _resItemInfoRep.GetVendorList(_ItemVendorDto);
return Ok(rstList);
}
else
{
Res_ItemVendorView rstInfo = _resItemInfoRep.getVendorInfo(_ItemVendorDto);
return Ok(rstInfo);
}
}
else
{
return Ok(JsonView(false, "参数反序列化失败"));
}
//return Ok(JsonView(false));
}
///
/// 创建/编辑/删除供应商信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostEditItemVendor(Edit_ResItemVendorDto _dto)
{
bool rst = false;
if (_dto.EditType >= 0)
{
if (string.IsNullOrEmpty(_dto.VendorFullName))
{
return Ok(JsonView(false, "全称未填写"));
}
if (string.IsNullOrEmpty(_dto.VendorLinker))
{
return Ok(JsonView(false, "联系人未填写"));
}
if (string.IsNullOrEmpty(_dto.VendorMobile))
{
return Ok(JsonView(false, "联系人手机号未填写"));
}
if (string.IsNullOrEmpty(_dto.BusRange))
{
return Ok(JsonView(false, "经营范围未选择"));
}
if (_dto.EditType == 0)
{
var checkEmpty = _resItemInfoRep.Query(s => s.FullName == _dto.VendorFullName).First();
if (checkEmpty != null)
{
return Ok(JsonView(false, "已存在同名供应商"));
}
rst = await _resItemInfoRep.addVendorInfo(_dto);
}
else if (_dto.EditType == 1)
{
if (_dto.VendorId > 0)
{
Res_ItemVendor _entity = _mapper.Map(_dto);
rst = await _resItemInfoRep.updVendorInfo(_entity);
}
else
{
return Ok(JsonView(false, "供应商不存在"));
}
}
}
else
{
if (_dto.VendorId < 1 || _dto.SysUserId < 1)
{
return Ok(JsonView(false, "用户Id或供应商Id不存在"));
}
Res_ItemVendor _entity = _mapper.Map(_dto);
rst = await _resItemInfoRep.delVendorInfo(_entity);
}
return Ok(JsonView(rst));
}
#endregion
#region 物料信息
///
/// 物料信息查询
///
/// Json序列化
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostSearchItemInfo(string paras)
{
if (string.IsNullOrEmpty(paras))
{
return Ok(JsonView(false, "参数为空"));
}
Search_ItemInfoDto _ItemInfoDto = System.Text.Json.JsonSerializer.Deserialize(paras);
if (_ItemInfoDto != null)
{
if (_ItemInfoDto.SearchType == 2) //获取列表
{
Res_ItemInfoListView rstList = _resItemInfoRep.GetItemList(_ItemInfoDto);
return Ok(rstList);
}
else
{
Res_ItemInfoView rstInfo = _resItemInfoRep.getItemInfo(_ItemInfoDto);
return Ok(rstInfo);
}
}
else
{
return Ok(JsonView(false, "参数反序列化失败"));
}
//return Ok(JsonView(false));
}
///
/// 创建/编辑/删除物料信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostEditItemInfo(Edit_ResItemInfoDto _dto)
{
bool rst = false;
if (_dto.EditType >= 0)
{
if (_dto.VendorId < 1)
{
return Ok(JsonView(false, "未选择供应商"));
}
if (string.IsNullOrEmpty(_dto.ItemName))
{
return Ok(JsonView(false, "物料名称为空"));
}
if (_dto.ItemTypeId < 1)
{
return Ok(JsonView(false, "未选择物料类型"));
}
if (_dto.SysUserId < 1)
{
return Ok(JsonView(false, "当前操作用户Id为空"));
}
if (_dto.CurrRate <= 0)
{
return Ok(JsonView(false, "物料录入价格不能小于等于0"));
}
if (_dto.EditType == 0)
{
//判断物料名称、类型、供应商全部重复
var checkEmpty = _resItemInfoRep.Query(s => s.ItemName == _dto.ItemName && s.ItemTypeId == _dto.ItemTypeId && s.VendorId == _dto.VendorId).First();
if (checkEmpty != null)
{
return Ok(JsonView(false, "已存在重复物料信息"));
}
Res_ItemDetailInfo _entity = _mapper.Map(_dto);
DateTime dtNow = DateTime.Now;
_entity.CreateUserId = _dto.SysUserId;
_entity.IsDel = 0;
_entity.MaxRate = _dto.CurrRate;
_entity.MaxDt = dtNow;
_entity.CurrRate = _dto.CurrRate;
_entity.CurrDt = dtNow;
_entity.MinRate = _dto.CurrRate;
_entity.MinDt = dtNow;
rst = await _resItemInfoRep.AddAsync(_entity) > 0;
}
else if (_dto.EditType == 1)
{
if (_dto.ItemId > 0)
{
Res_ItemDetailInfo _entity = _mapper.Map(_dto);
_entity.Id = _dto.ItemId;
rst = await _resItemInfoRep.updItemInfo(_entity);
}
else
{
return Ok(JsonView(false, "供应商不存在"));
}
}
}
else
{
if (_dto.ItemId < 1 || _dto.SysUserId < 1)
{
return Ok(JsonView(false, "用户Id或物料信息Id不存在"));
}
Res_ItemDetailInfo _entity = _mapper.Map(_dto);
rst = await _resItemInfoRep.delItemInfo(_entity);
}
return Ok(JsonView(rst));
}
#endregion
#region 物料类型获取
#endregion
#endregion
#region 备忘录
///
/// 备忘录查询
///
/// Json序列化
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostSearchMemo(JsonDtoBase _jsonDto)
{
if (string.IsNullOrEmpty(_jsonDto.Paras))
{
return Ok(JsonView(false, "参数为空"));
}
Search_ResMemoDto _memoDto = JsonConvert.DeserializeObject(_jsonDto.Paras);
if (_memoDto != null)
{
if (_memoDto.SearchType == 2)
{
//获取列表
string sqlWhere = string.Format(" Where IsDel=0 ");
#region SqlWhere
if (!string.IsNullOrEmpty(_memoDto.Abstracts))
{
sqlWhere += string.Format(@" And m.Abstracts Like '%{0}%' ", _memoDto.Abstracts);
}
if (!string.IsNullOrEmpty(_memoDto.Title))
{
sqlWhere += string.Format(@" And m.Title Like '%{0}%' ", _memoDto.Title);
}
if (_memoDto.ReadLevel > 0)
{
sqlWhere += string.Format(@" And m.ReadLevel = {0} ", _memoDto.ReadLevel);
}
#endregion
int currPIndex = (((_memoDto.PageIndex > 0) ? (_memoDto.PageIndex - 1) : 0) * _memoDto.PageSize) + 1;
int currPSize = (((_memoDto.PageIndex > 0) ? (_memoDto.PageIndex - 1) : 0) + 1) * _memoDto.PageSize;
string sql = string.Format(@" Select * From(Select ROW_NUMBER() Over(order By m.Id desc) as RowNumber,
m.Id as MemoId,d.DepName as DepartmentName,m.ReadLevel,m.Title,m.Abstracts,
m.LastedEditDt,m.LastedEditorId
From Res_Memo as m With(Nolock) Inner Join Sys_Users as u With(Nolock) On m.CreateUserId=u.Id
Inner Join Sys_Department as d With(Nolock) On u.DepId=d.Id {2}
) as tb Where tb.RowNumber Between {0} And {1} ", currPIndex, currPSize, sqlWhere);
Res_MemoListView rst = new Res_MemoListView();
rst.CurrPageIndex = currPIndex;
rst.CurrPageSize = currPSize;
List dataSource = _carDataRep._sqlSugar.SqlQueryable(sql).ToList();
Dictionary userDic = new Dictionary();
foreach (var item in dataSource)
{
if (userDic.ContainsKey(item.LastedEditorId))
{
item.LastedEditor = userDic[item.LastedEditorId];
}
else
{
var _sysUser = _carDataRep.Query(s => s.Id == item.LastedEditorId).First();
userDic[item.LastedEditorId] = _sysUser.CnName;
item.LastedEditor = _sysUser.CnName;
}
}
rst.DataList = new List(dataSource);
if (rst.DataList.Count > 0)
{
string sqlCount = string.Format(@" Select Id From Res_Memo as m With(Nolock) {0} ", sqlWhere);
int dataCount = _carDataRep._sqlSugar.SqlQueryable(sqlCount).Count();
rst.DataCount = dataCount;
}
return Ok(JsonView(rst));
}
else
{
//获取对象
string sqlSingle = string.Format(@" Select
m.Id as MemoId,d.DepName as DepartmentName,m.ReadLevel,m.Title,m.Abstracts,
m.LastedEditDt,m.LastedEditor,m.MDFilePath
From Res_Memo as m With(Nolock) Inner Join Sys_Users as u With(Nolock) On m.CreateUserId=u.Id
Inner Join Sys_Department as d With(Nolock) On u.DepId=d.Id Where m.Id={0} ", _memoDto.MemoId);
Res_MemoView _result = _carDataRep._sqlSugar.SqlQueryable(sqlSingle).First();
if (_result != null)
{
var _sysUser = _carDataRep.Query(s => s.Id == _result.LastedEditorId).First();
_result.LastedEditor = _sysUser.CnName;
_result.MarkDownContent = new IOOperatorHelper().Read(_result.MDFilePath);
return Ok(JsonView(_result));
}
}
}
else
{
return Ok(JsonView(false, "参数反序列化失败"));
}
return Ok(JsonView(false));
}
///
/// 创建/编辑/删除备忘录信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostEditMemo(Edit_ResMemoDto _dto)
{
bool rst = false;
if (_dto.SysUserId < 1)
{
return Ok(JsonView(false, "操作人失效"));
}
var _sysUser = _resItemInfoRep.Query(s => s.Id == _dto.SysUserId).First();
if (_sysUser == null)
{
return Ok(JsonView(false, "操作人失效02"));
}
if (_dto.EditType >= 0)
{
if (_dto.ReadLevel < 1)
{
return Ok(JsonView(false, "未知的阅读等级"));
}
if (string.IsNullOrEmpty(_dto.Title.Trim()))
{
return Ok(JsonView(false, "标题不能为空"));
}
if (string.IsNullOrEmpty(_dto.Content.Trim()))
{
return Ok(JsonView(false, "正文内容不能为空"));
}
//新增备忘录
DateTime dtNow = DateTime.Now;
string dir = AppSettingsHelper.Get("MemoCurrPath");
string fileName = dtNow.ToString("yyyyMMddHHmmss") + _dto.Title + ".md";
string content = JsonConvert.SerializeObject(_dto.Content);
if (_dto.EditType == 0)//新增
{
string savePath = new IOOperatorHelper().Write_CoverFile(content, dir, fileName);
if (savePath.Length > 0)
{
Res_MemoInfo _insert = new Res_MemoInfo();
_insert.Abstracts = _dto.Abstracts;
_insert.Title = _dto.Title;
_insert.DepartmentId = _sysUser.DepId;
_insert.CreateUserId = _sysUser.Id;
_insert.LastedEditDt = dtNow;
_insert.LastedEditor = _sysUser.Id;
_insert.MDFilePath = savePath;
_insert.ReadLevel = _dto.ReadLevel;
_insert.Title = _dto.Title;
int result = await _resItemInfoRep.AddAsync(_insert);
return Ok(JsonView(result > 0));
}
else
{
return Ok(JsonView(false, "路径保存失败"));
}
}
else//修改
{
if (_dto.MemoId < 1)
{
return Ok(JsonView(false, "MemoId不存在"));
}
Res_MemoInfo _source = _resItemInfoRep.Query(s => s.Id == _dto.MemoId).First();
if (_source == null)
{
return Ok(JsonView(false, "MemoInfo不存在"));
}
//修改
string sourcePath = _source.MDFilePath;
string recycDir = AppSettingsHelper.Get("MemoRecycleBinPath");
new IOOperatorHelper().MoveFile(sourcePath, recycDir);
string savePath = new IOOperatorHelper().Write_CoverFile(content, dir, fileName);
if (savePath.Length > 0)
{
var result = await _resItemInfoRep._sqlSugar.Updateable()
.SetColumns(it => it.LastedEditDt == DateTime.Now)
.SetColumns(it => it.LastedEditor == _sysUser.Id)
.SetColumns(it => it.Abstracts == _dto.Abstracts)
.SetColumns(it => it.MDFilePath == savePath)
.SetColumns(it => it.ReadLevel == _dto.ReadLevel)
.SetColumns(it => it.Title == _dto.Title)
.Where(s => s.Id == _source.Id)
.ExecuteCommandAsync();
return Ok(JsonView(result > 0));
}
}
}
else
{
//删除
if (_dto.MemoId < 1)
{
return Ok(JsonView(false, "MemoId不存在"));
}
Res_MemoInfo _source = _resItemInfoRep.Query(s => s.Id == _dto.MemoId).First();
if (_source == null)
{
return Ok(JsonView(false, "MemoInfo不存在"));
}
//修改
string sourcePath = _source.MDFilePath;
string recycDir = AppSettingsHelper.Get("MemoRecycleBinPath");
new IOOperatorHelper().MoveFile(sourcePath, recycDir);
var result = await _resItemInfoRep._sqlSugar.Updateable()
.SetColumns(it => it.IsDel == 1)
.SetColumns(it => it.DeleteUserId == _sysUser.Id)
.SetColumns(it => it.DeleteTime == DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
.Where(s => s.Id == _source.Id)
.ExecuteCommandAsync();
return Ok(JsonView(result > 0));
}
return Ok(JsonView(rst));
}
#endregion
#region 商邀资料
///
/// 商邀资料 基础数据源
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryIOAInitData(QueryIOAInitDataDto dto)
{
#region 参数验证
if (dto.PortType < 1) return Ok(JsonView(false, "请传入有效的PortType参数!"));
#endregion
var ExcludedKeyStr = new string[] { "快递费" };
var ClientKeyStr = new string[] { "邀请函翻译" };
List _DelegationInfos = _sqlSugar.Queryable().Where(it => it.IsDel == 0).OrderByDescending(it => it.JietuanTime).ToList();
List _ioaDatas = _sqlSugar.Queryable()
.Where(it => it.IsDel == 0)
.Select(x => new Res_InvitationOfficialActivityData
{
Country = x.Country,
UnitName = x.UnitName,
Contact = x.Contact,
Field = x.Field,
})
.ToList();
foreach (var item in _ioaDatas)
{
EncryptionProcessor.DecryptProperties(item);
}
foreach (var item in ExcludedKeyStr)
{
_ioaDatas = _ioaDatas.Where(x => string.IsNullOrWhiteSpace(x.UnitName) || !x.UnitName.Contains(item)).ToList();
}
foreach (var item in ClientKeyStr)
{
_ioaDatas = _ioaDatas.Where(x => string.IsNullOrWhiteSpace(x.Contact) || !x.Contact.Contains(item)).ToList();
}
List _Users = _sqlSugar.Queryable().Where(it => it.IsDel == 0).ToList();
var _countryData = _ioaDatas.Select(it => it.Country).Distinct().ToList(); _countryData.Remove("");
var _inviterData = _ioaDatas.Select(it => it.UnitName).Distinct().ToList(); _inviterData.Remove("");
var _contactData = _ioaDatas.Select(it => it.Contact).Distinct().ToList(); _contactData.Remove("");
var _domainData = _ioaDatas.Select(it => it.Field).Distinct().ToList(); _domainData.Remove("");
var _groupNameData = _DelegationInfos.Select(it => new { it.Id, it.TeamName }).ToList();
var _userNameData = _Users.Select(it => new { it.Id, it.CnName }).ToList();
var _data = new
{
CountryData = _countryData,
InviterData = _inviterData,
DomainData = _domainData,
ContactData = _contactData,
GroupNameData = _groupNameData,
UserNameData = _userNameData,
};
return Ok(JsonView(true, $"查询成功!", _data));
}
///
/// 商邀资料查询
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryInvitationOfficialActivityData(QueryInvitationOfficialActivityDataDto dto)
{
var ExcludedKeyStr = new string[] { "快递费" };
var ClientKeyStr = new string[] { "邀请函翻译" };
var columns = "Id,UnitName,Contact,City";
try
{
#region 参数验证
if (dto.PageIndex < 1) return Ok(JsonView(false, "请传入有效的PageIndex参数!"));
if (dto.PageSize < 1) return Ok(JsonView(false, "请传入有效的PageSize参数!"));
#endregion
//string sqlWhere = string.Empty;
if (!string.IsNullOrWhiteSpace(dto.Country)) { columns += ",Country"; }
//if (!string.IsNullOrWhiteSpace(dto.UnitName)) { columns += ",UnitName"; }
//if (!string.IsNullOrWhiteSpace(dto.Contact)) { columns += ",Contact"; }
if (!string.IsNullOrWhiteSpace(dto.Delegation)) { columns += ",Delegation"; }
if (!string.IsNullOrWhiteSpace(dto.Field)) { columns += ",Field"; }
//if (dto.CreateUserId != 0 && !string.IsNullOrWhiteSpace(dto.CreateUserId.ToString())) { columns += ",CreateUserId"; }
//if (!string.IsNullOrWhiteSpace(dto.StartCreateTime) && !string.IsNullOrWhiteSpace(dto.EndCreateTime))
//{
// columns += ",CreateUserId";
//}
DateTime endTime = new DateTime();
var InvitationOfficialActivityDataList = _sqlSugar.Queryable()
.Where(x => x.IsDel == 0)
.WhereIF(dto.CreateUserId != 0 && !string.IsNullOrWhiteSpace(dto.CreateUserId.ToString()), x => x.CreateUserId == dto.CreateUserId)
.WhereIF(DateTime.TryParse(dto.StartCreateTime, out DateTime startTime) && DateTime.TryParse(dto.EndCreateTime, out endTime), x => x.CreateTime >= startTime && x.CreateTime <= endTime)
.Select(columns)
.ToList();
foreach (var item in InvitationOfficialActivityDataList)
{
EncryptionProcessor.DecryptProperties(item);
}
InvitationOfficialActivityDataList = InvitationOfficialActivityDataList
.WhereIF(!string.IsNullOrWhiteSpace(dto.Country), x => (!string.IsNullOrWhiteSpace(x.Country) && x.Country.Contains(dto.Country)) || (!string.IsNullOrWhiteSpace(x.City) && x.City.Contains(dto.Country)))
.WhereIF(!string.IsNullOrWhiteSpace(dto.UnitName), x => !string.IsNullOrWhiteSpace(x.UnitName) && x.UnitName.Contains(dto.UnitName))
.WhereIF(!string.IsNullOrWhiteSpace(dto.Contact), x => !string.IsNullOrWhiteSpace(x.Contact) && x.Contact.Contains(dto.Contact))
.WhereIF(!string.IsNullOrWhiteSpace(dto.Delegation), x => !string.IsNullOrWhiteSpace(x.Delegation) && x.Delegation.Contains(dto.Delegation))
.WhereIF(!string.IsNullOrWhiteSpace(dto.Field), x => !string.IsNullOrWhiteSpace(x.Field) && x.Field.Contains(dto.Field))
.ToList();
foreach (var item in ExcludedKeyStr)
{
InvitationOfficialActivityDataList = InvitationOfficialActivityDataList.Where(x => string.IsNullOrWhiteSpace(x.UnitName) || !x.UnitName.Contains(item)).ToList();
//sqlWhere += $" And i.UnitName not like '%{item}%' ";
}
foreach (var item in ClientKeyStr)
{
InvitationOfficialActivityDataList = InvitationOfficialActivityDataList.Where(x => string.IsNullOrWhiteSpace(x.Contact) || !x.Contact.Contains(item)).ToList();
//sqlWhere += $" And i.Contact not like '%{item}%' ";
}
var ids = InvitationOfficialActivityDataList.Select(x => x.Id);
RefAsync totalCount = 0;
var _ivitiesViews = await _sqlSugar.Queryable()
.LeftJoin((a, b) => b.IsDel == 0 && a.CreateUserId == b.Id)
.Where((a, b) => ids.Contains(a.Id))
.OrderByDescending((a, b) => a.CreateTime)
.Select((a, b) => new InvitationOfficialActivityDataView
{
FaceBook = a.FaceBook,
Id = a.Id,
CreateUserId = a.CreateUserId,
IsDel = 0,
Address = a.Address,
Background = a.Background,
City = a.City,
Contact = a.Contact,
Country = a.Country,
CreateTime = a.CreateTime,
CreateUserName = b.CnName,
Delegation = a.Delegation,
Email = a.Email,
Fax = a.Fax,
Field = a.Field,
FilePath = a.FilePath,
Ins = a.Ins,
WeChat = a.WeChat,
UnitWeb = a.UnitWeb,
UnitName = a.UnitName,
UnitInfo = a.UnitInfo,
Tel = a.Tel,
SndFilePath = a.SndFilePath,
SndFileName = a.SndFileName,
Remark = a.Remark,
OtherInfo = a.OtherInfo,
Job = a.Job
})
.ToPageListAsync(dto.PageIndex, dto.PageSize, totalCount);
var allGroupIds = new HashSet();
foreach (var item in _ivitiesViews)
{
EncryptionProcessor.DecryptProperties(item);
if (!string.IsNullOrEmpty(item.Delegation))
{
allGroupIds.UnionWith(item.Delegation.Split(',').Select(x =>
{
int id;
if (int.TryParse(x, out id)) return id;
return 0;
}).Where(id => id != 0));
}
}
var _DelegationInfos = _sqlSugar.Queryable()
.Where(x => allGroupIds.Contains(x.Id) && x.IsDel == 0)
.ToList()
.GroupBy(x => x.Id)
.ToDictionary(group => group.Key, group => group.Select(g => g.TeamName));
foreach (var item in _ivitiesViews)
{
string groupNameStr = "";
if (!string.IsNullOrEmpty(item.Delegation))
{
var groupIds = item.Delegation.Split(',').Select(x =>
{
int id;
if (int.TryParse(x, out id)) return id;
return 0;
})
.Where(id => id != 0)
.ToArray();
foreach (var id in groupIds)
{
if (_DelegationInfos.ContainsKey(id))
{
groupNameStr += string.Join("", _DelegationInfos[id]) + ",";
}
}
if (groupNameStr.Length > 1)
{
groupNameStr = groupNameStr.Substring(0, groupNameStr.Length - 1);
}
}
item.DelegationStr = groupNameStr;
}
return Ok(JsonView(true, $"查询成功!", _ivitiesViews, totalCount));
}
catch (Exception ex)
{
return Ok(JsonView(false, ex.Message));
}
}
///
/// 商邀资料查询-欧洲
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryInvitationOfficialActivityData1()
{
try
{
// 定义欧洲国家数组
string[] europeanCountries = {
// 北欧国家
"瑞典", "芬兰", "挪威", "丹麦", "冰岛",
// 西欧国家
"英国", "爱尔兰", "法国", "荷兰", "比利时", "卢森堡", "摩纳哥",
// 中欧国家
"德国", "瑞士", "奥地利", "波兰", "捷克", "斯洛伐克", "匈牙利", "列支敦士登",
// 南欧国家
"意大利", "西班牙", "葡萄牙", "希腊", "马耳他", "圣马力诺", "梵蒂冈", "安道尔",
"克罗地亚", "斯洛文尼亚", "波斯尼亚和黑塞哥维那", "黑山", "塞尔维亚", "北马其顿", "阿尔巴尼亚", "保加利亚", "罗马尼亚",
// 东欧国家
"俄罗斯", "乌克兰", "白俄罗斯", "摩尔多瓦", "爱沙尼亚", "拉脱维亚", "立陶宛"
};
var InvitationOfficialActivityDataList = _sqlSugar.Queryable()
.Where(x => x.IsDel == 0)
.Select(x => new Res_InvitationOfficialActivityData() { Id = x.Id, Country = x.Country })
.ToList();
foreach (var item in InvitationOfficialActivityDataList)
{
EncryptionProcessor.DecryptProperties(item);
}
var ids = InvitationOfficialActivityDataList
.WhereIF(europeanCountries.Any(), x => !string.IsNullOrWhiteSpace(x.Country) && europeanCountries.Contains(x.Country))
.Select(x => x.Id)
.ToList();
RefAsync totalCount = 0;
var _ivitiesViews = await _sqlSugar.Queryable()
.LeftJoin((a, b) => b.IsDel == 0 && a.CreateUserId == b.Id)
.Where((a, b) => ids.Contains(a.Id))
.OrderByDescending((a, b) => a.CreateTime)
.Select((a, b) => new InvitationOfficialActivityDataView1
{
Country = a.Country,
City = a.City,
UnitName = a.UnitName,
Field = a.Field,
Address = a.Address,
UnitInfo = a.UnitInfo,
Delegation = a.Delegation,
OtherInfo = a.OtherInfo
})
.ToListAsync();
var allGroupIds = new HashSet();
foreach (var item in _ivitiesViews)
{
EncryptionProcessor.DecryptProperties(item);
if (!string.IsNullOrEmpty(item.Delegation))
{
allGroupIds.UnionWith(item.Delegation.Split(',').Select(x =>
{
int id;
if (int.TryParse(x, out id)) return id;
return 0;
}).Where(id => id != 0));
}
}
var _DelegationInfos = _sqlSugar.Queryable()
.Where(x => allGroupIds.Contains(x.Id) && x.IsDel == 0)
.ToList()
.GroupBy(x => x.Id)
.ToDictionary(group => group.Key, group => group.Select(g => g.TeamName));
foreach (var item in _ivitiesViews)
{
string groupNameStr = "";
if (!string.IsNullOrEmpty(item.Delegation))
{
var groupIds = item.Delegation.Split(',').Select(x =>
{
int id;
if (int.TryParse(x, out id)) return id;
return 0;
})
.Where(id => id != 0)
.ToArray();
foreach (var id in groupIds)
{
if (_DelegationInfos.ContainsKey(id))
{
groupNameStr += string.Join("", _DelegationInfos[id]) + ",";
}
}
if (groupNameStr.Length > 1)
{
groupNameStr = groupNameStr.Substring(0, groupNameStr.Length - 1);
}
}
item.DelegationStr = groupNameStr;
}
//获取模板
string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/商邀资料模板.xls");
var designer = new WorkbookDesigner();
designer.Workbook = new Workbook(tempPath);
var dt = CommonFun.ToDataTableArray(_ivitiesViews);
dt.TableName = $"OADataView";
designer.SetDataSource(dt);
designer.Process();
//文件名
string fileName = $"商邀资料{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "InvitationOfficialActivityExport/" + fileName);
string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/InvitationOfficialActivityExport/" + fileName;
return Ok(JsonView(true, "成功", url));
}
catch (Exception ex)
{
return Ok(JsonView(false, ex.Message));
}
}
//[HttpPost]
//public IActionResult EncipherInvitationOfficialActivityData()
//{
// var jw = JsonView(false);
// var List_DB = _sqlSugar.Queryable().ToList();
// try
// {
// //foreach (var item in List_DB)
// //{
// // EncryptionProcessor.DecryptProperties(item);
// //}
// _sqlSugar.BeginTran();
// foreach (var item in List_DB)
// {
// EncryptionProcessor.EncryptProperties(item);
// }
// var updateRow = _sqlSugar.Updateable(List_DB).ExecuteCommand();
// jw = JsonView(true, "success", "修改行数:" + updateRow);
// _sqlSugar.CommitTran();
// }
// catch (Exception ex)
// {
// _sqlSugar.RollbackTran();
// jw.Msg = ex.Message;
// }
// return Ok(jw);
//}
///
/// 根据商邀资料Id查询信息
///
///
///
[HttpGet("{id}")]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryInvitationOfficialActivityById(int id)
{
if (id < 1) return Ok(JsonView(false, "Id参数错误!"));
return Ok(await _InvitationOfficialActivityDataRep.Info(id));
}
///
/// 商邀资料操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OpInvitationOfficialActivity([FromForm] OpInvitationOfficialActivityDto dto)
{
return Ok(await _InvitationOfficialActivityDataRep.IOA_OP(dto));
}
///
/// 商邀资料 删除文件
///
///
///
///
[HttpDelete("{id}")]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivityDelFile(int id, string fileName)
{
if (id < 1) return Ok(JsonView(false, "请传入有效的Id"));
if (string.IsNullOrEmpty(fileName)) return Ok(JsonView(false, "文件名称不能为空!"));
var info = await _sqlSugar.Queryable().FirstAsync(x => x.Id == id);
if (info == null) return Ok(JsonView(false, "该条数据不存在!"));
var files = new List();
try
{
files = JsonConvert.DeserializeObject>(info.SndFileName);
}
catch (Exception) { }
if (files != null && files.Count > 0 && files.Contains(fileName))
{
var filePath = $@"{AppSettingsHelper.Get("GrpFileBasePath")}/商邀相关文件/{fileName}";
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
//更改文件值
files.Remove(fileName);
var fileUpd = await _sqlSugar.Updateable()
.SetColumns(x => x.SndFileName == JsonConvert.SerializeObject(files))
.Where(x => x.Id == id)
.ExecuteCommandAsync();
if (fileUpd > 0) return Ok(JsonView(true, "操作成功!"));
}
return Ok(JsonView(false, "操作失败!"));
}
///
/// 删除商邀资料信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelInvitationOfficialActivity(DelBaseDto dto)
{
var res = await _InvitationOfficialActivityDataRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res) return Ok(JsonView(false, "删除失败"));
var info = await _sqlSugar.Queryable().FirstAsync(x => x.Id == dto.Id);
if (info == null) return Ok(JsonView(false, "该条数据不存在!"));
var files = new List();
try
{
files = JsonConvert.DeserializeObject>(info.SndFileName);
}
catch (Exception) { }
if (files != null && files.Count > 0)
{
foreach (var fileName in files)
{
var filePath = $@"{AppSettingsHelper.Get("GrpFileBasePath")}/商邀相关文件/{fileName}";
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
}
}
return Ok(JsonView(true, "删除成功!"));
}
///
/// 商邀资料 ExcelExport
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivityExcelExport(QueryInvitationOfficialActivityDataDto dto)
{
var ExcludedKeyStr = new string[] { "快递费" };
var ClientKeyStr = new string[] { "邀请函翻译" };
var columns = "Id,UnitName,Contact";
#region 参数验证
if (dto.PageIndex < 1) return Ok(JsonView(false, "请传入有效的PageIndex参数!"));
if (dto.PageSize < 1) return Ok(JsonView(false, "请传入有效的PageSize参数!"));
#endregion
if (!string.IsNullOrWhiteSpace(dto.Country)) { columns += ",Country"; }
if (!string.IsNullOrWhiteSpace(dto.Delegation)) { columns += ",Delegation"; }
if (!string.IsNullOrWhiteSpace(dto.Field)) { columns += ",Field"; }
DateTime endTime = new DateTime();
var InvitationOfficialActivityDataList = _sqlSugar.Queryable()
.Where(x => x.IsDel == 0)
.WhereIF(dto.CreateUserId != 0 && !string.IsNullOrWhiteSpace(dto.CreateUserId.ToString()), x => x.CreateUserId == dto.CreateUserId)
.WhereIF(DateTime.TryParse(dto.StartCreateTime, out DateTime startTime) && DateTime.TryParse(dto.EndCreateTime, out endTime), x => x.CreateTime >= startTime && x.CreateTime <= endTime)
.Select(columns)
.ToList();
foreach (var item in InvitationOfficialActivityDataList)
{
EncryptionProcessor.DecryptProperties(item);
}
InvitationOfficialActivityDataList = InvitationOfficialActivityDataList
.WhereIF(!string.IsNullOrWhiteSpace(dto.Country), x => !string.IsNullOrWhiteSpace(x.Country) && x.Country.Contains(dto.Country))
.WhereIF(!string.IsNullOrWhiteSpace(dto.UnitName), x => !string.IsNullOrWhiteSpace(x.UnitName) && x.UnitName.Contains(dto.UnitName))
.WhereIF(!string.IsNullOrWhiteSpace(dto.Contact), x => !string.IsNullOrWhiteSpace(x.Contact) && x.Contact.Contains(dto.Contact))
.WhereIF(!string.IsNullOrWhiteSpace(dto.Delegation), x => !string.IsNullOrWhiteSpace(x.Delegation) && x.Delegation.Contains(dto.Delegation))
.WhereIF(!string.IsNullOrWhiteSpace(dto.Field), x => !string.IsNullOrWhiteSpace(x.Field) && x.Field.Contains(dto.Field))
.ToList();
foreach (var item in ExcludedKeyStr)
{
InvitationOfficialActivityDataList = InvitationOfficialActivityDataList.Where(x => string.IsNullOrWhiteSpace(x.UnitName) || !x.UnitName.Contains(item)).ToList();
//sqlWhere += $" And i.UnitName not like '%{item}%' ";
}
foreach (var item in ClientKeyStr)
{
InvitationOfficialActivityDataList = InvitationOfficialActivityDataList.Where(x => string.IsNullOrWhiteSpace(x.Contact) || !x.Contact.Contains(item)).ToList();
//sqlWhere += $" And i.Contact not like '%{item}%' ";
}
var ids = InvitationOfficialActivityDataList.Select(x => x.Id);
var _ivitiesViews = await _sqlSugar.Queryable()
.LeftJoin((a, b) => b.IsDel == 0 && a.CreateUserId == b.Id)
.Where((a, b) => ids.Contains(a.Id))
.OrderByDescending((a, b) => a.CreateTime)
.Select((a, b) => new IOAInfoView
{
FaceBook = a.FaceBook,
Id = a.Id,
Address = a.Address,
Background = a.Background,
City = a.City,
Contact = a.Contact,
Country = a.Country,
Delegation = a.Delegation,
Email = a.Email,
Fax = a.Fax,
Field = a.Field,
Ins = a.Ins,
WeChat = a.WeChat,
UnitWeb = a.UnitWeb,
UnitName = a.UnitName,
UnitInfo = a.UnitInfo,
Tel = a.Tel,
SndFileName = a.SndFileName,
Remark = a.Remark,
OtherInfo = a.OtherInfo,
Job = a.Job
})
.ToListAsync();
if (!_ivitiesViews.Any()) return Ok(JsonView(false, $"您查询的数据暂无内容,不可导出!"));
var allGroupIds = new HashSet();
foreach (var item in _ivitiesViews)
{
EncryptionProcessor.DecryptProperties(item);
if (!string.IsNullOrEmpty(item.Delegation))
{
allGroupIds.UnionWith(
item.Delegation.Split(',')
.Select(x =>
{
int id;
if (int.TryParse(x, out id)) return id;
return 0;
})
.Where(id => id != 0)
);
}
}
var _DelegationInfos = _sqlSugar.Queryable()
.Where(x => allGroupIds.Contains(x.Id) && x.IsDel == 0)
.ToList()
.GroupBy(x => x.Id)
.ToDictionary(group => group.Key, group => group.Select(g => g.TeamName));
foreach (var item in _ivitiesViews)
{
string groupNameStr = "";
if (!string.IsNullOrEmpty(item.Delegation))
{
var groupIds = item.Delegation.Split(',').Select(x =>
{
int id;
if (int.TryParse(x, out id)) return id;
return 0;
})
.Where(id => id != 0)
.ToArray();
foreach (var id in groupIds)
{
if (_DelegationInfos.ContainsKey(id))
{
groupNameStr += string.Join("", _DelegationInfos[id]) + ",";
}
}
if (groupNameStr.Length > 1)
{
groupNameStr = groupNameStr.Substring(0, groupNameStr.Length - 1);
}
}
item.DelegationStr = groupNameStr;
}
//获取模板
string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/商邀资料模板.xls");
var designer = new WorkbookDesigner();
designer.Workbook = new Workbook(tempPath);
var dt = CommonFun.ToDataTableArray(_ivitiesViews);
dt.TableName = $"OADataView";
designer.SetDataSource(dt);
designer.Process();
//文件名
string fileName = $"商邀资料{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "InvitationOfficialActivityExport/" + fileName);
string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/InvitationOfficialActivityExport/" + fileName;
return Ok(JsonView(true, "成功", url));
}
///
/// 商邀资料 导入文件(Excel)模板下载
///
///
[HttpGet]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivityExcelTemplateExport()
{
//获取模板
string fileName = $"商邀资料上传文件模板.xls";
string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/Template/" + fileName;
return Ok(JsonView(true, "成功", url));
}
///
/// 商邀资料 上传Excel文件添加
///
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationOfficialActivityExcelUpload(IFormFile file, int currUserId)
{
var fileName = file.FileName;
var filePostfix = fileName.Split(".")[1].ToUpper();
if (!filePostfix.Contains("XLS")) return Ok(JsonView(false, $"请传入Excel文件"));
if (file.Length < 1) return Ok(JsonView(false, $"请传入有效的文件"));
if (currUserId < 1) return Ok(JsonView(false, $"请传入有效的UserId"));
//保存文件
string fileDirPath = string.Format(@"{0}InvitationOfficialActivityExcelUpload/", AppSettingsHelper.Get("ExcelBasePath"));
if (!Directory.Exists(fileDirPath))
{
Directory.CreateDirectory(fileDirPath);
}
var filePath = Path.Combine(fileDirPath, fileName);
await using var stream = new FileStream(filePath, FileMode.Create);
await file.CopyToAsync(stream);
//读取保存的文件
Workbook workbook = new Workbook(filePath);
if (workbook == null) return Ok(JsonView(false, $"Excel文件不存在!"));
Worksheet worksheet = workbook.Worksheets[0];
if (worksheet == null) return Ok(JsonView(false, $"Excel文件工作簿不存在!"));
var infos = new List();
var groupNames = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.TeamName)).Select(x => new { x.Id, x.TeamName }).ToListAsync();
for (int row = 1; row < worksheet.Cells.MaxDataRow + 1; row++)
{
var groupIdsLabel = string.Empty;
var groupNames1 = worksheet.Cells[row, 14].StringValue ?? "-";
if (!string.IsNullOrEmpty(groupNames1))
{
if (groupNames1.Contains(";"))
{
var groupNameArray = groupNames1.Split(";").Where(x => !string.IsNullOrEmpty(x)).ToList();
var groupIds = groupNames.Where(x => groupNameArray.Contains(x.TeamName)).Select(x => x.Id).ToList();
if (groupIds.Any()) groupIdsLabel = string.Join(',', groupIds);
}
else groupIdsLabel = groupNames.Where(x => groupNames1.Equals(x.TeamName)).FirstOrDefault()?.Id.ToString() ?? string.Empty;
}
infos.Add(new Res_InvitationOfficialActivityData()
{
Country = worksheet.Cells[row, 0].StringValue ?? "-",
City = worksheet.Cells[row, 1].StringValue ?? "-",
UnitName = worksheet.Cells[row, 2].StringValue ?? "-",
Field = worksheet.Cells[row, 3].StringValue ?? "-",
Address = worksheet.Cells[row, 4].StringValue ?? "-",
UnitInfo = worksheet.Cells[row, 5].StringValue ?? "-",
Contact = worksheet.Cells[row, 6].StringValue ?? "-",
Job = worksheet.Cells[row, 7].StringValue ?? "-",
Tel = worksheet.Cells[row, 8].StringValue ?? "-",
Email = worksheet.Cells[row, 9].StringValue ?? "-",
WeChat = worksheet.Cells[row, 10].StringValue ?? "-",
FaceBook = worksheet.Cells[row, 11].StringValue ?? "-",
Ins = worksheet.Cells[row, 12].StringValue ?? "-",
Fax = worksheet.Cells[row, 13].StringValue ?? "-",
Delegation = groupIdsLabel,
SndFilePath = worksheet.Cells[row, 15].StringValue ?? "-",
OtherInfo = worksheet.Cells[row, 16].StringValue ?? "-",
Remark = $"[{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] Excel上传文件添加! 文件存储地址[{filePath}]",
CreateUserId = currUserId,
IsDel = 0
});
}
//加密
foreach (var item in infos) EncryptionProcessor.EncryptProperties(item);
var addCount = await _sqlSugar.Insertable(infos).ExecuteCommandAsync();
if (addCount < 1) return Ok(JsonView(false, "文件上传添加失败!"));
return Ok(JsonView(true, $"上传文件添加成功!共添加{addCount}条!"));
}
#endregion
#region 商邀资料 AI
///
/// 商邀资料AI 基础数据源
///
///
[HttpGet]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAIInit()
{
var itemNames = await GeneralMethod.InvitationAIInvName();
var unitNames = await GeneralMethod.InvitationAIClientName();
var countries = await GeneralMethod.InvitationAICountryName();
return Ok(JsonView(true, $"查询成功!", new
{
itemNames,
unitNames,
countries
}));
}
///
/// 商邀资料AI 资料列表
///
///
[HttpGet("{name}")]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAIItemByName(string name)
{
// 基础校验
if (string.IsNullOrWhiteSpace(name))
return Ok(JsonView(false, "请传入有效的名称!"));
var info = await _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 && x.InvName == name)
.FirstAsync();
if (info == null)
{
return Ok(JsonView(true, $"暂无数据",new {
Id = 0,
GroupId= 0,
InvName = "",
AiCrawledDetails = new List(),
}));
}
var view = new
{
info.Id,
info.InvName,
info.GroupId,
info.AiCrawledDetails,
Entry = info.EntryInfo,
};
return Ok(JsonView(true, $"查询成功!", view));
}
///
/// 商邀资料AI 混元AI查询资料
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAISearch(InvitationAISearchDto dto)
{
var invAiInfo = await _sqlSugar.Queryable().Where(x => x.Id == dto.Id).FirstAsync();
if (invAiInfo == null || invAiInfo?.EntryInfo == null)
{
return Ok(JsonView(false, "请先设置关键字信息!"));
}
var entryInfo = invAiInfo.EntryInfo;
// 当前企业领域
string industryFocus = string.Empty;
// 动态计算 AI 需求缺口
int totalTarget = entryInfo.NeedCount;
// 词条
string question = string.Empty;
string operatorName = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == dto.CurrUserId).Select(x => x.CnName).FirstAsync() ?? "-";
var localInvDatas = new List(); // 本地数据源(商邀资料)
#region 本地数据源(商邀资料)
var rawData = await _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 && x.Country.Equals(entryInfo.TargetCountry))
.ToListAsync();
// 解密
localInvDatas = rawData.AsParallel().AsOrdered().Select(item => new InvitationAIInfo
{
Guid = Guid.NewGuid().ToString("N"),
Source = 0, // 明确来源标识
Region = entryInfo.OriginUnit,
NameCn = AesEncryptionHelper.Decrypt(item.UnitName),
Address = AesEncryptionHelper.Decrypt(item.Address),
Scope = AesEncryptionHelper.Decrypt(item.Field),
Contact = AesEncryptionHelper.Decrypt(item.Contact),
Phone = AesEncryptionHelper.Decrypt(item.Tel),
Email = AesEncryptionHelper.Decrypt(item.Email),
OperatedAt = DateTime.Now,
Operator = operatorName,
}).ToList();
#endregion
#region 混元AI 获取商邀资料
var hunyuanAIInvDatas = new List();
int aiNeedCount = Math.Max(0, totalTarget - localInvDatas.Count);
if (aiNeedCount > 0)
{
question = @$"# [SYSTEM_CONTEXT]
- Role: Senior Business Consultant (Global Supply Chain & Cross-border Trade Expert)
- Framework: S.P.A.R. (Situation-Problem-Action-Result)
- Target Architecture: .NET 6 DTO Compatible Interface
# [INPUT_CONFIG]
- OriginUnit: {{{entryInfo.OriginUnit}}}
- TargetCountry: {{{entryInfo.TargetCountry}}}
- Objective: {{{entryInfo.Objective}}}
- DataCount: {{{aiNeedCount}}}
- OtherConstraints: {{{entryInfo.OtherConstraints}}}
# [ROLE_DEFINITION]
你是一位精通全球跨境经贸、海外园区政策及 {{TargetCountry}} 本地准入法规的【顶级商务咨询顾问】。你擅长通过“产业链对等原则(Chain-Parity Principle)”为跨国企业精准匹配具备落地价值的合作伙伴。
# [BUSINESS_LOGIC_CoT]
在生成结果前,请严格执行以下思维链拆解:
1. **EntityProfiling**: 识别 {{OriginUnit}} 的核心生态位(如:Supply/Demand/Capital/Logistics)。
2. **ParityMatching**: 检索 {{TargetCountry}} 境内业务闭环对等机构(例如:若 Origin 为分销,则 Target 为源头工厂/种植园)。
3. **RegulatoryCheck**: 验证目标机构的合规性(如:GACC 备案、SPS 协议、或当地政府特许经营权)。
4. **DataSynthesis**: 针对无法直接获取的动态(如 PostUrl),优先检索其官网 News 频道或 LinkedIn 企业号。
# [CONSTRAINTS_&_STANDARDS]
- **NamingConvention**: 所有 JSON Key 必须严格遵循 **PascalCase**(例如:`UnitNameCn` 而非 `unit_name_cn`)。
- **DataIntegrity**:
- 必须输出精确的 {{DataCount}} 条记录。
- 优先级:Core (核心机构) > Backup (关联替代机构)。
- **ValidationRules**:
- `Phone`: 必须包含 {{TargetCountry}} 国际区号(如 +856, +66 等)。
- `IntgAdvice`: 必须包含“对等性分析”,解释该机构如何与 {{OriginUnit}} 形成业务闭环(50-100字)。
- `Status`: 若字段确实无法获取,统一填充 'N/A',禁止编造。
- **Safety**: 确保推荐机构不涉及敏感黑名单或已破产企业。
# [INFORMATION_SCHEMA]
请将结果填充至以下结构的 JSON 数组中:
- NameCn: 单位名称(中文)
- NameEn: 单位名称(英文)
- Address: 详细地理位置(含省市区街道)
- Scope: 经营范围(需强调其出口配额、生产能力或行业地位)
- Contact: 联系人姓名及职务
- Phone: 拨打全号(含区号)
- Email: 商务联络邮箱
- SiteUrl: 官方网站或权威社媒主页
- PostUrl: 近一年内的商务动态/新闻链接
- RecLevel: 推荐等级(枚举值:Core, Backup)
- IntgAdvice: 对接深度建议(基于产业链交合、互补逻辑)
# [OUTPUT_PROTOCOL]
- 仅输出一个标准的 JSON Array 字符串。
- 严禁任何 Markdown 说明文字、代码块之外的解释或开场白。
- 确保 JSON 语法在 .NET `JsonSerializer.Deserialize` 下可直接解析。
# [EXECUTION]
根据以上配置,开始生成。";
string response = string.Empty;
try
{
response = await _hunyuanService.ChatCompletionsHunyuan_t1_latestAsync(question);
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "网络连接失败,无法调用混元API");
return Ok(JsonView(false, $"网络连接异常,请检查网络后重试!Ex:{ex.Message}"));
}
catch (TaskCanceledException ex)
{
_logger.LogError(ex, "请求超时");
return Ok(JsonView(false, $"AI 响应超时,请稍后再试!Ex:{ex.Message}"));
}
catch (TencentCloudSDKException ex)
{
// 记录完整日志
_logger.LogError(ex, "腾讯云API调用失败 | 错误码: {ErrorCode} | 请求ID: {RequestId}", ex.ErrorCode, ex.RequestId);
// 根据错误码做差异化处理
if (ex.ErrorCode != null && ex.ErrorCode == "AuthFailure.SignatureExpire")
{
return Ok(JsonView(false, $"系统时间异常,请同步时间后重试!Ex:{ex.Message}"));
}
else if (ex.ErrorCode != null && ex.ErrorCode.StartsWith("Unauthorized"))
{
return Ok(JsonView(false, $"当前账号无权限访问该服务!Ex:{ex.Message}"));
}
else
{
return Ok(JsonView(false, $"腾讯云服务调用失败,请稍后重试!Ex:{ex.Message}"));
}
}
catch (Exception ex)
{
_logger.LogError(ex, "未知错误,调用混元API失败");
return Ok(JsonView(false, $"未知错误,调用混元API失败!Ex:{ex.Message}"));
}
if (!string.IsNullOrWhiteSpace(response))
{
// 预处理:过滤 AI 可能返回的 Markdown 标记
string cleanJson = response.Trim();
if (cleanJson.StartsWith("```json"))
cleanJson = cleanJson.Substring(7, cleanJson.Length - 10).Trim();
else if (cleanJson.StartsWith("```"))
cleanJson = cleanJson.Substring(3, cleanJson.Length - 6).Trim();
try
{
// 解析并注入 Source 标识
hunyuanAIInvDatas = JsonConvert.DeserializeObject>(cleanJson);
if (hunyuanAIInvDatas != null)
{
hunyuanAIInvDatas = hunyuanAIInvDatas.Select(x =>
{
x.Guid = Guid.NewGuid().ToString("N");
x.Source = 1;
x.Region = entryInfo.TargetCountry;
x.Operator = operatorName;
x.OperatedAt = DateTime.Now;
return x;
}).ToList();
}
}
catch (JsonException ex)
{
// 记录日志并考虑 fallback 策略
_logger.LogError(ex, "Hunyuan AI 响应解析失败。原始数据:{Response}", response);
}
}
}
#endregion
#region 数据库操作
// 数据整合 (高效合并)
var finalResult = localInvDatas.Concat(hunyuanAIInvDatas).ToList();
string invName = $"{entryInfo.OriginUnit}拜访{entryInfo.TargetCountry}";
invAiInfo.AiCrawledDetails = finalResult;
var update = await _sqlSugar.Updateable(invAiInfo).ExecuteCommandAsync();
if (update < 1)
{
return Ok(JsonView(false, $"数据更新失败!"));
}
#endregion
return Ok(JsonView(true, $"查询成功!", new
{
invAiInfo.Id,
invAiInfo.InvName,
invAiInfo.GroupId,
invAiInfo.AiCrawledDetails,
Entry = invAiInfo.EntryInfo
}));
}
///
/// 商邀资料AI 设置词条
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAISetPrompt(InvitationAISetPromptDto dto)
{
// 基础校验
if (string.IsNullOrWhiteSpace(dto.OriginUnit) || string.IsNullOrWhiteSpace(dto.TargetCountry))
return Ok(JsonView(false, "请传入有效的单位名称和国家!"));
var groupInfo = await _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 && x.Id == dto.GroupId)
.Select(x => new { x.TeamName, x.VisitPurpose })
.FirstAsync();
string invName = $"{dto.OriginUnit}拜访{dto.TargetCountry}";
#region 数据库操作
// 数据库信息获取方式
// 1.通过团组 GroupId 关联查询
var dataInfo = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.GroupId == dto.GroupId).FirstAsync();
// 2.通过InvName 关联查询(考虑到可能存在同名情况,优先使用 GroupId 关联查询,确保数据准确性)
dataInfo ??= await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.InvName == invName).FirstAsync();
#region 词条信息
string operatorName = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == dto.CurrUserId).Select(x => x.CnName).FirstAsync() ?? "-";
var entryInfo = new EntryInfo()
{
OriginUnit = dto.OriginUnit,
TargetCountry = dto.TargetCountry,
Objective = groupInfo?.VisitPurpose ?? "商务考察与合作对接",
OtherConstraints = dto.OtherConstraints,
Operator = operatorName,
OperatedAt = DateTime.Now
};
#endregion
// 3.如果以上两种方式都没有查询到数据,则说明是新数据,需要添加到数据库
if (dataInfo == null)
{
// 3.1 新数据,需要添加到数据库
dataInfo = new Res_InvitationAI()
{
InvName = groupInfo?.TeamName ?? invName, //默认团组名称
GroupId = dto.GroupId,
EntryInfo = entryInfo,
CreateUserId = dto.CurrUserId
};
var insert = await _sqlSugar.Insertable(dataInfo).ExecuteCommandAsync();
if (insert < 1)
{
return Ok(JsonView(false, $"词条信息新增失败!"));
}
}
else
{
// 3.2 数据存在 则更新数据(覆盖原有的AI爬取详情,保留原有的其他字段不变)
dataInfo.EntryInfo = entryInfo;
var update = await _sqlSugar.Updateable(dataInfo).ExecuteCommandAsync();
if (update < 1)
{
return Ok(JsonView(false, $"词条信息更新失败!"));
}
}
#endregion
return Ok(JsonView(true, $"设置成功!", new
{
dataInfo.Id,
dataInfo.InvName,
dataInfo.GroupId,
Entry = dataInfo.EntryInfo,
}));
}
///
/// 商邀资料AI 保存
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAISave(InvitationAISaveDto dto)
{
if (dto.Id < 1) return Ok(JsonView(false, "请选择保存的团组"));
if (dto.CurrUserId < 1) return Ok(JsonView(false, "请传入用户Id"));
if (dto.AiCrawledDetail == null) return Ok(JsonView(false, "请选择保存的邀请方详情"));
var invAiInfo = await _sqlSugar.Queryable()
.Where(x => x.Id == dto.Id)
.FirstAsync();
if (invAiInfo == null) return Ok(JsonView(false, "数据信息为空"));
var dataList = invAiInfo?.AiCrawledDetails;
if (dataList == null) return Ok(JsonView(false, "邀请方数据信息为空"));
var datas = dataList.Where(x => x.Guid != dto.AiCrawledDetail.Guid).ToList();
var editInfo = dto.AiCrawledDetail;
var opUserName = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == dto.CurrUserId).Select(x => x.CnName).FirstAsync() ?? "-";
editInfo.Operator = opUserName;
editInfo.OperatedAt = DateTime.Now;
datas.Add(editInfo);
invAiInfo.AiCrawledDetails = datas;
var editUpd = await _sqlSugar.Updateable(invAiInfo).UpdateColumns(x => x.AiCrawledDetails).ExecuteCommandAsync();
if (editUpd < 1)
{
return Ok(JsonView(true, "保存失败"));
}
return Ok(JsonView(true, "保存成功"));
}
///
/// 商邀资料AI 单条删除
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAISingleDel(InvitationAISingleDelDto dto)
{
int id = dto.Id;
string guid = dto.Guid;
// 基础校验
if (id < 1 || string.IsNullOrWhiteSpace(guid))
return Ok(JsonView(false, "请传入有效的Id和Guid!"));
var dataInfo = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == id).FirstAsync();
if (dataInfo == null)
return Ok(JsonView(false, "当前数据信息不存在!"));
var newDataInfos = dataInfo.AiCrawledDetails.Where(x => x.Guid != guid).ToList();
dataInfo.AiCrawledDetails = newDataInfos;
var update = await _sqlSugar.Updateable(dataInfo).ExecuteCommandAsync();
if (update < 1)
{
return Ok(JsonView(false, $"删除失败!"));
}
return Ok(JsonView(true, $"删除成功!", new
{
dataInfo.Id,
dataInfo.InvName,
dataInfo.GroupId,
dataInfo.AiCrawledDetails
}));
}
///
/// 商邀资料AI 混元AI续写
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAICompleteText(InvitationAICompleteTextDto dto)
{
var invAiInfo = await _sqlSugar.Queryable().Where(x => x.Id == dto.Id).FirstAsync();
if (invAiInfo == null || invAiInfo?.EntryInfo == null)
{
return Ok(JsonView(false, "请先设置关键字信息!"));
}
var entryInfo = invAiInfo.EntryInfo;
// 已搜索出的数据(AI 数据源)
var hunyuanAIDatas = invAiInfo.AiCrawledDetails.Where(x => x.Source == 1).ToList() ?? new List();
// 当前企业领域
string industryFocus = string.Empty;
// 动态计算 AI 需求缺口
int totalTarget = entryInfo.NeedCount;
// 词条
string question = string.Empty;
string operatorName = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == dto.CurrUserId).Select(x => x.CnName).FirstAsync() ?? "-";
#region 混元AI 获取商邀资料
var hunyuanAIInvDatas = new List();
int aiNeedCount = Math.Max(0, totalTarget - hunyuanAIDatas.Count);
// 已存在数据名称整理
var existingNames = new HashSet(hunyuanAIDatas.Select(x => x.NameCn));
entryInfo.OtherConstraints = $"请基于以下已存在的名称列表进行推荐,避免重复:{string.Join(", ", existingNames)}。{entryInfo.OtherConstraints}";
if (aiNeedCount > 0)
{
question = @$"# [SYSTEM_CONTEXT]
- Role: Senior Business Consultant (Global Supply Chain & Cross-border Trade Expert)
- Framework: S.P.A.R. (Situation-Problem-Action-Result)
- Target Architecture: .NET 6 DTO Compatible Interface
# [INPUT_CONFIG]
- OriginUnit: {{{entryInfo.OriginUnit}}}
- TargetCountry: {{{entryInfo.TargetCountry}}}
- Objective: {{{entryInfo.Objective}}}
- DataCount: {{{aiNeedCount}}}
- OtherConstraints: {{{entryInfo.OtherConstraints}}}
# [ROLE_DEFINITION]
你是一位精通全球跨境经贸、海外园区政策及 {{TargetCountry}} 本地准入法规的【顶级商务咨询顾问】。你擅长通过“产业链对等原则(Chain-Parity Principle)”为跨国企业精准匹配具备落地价值的合作伙伴。
# [BUSINESS_LOGIC_CoT]
在生成结果前,请严格执行以下思维链拆解:
1. **EntityProfiling**: 识别 {{OriginUnit}} 的核心生态位(如:Supply/Demand/Capital/Logistics)。
2. **ParityMatching**: 检索 {{TargetCountry}} 境内业务闭环对等机构(例如:若 Origin 为分销,则 Target 为源头工厂/种植园)。
3. **RegulatoryCheck**: 验证目标机构的合规性(如:GACC 备案、SPS 协议、或当地政府特许经营权)。
4. **DataSynthesis**: 针对无法直接获取的动态(如 PostUrl),优先检索其官网 News 频道或 LinkedIn 企业号。
# [CONSTRAINTS_&_STANDARDS]
- **NamingConvention**: 所有 JSON Key 必须严格遵循 **PascalCase**(例如:`UnitNameCn` 而非 `unit_name_cn`)。
- **DataIntegrity**:
- 必须输出精确的 {{DataCount}} 条记录。
- 优先级:Core (核心机构) > Backup (关联替代机构)。
- **ValidationRules**:
- `Phone`: 必须包含 {{TargetCountry}} 国际区号(如 +856, +66 等)。
- `IntgAdvice`: 必须包含“对等性分析”,解释该机构如何与 {{OriginUnit}} 形成业务闭环(50-100字)。
- `Status`: 若字段确实无法获取,统一填充 'N/A',禁止编造。
- **Safety**: 确保推荐机构不涉及敏感黑名单或已破产企业。
# [INFORMATION_SCHEMA]
请将结果填充至以下结构的 JSON 数组中:
- NameCn: 单位名称(中文)
- NameEn: 单位名称(英文)
- Address: 详细地理位置(含省市区街道)
- Scope: 经营范围(需强调其出口配额、生产能力或行业地位)
- Contact: 联系人姓名及职务
- Phone: 拨打全号(含区号)
- Email: 商务联络邮箱
- SiteUrl: 官方网站或权威社媒主页
- PostUrl: 近一年内的商务动态/新闻链接
- RecLevel: 推荐等级(枚举值:Core, Backup)
- IntgAdvice: 对接深度建议(基于产业链交合、互补逻辑)
# [OUTPUT_PROTOCOL]
- 仅输出一个标准的 JSON Array 字符串。
- 严禁任何 Markdown 说明文字、代码块之外的解释或开场白。
- 确保 JSON 语法在 .NET `JsonSerializer.Deserialize` 下可直接解析。
# [EXECUTION]
根据以上配置,开始生成。";
string response = string.Empty;
try
{
response = await _hunyuanService.ChatCompletionsHunyuan_t1_latestAsync(question);
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "网络连接失败,无法调用混元API");
return Ok(JsonView(false, $"网络连接异常,请检查网络后重试!Ex:{ex.Message}"));
}
catch (TaskCanceledException ex)
{
_logger.LogError(ex, "请求超时");
return Ok(JsonView(false, $"AI 响应超时,请稍后再试!Ex:{ex.Message}"));
}
catch (TencentCloudSDKException ex)
{
// 记录完整日志
_logger.LogError(ex, "腾讯云API调用失败 | 错误码: {ErrorCode} | 请求ID: {RequestId}", ex.ErrorCode, ex.RequestId);
// 根据错误码做差异化处理
if (ex.ErrorCode != null && ex.ErrorCode == "AuthFailure.SignatureExpire")
{
return Ok(JsonView(false, $"系统时间异常,请同步时间后重试!Ex:{ex.Message}"));
}
else if (ex.ErrorCode != null && ex.ErrorCode.StartsWith("Unauthorized"))
{
return Ok(JsonView(false, $"当前账号无权限访问该服务!Ex:{ex.Message}"));
}
else
{
return Ok(JsonView(false, $"腾讯云服务调用失败,请稍后重试!Ex:{ex.Message}"));
}
}
catch (Exception ex)
{
_logger.LogError(ex, "未知错误,调用混元API失败");
return Ok(JsonView(false, $"未知错误,调用混元API失败!Ex:{ex.Message}"));
}
if (!string.IsNullOrWhiteSpace(response))
{
// 预处理:过滤 AI 可能返回的 Markdown 标记
string cleanJson = response.Trim();
if (cleanJson.StartsWith("```json"))
cleanJson = cleanJson.Substring(7, cleanJson.Length - 10).Trim();
else if (cleanJson.StartsWith("```"))
cleanJson = cleanJson.Substring(3, cleanJson.Length - 6).Trim();
try
{
// 解析并注入 Source 标识
hunyuanAIInvDatas = JsonConvert.DeserializeObject>(cleanJson);
if (hunyuanAIInvDatas != null)
{
hunyuanAIInvDatas = hunyuanAIInvDatas.Select(x =>
{
x.Guid = Guid.NewGuid().ToString("N");
x.Source = 1;
x.Region = entryInfo.TargetCountry;
x.Operator = operatorName;
x.OperatedAt = DateTime.Now;
return x;
}).ToList();
}
}
catch (JsonException ex)
{
// 记录日志并考虑 fallback 策略
_logger.LogError(ex, "Hunyuan AI 响应解析失败。原始数据:{Response}", response);
}
}
#region 数据库操作
invAiInfo.AiCrawledDetails.AddRange(hunyuanAIInvDatas);
var update = await _sqlSugar.Updateable(invAiInfo).ExecuteCommandAsync();
if (update < 1)
{
return Ok(JsonView(false, $"AI续写,数据更新失败!"));
}
return Ok(JsonView(true, $"AI续写成功!操作数据{hunyuanAIInvDatas.Count}条"));
#endregion
}
#endregion
return Ok(JsonView(false, $"AI续写失败!"));
}
///
/// 商邀资料AI 文件生成(基于混元AI已爬取数据进行格式化输出,供用户下载使用)
///
///
[HttpGet("{id}")]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAIFileGenerator(int id)
{
var invAiInfo = await _sqlSugar.Queryable()
.Where(x => x.Id == id)
.FirstAsync();
var dataList = invAiInfo?.AiCrawledDetails;
if (dataList == null)
return Ok(JsonView(false, "数据为空"));
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// A4页面设置
double usableWidth = 495;
foreach (Section sec in doc.Sections)
{
sec.PageSetup.PaperSize = Aspose.Words.PaperSize.A4;
sec.PageSetup.LeftMargin = 50;
sec.PageSetup.RightMargin = 50;
sec.PageSetup.TopMargin = 50;
sec.PageSetup.BottomMargin = 50;
}
// 卡片背景
Color cardBg = Color.FromArgb(252, 252, 252);
string fontName = "微软雅黑";
int count = 1;
foreach (var item in dataList)
{
// 标题
builder.ParagraphFormat.ClearFormatting();
builder.Font.ClearFormatting();
builder.Font.Name = fontName;
builder.Font.Size = 16;
builder.Font.Bold = true;
builder.Font.Color = Color.Black;
builder.Write($"{count++}. {item.NameCn}");
builder.InsertParagraph();
// 英文名
builder.Font.Size = 10;
builder.Font.Bold = false;
builder.Font.Color = Color.FromArgb(120, 120, 120);
builder.Write(item.NameEn ?? "");
builder.InsertParagraph();
builder.InsertParagraph();
// ====== 卡片表格 ======
Aspose.Words.Tables.Table table = builder.StartTable();
builder.CellFormat.Shading.BackgroundPatternColor = cardBg;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.CellFormat.WrapText = true;
builder.CellFormat.LeftPadding = 12;
builder.CellFormat.RightPadding = 12;
builder.CellFormat.TopPadding = 8;
builder.CellFormat.BottomPadding = 8;
double labelW = 120;
AddSingleRow(builder, fontName, labelW, usableWidth - labelW, "详细地址", item.Address);
AddSingleRow(builder, fontName, labelW, usableWidth - labelW, "联系人", item.Contact);
AddSingleRow(builder, fontName, labelW, usableWidth - labelW, "联系电话", item.Phone);
AddSingleRow(builder, fontName, labelW, usableWidth - labelW, "电子邮箱", item.Email);
AddSingleLinkRow(builder, fontName, labelW, usableWidth - labelW, "官方网站", item.SiteUrl);
AddSingleLinkRow(builder, fontName, labelW, usableWidth - labelW, "最新动态", item.PostUrl);
AddFullWidthRow(builder, fontName, labelW, usableWidth - labelW, "推荐等级", item.RecLevel);
AddFullWidthRow(builder, fontName, labelW, usableWidth - labelW, "经营范围", item.Scope);
AddFullWidthRow(builder, fontName, labelW, usableWidth - labelW, "对接建议", item.IntgAdvice);
// 表格样式
table.SetBorders(Aspose.Words.LineStyle.Single, 0.5, Color.FromArgb(230, 230, 230));
table.AutoFit(AutoFitBehavior.FixedColumnWidths);
table.AllowAutoFit = false;
table.PreferredWidth = PreferredWidth.FromPoints(usableWidth);
builder.EndTable();
builder.InsertParagraph();
builder.InsertParagraph();
}
// 保存逻辑
string fileName = $"{invAiInfo.InvName}_Professional.docx";
string filePath = Path.Combine(AppSettingsHelper.Get("InvitationAIAssistBasePath"), fileName);
doc.Save(filePath, Aspose.Words.SaveFormat.Docx);
return Ok(JsonView(true, "生成成功", new { Url = $"{AppSettingsHelper.Get("WordBaseUrl")}/{AppSettingsHelper.Get("InvitationAIAssistFtpPath")}/{fileName}" }));
}
#region 15.12 适配助手方法
private void AddSingleRow(DocumentBuilder builder, string font, double labelW, double contentW, string label, string value)
{
// 标签
builder.InsertCell();
builder.CellFormat.Width = labelW;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Name = font;
builder.Font.Size = 9;
builder.Font.Bold = false;
builder.Font.Color = Color.FromArgb(120, 120, 120);
builder.Write(label);
// 内容
builder.InsertCell();
builder.CellFormat.Width = contentW;
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Size = 10;
builder.Font.Bold = false;
builder.Font.Color = Color.FromArgb(60, 60, 60);
builder.Write(string.IsNullOrEmpty(value) ? "—" : value);
// 合并剩余列
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.EndRow();
builder.CellFormat.HorizontalMerge = CellMerge.None;
}
private void AddSingleLinkRow(DocumentBuilder builder, string font, double labelW, double contentW, string label, string url)
{
builder.InsertCell();
builder.CellFormat.Width = labelW;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Size = 9;
builder.Font.Bold = false;
builder.Font.Color = Color.FromArgb(120, 120, 120);
builder.Write(label);
builder.InsertCell();
builder.CellFormat.Width = contentW;
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
if (!string.IsNullOrEmpty(url) && url.StartsWith("http"))
{
builder.Font.Size = 10;
builder.Font.Color = Color.FromArgb(0, 102, 204);
builder.Font.Underline = Underline.None;
builder.InsertHyperlink(url, url, false);
}
else
{
builder.Font.Color = Color.FromArgb(60, 60, 60);
builder.Write("—");
}
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.EndRow();
builder.CellFormat.HorizontalMerge = CellMerge.None;
}
private void AddFullWidthRow(DocumentBuilder builder, string font, double lw, double cw, string label, string value)
{
// 标签
builder.InsertCell();
builder.CellFormat.Width = lw;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Font.Size = 9;
builder.Font.Bold = false;
builder.Font.Color = Color.FromArgb(120, 120, 120);
builder.Write(label);
// 内容
builder.InsertCell();
builder.CellFormat.Width = cw;
builder.CellFormat.HorizontalMerge = CellMerge.First;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
builder.Font.Size = 10;
builder.Font.Bold = false;
builder.Font.Color = Color.FromArgb(60, 60, 60);
builder.Write(string.IsNullOrEmpty(value) ? "—" : value);
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.InsertCell();
builder.CellFormat.HorizontalMerge = CellMerge.Previous;
builder.EndRow();
builder.CellFormat.HorizontalMerge = CellMerge.None;
}
#endregion
///
/// 商邀资料AI 生成邮件
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAIGenerateEmail(InvitationAIGenerateEmailDto dto)
{
if (dto.Id < 1) return Ok(JsonView(false, "请选择保存的团组"));
if (dto.CurrUserId < 1) return Ok(JsonView(false, "请传入用户Id"));
if (dto.Guids == null || !dto.Guids.Any()) return Ok(JsonView(false, "请传入需要生成邮件的单位列表"));
var invAiInfo = await _sqlSugar.Queryable()
.Where(x => x.Id == dto.Id)
.FirstAsync();
if (invAiInfo == null) return Ok(JsonView(false, "数据信息为空"));
var dataList = invAiInfo?.AiCrawledDetails;
if (dataList == null) return Ok(JsonView(false, "邀请方数据信息为空"));
var clientInfoSources = dataList.Where(x => dto.Guids.Contains(x.Guid)).ToList();
var clientInfos = clientInfoSources.Select(x => new AICreateEmailInfo()
{
Guid = x.Guid,
NameCn = x.NameCn,
Scope = x.Scope,
Subject = "",
Content = ""
}).ToList();
if (clientInfos == null || !clientInfos.Any()) return Ok(JsonView(false, "邀请单位信息为空"));
var groupInfo = await _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 && x.Id == invAiInfo.GroupId)
.Select(x => new { x.TeamName, x.VisitPurpose,x.VisitDate})
.FirstAsync();
string operatorName = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == dto.CurrUserId).Select(x => x.CnName).FirstAsync() ?? "-";
string pormpt = $@"
# Role
你是一位精通国际政企关系的【首席联络官】。你具备极强的行业分析能力,能通过 [SourceEntity] 的名称自动检索并推导其行政职能与行业地位,并以此撰写具有战略高度、语调优雅的正式商务邮件。
# Intelligence Task: Source Profiling
在生成邮件前,请先执行以下逻辑:
1. **职能推导**:基于 [SourceEntity] 的名称,自动识别其在所属领域的具体行政职能与政策影响力。
2. **战略对齐**:将其职能与全球大趋势(如:Sustainable Urbanization, Digital Transformation, Carbon Neutrality)挂钩,作为邮件第二段的叙事背景。
# Reference Model (Few-Shot Example)
在生成时,请严格参考以下范例的【语气】、【五段式结构】和【外交辞令】:
- Subject: Official Study Visit Inquiry – [Delegation Name] ([Date])
- Para 1: ""On behalf of [SourceEntity], I am writing to formally propose...""
- Para 2: ""As a pivotal megacity [AI根据Source地位补全]... we recognize [Target]’s leadership in...""
- Para 3: ""We are particularly keen to explore... [基于Target经营范围推导的3个技术点]...""
- Para 4: ""We propose a 2–3 day visit... during the week of [Logistics]...""
- Para 5: ""Enclosed please find the [PascalCase_File]...""
# Task
根据 [TargetList] 中每个单位的【经营范围】,为 [SourceEntity] 生成独立的英文访问请求邮件。
# Inputs
- [SourceEntity]: [{invAiInfo.EntryInfo?.OriginUnit ?? ""}]
- [VisitPurpose]: [{groupInfo?.VisitPurpose}]
- [TargetList]: [{JsonConvert.SerializeObject(clientInfos)}]
- [Logistics]: [{groupInfo?.VisitDate.ToString("yyyy-MM-dd")}]
# Execution Logic (Chain of Thought)
1. **Scope-to-Focus Analysis**:
- 深入分析每个 Target 的【经营范围】。
- 自动推导 3 个与 [VisitPurpose] 高度对齐的专业考察点(如:Policy Frameworks, Technical Standards, Operational Case Studies)。
2. **Modular Drafting**:
- 必须严格遵循参考范例的 5 段式逻辑。
- 针对不同职能属性(监管/技术/运营)动态微调邮件主题(Subject)。
3. **No Personnel Reference**: 严禁提及“名单、人数、成员、审核中”等任何具体人员信息,保持机构对等对话的高度。
# Constraints & Standards
- **Tone**: Formal, Strategic, and Executive (庄重、具战略高度、执行力强)。
- **Naming Protocol**: 附件引用统一使用 `JointVisitAgenda`, `StrategicInquiryBrief` (PascalCase)。
- **Output Format**: 仅输出一个合规的 JSON 数组,不包含任何解释性文字。
- **Field Mapping**:
- `Guid`: 原样保留。
- `NameCn`: 原样保留。
- `Scope`: 原样保留。
- `Subject`: 动态生成的英文主题。
- `Content`: 包含 Markdown 格式符号(`###`, `**`, `*`, `---`)的英文正文。
# JSON Structure Template
[
{{
""Guid"": ""ID"",
""NameCn"": ""Entity Name"",
""Scope"": ""Scope Description"",
""Subject"": ""Dynamic English Subject"",
""Content"": ""### Subject\n\n**Dear...**\n\nBody content with *Markdown*...\n\n--- \n\nClosing.""
}}
]";
string response = string.Empty;
try
{
response = await _hunyuanService.ChatCompletionsHunyuan_t1_latestAsync(pormpt);
}
catch (HttpRequestException ex)
{
_logger.LogError(ex, "网络连接失败,无法调用混元API");
return Ok(JsonView(false, $"网络连接异常,请检查网络后重试!Ex:{ex.Message}"));
}
catch (TaskCanceledException ex)
{
_logger.LogError(ex, "请求超时");
return Ok(JsonView(false, $"AI 响应超时,请稍后再试!Ex:{ex.Message}"));
}
catch (TencentCloudSDKException ex)
{
// 记录完整日志
_logger.LogError(ex, "腾讯云API调用失败 | 错误码: {ErrorCode} | 请求ID: {RequestId}", ex.ErrorCode, ex.RequestId);
// 根据错误码做差异化处理
if (ex.ErrorCode != null && ex.ErrorCode == "AuthFailure.SignatureExpire")
{
return Ok(JsonView(false, $"系统时间异常,请同步时间后重试!Ex:{ex.Message}"));
}
else if (ex.ErrorCode != null && ex.ErrorCode.StartsWith("Unauthorized"))
{
return Ok(JsonView(false, $"当前账号无权限访问该服务!Ex:{ex.Message}"));
}
else
{
return Ok(JsonView(false, $"腾讯云服务调用失败,请稍后重试!Ex:{ex.Message}"));
}
}
catch (Exception ex)
{
_logger.LogError(ex, "未知错误,调用混元API失败");
return Ok(JsonView(false, $"未知错误,调用混元API失败!Ex:{ex.Message}"));
}
var hunyuanAIEmailDatas = new List();
if (!string.IsNullOrWhiteSpace(response))
{
// 预处理:过滤 AI 可能返回的 Markdown 标记
string cleanJson = response.Trim();
if (cleanJson.StartsWith("```json"))
cleanJson = cleanJson.Substring(7, cleanJson.Length - 10).Trim();
else if (cleanJson.StartsWith("```"))
cleanJson = cleanJson.Substring(3, cleanJson.Length - 6).Trim();
try
{
// 解析并注入 Source 标识
hunyuanAIEmailDatas = JsonConvert.DeserializeObject>(cleanJson);
}
catch (JsonException ex)
{
// 记录日志并考虑 fallback 策略
_logger.LogError(ex, "Hunyuan AI 响应解析失败。原始数据:{Response}", response);
}
}
if (hunyuanAIEmailDatas == null || !hunyuanAIEmailDatas.Any())
{
return Ok(JsonView(false, "Hunyuan AI 生成的邮件为空"));
}
// 数据邮件存储在数据库
StringBuilder msgSb = new StringBuilder();
foreach (var client in clientInfoSources)
{
var aiEmailInfo = hunyuanAIEmailDatas.Where(x => x.Guid == client.Guid).FirstOrDefault();
if (aiEmailInfo == null)
{
msgSb.AppendLine($"{client.NameCn}: 邮件AI生成失败!");
continue;
}
client.EmailInfo.Status = 2; // AI已生成
client.EmailInfo.EmailTitle = aiEmailInfo.Subject;
client.EmailInfo.EmailContent = aiEmailInfo.Content;
client.EmailInfo.Operator = operatorName;
client.EmailInfo.OperatedAt = DateTime.Now;
msgSb.AppendLine($"{client.NameCn}: 邮件AI生成成功!");
}
// 先删除原有数据中对应的单位数据
invAiInfo.AiCrawledDetails = invAiInfo.AiCrawledDetails.Where(x => !dto.Guids.Contains(x.Guid)).ToList();
// 再添加AI生成的邮件数据
invAiInfo.AiCrawledDetails.AddRange(clientInfoSources);
var update = await _sqlSugar.Updateable(invAiInfo).UpdateColumns(x => x.AiCrawledDetails).ExecuteCommandAsync();
if (update < 1)
{
return Ok(JsonView(false, $"邮件AI生成,数据更新失败!"));
}
return Ok(JsonView(true, msgSb.ToString()));
}
///
/// 商邀资料AI 邮件保存
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAIEmailSave(InvitationAIEmailSaveDto dto)
{
if (dto.Id < 1) return Ok(JsonView(false, "请选择保存的团组"));
if (dto.CurrUserId < 1) return Ok(JsonView(false, "请传入用户Id"));
if (string.IsNullOrEmpty(dto.Guid)) return Ok(JsonView(false, "请传入Guid"));
if (string.IsNullOrEmpty(dto.EmailTitle)) return Ok(JsonView(false, "请传入邮件标题"));
if (string.IsNullOrEmpty(dto.EmailContent)) return Ok(JsonView(false, "请传入邮件内容"));
var invAiInfo = await _sqlSugar.Queryable()
.Where(x => x.Id == dto.Id)
.FirstAsync();
if (invAiInfo == null) return Ok(JsonView(false, "数据信息为空"));
var dataList = invAiInfo?.AiCrawledDetails;
if (dataList == null) return Ok(JsonView(false, "邀请方数据信息为空"));
var editInfo = dataList.Where(x => x.Guid == dto.Guid).FirstOrDefault();
if (editInfo == null) return Ok(JsonView(false, "邀请方信息为空"));
var opUserName = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == dto.CurrUserId).Select(x => x.CnName).FirstAsync() ?? "-";
editInfo.EmailInfo.EmailTitle = dto.EmailTitle;
editInfo.EmailInfo.EmailContent = dto.EmailContent;
editInfo.EmailInfo.Operator = opUserName;
editInfo.EmailInfo.OperatedAt = DateTime.Now;
var datas = dataList.Where(x => x.Guid != dto.Guid).ToList();
datas.Add(editInfo);
invAiInfo.AiCrawledDetails = datas;
var editUpd = await _sqlSugar.Updateable(invAiInfo).UpdateColumns(x => x.AiCrawledDetails).ExecuteCommandAsync();
if (editUpd < 1)
{
return Ok(JsonView(true, "邮件失败"));
}
return Ok(JsonView(true, "邮件成功"));
}
///
/// 商邀资料AI 发送邮件(默认当前用户企业微信邮件)
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task InvitationAISeedEmail(InvitationAISeedEmailDto dto)
{
if (dto.Id < 1) return Ok(JsonView(false, "请选择发送邮件的团组"));
if (dto.CurrUserId < 1) return Ok(JsonView(false, "请传入用户Id"));
if (dto.Guids == null || dto.Guids.Count < 1) return Ok(JsonView(false, "请选择发送邮件的单位"));
var invAiInfo = await _sqlSugar.Queryable()
.Where(x => x.Id == dto.Id)
.FirstAsync();
if (invAiInfo == null) return Ok(JsonView(false, "数据信息为空"));
var dataList = invAiInfo?.AiCrawledDetails;
if (dataList == null) return Ok(JsonView(false, "邀请方数据信息为空"));
var seedInvInfos = dataList.Where(x => dto.Guids.Contains(x.Guid)).ToList();
if (seedInvInfos == null) Ok(JsonView(false, "发送邮件的邀请方信息为空"));
var userInfo = await _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.Id == dto.CurrUserId).Select(x => new { x.Email, x.CnName }).FirstAsync();
if (string.IsNullOrEmpty(userInfo.Email)) Ok(JsonView(false, "当前账号未配置邮箱,请先配置邮箱!"));
var seedEmails = new List();
#region 发送邮件
foreach (var item in seedInvInfos)
{
int seedStatus = 4;
try
{
var req = new EmailRequestDto()
{
ToEmails = new List { "johnny.yang@pan-american-intl.com" },
CcEmails = new List { userInfo.Email },
BccEmails = new List { userInfo.Email },
Subject = "测试邮件 - 来自企业微信API",
Body = "这是一封通过企业微信API发送的测试邮件,包含附件。",
Files = Array.Empty()
};
var response = await _qiYeWeChatApiService.EmailSendAsync(req);
if (response.errcode == 0)
{
seedStatus = 3;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "商邀AI调用企业微信邮件API失败。");
}
seedEmails.Add(new() { EmailContent = "邮件内容", Status = seedStatus, OperatedAt = DateTime.Now, Operator = userInfo.CnName });
}
#endregion
return Ok(JsonView(true, "发送成功"));
}
#endregion
#region 公务出访
///
/// 获取团组所有信息,绑定下拉框
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task GetGroupAllList(OfficialActivitiesByDiIdDto dto)
{
//string groupSql = string.Format("Select * From Grp_DelegationInfo With(NoLock) Where IsDel = 0 Order By CreateTime Desc");
//List _DelegationInfos = _sqlSugar.SqlQueryable< Grp_DelegationInfo >(groupSql).ToList();
var _groupData = await _delegationInfoRep.PostShareGroupInfos(1);
dynamic groupInfos = null;
if (_groupData.Code == 0) groupInfos = _groupData.Data;
var data = _sqlSugar.Queryable().Where(a => a.IsDel == 0).ToList();
var data1 = data.Where(a => a.STid == 38).Select(x => new { x.Id, x.Name }).ToList();
var data2 = data.Where(a => a.STid == 101).Select(x => new { x.Id, x.Name }).ToList();
//张总安排未参与对接
if (data2.Any(x => x.Name.Equals("张总安排未参与对接")))
{
var zhangZong = data2.FirstOrDefault(x => x.Name.Equals("张总安排未参与对接"));
if (zhangZong != null) data2.Remove(zhangZong);
data2.Insert(0, zhangZong);
}
var data3 = data.Where(a => a.STid == 66).Select(x => new { x.Id, x.Name, x.Remark }).ToList();
var _DeleFile = _sqlSugar.Queryable().Where(a => a.Diid == dto.DiId && a.IsDel == 0 && a.Category == 970).ToList();
var translatorData = _sqlSugar.Queryable().Where(a => a.IsDel == 0).ToList();
var translatorData1 = _mapper.Map>(translatorData);
foreach (var item in translatorData1) EncryptionProcessor.DecryptProperties(item);
return Ok(JsonView(true,
"查询成功!",
new
{
Delegation = groupInfos,
SetData = data1,
DataSource = data2,
currencyData = data3,
DeleFile = _DeleFile,
TranslatorData = translatorData1
}));
}
///
/// 公务 团组名称 Page List
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OfficialActivitiesGroupNameList(OfficialActivitiesGroupNameListDto dto)
{
var sw = Stopwatch.StartNew();
if (!SharingStaticData.PortTypes.Contains(dto.PortType))
{
return Ok(JsonView(false, MsgTips.Port));
}
dto.PageIndex = dto.PageIndex == 0 ? 1 : dto.PageIndex;
dto.PageSize = dto.PageSize == 0 ? 10 : dto.PageSize;
RefAsync total = 0;
// 只查询需要的字段,避免Select后再赋值,减少内存占用
var groupInfos = await _officialActivitiesRep._sqlSugar
.Queryable()
.Where(x => x.IsDel == 0)
.WhereIF(!string.IsNullOrEmpty(dto.GroupName), x => x.TeamName.Contains(dto.GroupName))
.OrderByDescending(x => x.VisitDate)
.Select(x => new Web_ShareGroupInfoView()
{
Id = x.Id,
TeamName = x.TeamName,
TourCode = x.TourCode,
ClientName = x.ClientName,
VisitCountry = x.VisitCountry,
VisitStartDate = x.VisitStartDate,
VisitEndDate = x.VisitEndDate,
VisitDays = x.VisitDays,
VisitPNumber = x.VisitPNumber
})
.ToPageListAsync(dto.PageIndex, dto.PageSize, total);
if (groupInfos.Count > 0)
{
for (int i = 0; i < groupInfos.Count; i++)
{
var visitCountry = groupInfos[i].VisitCountry;
groupInfos[i].VisitCountry = !string.IsNullOrEmpty(visitCountry)
? _delegationInfoRep.FormartTeamName(visitCountry)
: string.Empty;
}
}
sw.Stop();
return Ok(JsonView(true, $"操作成功!耗时:{sw.ElapsedMilliseconds}ms", groupInfos, total));
}
///
/// 公务 翻译人员 Page List
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OfficialActivitiesTranslatorList(OfficialActivitiesTranslatorListDto dto)
{
var sw = Stopwatch.StartNew();
if (!SharingStaticData.PortTypes.Contains(dto.PortType))
{
return Ok(JsonView(false, MsgTips.Port));
}
dto.PageIndex = dto.PageIndex == 0 ? 1 : dto.PageIndex;
dto.PageSize = dto.PageSize == 0 ? 10 : dto.PageSize;
var translatorIds = new List();
if (!string.IsNullOrEmpty(dto.TranslatorName))
{
var translators = await _sqlSugar.Queryable()
.Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Name))
.Select(x => new { x.Id, x.Name })
.ToListAsync();
if (translators.Any())
{
foreach (var item in translators)
{
var decryptedName = AesEncryptionHelper.Decrypt(item.Name);
if (!string.IsNullOrEmpty(decryptedName) && decryptedName.Contains(dto.TranslatorName))
{
translatorIds.Add(item.Id);
}
}
}
if (translatorIds.Count == 0)
{
sw.Stop();
return Ok(JsonView(true, $"暂无翻译人员信息!耗时: {sw.ElapsedMilliseconds}ms", Array.Empty(), 0));
}
}
RefAsync total = 0;
var translatorInfos = await _officialActivitiesRep._sqlSugar
.Queryable()
.Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Name))
.WhereIF(translatorIds != null && translatorIds.Count > 0, x => translatorIds.Contains(x.Id))
.OrderByDescending(x => x.CreateTime)
.Select(x => new TranslatorView()
{
Id = x.Id,
Area = x.Area,
Name = x.Name,
Sex = x.Sex,
Tel = x.Tel,
Email = x.Email,
WechatNo = x.WechatNo,
OtherSocialAccounts = x.OtherSocialAccounts,
Language = x.Language,
Price = x.Price,
Currency = x.Currency,
})
.ToPageListAsync(dto.PageIndex, dto.PageSize, total);
for (int i = 0; i < translatorInfos.Count; i++)
{
EncryptionProcessor.DecryptProperties(translatorInfos[i]);
}
sw.Stop();
string msg = translatorInfos.Count == 0 ? $"暂无您查询的翻译人员信息!耗时: {sw.ElapsedMilliseconds}ms" : $"操作成功!耗时: {sw.ElapsedMilliseconds}ms";
return Ok(JsonView(true, msg, translatorInfos, total));
}
///
/// 公务 绑定下拉框
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OfficialActivitiesInitDatabase(OfficialActivitiesByDiIdDto dto)
{
var data = _sqlSugar.Queryable().Where(a => a.IsDel == 0).ToList();
var data1 = data.Where(a => a.STid == 38).Select(x => new { x.Id, x.Name }).ToList();
var data2 = data.Where(a => a.STid == 101).Select(x => new { x.Id, x.Name }).ToList();
//张总安排未参与对接
if (data2.Any(x => x.Name.Equals("张总安排未参与对接")))
{
var zhangZong = data2.FirstOrDefault(x => x.Name.Equals("张总安排未参与对接"));
if (zhangZong != null) data2.Remove(zhangZong);
data2.Insert(0, zhangZong);
}
var data3 = data.Where(a => a.STid == 66).Select(x => new { x.Id, x.Name, x.Remark }).ToList();
var _DeleFile = _sqlSugar.Queryable().Where(a => a.Diid == dto.DiId && a.IsDel == 0 && a.Category == 970).ToList();
return Ok(JsonView(true,
"查询成功!",
new
{
SetData = data1,
DataSource = data2,
currencyData = data3,
DeleFile = _DeleFile
}));
}
///
/// 公务List
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryOfficialActivitiesByDiId(OfficialActivitiesByDiIdDto dto)
{
return Ok(await _officialActivitiesRep.QueryOfficialActivitiesByDiId(dto));
}
///
/// 根据公务出访数据Id查询数据
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task QueryOfficialActivitiesById(OfficialActivitiesDiIdDto dto)
{
Result groupData = await _officialActivitiesRep.QueryOfficialActivitiesById(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(false, groupData.Msg));
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 公务出访操作(Status:1.新增,2.修改)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OpOfficialActivities(OpOfficialActivitiesDto dto)
{
Result groupData = await _officialActivitiesRep.OpOfficialActivities(dto);
if (groupData.Code != 0)
{
return Ok(JsonView(StatusCodes.Status400BadRequest, groupData.Msg, new { Id = 0 }));
}
try
{
//公务出访变更发送通知
await AppNoticeLibrary.SendUserMsg_GroupShare_ToOP(dto.DiId, dto.CreateUserId);
}
catch (Exception ex)
{
//抄送日志
}
return Ok(JsonView(true, groupData.Msg, groupData.Data));
}
///
/// 上传文件(邮件截图)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OfficialActivitiesUploadFiles([FromForm] OfficialActivitiesUploadFilesDto dto)
{
string networkPath = AppSettingsHelper.Get("GrpFileBaseUrl");
string localPath = AppSettingsHelper.Get("GrpFileBasePath");
string ptfPath = AppSettingsHelper.Get("GrpFileFtpPath");
if (dto.diId < 1 || dto.currUserId < 1)
{
return Ok(JsonView(false, "参数有误,上传失败!"));
}
if (dto.files == null || dto.files.Count < 1)
{
return Ok(JsonView(false, "文件为空,上传失败!"));
}
string localFileDir = $"{localPath}{ptfPath}";
List fileUrls = new List();
string[] failFiles = new string[] { };
foreach (var file in dto.files)
{
//文件名称
string[] fileNameArray = file.FileName.Split(".");
string projectFileName = $"{fileNameArray[0].ToString().Replace("-", "_").Replace("/", "_")}{DateTime.UtcNow:yyyyMMddHHmmss}.{fileNameArray[1]}";
//上传的文件的路径
string filePath = $@"{localPath}公务相关文件";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
var path = Path.Combine(filePath, projectFileName);
//using var stream = new FileStream(path, FileMode.Create);
//await file.CopyToAsync(stream);
try
{
using (FileStream fs = System.IO.File.Create(path))
{
file.CopyTo(fs);
fs.Flush();
}
fileUrls.Add($"/{ptfPath}公务相关文件/{projectFileName}");
}
catch (Exception ex)
{
failFiles.Append(file.FileName);
}
}
var oaInfo = await _sqlSugar.Queryable().Where(x => x.Id == dto.id).FirstAsync();
List files = new List();
var status = false;
var _oaInfo = new Res_OfficialActivities()
{
DiId = dto.diId,
ScreenshotOfMailUrl = JsonConvert.SerializeObject(fileUrls),
IsDel = 0,
CreateUserId = dto.currUserId,
CreateTime = DateTime.Now
};
if (oaInfo == null)
{
var id = await _sqlSugar.Insertable(_oaInfo)
.ExecuteReturnIdentityAsync();
if (id > 0)
{
status = true;
dto.id = id;
}
}
else
{
var oldFiles = string.IsNullOrEmpty(oaInfo.ScreenshotOfMailUrl)
? new List()
: JsonConvert.DeserializeObject>(oaInfo.ScreenshotOfMailUrl);
if (oldFiles.Count > 0)
{
fileUrls.AddRange(oldFiles);
}
fileUrls = fileUrls.Distinct().ToList();
if (fileUrls.Count > 0)
{
var upd = await _sqlSugar.Updateable()
.SetColumns(x => x.ScreenshotOfMailUrl == JsonConvert.SerializeObject(fileUrls))
.Where(x => x.Id == dto.id)
.ExecuteCommandAsync();
if (upd > 0) status = true;
}
}
List returnFileUrls = new List();
fileUrls.ForEach(x =>
{
returnFileUrls.Add($"{networkPath}{x}");
});
if (status)
{
string msg = "操作成功!";
if (failFiles.Length > 1)
{
foreach (var item in failFiles)
{
msg += $"{failFiles}、";
}
msg = msg.Substring(0, msg.Length - 1);
msg += "等文件保存失败!";
}
return Ok(JsonView(true, msg, new { id = dto.id, fileUrls = returnFileUrls }));
}
return Ok(JsonView(false, "操作失败!"));
}
///
/// 删除文件(邮件截图)
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OfficialActivitiesDelFile(OfficialActivitiesDelFileDto dto)
{
string networkPath = AppSettingsHelper.Get("GrpFileBaseUrl");
string localPath = AppSettingsHelper.Get("GrpFileBasePath");
string ptfPath = AppSettingsHelper.Get("GrpFileFtpPath");
if (dto.Id < 1 || string.IsNullOrEmpty(dto.FileName))
{
return Ok(JsonView(false, "参数有误,上传失败!"));
}
string localFileDir = $"{localPath}{ptfPath}";
List fileUrls = new List();
var oaInfo = await _sqlSugar.Queryable().Where(x => x.Id == dto.Id).FirstAsync();
if (oaInfo != null)
{
string urlJson = oaInfo.ScreenshotOfMailUrl ?? "";
if (!string.IsNullOrEmpty(urlJson))
{
List urls = JsonConvert.DeserializeObject>(urlJson);
var filePath = urls.Find(x => x.Contains(dto.FileName));
if (string.IsNullOrEmpty(filePath)) return Ok(JsonView(false, "文件不存在!"));
var updFile = urls.Remove(filePath);
if (updFile)
{
//删除文件
string fileUrl = AppSettingsHelper.Get("GrpFileBasePath").Replace(@"/Office/GrpFile", "") + filePath;
if (System.IO.File.Exists(fileUrl))
{
System.IO.File.Delete(fileUrl);
}
string urlJsonstr = JsonConvert.SerializeObject(urls);
var upd = await _sqlSugar.Updateable()
.SetColumns(x => x.ScreenshotOfMailUrl == urlJsonstr)
.Where(x => x.Id == dto.Id)
.ExecuteCommandAsync();
if (upd > 0) return Ok(JsonView(true, "操作成功!"));
}
}
}
return Ok(JsonView(false, "操作失败!"));
}
///
/// 公务出访 确认、取消邀请
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OfficialActivitiesInviteOperation(OfficialActivitiesInviteOperationDto dto)
{
if (dto.Id < 1) return Ok(JsonView(false, "Id参数有误!"));
if (dto.Type < 0 || dto.Type > 1) return Ok(JsonView(false, "Type参数有误!"));
var upd = await _sqlSugar.Updateable()
.SetColumns(x => x.ConfirmTheInvitation == dto.Type)
.Where(x => x.Id == dto.Id)
.ExecuteCommandAsync();
if (upd > 0) return Ok(JsonView(true, "操作成功!"));
return Ok(JsonView(false, "操作失败!"));
}
///
/// 上传文件
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task UploadOfficialActivities(IFormFile file)
{
try
{
int Type = int.Parse(Request.Headers["Type"]);//1公务方简介,2公务活动图片,3发票
int DiId = int.Parse(Request.Headers["DiId"]);
int CreateUserId = int.Parse(Request.Headers["CreateUserId"]);
if (file != null)
{
var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
//文件名称
string projectFileName = file.FileName;
//上传的文件的路径
string filePath = "";
if (!Directory.Exists(fileDir))
{
Directory.CreateDirectory(fileDir);
}
//上传的文件的路径
filePath = fileDir + $@"\商邀相关文件\{projectFileName}";
using (FileStream fs = System.IO.File.Create(filePath))
{
file.CopyTo(fs);
fs.Flush();
}
Grp_DeleFile d = new Grp_DeleFile();
d.Diid = DiId;
d.Category = 970;
if (Type == 1) d.Kind = 1;
else if (Type == 2) d.Kind = 2;
else if (Type == 3) d.Kind = 3;
d.FileName = projectFileName;
d.FilePath = "";
d.CreateUserId = CreateUserId;
int id = await _sqlSugar.Insertable(d).ExecuteReturnIdentityAsync();
return Ok(JsonView(true, "上传成功!", projectFileName));
}
else
{
return Ok(JsonView(false, "上传失败!"));
}
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 删除文件
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelloadOfficialActivities(DelBaseDto dto)
{
try
{
var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
Grp_DeleFile _DeleFile = await _sqlSugar.Queryable().FirstAsync(a => a.Id == dto.Id);
if (_DeleFile != null)
{
string fileName = _DeleFile.FileName;
string filePath = fileDir + "/团组增减款项相关文件/" + fileName;
// 删除该文件
System.IO.File.Delete(filePath);
int id = await _sqlSugar.Updateable().Where(a => a.Id == dto.Id).SetColumns(a => new Grp_DeleFile { IsDel = 1, DeleteUserId = dto.DeleteUserId, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }).ExecuteCommandAsync();
return Ok(JsonView(true, "取消文件成功!"));
}
else
{
return Ok(JsonView(false, "取消文件失败!"));
}
}
catch (Exception ex)
{
return Ok(JsonView(false, "程序错误!"));
throw;
}
}
///
/// 删除公务出访信息
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task DelOfficialActivities(DelBaseDto dto)
{
_sqlSugar.BeginTran();
var res = await _officialActivitiesRep.SoftDeleteByIdAsync(dto.Id.ToString(), dto.DeleteUserId);
if (!res)
{
_sqlSugar.RollbackTran();
return Ok(JsonView(false, "删除失败"));
}
#region 删除公务出访
await _sqlSugar.Updateable()
.SetColumns(x => new Grp_OfficialDutyLinkTranslator()
{
DeleteUserId = dto.DeleteUserId,
DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
IsDel = 1,
Remark = $"公务出访-->删除"
})
.Where(x => x.OfficialDutyId == dto.Id)
.ExecuteCommandAsync();
#endregion
_sqlSugar.CommitTran();
return Ok(JsonView(true, "删除成功!"));
}
///
/// 公务出访
/// 请示范例提示
/// Add Time:2024-05-13 13:56:44
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task PostOfficialActivitiesReqReqSampleTips(PostOfficialActivitiesReqReqSampleTipsDto dto)
{
var res = await _officialActivitiesRep.PostReqReqSampleTips(dto.country, dto.area, dto.client);
if (res.Code == 0)
{
return Ok(JsonView(true, "操作成功!", res.Data));
}
return Ok(JsonView(false, res.Msg));
}
///
/// 公务出访 (省外办,市外办) File Downlaod
///
///
///
[HttpPost]
[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
public async Task OfficialActivitiesFileDownload(OfficialActivitiesFileDownload dto)
{
#region 参数验证
if (dto.FileType < 1 || dto.FileType > 2) return Ok(JsonView(false, "请传入有效的FileType参数. 1 省外办出访请示 2 市外办出访请示", ""));
if (dto.DiId < 1) return Ok(JsonView(false, "请传入有效的DiId参数.", ""));
#endregion
//团组基础信息
var groupInfo = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.Id == dto.DiId).First();
if (groupInfo == null) return Ok(JsonView(false, "该团组基本信息不存在", ""));
groupInfo.VisitCountry = groupInfo.VisitCountry.Replace("|", "、");
//团组公务信息
var obDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.DiId == dto.DiId).OrderBy(it => it.Date).ToList();
//if (obDatas.Count < 1) return Ok(JsonView(false, "请先录入公务信息!"));
//团组客户名单
var guestResult = _tourClientListRep._ItemByDiId(1, dto.DiId);
List guestInfos = new List();
if (guestResult.Result.Code == 0) guestInfos = guestResult.Result.Data as List;
string visitCountrys = ""; //××国家(或地区)×天,××国家(或地区)×天
string countryStayStr = ""; // xx、xx、xx
//出入境费用 住宿类型
var dayCostDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.DiId == dto.DiId && it.Type == 1).ToList();
if (dayCostDatas.Count > 0)
{
List nationalIds = dayCostDatas.Select(it => it.NationalTravelFeeId).ToList();
var nationalDatas = _sqlSugar.Queryable().Where(it => nationalIds.Contains(it.Id)).ToList();
var nationalDataGroupByCountry = nationalDatas.GroupBy(it => it.Country);
foreach (var item in nationalDataGroupByCountry)
{
visitCountrys += $"{item.Key}、";
int stayDays = nationalIds.Where(it => it == item.ToList()[0].Id).Count();
countryStayStr += $"{item.Key}{stayDays}天,";
}
if (visitCountrys.Length > 0) visitCountrys = visitCountrys.Substring(0, visitCountrys.Length - 1);
if (countryStayStr.Length > 0) countryStayStr = countryStayStr.Substring(0, countryStayStr.Length - 1);
}
else
{
visitCountrys = groupInfo.VisitCountry;
countryStayStr = GeneralMethod.GetCountryStandingTime(groupInfo.Id); //计算国家出访天数
}
//出访人数
int visitPeopleNum = groupInfo.VisitPNumber;
int visitDaysNum = groupInfo.VisitDays;
//出访单位
string obInfoStr = "";
foreach (var ob in obDatas) obInfoStr += @$"{ob.Client.Trim()}{ob.Job.Trim()}{ob.Contact.Trim()}、";
if (obInfoStr.Length > 0) obInfoStr = obInfoStr.Substring(0, obInfoStr.Length - 1);
obInfoStr = obInfoStr ?? "[公务出访未录入]";
//出访路线
string lineStr = GeneralMethod.GetGroupCityLine(groupInfo.Id, "—");
if (dto.FileType == 1)
{
//载入模板
string tempPath = AppSettingsHelper.Get("WordBasePath") + "Template/省外办出访请示 - 模板.docx";
var doc = new Document(tempPath);
DocumentBuilder builder = new DocumentBuilder(doc);
//键值对存放数据
Dictionary dic = new Dictionary