using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using NCC.ClayObject; using NCC.Common.Configuration; using NCC.Common.Const; using NCC.Common.Core.Manager; using NCC.Common.Extension; using NCC.Common.Filter; using NCC.Common.Helper; using NCC.Common.Model.NPOI; using NCC.DataEncryption; using NCC.Dependency; using NCC.DynamicApiController; using NCC.Extend.Entitys.Dto.Mall; using NCC.Extend.Entitys.Enum; using NCC.Extend.Entitys.lq_mall_appointment; using NCC.Extend.Entitys.lq_mall_member; using NCC.Extend.Entitys.lq_mdxx; using NCC.Extend.Interfaces.BusinessOperationLog; using NCC.FriendlyException; using NCC.JsonSerialization; using NCC.System.Entitys.Permission; using SqlSugar; using Yitter.IdGenerator; namespace NCC.Extend { /// /// 会员商城-预约意向(会员提交到店预约意向,门店/后台查看后电话确认;不关联现有预约业务) /// [ApiDescriptionSettings(Tag = "会员商城-预约", Name = "LqMallAppointment", Order = 304)] [Route("api/Extend/LqMallAppointment")] public class LqMallAppointmentService : IDynamicApiController, ITransient { private readonly IUserManager _userManager; private readonly ILogger _logger; private readonly ISqlSugarClient _db; private readonly IBusinessOperationLogService _log; /// /// 构造函数 /// public LqMallAppointmentService( IUserManager userManager, ILogger logger, ISqlSugarClient db, IBusinessOperationLogService log) { _userManager = userManager; _logger = logger; _db = db; _log = log; } #region C 端(会员小程序) /// /// 创建预约意向 /// /// 预约输入 /// 预约 Id 与单号 [HttpPost("CreateAppointment")] public async Task CreateAppointmentAsync([FromBody] MallAppointmentCreateInput input) { var memberId = GetCurrentMemberId(); if (input == null) throw NCCException.Oh("参数不能为空"); if (string.IsNullOrWhiteSpace(input.StoreId)) throw NCCException.Oh("请选择预约门店"); if (input.AppointDate == null) throw NCCException.Oh("请选择期望到店日期"); if (string.IsNullOrWhiteSpace(input.TimeSlot)) throw NCCException.Oh("请选择期望到店时段"); var member = await _db.Queryable() .Where(x => x.Id == memberId && x.DeleteMark == null).FirstAsync(); if (member == null) throw NCCException.Oh("会员不存在"); var store = await _db.Queryable().Where(x => x.Id == input.StoreId).FirstAsync(); if (store == null) throw NCCException.Oh("预约门店不存在"); var phone = string.IsNullOrWhiteSpace(input.ContactPhone) ? member.Phone : input.ContactPhone.Trim(); if (string.IsNullOrWhiteSpace(phone)) throw NCCException.Oh("请填写联系手机号"); var entity = new LqMallAppointmentEntity { Id = YitIdHelper.NextId().ToString(), AppointmentNo = GenerateAppointmentNo(), MemberId = member.Id, MemberName = member.NickName, MemberPhone = phone, StoreId = store.Id, StoreName = store.Dm, AppointDate = input.AppointDate.Value.Date, TimeSlot = input.TimeSlot.Trim(), ProjectDesc = input.ProjectDesc, Remark = input.Remark, Status = (int)MallAppointmentStatusEnum.待确认, CreateTime = DateTime.Now, UpdateTime = DateTime.Now }; var ok = await _db.Insertable(entity).ExecuteCommandAsync(); if (ok <= 0) throw NCCException.Oh("预约提交失败,请重试"); return new { id = entity.Id, appointmentNo = entity.AppointmentNo }; } /// /// 我的预约列表(分页,可按状态过滤) /// /// 查询条件 /// 预约分页列表 [HttpGet("GetMyAppointments")] public async Task GetMyAppointmentsAsync([FromQuery] MallMyAppointmentQueryInput input) { var memberId = GetCurrentMemberId(); var data = await _db.Queryable() .Where(x => x.MemberId == memberId && x.DeleteMark == null) .WhereIF(input.Status.HasValue, x => x.Status == input.Status.Value) .OrderBy(x => x.CreateTime, OrderByType.Desc) .Select(x => new MallAppointmentListOutput { id = x.Id, appointmentNo = x.AppointmentNo, memberId = x.MemberId, memberName = x.MemberName, memberPhone = x.MemberPhone, storeId = x.StoreId, storeName = x.StoreName, appointDate = x.AppointDate, timeSlot = x.TimeSlot, projectDesc = x.ProjectDesc, remark = x.Remark, status = x.Status, confirmUserName = x.ConfirmUserName, confirmTime = x.ConfirmTime, confirmRemark = x.ConfirmRemark, cancelReason = x.CancelReason, createTime = x.CreateTime }) .ToPagedListAsync(input.currentPage, input.pageSize); return PageResult.SqlSugarPageResult(data); } /// /// 我的预约详情 /// /// 预约 Id /// 预约详情 [HttpGet("GetAppointmentDetail")] public async Task GetAppointmentDetailAsync([FromQuery] string id) { var memberId = GetCurrentMemberId(); if (string.IsNullOrWhiteSpace(id)) throw NCCException.Oh("预约 Id 不能为空"); var entity = await _db.Queryable() .Where(x => x.Id == id && x.MemberId == memberId && x.DeleteMark == null).FirstAsync(); if (entity == null) throw NCCException.Oh("预约不存在"); return MapDetail(entity); } /// /// 取消预约(仅待确认可取消) /// /// 预约 Id [HttpPut("CancelAppointment/{id}")] public async Task CancelAppointmentAsync([FromRoute] string id) { var memberId = GetCurrentMemberId(); var entity = await _db.Queryable() .Where(x => x.Id == id && x.MemberId == memberId && x.DeleteMark == null).FirstAsync(); if (entity == null) throw NCCException.Oh("预约不存在"); if (entity.Status != (int)MallAppointmentStatusEnum.待确认) throw NCCException.Oh("仅待确认的预约可取消"); entity.Status = (int)MallAppointmentStatusEnum.已取消; entity.CancelReason = "会员取消"; entity.UpdateTime = DateTime.Now; await _db.Updateable(entity) .UpdateColumns(x => new { x.Status, x.CancelReason, x.UpdateTime }) .ExecuteCommandAsync(); } #endregion #region 管理端 /// /// 管理端预约列表(分页,多条件筛选,全门店) /// /// 查询条件 /// 预约分页列表 [HttpGet("GetAdminList")] public async Task GetAdminListAsync([FromQuery] MallAppointmentAdminQueryInput input) { var data = await BuildAdminQuery(input).ToPagedListAsync(input.currentPage, input.pageSize); return PageResult.SqlSugarPageResult(data); } /// /// 管理端预约详情 /// /// 预约 Id /// 预约详情 [HttpGet("GetAdminDetail")] public async Task GetAdminDetailAsync([FromQuery] string id) { if (string.IsNullOrWhiteSpace(id)) throw NCCException.Oh("预约 Id 不能为空"); var entity = await _db.Queryable() .Where(x => x.Id == id && x.DeleteMark == null).FirstAsync(); if (entity == null) throw NCCException.Oh("预约不存在"); return MapDetail(entity); } /// /// 确认预约(待确认→已确认,记录确认人与沟通结果;管理端与门店端共用) /// /// 确认输入(门店端需传 StoreId 做归属校验) /// 确认结果 [HttpPut("Confirm")] public async Task ConfirmAsync([FromBody] MallAppointmentConfirmInput input) { if (input == null || string.IsNullOrWhiteSpace(input.Id)) throw NCCException.Oh("预约 Id 不能为空"); var entity = await _db.Queryable() .Where(x => x.Id == input.Id && x.DeleteMark == null).FirstAsync(); if (entity == null) throw NCCException.Oh("预约不存在"); if (!string.IsNullOrWhiteSpace(input.StoreId) && entity.StoreId != input.StoreId) throw NCCException.Oh("该预约不属于当前门店"); if (entity.Status == (int)MallAppointmentStatusEnum.已取消) throw NCCException.Oh("预约已取消,无法确认"); if (entity.Status == (int)MallAppointmentStatusEnum.已确认) throw NCCException.Oh("预约已确认,请勿重复操作"); var operatorId = _userManager.UserId; var operatorName = ""; if (!string.IsNullOrWhiteSpace(operatorId)) { operatorName = await _db.Queryable() .Where(x => x.Id == operatorId).Select(x => x.RealName).FirstAsync(); } entity.Status = (int)MallAppointmentStatusEnum.已确认; entity.ConfirmUser = operatorId; entity.ConfirmUserName = operatorName; entity.ConfirmTime = DateTime.Now; entity.ConfirmRemark = input.ConfirmRemark; entity.UpdateTime = DateTime.Now; await _db.Updateable(entity) .UpdateColumns(x => new { x.Status, x.ConfirmUser, x.ConfirmUserName, x.ConfirmTime, x.ConfirmRemark, x.UpdateTime }) .ExecuteCommandAsync(); await _log.WriteAsync("会员商城", "确认预约", "mall_appointment", entity.Id, $"确认会员预约:{entity.MemberName}({entity.MemberPhone}){entity.AppointmentNo}"); return new { success = true, id = entity.Id }; } /// /// 管理端取消预约(待确认/已确认均可取消,记录原因) /// /// 确认输入(复用,读取 Id / ConfirmRemark 作为取消原因) [HttpPut("AdminCancel")] public async Task AdminCancelAsync([FromBody] MallAppointmentConfirmInput input) { if (input == null || string.IsNullOrWhiteSpace(input.Id)) throw NCCException.Oh("预约 Id 不能为空"); var entity = await _db.Queryable() .Where(x => x.Id == input.Id && x.DeleteMark == null).FirstAsync(); if (entity == null) throw NCCException.Oh("预约不存在"); if (!string.IsNullOrWhiteSpace(input.StoreId) && entity.StoreId != input.StoreId) throw NCCException.Oh("该预约不属于当前门店"); if (entity.Status == (int)MallAppointmentStatusEnum.已取消) throw NCCException.Oh("预约已取消"); entity.Status = (int)MallAppointmentStatusEnum.已取消; entity.CancelReason = string.IsNullOrWhiteSpace(input.ConfirmRemark) ? "门店取消" : input.ConfirmRemark.Trim(); entity.UpdateTime = DateTime.Now; await _db.Updateable(entity) .UpdateColumns(x => new { x.Status, x.CancelReason, x.UpdateTime }) .ExecuteCommandAsync(); await _log.WriteAsync("会员商城", "取消预约", "mall_appointment", entity.Id, $"取消会员预约:{entity.MemberName}({entity.MemberPhone}){entity.AppointmentNo}"); } /// /// 导出线上预约(固定列,忽略 selectKey) /// /// /// GET /api/Extend/LqMallAppointment/Actions/Export?dataType=1 /// dataType:0 当前页,1 全部;筛选条件与 GetAdminList 一致。 /// /// 管理端查询参数 /// Excel 下载信息(name、url) [HttpGet("Actions/Export")] public async Task ExportAsync([FromQuery] MallAppointmentAdminQueryInput input) { input ??= new MallAppointmentAdminQueryInput(); var list = new List(); if (input.dataType == 0) { var data = Clay.Object(await GetAdminListAsync(input)); list = data.Solidify>().list; } else { list = await BuildAdminQuery(input).ToListAsync(); } var exportData = list.Select(x => new MallAppointmentExportOutput { appointmentNo = x.appointmentNo, memberName = x.memberName, memberPhone = x.memberPhone, storeName = x.storeName, appointDisplay = FormatAppointDisplay(x.appointDate, x.timeSlot), projectDesc = x.projectDesc, statusText = ResolveMallAppointmentStatusText(x.status), createTime = x.createTime }).ToList(); List paramList = "[{\"value\":\"预约单号\",\"field\":\"appointmentNo\"},{\"value\":\"会员名称\",\"field\":\"memberName\"},{\"value\":\"手机号\",\"field\":\"memberPhone\"},{\"value\":\"门店名称\",\"field\":\"storeName\"},{\"value\":\"期望到店\",\"field\":\"appointDisplay\"},{\"value\":\"需求\",\"field\":\"projectDesc\"},{\"value\":\"状态\",\"field\":\"statusText\"},{\"value\":\"提交时间\",\"field\":\"createTime\"}]" .ToList(); var excelconfig = new ExcelConfig { FileName = "线上预约.xls", HeadFont = "微软雅黑", HeadPoint = 10, IsAllSizeColumn = true, ColumnModel = new List() }; foreach (var param in paramList) { excelconfig.ColumnModel.Add(new ExcelColumnModel { Column = param.field, ExcelColumn = param.value }); } var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName; ExcelExportHelper.Export(exportData, excelconfig, addPath); var fileName = _userManager.UserId + "|" + addPath + "|xls"; await TryWriteBizLogAsync( "导出线上预约", "mall_appointment", null, $"导出线上预约,共 {exportData.Count} 条", new { filters = new { input.StoreId, input.Status, input.Keyword, input.StartDate, input.EndDate, input.dataType }, rowCount = exportData.Count, fileName = excelconfig.FileName }.Serialize()); return new { name = excelconfig.FileName, url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "NCC") }; } #endregion #region 门店端 /// /// 门店端预约列表(仅本门店,分页,可按状态过滤) /// /// 查询条件(StoreId 必填) /// 预约分页列表 [HttpGet("GetStoreList")] public async Task GetStoreListAsync([FromQuery] MallAppointmentAdminQueryInput input) { if (input == null || string.IsNullOrWhiteSpace(input.StoreId)) throw NCCException.Oh("门店 Id 不能为空"); var data = await BuildAdminQuery(input).ToPagedListAsync(input.currentPage, input.pageSize); return PageResult.SqlSugarPageResult(data); } #endregion #region 私有方法 /// /// 构建管理端/门店端通用查询 /// private ISugarQueryable BuildAdminQuery(MallAppointmentAdminQueryInput input) { return _db.Queryable() .Where(x => x.DeleteMark == null) .WhereIF(!string.IsNullOrWhiteSpace(input.StoreId), x => x.StoreId == input.StoreId) .WhereIF(input.Status.HasValue, x => x.Status == input.Status.Value) .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), x => x.MemberName.Contains(input.Keyword) || x.MemberPhone.Contains(input.Keyword)) .WhereIF(input.StartDate.HasValue, x => x.AppointDate >= input.StartDate.Value.Date) .WhereIF(input.EndDate.HasValue, x => x.AppointDate <= input.EndDate.Value.Date) .OrderBy(x => x.CreateTime, OrderByType.Desc) .Select(x => new MallAppointmentListOutput { id = x.Id, appointmentNo = x.AppointmentNo, memberId = x.MemberId, memberName = x.MemberName, memberPhone = x.MemberPhone, storeId = x.StoreId, storeName = x.StoreName, appointDate = x.AppointDate, timeSlot = x.TimeSlot, projectDesc = x.ProjectDesc, remark = x.Remark, status = x.Status, confirmUserName = x.ConfirmUserName, confirmTime = x.ConfirmTime, confirmRemark = x.ConfirmRemark, cancelReason = x.CancelReason, createTime = x.CreateTime }); } private static object MapDetail(LqMallAppointmentEntity x) { return new { id = x.Id, appointmentNo = x.AppointmentNo, memberId = x.MemberId, memberName = x.MemberName, memberPhone = x.MemberPhone, storeId = x.StoreId, storeName = x.StoreName, appointDate = x.AppointDate, timeSlot = x.TimeSlot, projectDesc = x.ProjectDesc, remark = x.Remark, status = x.Status, confirmUser = x.ConfirmUser, confirmUserName = x.ConfirmUserName, confirmTime = x.ConfirmTime, confirmRemark = x.ConfirmRemark, cancelReason = x.CancelReason, createTime = x.CreateTime, updateTime = x.UpdateTime }; } /// /// 生成预约单号(Y + 时间戳 + 随机) /// private static string GenerateAppointmentNo() { var rnd = new Random(Guid.NewGuid().GetHashCode()).Next(1000, 9999); return "Y" + DateTime.Now.ToString("yyyyMMddHHmmss") + rnd; } /// /// 获取当前登录会员 Id /// private string GetCurrentMemberId() { var memberId = App.User?.FindFirstValue(ClaimConst.CLAINM_USERID); if (string.IsNullOrWhiteSpace(memberId)) throw NCCException.Oh("未登录"); return memberId; } private static string FormatAppointDisplay(DateTime? appointDate, string timeSlot) { var datePart = appointDate?.ToString("yyyy-MM-dd") ?? string.Empty; var slotPart = (timeSlot ?? string.Empty).Trim(); if (string.IsNullOrEmpty(datePart)) return slotPart; if (string.IsNullOrEmpty(slotPart)) return datePart; return $"{datePart} {slotPart}"; } private static string ResolveMallAppointmentStatusText(int status) { if (global::System.Enum.IsDefined(typeof(MallAppointmentStatusEnum), status)) return ((MallAppointmentStatusEnum)status).GetDescription(); return status.ToString(); } private async Task TryWriteBizLogAsync( string actionCode, string bizType, string bizId, string summary, string detailJson) { try { await _log.WriteAsync("线上预约", actionCode, bizType, bizId, summary, detailJson); } catch (Exception ex) { _logger.LogWarning(ex, "写入线上预约业务操作日志失败 action={Action}", actionCode); } } #endregion } }