using NCC.Common.Core.Manager;
using NCC.Common.Enum;
using NCC.Common.Extension;
using NCC.Common.Filter;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.FriendlyException;
using NCC.Blind.Interfaces.TbBoxOrder;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NCC.Blind.Entitys;
using NCC.Blind.Entitys.Dto.TbBoxOrder;
using Yitter.IdGenerator;
using NCC.Common.Helper;
using NCC.JsonSerialization;
using NCC.Common.Model.NPOI;
using NCC.Common.Configuration;
using NCC.DataEncryption;
using NCC.ClayObject;
using NCC.System.Interfaces.System;
using NCC.System.Entitys.Permission;
using NCC.Education.Entitys;
using NCC.BlindBox;
using Microsoft.Extensions.Logging;
using Antis.Pay.Core.Enum;
using System.Collections;
using Microsoft.AspNetCore.Http;
using NCC.Common.Extensions;
using Antis.Pay.Core.Interface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Antis.Pay.Core.Model;
using Microsoft.AspNetCore.Authorization;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Hosting;
using MySqlX.XDevAPI.Common;
using Spire.Presentation.Drawing.TimeLine;
using NCC.Common.Model;
using NCC.Blind.Entitys.Dto.TbAreaLineNode;
using NCC.Blind.Entitys.Dto.TbMbtLine;
using NCC.Blind.Entitys.Dto.TbMbtLineNode;
using NCC.Blind.Entitys.Dto.TbAreaLine;
using Serilog;
namespace NCC.Blind.TbBoxOrder
{
///
/// 盲盒订单服务
///
[ApiDescriptionSettings(Tag = "盲盒订单",Name = "TbBoxOrder", Order = 200)]
[Route("api/Blind/[controller]")]
public class TbBoxOrderService : ITbBoxOrderService, IDynamicApiController, ITransient
{
private readonly ISqlSugarRepository _tbBoxOrderRepository;
private readonly IDbLinkService _dbLinkService;
private readonly IDataBaseService _dataBaseService;
private readonly SqlSugarScope _db;
private readonly ILogger _logger;
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IUserManager _userManager;
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly IWePay _wepay;
private static WepayOptions WepayConfig = App.GetConfig("PaymentSettings", true).WepayConfig;
///
/// 初始化一个类型的新实例
///
public TbBoxOrderService(
ISqlSugarRepository tbBoxOrderRepository,
IDbLinkService dbLinkService,
IDataBaseService dataBaseService,
IUserManager userManager,
ILogger logger,
IHttpContextAccessor httpContextAccessor,
IHostingEnvironment hostingEnvironment,
IWePay wepay)
{
_tbBoxOrderRepository = tbBoxOrderRepository;
_db = _tbBoxOrderRepository.Context;
_dbLinkService = dbLinkService;
_dataBaseService = dataBaseService;
_userManager = userManager;
_logger = logger;
_httpContextAccessor = httpContextAccessor;
_hostingEnvironment = hostingEnvironment;
_wepay = wepay;
}
public class OutOrderLineOptions
{
///
/// 地域线路信息
///
public TbAreaLineInfoOutput areaLine { get; set; }
///
/// MBTI线路信息
///
public TbMbtLineInfoOutput mbtLine { get; set; }
///
/// 地域线路节点集合
///
public List areaLineNodeList { get; set; }
///
/// MBTI人格线路节点集合
///
public List mbtLineNodeList { get; set; }
///
/// 类型 1--地域线路 2--MBT线路
///
public string type { get; set; }
}
///
/// 根据订单ID查询路线信息
///
///
///
[HttpPost("GetOrderLineByOrderId")]
public async Task GetOrderLineByOrderId(string id)
{
OutOrderLineOptions result = new OutOrderLineOptions();
var order = _db.Queryable().Where(o => o.Id == id).First();
if (order.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到订单信息!");
if (order.Type == BlindBoxStatus.BlindBoxLineStatus.地域线路.GetHashCode().ToString())
{
//地域路线
var entity = await _db.Queryable().FirstAsync(p => p.Id == order.AreaLineId);
var output = entity.Adapt();
result.areaLine = output;
Log.Information($"查询的订单路线ID:{order.AreaLineId}");
var model = _db.Queryable().Where(o => o.AreaLineId == order.AreaLineId).Select(it => new TbAreaLineNodeListOutput
{
id = it.Id,
areaLineId = it.AreaLineId,
title = it.Title,
description = it.Description,
remark = it.Remark,
creatorTime = it.CreatorTime,
lastModifyTime = it.LastModifyTime,
banner = it.Banner,
sorts = it.Sorts,
}).MergeTable().Mapper(p =>
{
//p.areaLine = _db.Queryable().Where(o => o.Id == p.areaLineId).First();
}).ToList();
Log.Information($"路线节点集合:{JsonConvert.SerializeObject(model)}");
result.areaLineNodeList = model;
}
else
{
//人格路线
var entity = await _db.Queryable().FirstAsync(p => p.Id == order.MbtLineId);
var output = entity.Adapt();
result.mbtLine = output;
var model = _db.Queryable().Where(o => o.MbtLineId == order.MbtLineId).Select(it => new TbMbtLineNodeListOutput
{
id = it.Id,
mbtLineId = it.MbtLineId,
title = it.Title,
description = it.Description,
remark = it.Remark,
creatorTime = it.CreatorTime,
lastModifyTime = it.LastModifyTime,
sorts = it.Sorts,
banner=it.Banner
}).MergeTable().Mapper(p =>
{
//p.mbtLine = _db.Queryable().Where(o => o.Id == p.mbtLineId).First();
}).ToList();
result.mbtLineNodeList = model;
}
result.type = order.Type;
return result;
}
///
/// 扫码获得盲盒券
///
public class ConfirmBindingCouponOptions
{
///
/// 盲盒订单ID
///
public string boxOrderId { get; set; }
///
/// 用户ID
///
public string userId { get; set; }
}
///
/// 扫码获得盲盒券
///
///
///
[HttpPost("CofirmBindingCoupon")]
public async Task CofirmBindingCoupon(ConfirmBindingCouponOptions query)
{
var boxOrder = _db.Queryable().Where(o => o.Id == query.boxOrderId).First();
if (boxOrder.IsNullOrEmpty()) throw NCCException.Oh($"暂无此订单哦");
if (!boxOrder.GiveUserId.IsNullOrEmpty()) throw NCCException.Oh($"该券已经被送出人接收了哦");
var user = _db.Queryable().Where(o => o.Id == query.userId).First();
if (user.IsNullOrEmpty()) throw NCCException.Oh($"暂无此用户哦");
var coupon = _db.Insertable(new TbMyBoxCouponEntity
{
Id=YitIdHelper.NextId().ToString(),
GiveUserId= boxOrder.UserId,
OrderId=boxOrder.Id,
Remark=$"赠送盲盒抽奖",
Title="赠送盲盒抽奖",
Type=BlindBoxStatus.BlindBoxCouponStatus.未使用.GetHashCode().ToString(),
UserId= user.Id,
CreatorTime=DateTime.Now
}).ExecuteReturnEntity();
_logger.LogInformation($"添加盲盒券实体:{coupon.ToJson()}");
boxOrder.GiveUserId = user.Id;
boxOrder.MyBoxCouponId = coupon.Id;
var result = _db.Updateable(boxOrder).ExecuteCommand();
_logger.LogInformation($"补全赠送信息:{result}");
}
///
/// 立即抽奖入参
///
public class ConfirmDrawOptions
{
///
/// 盲盒订单ID
///
public string boxOrderId { get; set; }
///
/// 盲盒券ID 赠送订单需传入
///
public string myBoxCouponId { get; set; }
}
///
/// 立即抽奖
///
///
///
[HttpPost("ConFirmDraw")]
public async Task ConFirmDraw(ConfirmDrawOptions query)
{
var model = _db.Queryable().Where(o => o.Id == query.boxOrderId).First();
if (model.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到该订单,无法抽奖!");
var logData = _db.Queryable().Where(o => o.BoxOrderId == model.Id).Count();
if (logData > 1) throw NCCException.Oh($"您的次数已用完了哦");
if (model.Type == BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString())
{
//人格
var list = _db.Queryable().Where(o=>o.MbtId==model.MbtId).ToList();
List ids = new List();
foreach (var item in list)
{
ids.Add(item.Id);
}
int r = new Random().Next(ids.Count);
var data = list.Find(o => o.Id == ids[r]);
if (data.IsNullOrEmpty()) throw NCCException.Oh($"暂无人格路线哦");
var logResult = new TbBoxLogEntity
{
Id = YitIdHelper.NextId().ToString(),
Type = BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString(),
BoxOrderId = model.Id,
CreatorTime = DateTime.Now,
MbtId = model.MbtId,
MbtLineId = data.Id,
UserId = model.UserId,
};
try
{
_db.BeginTran();
if (model.IsMe == BlindBoxStatus.BlindIsMeStatus.赠送他人.GetHashCode().ToString())
{
logResult.UserId = model.GiveUserId;
var couponResult = _db.Updateable().SetColumns(o => o.Type == BlindBoxStatus.BlindBoxCouponStatus.已使用.GetHashCode().ToString()).Where(o => o.Id == query.myBoxCouponId).ExecuteCommand();
_logger.LogInformation($"我的盲盒券状态更改失败:{couponResult}");
}
var result = _db.Insertable(logResult).ExecuteCommand();
_logger.LogInformation($"添加MBT抽奖记录状态:{result}");
model.MbtLineId = data.Id;
var orderResult = _db.Updateable(model).ExecuteCommand();
_logger.LogInformation($"更改人格订单抽奖线路信息:{orderResult}");
_db.CommitTran();
var lineNode = _db.Queryable().Where(o => o.MbtLineId == data.Id).ToList();
return new
{
type = BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString(),
mbtLine = data,
mbtLineNode = lineNode,
};
}
catch (Exception ex)
{
_logger.LogInformation($"抽奖人格报错:{ex.Message}");
_db.RollbackTran();
throw NCCException.Oh($"抽奖人格报错:{ex.Message}");
}
}
else
{
//地域
var list = _db.Queryable().Where(o => o.AreaId == model.AreaId).ToList();
List ids = new List();
foreach (var item in list)
{
ids.Add(item.Id);
}
var data = GetRandomItem(list);
Log.Information($"概率值:{JsonConvert.SerializeObject(data)}");
//int r = new Random().Next(ids.Count);
//var data = list.Find(o => o.Id == ids[r]);
if (data.IsNullOrEmpty()) throw NCCException.Oh($"暂无地域路线或者百分比之和不等于100!");
var logResult = new TbBoxLogEntity
{
Id = YitIdHelper.NextId().ToString(),
Type = BlindBoxStatus.BlindBoxLineStatus.地域线路.GetHashCode().ToString(),
BoxOrderId = model.Id,
CreatorTime = DateTime.Now,
AreaId = model.AreaId,
AreaLineId = data.Id,
UserId = model.UserId,
};
try
{
_db.BeginTran();
if (model.IsMe == BlindBoxStatus.BlindIsMeStatus.赠送他人.GetHashCode().ToString())
{
logResult.UserId = model.GiveUserId;
var couponResult = _db.Updateable().SetColumns(o => o.Type == BlindBoxStatus.BlindBoxCouponStatus.已使用.GetHashCode().ToString()).Where(o => o.Id == query.myBoxCouponId).ExecuteCommand();
_logger.LogInformation($"我的盲盒券状态更改失败:{couponResult}");
}
var result = _db.Insertable(logResult).ExecuteCommand();
_logger.LogInformation($"添加地域抽奖记录状态:{result}");
model.AreaLineId = data.Id;
var orderResult = _db.Updateable(model).ExecuteCommand();
_logger.LogInformation($"更改地域订单抽奖线路信息:{orderResult}");
var lineNode = _db.Queryable().Where(o => o.AreaLineId == data.Id).ToList();
_db.CommitTran();
return new
{
type=BlindBoxStatus.BlindBoxLineStatus.地域线路.GetHashCode().ToString(),
areaLine = data,
areaLineNode = lineNode,
};
}
catch (Exception ex)
{
_logger.LogInformation($"抽奖地域报错:{ex.Message}");
_db.RollbackTran();
throw NCCException.Oh($"抽奖地域报错:{ex.Message}");
}
}
}
///
/// 概率算法
///
///
///
public static TbAreaLineEntity GetRandomItem(List items)
{
double totalPercentage = items.Sum(x => x.Ratio.ToDouble());
double randomValue = new Random().NextDouble() * totalPercentage;
foreach (TbAreaLineEntity item in items)
{
randomValue -= item.Ratio.ToDouble();
if (randomValue <= 0)
{
return item;
}
}
return null; // 如果总百分比小于100%或列表为空,则返回null
}
///
/// 支付后回调处理
///
///
[HttpGet("WePayNotify")]
[HttpPost("WePayNotify")]
[AllowAnonymous]
public string WePayNotify()
{
_logger.LogInformation("进入支付回调");
WePayReturnModel payResult = new WePayReturnModel();
if (_wepay.VerifyNotify(out payResult))
{
_logger.LogInformation("验证成功" + JsonConvert.SerializeObject(payResult));
var boxOrder = _db.Queryable().Where(o => o.OrderNumber == payResult.OutTradeNo).First();
if (boxOrder.Status == BlindBoxStatus.BlindBoxOrderStatus.已付款.GetHashCode().ToString())
{
return _wepay.GetReturnXml("SUCCESS", "OK");
}
else
{
boxOrder.Status = BlindBoxStatus.BlindBoxOrderStatus.已付款.GetHashCode().ToString();
var result = _db.Updateable(boxOrder).ExecuteCommand();
_logger.LogInformation($"盲盒回调更改订单状态:{result}");
}
}
_logger.LogInformation("支付回调验证失败 payResult=" + JsonHelper.ToJson((object)payResult));
return _wepay.GetReturnXml("FAIL", "ERROR");
}
///
/// 盲盒订单下单参数
///
public class PlanceBoxOptions
{
///
/// 用户ID
///
public string userId { get; set; }
///
/// 路线 1--地域路线 2--MBT人格路线
///
public string type { get; set; }
///
/// 地域ID
///
public string areaId { get; set; }
///
/// 人格ID
///
public string mbtId { get; set; }
///
/// 购买类型 1--自己购买 2--赠送他人
///
public string isMe { get; set; }
///
/// 创建时间
///
public DateTime? creatorTime { get; set; }
///
/// 修改时间
///
public DateTime? lastModifyTime { get; set; }
}
///
/// 盲盒订单下单
///
///
///
[HttpPost("PlanceBoxOrder")]
public async Task PlanceBoxOrder(PlanceBoxOptions input)
{
if (input.userId.IsNullOrEmpty()) throw NCCException.Oh($"请设置用户标识");
if (input.type.IsNullOrEmpty()) throw NCCException.Oh($"请选择路线类型");
if (input.isMe.IsNullOrEmpty()) throw NCCException.Oh($"请选择购买类型");
var user = _db.Queryable().Where(o => o.Id == input.userId).First();
if (user.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到该用户");
if (input.type.Equals(BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString()))
{
//人格
if (input.mbtId.IsNullOrEmpty()) throw NCCException.Oh($"请选择人格");
var mbt = _db.Queryable().Where(o => o.Id == input.mbtId).First();
if (mbt.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到人格");
}
else
{
//地域
if (input.areaId.IsNullOrEmpty()) throw NCCException.Oh($"请选择地域!");
var area = _db.Queryable().Where(o => o.Id == input.areaId).First();
if (area.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到地域");
}
//if(input.isMe==BlindBoxStatus.BlindIsMeStatus.自己购买.GetHashCode().ToString())
//{
// //自己购买
// if (input.type.Equals(BlindBoxStatus.BlindBoxLineStatus.MBT人格线路.GetHashCode().ToString()))
// {
// //人格路线
// if (input.mbtLineId.IsNullOrEmpty()) throw NCCException.Oh($"请选择人格路线");
// var mbtLine = _db.Queryable().Where(o => o.Id == input.mbtLineId).First();
// if (mbtLine.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到人格路线");
// }
// else
// {
// //地域路线
// if (input.areaLineId.IsNullOrEmpty()) throw NCCException.Oh($"请选择地域路线!");
// var areaLine = _db.Queryable().Where(o => o.Id == input.areaLineId).First();
// if (areaLine.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到地域路线");
// }
//}
var settingPrice = _db.Queryable().ToList();
if (settingPrice.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到价格设定数据,请联系管理员!");
var manghe = settingPrice.Find(o => o.Type == BlindBoxStatus.BlindBoxSettingPriceType.盲盒价格.GetHashCode().ToString());
var menpiao = settingPrice.Find(o => o.Type == BlindBoxStatus.BlindBoxSettingPriceType.门票价格.GetHashCode().ToString());
if (menpiao.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到门票价格,请联系管理员!");
if (manghe.IsNullOrEmpty()) throw NCCException.Oh($"暂未查询到盲盒价格,请联系管理员!");
decimal totalMoneys = manghe.Price + menpiao.Price;
Log.Information($"支付总价:{totalMoneys}");
var entity = input.Adapt();
entity.OrderNumber = ServiceHelper.getTime().ToString();
entity.Status = BlindBoxStatus.BlindBoxOrderStatus.未付款.GetHashCode().ToString();
entity.CreatorTime = DateTime.Now;
entity.TotalPrice = totalMoneys;
entity.Status = BlindBoxStatus.BlindBoxOrderStatus.未付款.GetHashCode().ToString();
entity.Id = YitIdHelper.NextId().ToString();
entity.CreatorTime = DateTime.Now;
var orderResult = _db.Insertable(entity).ExecuteReturnEntity();
_logger.LogInformation($"添加订单状态:{orderResult.ToJson()}");
if (entity.IsMe == "2")
{
_logger.LogInformation($"进入二维码");
entity.QrCode = GetQRCode("pages/index/index", $"boxOrderId={orderResult.Id}").GetAwaiter().GetResult();
_logger.LogInformation($"生成二维码:{entity.QrCode}");
}
//1--盲盒下单
string result = _wepay.BuildWePay(user.OpenId, entity.OrderNumber, "盲盒抽奖", _wepay.GetMoneyYuanToFen(entity.TotalPrice), HttpContextExtensions.GetRemoteIpAddressToIPv4(_httpContextAccessor.HttpContext),0,1);
_logger.LogInformation($"这是盲和下单数据:{result.ToJson()}");
var dataResult = new PlanceBoxOrderResult
{
order = entity,
data =JObject.Parse(result)
};
return dataResult;
}
///
/// 盲盒下单返回信息
///
public class PlanceBoxOrderResult
{
///
/// 订单信息
///
public TbBoxOrderEntity order { get; set; }
public object data { get; set; }
}
///
/// 小程序获取accesstoken
///
public class WXApi
{
public string access_token { get; set; }
}
public class ModelJson
{
public string scene = "";
public string page = "";
public bool check_path = false;
}
///
/// 获取小程序accesstoken
///
/// APPID
/// 密钥
///
[HttpGet("GetAccessToken")]
[AllowAnonymous]
public string GetAccessToken()
{
string apiurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + WepayConfig.APPLETE_APPID + "&secret=" + WepayConfig.APPLETE_APPSECRET;
WebRequest request = WebRequest.Create(apiurl);
request.Method = "GET";
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
Encoding encode = Encoding.UTF8;
StreamReader reader = new StreamReader(stream, encode);
string detail = reader.ReadToEnd();
_logger.LogInformation($"信息access:{detail}");
WXApi jd = JsonConvert.DeserializeObject(detail);
return jd.access_token;
}
///
/// 获取二维码数据 带参数
///
/// 扫描二维码跳转的页面
/// 携带的参数多个参数逗号隔开
///
[HttpPost("GetQRCode")]
[AllowAnonymous]
public async Task GetQRCode(string page = "", string scene = "")
{
ModelJson jsons = new ModelJson();
_ = string.Empty;
string access_token = GetAccessToken();
_logger.LogInformation($"获取token:{access_token}");
string apiurl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token;
WebRequest request = WebRequest.Create(apiurl);
request.Method = "POST";
request.ContentType = "image/jpeg";
jsons.scene = scene;
jsons.page = page;
jsons.check_path = false;
string DataJson = JsonHelper.ToJson((object)jsons);
byte[] bytearray = Encoding.UTF8.GetBytes(DataJson);
request.ContentLength = bytearray.Length;
Stream strStream = request.GetRequestStream();
strStream.Write(bytearray, 0, bytearray.Length);
strStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
Bitmap bitimg = new Bitmap(stream);
MemoryStream memoryStream = new MemoryStream();
bitimg.Save(memoryStream, ImageFormat.Jpeg);
byte[] arr = new byte[memoryStream.Length];
memoryStream.Position = 0L;
memoryStream.Read(arr, 0, (int)memoryStream.Length);
Image imgs = Image.FromStream(memoryStream);
string filename = _hostingEnvironment.ContentRootPath + "\\UploadFile\\SystemFile\\" + Guid.NewGuid().ToString() + ".jpg";
imgs.Save(filename);
return Path.GetFileName(filename);
}
///
/// 获取盲盒订单
///
/// 参数
///
[HttpGet("{id}")]
public async Task GetInfo(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable().FirstAsync(p => p.Id == id);
var output = entity.Adapt();
return output;
}
///
/// 获取盲盒订单列表
///
/// 请求参数
///
[HttpGet("")]
public async Task GetList([FromQuery] TbBoxOrderListQueryInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var sidx = input.sidx == null ? "id" : input.sidx;
var data = await _db.Queryable()
.WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
.WhereIF(!string.IsNullOrEmpty(input.orderNumber), p => p.OrderNumber.Contains(input.orderNumber))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.WhereIF(!string.IsNullOrEmpty(input.areaId), p => p.AreaId.Equals(input.areaId))
.WhereIF(!string.IsNullOrEmpty(input.areaLineId), p => p.AreaLineId.Equals(input.areaLineId))
.WhereIF(!string.IsNullOrEmpty(input.mbtId), p => p.MbtId.Equals(input.mbtId))
.WhereIF(!string.IsNullOrEmpty(input.mbtLineId), p => p.MbtLineId.Equals(input.mbtLineId))
.WhereIF(!string.IsNullOrEmpty(input.status), p => p.Status.Equals(input.status))
.WhereIF(!string.IsNullOrEmpty(input.isMe), p => p.IsMe.Equals(input.isMe))
.WhereIF(!string.IsNullOrEmpty(input.giveUserId), p => p.GiveUserId.Equals(input.giveUserId))
.WhereIF(!string.IsNullOrEmpty(input.myBoxCouponId), p => p.MyBoxCouponId.Equals(input.myBoxCouponId))
.Select(it=> new TbBoxOrderListOutput
{
id = it.Id,
userId=it.UserId,
orderNumber=it.OrderNumber,
type=it.Type,
areaId=it.AreaId,
areaLineId=it.AreaLineId,
mbtId=it.MbtId,
mbtLineId=it.MbtLineId,
totalPrice=it.TotalPrice,
status=it.Status,
isMe=it.IsMe,
giveUserId=it.GiveUserId,
myBoxCouponId=it.MyBoxCouponId,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
qrCode=it.QrCode
}).MergeTable().Mapper(p =>
{
var logData = _db.Queryable().Where(o => o.BoxOrderId == p.id).Count();
p.isAnewDraw = logData > 1 ? "1" : "2";
p.tickets = _db.Queryable().Where(o => o.OrderId == p.id).First();
p.isAppend = p.tickets.IsNullOrEmpty() ? "1" : "2";
p.user = _db.Queryable().Where(o => o.Id == p.userId).First();
p.area = _db.Queryable().Where(o => o.Id == p.areaId).First();
p.areaLine = _db.Queryable().Where(o => o.Id == p.areaLineId).First();
p.mbt = _db.Queryable().Where(o => o.Id == p.mbtId).First();
p.mbtLine = _db.Queryable().Where(o => o.Id == p.mbtLineId).First();
p.giveUser = _db.Queryable().Where(o => o.Id == p.giveUserId).First();
p.myBoxCoupon = _db.Queryable().Where(o => o.Id == p.myBoxCouponId).First();
}).OrderBy(sidx+" "+input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult.SqlSugarPageResult(data);
}
///
/// 新建盲盒订单
///
/// 参数
///
[HttpPost("")]
public async Task Create([FromBody] TbBoxOrderCrInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var userInfo = await _userManager.GetUserInfo();
var entity = input.Adapt();
entity.Id = YitIdHelper.NextId().ToString();
entity.CreatorTime = DateTime.Now;
var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1000);
}
///
/// 获取盲盒订单无分页列表
///
/// 请求参数
///
[NonAction]
public async Task GetNoPagingList([FromQuery] TbBoxOrderListQueryInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var sidx = input.sidx == null ? "id" : input.sidx;
var data = await _db.Queryable()
.WhereIF(!string.IsNullOrEmpty(input.userId), p => p.UserId.Equals(input.userId))
.WhereIF(!string.IsNullOrEmpty(input.orderNumber), p => p.OrderNumber.Contains(input.orderNumber))
.WhereIF(!string.IsNullOrEmpty(input.type), p => p.Type.Equals(input.type))
.WhereIF(!string.IsNullOrEmpty(input.areaId), p => p.AreaId.Equals(input.areaId))
.WhereIF(!string.IsNullOrEmpty(input.areaLineId), p => p.AreaLineId.Equals(input.areaLineId))
.WhereIF(!string.IsNullOrEmpty(input.mbtId), p => p.MbtId.Equals(input.mbtId))
.WhereIF(!string.IsNullOrEmpty(input.mbtLineId), p => p.MbtLineId.Equals(input.mbtLineId))
.WhereIF(!string.IsNullOrEmpty(input.status), p => p.Status.Equals(input.status))
.WhereIF(!string.IsNullOrEmpty(input.isMe), p => p.IsMe.Equals(input.isMe))
.WhereIF(!string.IsNullOrEmpty(input.giveUserId), p => p.GiveUserId.Equals(input.giveUserId))
.WhereIF(!string.IsNullOrEmpty(input.myBoxCouponId), p => p.MyBoxCouponId.Equals(input.myBoxCouponId))
.Select(it=> new TbBoxOrderListOutput
{
id = it.Id,
userId=it.UserId,
orderNumber=it.OrderNumber,
type=it.Type,
areaId=it.AreaId,
areaLineId=it.AreaLineId,
mbtId=it.MbtId,
mbtLineId=it.MbtLineId,
totalPrice=it.TotalPrice,
status=it.Status,
isMe=it.IsMe,
giveUserId=it.GiveUserId,
myBoxCouponId=it.MyBoxCouponId,
creatorTime=it.CreatorTime,
lastModifyTime=it.LastModifyTime,
}).MergeTable().OrderBy(sidx+" "+input.sort).ToListAsync();
return data;
}
///
/// 导出盲盒订单
///
/// 请求参数
///
[HttpGet("Actions/Export")]
public async Task Export([FromQuery] TbBoxOrderListQueryInput input)
{
var userInfo = await _userManager.GetUserInfo();
var exportData = new List();
if (input.dataType == 0)
{
var data = Clay.Object(await this.GetList(input));
exportData = data.Solidify>().list;
}
else
{
exportData = await this.GetNoPagingList(input);
}
List paramList = "[{\"value\":\"用户\",\"field\":\"userId\"},{\"value\":\"订单号\",\"field\":\"orderNumber\"},{\"value\":\"路线\",\"field\":\"type\"},{\"value\":\"地域\",\"field\":\"areaId\"},{\"value\":\"地域线路\",\"field\":\"areaLineId\"},{\"value\":\"人格\",\"field\":\"mbtId\"},{\"value\":\"人格线路\",\"field\":\"mbtLineId\"},{\"value\":\"状态\",\"field\":\"status\"},{\"value\":\"购买类型\",\"field\":\"isMe\"},{\"value\":\"赠送人\",\"field\":\"giveUserId\"},{\"value\":\"盲盒券\",\"field\":\"myBoxCouponId\"},{\"value\":\"创建时间\",\"field\":\"creatorTime\"},{\"value\":\"修改时间\",\"field\":\"lastModifyTime\"},{\"value\":\"总金额\",\"field\":\"totalPrice\"},]".ToList();
ExcelConfig excelconfig = new ExcelConfig();
excelconfig.FileName = "盲盒订单.xls";
excelconfig.HeadFont = "微软雅黑";
excelconfig.HeadPoint = 10;
excelconfig.IsAllSizeColumn = true;
excelconfig.ColumnModel = new List();
List selectKeyList = input.selectKey.Split(',').ToList();
foreach (var item in selectKeyList)
{
var isExist = paramList.Find(p => p.field == item);
if (isExist != null)
{
excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
}
}
var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
ExcelExportHelper.Export(exportData, excelconfig, addPath);
var fileName = _userManager.UserId + "|" + addPath + "|xls";
var output = new
{
name = excelconfig.FileName,
url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC")
};
return output;
}
///
/// 批量删除盲盒订单
///
/// 主键数组
///
[HttpPost("batchRemove")]
public async Task BatchRemove([FromBody] List ids)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entitys = await _db.Queryable().In(it => it.Id, ids).ToListAsync();
if (entitys.Count > 0)
{
try
{
//开启事务
_db.BeginTran();
//批量删除盲盒订单
await _db.Deleteable().In(d => d.Id,ids).ExecuteCommandAsync();
//关闭事务
_db.CommitTran();
}
catch (Exception)
{
//回滚事务
_db.RollbackTran();
throw NCCException.Oh(ErrorCode.COM1002);
}
}
}
///
/// 更新盲盒订单
///
/// 主键
/// 参数
///
[HttpPut("{id}")]
public async Task Update(string id, [FromBody] TbBoxOrderUpInput input)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = input.Adapt();
entity.LastModifyTime = DateTime.Now;
var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1001);
}
///
/// 删除盲盒订单
///
///
[HttpDelete("{id}")]
public async Task Delete(string id)
{
var dbLink = await _dbLinkService.GetInfo("218239598550058245");
_db.AddConnection(new ConnectionConfig()
{
ConfigId = dbLink.Id,
DbType = _dataBaseService.ToDbType(dbLink.DbType),
ConnectionString = _dataBaseService.ToConnectionString(dbLink),
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
_db.ChangeDatabase(dbLink.Id);
var entity = await _db.Queryable().FirstAsync(p => p.Id == id);
_ = entity ?? throw NCCException.Oh(ErrorCode.COM1005);
var isOk = await _db.Deleteable().Where(d => d.Id == id).ExecuteCommandAsync();
if (!(isOk > 0)) throw NCCException.Oh(ErrorCode.COM1002);
}
}
}